file_id
stringlengths 5
10
| content
stringlengths 110
41.7k
| repo
stringlengths 7
108
| path
stringlengths 8
211
| token_length
int64 35
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 73
41.6k
|
---|---|---|---|---|---|---|---|---|
83557_9 | /*
* B3P Commons Core is a library with commonly used classes for webapps.
* Included are clieop3, oai, security, struts, taglibs and other
* general helper classes and extensions.
*
* Copyright 2000 - 2008 B3Partners BV
*
* This file is part of B3P Commons Core.
*
* B3P Commons Core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons Core is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons Core. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* $Id: ClieOp3OutputStream.java 2202 2005-12-14 16:14:18Z Matthijs $
*/
package nl.b3p.commons.clieop3;
import java.io.*;
import java.math.BigInteger;
import org.apache.commons.logging.*;
import nl.b3p.commons.clieop3.record.*;
/**
* Gebaseerd op de ClieOp3 specificatie van Interpay januari 2005 en die van
* ING Bank.
*
* TODO impl incasso's
*/
public class ClieOp3OutputStream {
private static final Log log = LogFactory.getLog(ClieOp3OutputStream.class);
/**
* Maximaal aantal posten per batch
*/
public static final int MAX_POSTEN = 100000;
/**
* Lengte van een record
*/
public static final int RECORD_LENGTH = 50;
/**
* Maximaal aantal regels per post (incl vaste omschrijvingen, omschrijvingen
* en betalingskenmerk)
*/
private static final int MAX_REGELS = 4;
private OutputStreamWriter writer;
private BatchState batchState = null;
private class BatchState {
int vasteOmschrijvingenCount;
BigInteger totaalBedragCenten;
BigInteger totaalRekeningnummers;
int postCount = 0;
}
private int batchCount = 0;
private BigInteger totaalRekeningnummers = new BigInteger("0");
public ClieOp3OutputStream(OutputStream out, BestandStart bestand) throws IOException {
this.writer = new OutputStreamWriter(out, "US-ASCII");
writeRecord(bestand);
}
private void writeRecord(Record record) throws IOException {
writer.write(record.getRecordData(), 0, RECORD_LENGTH);
/* records moeten worden afgesloten door CR LF */
writer.write('\r');
writer.write('\n');
}
private static final String allowed = " .()+&$*:;-/,%?@='\"";
public static String replaceForbiddenChars(String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
allowed.indexOf(c) != -1) {
continue;
}
chars[i] = '?';
}
return new String(chars);
}
public static String cleanClieOp3String(String str) {
return replaceForbiddenChars(str);
}
public void endBestand() throws IOException {
if (batchState != null) {
endBatch();
}
writeRecord(new BestandEnd());
writer.flush();
}
public void startBatch(
BatchStart batch,
VasteOmschrijving[] vasteOmschrijvingRegels,
Opdrachtgever opdrachtgever)
throws IOException {
if (batchState != null) {
endBatch();
}
/* TODO check max. aantal batches? */
/* TODO check transactiegroup? */
/* TODO check rekeningnummer opdrachtgever? */
batch.setVolgnummer(++batchCount);
writeRecord(batch);
batchState = new BatchState();
batchState.postCount = 0;
batchState.totaalBedragCenten = new BigInteger("0");
batchState.totaalRekeningnummers = new BigInteger("0");
if (vasteOmschrijvingRegels != null) {
batchState.vasteOmschrijvingenCount = vasteOmschrijvingRegels.length;
int max = Math.min(MAX_REGELS, batchState.vasteOmschrijvingenCount);
for (int i = 0; i < max; i++) {
writeRecord(vasteOmschrijvingRegels[i]);
}
}
writeRecord(opdrachtgever);
}
public void addBetaalPost(
Transactie transactie,
Betalingskenmerk betalingskenmerk,
Omschrijving[] omschrijvingsRegels,
NaamBegunstigde naamBegunstigde,
WoonplaatsBegunstigde woonplaatsBegunstigde) throws IOException {
if (batchState == null) {
throw new IllegalStateException("niet in batch");
}
if (batchState.postCount == MAX_POSTEN) {
throw new IllegalStateException("maximaal aantal posten bereikt");
}
writeRecord(transactie);
batchState.totaalBedragCenten = batchState.totaalBedragCenten.add(transactie.getBedragCenten());
batchState.totaalRekeningnummers = batchState.totaalRekeningnummers.add(transactie.getRekeningnummberBegunstigde());
batchState.totaalRekeningnummers = batchState.totaalRekeningnummers.add(transactie.getRekeningnummerBetaler());
if (betalingskenmerk != null) {
writeRecord(betalingskenmerk);
}
if (omschrijvingsRegels != null) {
int maxOmschrijvingen = MAX_REGELS;
maxOmschrijvingen = maxOmschrijvingen - batchState.vasteOmschrijvingenCount;
if (betalingskenmerk != null) {
maxOmschrijvingen--;
}
int max = Math.min(maxOmschrijvingen, omschrijvingsRegels.length);
for (int i = 0; i < max; i++) {
writeRecord(omschrijvingsRegels[i]);
}
}
if (naamBegunstigde != null) {
writeRecord(naamBegunstigde);
}
if (woonplaatsBegunstigde != null) {
writeRecord(woonplaatsBegunstigde);
}
batchState.postCount++;
}
public BatchTotalen endBatch() throws IOException {
if (batchState == null) {
throw new IllegalStateException("niet in batch");
}
if (batchState.postCount == 0) {
throw new IllegalStateException("minimaal een post per batch");
}
writeRecord(new BatchEnd(batchState.totaalBedragCenten, batchState.totaalRekeningnummers, batchState.postCount));
BatchTotalen result = new BatchTotalen(batchState.totaalBedragCenten, batchState.totaalRekeningnummers, batchState.postCount, batchCount);
batchState = null;
return result;
}
/*
public static void main(String[] args) throws Exception {
ClieOp3OutputStream clieop = new ClieOp3OutputStream(
System.out,
new BestandStart(new java.util.Date(), "AVR01", 1, false)
);
clieop.startBatch(
new BatchStart(BatchStart.TRANSACTIEGROEP_BETALINGEN, new BigInteger("0679411372"), "EUR"),
new VasteOmschrijving[] {new VasteOmschrijving("Dit is de omschrijving Joehoe")},
new Opdrachtgever(Opdrachtgever.NAW_GEWENST, null, "Ikke", Opdrachtgever.TESTCODE_PRODUCTIE)
);
clieop.addBetaalPost(
new Transactie(
Transactie.TRANSACTIE_ONZUIVERE_CREDITEURENBETALING,
new BigInteger("100"),
new BigInteger("0679411372"),
new BigInteger("43252")
),
new Betalingskenmerk("hoppa"),
new Omschrijving[] {
new Omschrijving("regel 1"),
new Omschrijving("regel 2")
},
new NaamBegunstigde("Piet"),
null
);
clieop.addBetaalPost(
new Transactie(
Transactie.TRANSACTIE_ONZUIVERE_CREDITEURENBETALING,
new BigInteger("12345"),
new BigInteger("0679411372"),
new BigInteger("32894")
),
new Betalingskenmerk("BETALINGSKENMERK"),
new Omschrijving[] {
new Omschrijving("regel 1"),
new Omschrijving("regel 2")
},
new NaamBegunstigde("Klaas"),
new WoonplaatsBegunstigde("Verweggistan")
);
clieop.endBestand();
}
*/
}
| tjidde-nl/b3p-commons-core | src/main/java/nl/b3p/commons/clieop3/ClieOp3OutputStream.java | 2,356 | /* TODO check rekeningnummer opdrachtgever? */ | block_comment | nl | /*
* B3P Commons Core is a library with commonly used classes for webapps.
* Included are clieop3, oai, security, struts, taglibs and other
* general helper classes and extensions.
*
* Copyright 2000 - 2008 B3Partners BV
*
* This file is part of B3P Commons Core.
*
* B3P Commons Core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons Core is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons Core. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* $Id: ClieOp3OutputStream.java 2202 2005-12-14 16:14:18Z Matthijs $
*/
package nl.b3p.commons.clieop3;
import java.io.*;
import java.math.BigInteger;
import org.apache.commons.logging.*;
import nl.b3p.commons.clieop3.record.*;
/**
* Gebaseerd op de ClieOp3 specificatie van Interpay januari 2005 en die van
* ING Bank.
*
* TODO impl incasso's
*/
public class ClieOp3OutputStream {
private static final Log log = LogFactory.getLog(ClieOp3OutputStream.class);
/**
* Maximaal aantal posten per batch
*/
public static final int MAX_POSTEN = 100000;
/**
* Lengte van een record
*/
public static final int RECORD_LENGTH = 50;
/**
* Maximaal aantal regels per post (incl vaste omschrijvingen, omschrijvingen
* en betalingskenmerk)
*/
private static final int MAX_REGELS = 4;
private OutputStreamWriter writer;
private BatchState batchState = null;
private class BatchState {
int vasteOmschrijvingenCount;
BigInteger totaalBedragCenten;
BigInteger totaalRekeningnummers;
int postCount = 0;
}
private int batchCount = 0;
private BigInteger totaalRekeningnummers = new BigInteger("0");
public ClieOp3OutputStream(OutputStream out, BestandStart bestand) throws IOException {
this.writer = new OutputStreamWriter(out, "US-ASCII");
writeRecord(bestand);
}
private void writeRecord(Record record) throws IOException {
writer.write(record.getRecordData(), 0, RECORD_LENGTH);
/* records moeten worden afgesloten door CR LF */
writer.write('\r');
writer.write('\n');
}
private static final String allowed = " .()+&$*:;-/,%?@='\"";
public static String replaceForbiddenChars(String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
allowed.indexOf(c) != -1) {
continue;
}
chars[i] = '?';
}
return new String(chars);
}
public static String cleanClieOp3String(String str) {
return replaceForbiddenChars(str);
}
public void endBestand() throws IOException {
if (batchState != null) {
endBatch();
}
writeRecord(new BestandEnd());
writer.flush();
}
public void startBatch(
BatchStart batch,
VasteOmschrijving[] vasteOmschrijvingRegels,
Opdrachtgever opdrachtgever)
throws IOException {
if (batchState != null) {
endBatch();
}
/* TODO check max. aantal batches? */
/* TODO check transactiegroup? */
/* TODO check rekeningnummer<SUF>*/
batch.setVolgnummer(++batchCount);
writeRecord(batch);
batchState = new BatchState();
batchState.postCount = 0;
batchState.totaalBedragCenten = new BigInteger("0");
batchState.totaalRekeningnummers = new BigInteger("0");
if (vasteOmschrijvingRegels != null) {
batchState.vasteOmschrijvingenCount = vasteOmschrijvingRegels.length;
int max = Math.min(MAX_REGELS, batchState.vasteOmschrijvingenCount);
for (int i = 0; i < max; i++) {
writeRecord(vasteOmschrijvingRegels[i]);
}
}
writeRecord(opdrachtgever);
}
public void addBetaalPost(
Transactie transactie,
Betalingskenmerk betalingskenmerk,
Omschrijving[] omschrijvingsRegels,
NaamBegunstigde naamBegunstigde,
WoonplaatsBegunstigde woonplaatsBegunstigde) throws IOException {
if (batchState == null) {
throw new IllegalStateException("niet in batch");
}
if (batchState.postCount == MAX_POSTEN) {
throw new IllegalStateException("maximaal aantal posten bereikt");
}
writeRecord(transactie);
batchState.totaalBedragCenten = batchState.totaalBedragCenten.add(transactie.getBedragCenten());
batchState.totaalRekeningnummers = batchState.totaalRekeningnummers.add(transactie.getRekeningnummberBegunstigde());
batchState.totaalRekeningnummers = batchState.totaalRekeningnummers.add(transactie.getRekeningnummerBetaler());
if (betalingskenmerk != null) {
writeRecord(betalingskenmerk);
}
if (omschrijvingsRegels != null) {
int maxOmschrijvingen = MAX_REGELS;
maxOmschrijvingen = maxOmschrijvingen - batchState.vasteOmschrijvingenCount;
if (betalingskenmerk != null) {
maxOmschrijvingen--;
}
int max = Math.min(maxOmschrijvingen, omschrijvingsRegels.length);
for (int i = 0; i < max; i++) {
writeRecord(omschrijvingsRegels[i]);
}
}
if (naamBegunstigde != null) {
writeRecord(naamBegunstigde);
}
if (woonplaatsBegunstigde != null) {
writeRecord(woonplaatsBegunstigde);
}
batchState.postCount++;
}
public BatchTotalen endBatch() throws IOException {
if (batchState == null) {
throw new IllegalStateException("niet in batch");
}
if (batchState.postCount == 0) {
throw new IllegalStateException("minimaal een post per batch");
}
writeRecord(new BatchEnd(batchState.totaalBedragCenten, batchState.totaalRekeningnummers, batchState.postCount));
BatchTotalen result = new BatchTotalen(batchState.totaalBedragCenten, batchState.totaalRekeningnummers, batchState.postCount, batchCount);
batchState = null;
return result;
}
/*
public static void main(String[] args) throws Exception {
ClieOp3OutputStream clieop = new ClieOp3OutputStream(
System.out,
new BestandStart(new java.util.Date(), "AVR01", 1, false)
);
clieop.startBatch(
new BatchStart(BatchStart.TRANSACTIEGROEP_BETALINGEN, new BigInteger("0679411372"), "EUR"),
new VasteOmschrijving[] {new VasteOmschrijving("Dit is de omschrijving Joehoe")},
new Opdrachtgever(Opdrachtgever.NAW_GEWENST, null, "Ikke", Opdrachtgever.TESTCODE_PRODUCTIE)
);
clieop.addBetaalPost(
new Transactie(
Transactie.TRANSACTIE_ONZUIVERE_CREDITEURENBETALING,
new BigInteger("100"),
new BigInteger("0679411372"),
new BigInteger("43252")
),
new Betalingskenmerk("hoppa"),
new Omschrijving[] {
new Omschrijving("regel 1"),
new Omschrijving("regel 2")
},
new NaamBegunstigde("Piet"),
null
);
clieop.addBetaalPost(
new Transactie(
Transactie.TRANSACTIE_ONZUIVERE_CREDITEURENBETALING,
new BigInteger("12345"),
new BigInteger("0679411372"),
new BigInteger("32894")
),
new Betalingskenmerk("BETALINGSKENMERK"),
new Omschrijving[] {
new Omschrijving("regel 1"),
new Omschrijving("regel 2")
},
new NaamBegunstigde("Klaas"),
new WoonplaatsBegunstigde("Verweggistan")
);
clieop.endBestand();
}
*/
}
|
5037_13 |
package Logica;
import Database.Database;
import java.awt.Image;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
//Deze nodig voor mail
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Account
{
private int accountnr;
private String naam; //bedrijf = bedrijfsnaam, particulier = naam klant
private String email;
private String adres;
private int punten;
private boolean wolverine;
private java.util.Date jstartw = new java.util.Date();
private java.sql.Date startw = new java.sql.Date(jstartw.getTime());
private boolean bigspender;
private java.util.Date jstartb = new java.util.Date();
private java.sql.Date startb = new java.sql.Date(jstartw.getTime());
private java.sql.Date startm = new java.sql.Date(jstartw.getTime());
private boolean bedrijf;
private String btwnummer;
private Image logo; // logo is niet geïmplementeerd.
Database db = new Database();
public Account()
{}
public Account(int accountnr, boolean wolverine, boolean bigspender, boolean bedrijf)
{
this.accountnr = accountnr;
this.wolverine = wolverine;
this.bigspender = bigspender;
this.bedrijf = bedrijf;
}
public Account(int accountnr, String naam, String email, String adres, int punten, boolean wolverine, java.sql.Date startw, boolean bigspender, java.sql.Date startb, boolean bedrijf, String btwnummer)
{
this.accountnr = accountnr;
this.naam = naam;
this.email = email;
this.adres = adres;
this.punten = punten;
this.wolverine = wolverine;
this.startw = startw;
this.bigspender = bigspender;
this.startb = startb;
this.bedrijf = bedrijf;
this.btwnummer = btwnummer;
}
public int getAccountnr()
{
return this.accountnr;
}
public void setAccountnr(int accountnr)
{
this.accountnr = accountnr;
}
public String getNaam()
{
return this.naam;
}
public void setNaam(String naam)
{
this.naam = naam;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getAdres()
{
return this.adres;
}
public void setAdres(String adres)
{
this.adres = adres;
}
public int getPunten()
{
return this.punten;
}
public void setPunten(int punten)
{
this.punten = punten;
}
public boolean isWolverine()
{
return this.wolverine;
}
public void setWolverine(boolean wolverine)
{
this.wolverine = wolverine;
}
public Date getStartw()
{
return this.startw;
}
public void setStartw(Date datum)
{
this.startw = startw;
}
public boolean isBigspender()
{
return this.bigspender;
}
public void setBigspender(boolean bigspender)
{
this.bigspender = bigspender;
}
public Date getStartb()
{
return this.startb;
}
public void setStartb(Date datum)
{
this.startb = startb;
}
public Date getStartm()
{
return this.startm;
}
public void setStartm(Date datum)
{
this.startm = startm;
}
public boolean isBedrijf()
{
return this.bedrijf;
}
public void setBedrijf(boolean bedrijf)
{
this.bedrijf = bedrijf;
}
public String getBtwnummer()
{
return this.btwnummer;
}
public void setBtwnummer(String btwnummer)
{
this.btwnummer = btwnummer;
}
// Logo niet geïmplementeerd
public Image getLogo()
{
return logo;
}
public void setLogo(Image logo)
{
this.logo = logo;
}
public void bedrijfOfParticulier(Boolean bedrijf)
{
if (bedrijf == true)
this.bedrijf = true;
else
this.bedrijf = false;
}
public boolean isVip(int accountnr){
return totaalPuntenJaar(accountnr) > 9999;
}
public void isMajorWorden(String winkelnaam){
Account acc1 = db.getAccount(this.getAccountnr());
Account acc2 = db.getAccount(db.getWinkel(winkelnaam).getAccount());
if(acc1.isVip(acc1.getAccountnr()))
{
if(db.heeftMajor(winkelnaam))
{
if(this.getAccountnr() != db.getWinkel(winkelnaam).getAccount())
{
if(acc1.totaalGeldJaar(acc1.getAccountnr()) > acc2.totaalGeldJaar(acc2.getAccountnr()))
{
Major major1 = db.getMajor(this.getAccountnr(), winkelnaam);
Major major2 = db.getMajor(db.getWinkel(winkelnaam).getAccount(), winkelnaam);
if(db.checkMajor(this.getAccountnr(), winkelnaam))
{
// acc1 wordt major
db.updateAccountnrWinkel(db.getWinkel(winkelnaam), acc1.getAccountnr());
if(db.krijgtPunten(major1))
{
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
// zet datum op vandaag
db.updateMajor(acc1, db.getWinkel(winkelnaam));
}
}
else
{
// acc1 was nog geen major geweest en wordt major
db.addMajor(this.getAccountnr(), winkelnaam);
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
}
}
else
{
// niets doen, acc2 blijft major
}
}
else
{
db.addMajor(acc1.getAccountnr(), winkelnaam);
}
}
else
{
db.updateAccountnrWinkel(db.getWinkel(winkelnaam), acc1.getAccountnr());
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
// acc1 was nog geen major geweest en wordt major
db.addMajor(this.getAccountnr(), winkelnaam);
}
}
else
{
}
}
public void isWolverineWorden(){
Account acc = db.getAccount(accountnr);
if(this.isVip(this.getAccountnr()))
{
if(this.isWolverine())
{
// Doe niets, is al Wolverine
}
else
{
if(db.getAantalVerschillendeWinkels(this) > 19)
{
if(db.getDatumVoorWolverine(accountnr))
{
int nieuwepunten = acc.getPunten() + 600; // Wolverine krijgt 600 punten bij.
db.updateAantalpunten(acc, nieuwepunten);
this.sendMailGoed("Wolverine", "600");
Date vandaag = new Date();
this.setStartw(vandaag);
db.updateWolverineAccountDatum(accountnr);
}
else
{
this.sendMailGoed("Wolverine", "0");
}
this.setWolverine(true);
}
else
this.setWolverine(false);
}
}
else
this.setWolverine(false);
// OPSLAAN NAAR DE DATABASE
db.updateWolverineAccount(accountnr, this.isWolverine());
}
public void isBigSpenderWorden(){
Account acc = db.getAccount(accountnr);
if(this.isVip(this.getAccountnr()))
{
if(this.isBigspender())
{
// niets doen, is al Big Spender
}
else
{
if(this.totaalGeldJaar(this.accountnr) > 5000)
{
this.setBigspender(true);
if(db.getDatumVoorBigspender(accountnr))
{
int nieuwepunten = acc.getPunten() + 500; // Bigspender krijgt 500
db.updateAantalpunten(acc, nieuwepunten);
this.sendMailGoed("Bigspender", "600");
Date vandaag = new Date();
this.setStartw(vandaag);
db.updateBigSpenderAccountDatum(accountnr);
}
else
{
this.sendMailGoed("Bigspender", "0");
}
}
else
{
this.setBigspender(false);
}
}
}
else
{
this.setBigspender(false);
}
// OPSLAAN NAAR DATABASE
db.updateBigSpenderAccount(accountnr, this.isBigspender());
}
public int totaalPuntenJaar(int accountnr){
return db.getTotaalPuntenVerkregenAccount(accountnr);
}
public double totaalGeldJaar(int accountnr){
return db.getTotaalGespendeerdeBedragAccount(this.accountnr);
}
public void sendMailGoed(String badge, String ptn){
final String username = " [email protected]";
final String password = "aeCahqu3";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(" [email protected]"));
// Zend email adres is vast.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.getEmail()));
// Ontvang email adres is variabel
message.setSubject(badge + "-badge verworven!");
message.setText("Beste " + this.getNaam() + ", \n\n"
+ "Bedankt om bij Bingo klant te zijn. \n"
+ "Proficiat, u bent " + badge + " geworden.\n\n"
+ "U krijgt " + Integer.parseInt(ptn) + " punten bij op uw account. \n"
+ "U heeft nu " + this.getPunten() + " punten."
+ "met vriendelijke groet, \n"
+ "uw Bingo-team");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}
}
public void sendMailSlecht(String badge){
final String username = " [email protected]";
final String password = "aeCahqu3";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(" [email protected]"));
// Zend email adres is vast.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.getEmail()));
// Ontvang email adres is variabel
message.setSubject(badge + "-badge verloren!");
message.setText("Beste " + this.getNaam() + ", \n\n"
+ "Bedankt om bij Bingo klant te zijn. \n"
+ "Helaas, u bent uw " + badge + "-badge kwijtgeraakt. \n\n "
+ "met vriendelijke groet, \n"
+ "uw Bingo-team");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}
}
public boolean isMajor(Winkel winkel){
return winkel.getAccount() == this.accountnr;
}
}
| dietervdm/Bingo | src/Logica/Account.java | 3,654 | // Wolverine krijgt 600 punten bij.
| line_comment | nl |
package Logica;
import Database.Database;
import java.awt.Image;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
//Deze nodig voor mail
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Account
{
private int accountnr;
private String naam; //bedrijf = bedrijfsnaam, particulier = naam klant
private String email;
private String adres;
private int punten;
private boolean wolverine;
private java.util.Date jstartw = new java.util.Date();
private java.sql.Date startw = new java.sql.Date(jstartw.getTime());
private boolean bigspender;
private java.util.Date jstartb = new java.util.Date();
private java.sql.Date startb = new java.sql.Date(jstartw.getTime());
private java.sql.Date startm = new java.sql.Date(jstartw.getTime());
private boolean bedrijf;
private String btwnummer;
private Image logo; // logo is niet geïmplementeerd.
Database db = new Database();
public Account()
{}
public Account(int accountnr, boolean wolverine, boolean bigspender, boolean bedrijf)
{
this.accountnr = accountnr;
this.wolverine = wolverine;
this.bigspender = bigspender;
this.bedrijf = bedrijf;
}
public Account(int accountnr, String naam, String email, String adres, int punten, boolean wolverine, java.sql.Date startw, boolean bigspender, java.sql.Date startb, boolean bedrijf, String btwnummer)
{
this.accountnr = accountnr;
this.naam = naam;
this.email = email;
this.adres = adres;
this.punten = punten;
this.wolverine = wolverine;
this.startw = startw;
this.bigspender = bigspender;
this.startb = startb;
this.bedrijf = bedrijf;
this.btwnummer = btwnummer;
}
public int getAccountnr()
{
return this.accountnr;
}
public void setAccountnr(int accountnr)
{
this.accountnr = accountnr;
}
public String getNaam()
{
return this.naam;
}
public void setNaam(String naam)
{
this.naam = naam;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getAdres()
{
return this.adres;
}
public void setAdres(String adres)
{
this.adres = adres;
}
public int getPunten()
{
return this.punten;
}
public void setPunten(int punten)
{
this.punten = punten;
}
public boolean isWolverine()
{
return this.wolverine;
}
public void setWolverine(boolean wolverine)
{
this.wolverine = wolverine;
}
public Date getStartw()
{
return this.startw;
}
public void setStartw(Date datum)
{
this.startw = startw;
}
public boolean isBigspender()
{
return this.bigspender;
}
public void setBigspender(boolean bigspender)
{
this.bigspender = bigspender;
}
public Date getStartb()
{
return this.startb;
}
public void setStartb(Date datum)
{
this.startb = startb;
}
public Date getStartm()
{
return this.startm;
}
public void setStartm(Date datum)
{
this.startm = startm;
}
public boolean isBedrijf()
{
return this.bedrijf;
}
public void setBedrijf(boolean bedrijf)
{
this.bedrijf = bedrijf;
}
public String getBtwnummer()
{
return this.btwnummer;
}
public void setBtwnummer(String btwnummer)
{
this.btwnummer = btwnummer;
}
// Logo niet geïmplementeerd
public Image getLogo()
{
return logo;
}
public void setLogo(Image logo)
{
this.logo = logo;
}
public void bedrijfOfParticulier(Boolean bedrijf)
{
if (bedrijf == true)
this.bedrijf = true;
else
this.bedrijf = false;
}
public boolean isVip(int accountnr){
return totaalPuntenJaar(accountnr) > 9999;
}
public void isMajorWorden(String winkelnaam){
Account acc1 = db.getAccount(this.getAccountnr());
Account acc2 = db.getAccount(db.getWinkel(winkelnaam).getAccount());
if(acc1.isVip(acc1.getAccountnr()))
{
if(db.heeftMajor(winkelnaam))
{
if(this.getAccountnr() != db.getWinkel(winkelnaam).getAccount())
{
if(acc1.totaalGeldJaar(acc1.getAccountnr()) > acc2.totaalGeldJaar(acc2.getAccountnr()))
{
Major major1 = db.getMajor(this.getAccountnr(), winkelnaam);
Major major2 = db.getMajor(db.getWinkel(winkelnaam).getAccount(), winkelnaam);
if(db.checkMajor(this.getAccountnr(), winkelnaam))
{
// acc1 wordt major
db.updateAccountnrWinkel(db.getWinkel(winkelnaam), acc1.getAccountnr());
if(db.krijgtPunten(major1))
{
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
// zet datum op vandaag
db.updateMajor(acc1, db.getWinkel(winkelnaam));
}
}
else
{
// acc1 was nog geen major geweest en wordt major
db.addMajor(this.getAccountnr(), winkelnaam);
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
}
}
else
{
// niets doen, acc2 blijft major
}
}
else
{
db.addMajor(acc1.getAccountnr(), winkelnaam);
}
}
else
{
db.updateAccountnrWinkel(db.getWinkel(winkelnaam), acc1.getAccountnr());
// geef punten
int nieuwepunten = acc1.getPunten() + 100; // Major krijgt 100 punten bij.
db.updateAantalpunten(acc1, nieuwepunten);
// acc1 was nog geen major geweest en wordt major
db.addMajor(this.getAccountnr(), winkelnaam);
}
}
else
{
}
}
public void isWolverineWorden(){
Account acc = db.getAccount(accountnr);
if(this.isVip(this.getAccountnr()))
{
if(this.isWolverine())
{
// Doe niets, is al Wolverine
}
else
{
if(db.getAantalVerschillendeWinkels(this) > 19)
{
if(db.getDatumVoorWolverine(accountnr))
{
int nieuwepunten = acc.getPunten() + 600; // Wolverine krijgt<SUF>
db.updateAantalpunten(acc, nieuwepunten);
this.sendMailGoed("Wolverine", "600");
Date vandaag = new Date();
this.setStartw(vandaag);
db.updateWolverineAccountDatum(accountnr);
}
else
{
this.sendMailGoed("Wolverine", "0");
}
this.setWolverine(true);
}
else
this.setWolverine(false);
}
}
else
this.setWolverine(false);
// OPSLAAN NAAR DE DATABASE
db.updateWolverineAccount(accountnr, this.isWolverine());
}
public void isBigSpenderWorden(){
Account acc = db.getAccount(accountnr);
if(this.isVip(this.getAccountnr()))
{
if(this.isBigspender())
{
// niets doen, is al Big Spender
}
else
{
if(this.totaalGeldJaar(this.accountnr) > 5000)
{
this.setBigspender(true);
if(db.getDatumVoorBigspender(accountnr))
{
int nieuwepunten = acc.getPunten() + 500; // Bigspender krijgt 500
db.updateAantalpunten(acc, nieuwepunten);
this.sendMailGoed("Bigspender", "600");
Date vandaag = new Date();
this.setStartw(vandaag);
db.updateBigSpenderAccountDatum(accountnr);
}
else
{
this.sendMailGoed("Bigspender", "0");
}
}
else
{
this.setBigspender(false);
}
}
}
else
{
this.setBigspender(false);
}
// OPSLAAN NAAR DATABASE
db.updateBigSpenderAccount(accountnr, this.isBigspender());
}
public int totaalPuntenJaar(int accountnr){
return db.getTotaalPuntenVerkregenAccount(accountnr);
}
public double totaalGeldJaar(int accountnr){
return db.getTotaalGespendeerdeBedragAccount(this.accountnr);
}
public void sendMailGoed(String badge, String ptn){
final String username = " [email protected]";
final String password = "aeCahqu3";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(" [email protected]"));
// Zend email adres is vast.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.getEmail()));
// Ontvang email adres is variabel
message.setSubject(badge + "-badge verworven!");
message.setText("Beste " + this.getNaam() + ", \n\n"
+ "Bedankt om bij Bingo klant te zijn. \n"
+ "Proficiat, u bent " + badge + " geworden.\n\n"
+ "U krijgt " + Integer.parseInt(ptn) + " punten bij op uw account. \n"
+ "U heeft nu " + this.getPunten() + " punten."
+ "met vriendelijke groet, \n"
+ "uw Bingo-team");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}
}
public void sendMailSlecht(String badge){
final String username = " [email protected]";
final String password = "aeCahqu3";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(" [email protected]"));
// Zend email adres is vast.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.getEmail()));
// Ontvang email adres is variabel
message.setSubject(badge + "-badge verloren!");
message.setText("Beste " + this.getNaam() + ", \n\n"
+ "Bedankt om bij Bingo klant te zijn. \n"
+ "Helaas, u bent uw " + badge + "-badge kwijtgeraakt. \n\n "
+ "met vriendelijke groet, \n"
+ "uw Bingo-team");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
throw new RuntimeException(e);
}
}
public boolean isMajor(Winkel winkel){
return winkel.getAccount() == this.accountnr;
}
}
|
17853_11 | package Controllers;
import Model.Model;
import View.View;
import java.beans.PropertyChangeSupport;
public class Controller {
// properties
private Model model;
public String s0, s1, s2;
PropertyChangeSupport pcs;
// Constructor method.
public Controller() {
// New PropertyChangeSupport object maken van de postbode.
pcs = new PropertyChangeSupport(this);
// Maak string leeg.
s0 = s1 = s2 = "";
// New model object.
model = new Model();
}
// Methode krijgt argument uit View binnen.
public void addClickText(String text) {
// Kijken of waarde uit text een cijfer is.
if (text.charAt(0) >= '0' && text.charAt(0) <= '9' || text.charAt(0) == '.') {
if (!s1.equals("")) {
s2 = s2 + text;
} else {
s0 = s0 + text;
}
// Updaten View.
setResult(s0 + s1 + s2);
} else if (text.charAt(0) == 'C') { // Als text C is maak String leeg.
s0 = s1 = s2 = "";
// update view.
setResult(s0 + s1 + s2);
} else if (text.charAt(0) == '=') { // Als text = bereken String
// Checken welk operator er is String s1 zit.
double te;
model.calculate(s0, s2, s1);
te = model.getCalculationValue();
// Updaten som View.
setResult(s0 + s1 + s2);
setTotaal(te);
// Bewaren van waarde.
s0 = Double.toString(te);
// Legen van String zodat je nieuwe som kan maken.
s1 = s2 = "";
} else {
// Als er geen operator was.
if (s1.equals("") || s2.equals(""))
s1 = text;
else {
double te;
// Bewaarde de eerste waarde.
model.calculate(s0, s2, s1);
te = model.getCalculationValue();
// Double naar string conversie.
s0 = Double.toString(te);
s1 = text;
s2 = "";
}
setResult(s0 + s1 + s2);
}
}
// Opsturen van de post.
private void setTotaal(double te) {
// Stuur post door naar elk persoon dat abonnement heeft met naam totaal
// geef een null waarde mee en de nieuwe waardes.
pcs.firePropertyChange("totaal", 0, Double.toString(te));
}
// Zelfde methode andere post.
private void setResult(String s) {
// Iedereen met brievenbus result krijg nieuwe waarde.
pcs.firePropertyChange("result", "", s);
}
// Aangeven dat de VIEW een abonnement heeft op deze PropertyChangeListener.
public void addPropertyChangeListener(View view) {
// Toevoegen view object aan PropertyChangeListener.
pcs.addPropertyChangeListener(view);
}
}
| TomasR16/CalculatorMVC | src/Controllers/Controller.java | 776 | // Als er geen operator was. | line_comment | nl | package Controllers;
import Model.Model;
import View.View;
import java.beans.PropertyChangeSupport;
public class Controller {
// properties
private Model model;
public String s0, s1, s2;
PropertyChangeSupport pcs;
// Constructor method.
public Controller() {
// New PropertyChangeSupport object maken van de postbode.
pcs = new PropertyChangeSupport(this);
// Maak string leeg.
s0 = s1 = s2 = "";
// New model object.
model = new Model();
}
// Methode krijgt argument uit View binnen.
public void addClickText(String text) {
// Kijken of waarde uit text een cijfer is.
if (text.charAt(0) >= '0' && text.charAt(0) <= '9' || text.charAt(0) == '.') {
if (!s1.equals("")) {
s2 = s2 + text;
} else {
s0 = s0 + text;
}
// Updaten View.
setResult(s0 + s1 + s2);
} else if (text.charAt(0) == 'C') { // Als text C is maak String leeg.
s0 = s1 = s2 = "";
// update view.
setResult(s0 + s1 + s2);
} else if (text.charAt(0) == '=') { // Als text = bereken String
// Checken welk operator er is String s1 zit.
double te;
model.calculate(s0, s2, s1);
te = model.getCalculationValue();
// Updaten som View.
setResult(s0 + s1 + s2);
setTotaal(te);
// Bewaren van waarde.
s0 = Double.toString(te);
// Legen van String zodat je nieuwe som kan maken.
s1 = s2 = "";
} else {
// Als er<SUF>
if (s1.equals("") || s2.equals(""))
s1 = text;
else {
double te;
// Bewaarde de eerste waarde.
model.calculate(s0, s2, s1);
te = model.getCalculationValue();
// Double naar string conversie.
s0 = Double.toString(te);
s1 = text;
s2 = "";
}
setResult(s0 + s1 + s2);
}
}
// Opsturen van de post.
private void setTotaal(double te) {
// Stuur post door naar elk persoon dat abonnement heeft met naam totaal
// geef een null waarde mee en de nieuwe waardes.
pcs.firePropertyChange("totaal", 0, Double.toString(te));
}
// Zelfde methode andere post.
private void setResult(String s) {
// Iedereen met brievenbus result krijg nieuwe waarde.
pcs.firePropertyChange("result", "", s);
}
// Aangeven dat de VIEW een abonnement heeft op deze PropertyChangeListener.
public void addPropertyChangeListener(View view) {
// Toevoegen view object aan PropertyChangeListener.
pcs.addPropertyChangeListener(view);
}
}
|
17483_3 | package mytset;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class MyMathTest {
/**
* Returns the square root (rounded down) of the given nonnegative number.
*
* @pre The given number must be nonnegative.
* | 0 <= x
* @post The result is the greatest nonnegative integer whose square is not greater than the given number.
* | 0 <= result &&
* | result * result <= x &&
* | x < (result + 1) * (result + 1)
*/
int sqrt(int x) {
int result = 0;
while ((result + 1) * (result + 1) <= x)
result++;
return result;
}
/**
* Geeft het grootste van de drie gegeven getallen terug.
*
* @post Het resultaat is groeter dan of gelijk aan de gegeven getallen.
* | result >= x && result >= y && result >= z
* @post Het resultaat is gelijk aan één van de gegeven getallen.
* | result == x || result == y || result == z
*/
int max3(int x, int y, int z) {
return x > y ? x > z ? x : z : y > z ? y : z;
}
/**
* Geeft de mediaan van de drie verschillende gegeven getallen terug.
* TODO: Schrijf volledige formele documentatie.
*/
int mediaan(int x, int y, int z) {
return 0; // TODO: Implementeer.
}
/**
* Geeft het aantal voorkomens van 'waarde' in 'getallen' terug.
* @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing.
* | getallen != null
* @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt.
* | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count()
*/
int tel(int[] getallen, int waarde) {
int result = 0;
for (int i = 0; i < getallen.length; i++)
if (getallen[i] == waarde)
result++;
return result;
}
/**
* Verhoogt het element op index `index` in array `array` met `bedrag`.
*
* @pre Het argument `array` wijst naar een array.
* | array != null
* @pre De gegeven index is een geldige index voor `array`.
* | 0 <= index && index < array.length
* @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag.
* | array[index] == old(array[index]) + bedrag
*/
void verhoogElement(int[] array, int index, int bedrag) {
array[index] += bedrag;
}
/**
* Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar.
* TODO: Schrijf volledige informele en formele documentatie.
*/
void verwissel(int[] getallen, int index1, int index2) {
// TODO: Implementeer
}
/**
* Vervangt elk getal in de gegeven array door zijn negatie.
* @pre Het argument `getallen` wijst naar een array.
* | getallen != null
* @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie.
* | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i])
*/
// voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet.
void negatie(int[] getallen) {
for (int i = 0; i < getallen.length; i++)
getallen[i] = -getallen[i];
}
/**
* Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`.
*
* @pre | haystack != null
* @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.)
* | !(haystack.length > 0 && haystack[0] == needle) || result == 0
* @post Als het resultaat -1 is, dan ...
* | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle)
* @post Als het resultaat niet -1 is, dan ...
* | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE
*/
int find(int[] haystack, int needle) {
return 0; // TODO: Implementeer
}
/**
* Sorteert de getallen in de gegeven array van klein naar groot.
* @post VUL AAN
* | true // VUL AAN
*/
void sort(int[] values) {
// TODO: Implementeer
}
@Test
void testSqrt() {
assertEquals(3, sqrt(9));
assertEquals(0, sqrt(0));
assertEquals(3, sqrt(15));
assertEquals(4, sqrt(16));
}
@Test
void testMax3() {
assertEquals(30, max3(10, 20, 30));
assertEquals(30, max3(20, 10, 30));
assertEquals(30, max3(10, 30, 20));
assertEquals(30, max3(20, 30, 10));
assertEquals(30, max3(30, 10, 20));
assertEquals(30, max3(30, 20, 10));
}
// TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort.
@Test
void testTel() {
assertEquals(0, tel(new int[] {10, 20, 30}, 15));
assertEquals(1, tel(new int[] {10, 20, 30}, 20));
assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20));
assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10));
}
@Test
void testVerhoogElement() {
int[] mijnArray = {10, 20, 30};
verhoogElement(mijnArray, 1, 5);
assertArrayEquals(new int[] {10, 25, 30}, mijnArray);
}
@Test
void testNegatie() {
int[] mijnArray = {10, -20, 30};
negatie(mijnArray);
assertArrayEquals(new int[] {-10, 20, -30}, mijnArray);
}
}
| milankkk/mytset-2024 | mytset/src/mytset/file2.java | 1,884 | /**
* Geeft het aantal voorkomens van 'waarde' in 'getallen' terug.
* @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing.
* | getallen != null
* @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt.
* | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count()
*/ | block_comment | nl | package mytset;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class MyMathTest {
/**
* Returns the square root (rounded down) of the given nonnegative number.
*
* @pre The given number must be nonnegative.
* | 0 <= x
* @post The result is the greatest nonnegative integer whose square is not greater than the given number.
* | 0 <= result &&
* | result * result <= x &&
* | x < (result + 1) * (result + 1)
*/
int sqrt(int x) {
int result = 0;
while ((result + 1) * (result + 1) <= x)
result++;
return result;
}
/**
* Geeft het grootste van de drie gegeven getallen terug.
*
* @post Het resultaat is groeter dan of gelijk aan de gegeven getallen.
* | result >= x && result >= y && result >= z
* @post Het resultaat is gelijk aan één van de gegeven getallen.
* | result == x || result == y || result == z
*/
int max3(int x, int y, int z) {
return x > y ? x > z ? x : z : y > z ? y : z;
}
/**
* Geeft de mediaan van de drie verschillende gegeven getallen terug.
* TODO: Schrijf volledige formele documentatie.
*/
int mediaan(int x, int y, int z) {
return 0; // TODO: Implementeer.
}
/**
* Geeft het aantal<SUF>*/
int tel(int[] getallen, int waarde) {
int result = 0;
for (int i = 0; i < getallen.length; i++)
if (getallen[i] == waarde)
result++;
return result;
}
/**
* Verhoogt het element op index `index` in array `array` met `bedrag`.
*
* @pre Het argument `array` wijst naar een array.
* | array != null
* @pre De gegeven index is een geldige index voor `array`.
* | 0 <= index && index < array.length
* @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag.
* | array[index] == old(array[index]) + bedrag
*/
void verhoogElement(int[] array, int index, int bedrag) {
array[index] += bedrag;
}
/**
* Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar.
* TODO: Schrijf volledige informele en formele documentatie.
*/
void verwissel(int[] getallen, int index1, int index2) {
// TODO: Implementeer
}
/**
* Vervangt elk getal in de gegeven array door zijn negatie.
* @pre Het argument `getallen` wijst naar een array.
* | getallen != null
* @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie.
* | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i])
*/
// voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet.
void negatie(int[] getallen) {
for (int i = 0; i < getallen.length; i++)
getallen[i] = -getallen[i];
}
/**
* Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`.
*
* @pre | haystack != null
* @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.)
* | !(haystack.length > 0 && haystack[0] == needle) || result == 0
* @post Als het resultaat -1 is, dan ...
* | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle)
* @post Als het resultaat niet -1 is, dan ...
* | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE
*/
int find(int[] haystack, int needle) {
return 0; // TODO: Implementeer
}
/**
* Sorteert de getallen in de gegeven array van klein naar groot.
* @post VUL AAN
* | true // VUL AAN
*/
void sort(int[] values) {
// TODO: Implementeer
}
@Test
void testSqrt() {
assertEquals(3, sqrt(9));
assertEquals(0, sqrt(0));
assertEquals(3, sqrt(15));
assertEquals(4, sqrt(16));
}
@Test
void testMax3() {
assertEquals(30, max3(10, 20, 30));
assertEquals(30, max3(20, 10, 30));
assertEquals(30, max3(10, 30, 20));
assertEquals(30, max3(20, 30, 10));
assertEquals(30, max3(30, 10, 20));
assertEquals(30, max3(30, 20, 10));
}
// TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort.
@Test
void testTel() {
assertEquals(0, tel(new int[] {10, 20, 30}, 15));
assertEquals(1, tel(new int[] {10, 20, 30}, 20));
assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20));
assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10));
}
@Test
void testVerhoogElement() {
int[] mijnArray = {10, 20, 30};
verhoogElement(mijnArray, 1, 5);
assertArrayEquals(new int[] {10, 25, 30}, mijnArray);
}
@Test
void testNegatie() {
int[] mijnArray = {10, -20, 30};
negatie(mijnArray);
assertArrayEquals(new int[] {-10, 20, -30}, mijnArray);
}
}
|
69651_6 | package isy.team4.projectisy.controller;
import isy.team4.projectisy.MainApplication;
import isy.team4.projectisy.util.EGame;
import isy.team4.projectisy.util.EPlayer;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import javafx.scene.Node;
public class HomeController extends Controller {
private static String selectedGame;
private static boolean is_cpu;
private static boolean isLocal = true;
private static EPlayer player1;
private static EPlayer player2;
public void navigateOnline(ActionEvent actionEvent) throws IOException {
isLocal = false;
// this.playerMenuText.setText("Kies je speler"); // TODO: temp, see initGame
navigate(actionEvent, "online-menu-view.fxml");
}
public void navigateOffline(ActionEvent actionEvent) throws IOException {
isLocal = true;
// this.playerMenuText.setText("Kies je tegenstander"); // TODO: temp, see initGame
navigate(actionEvent, "offline-menu-view.fxml");
}
public void navigateHome(ActionEvent actionEvent) throws IOException {
navigate(actionEvent, "main-menu-view.fxml");
}
public void navigateOptions(ActionEvent actionEvent) throws IOException {
navigate(actionEvent, "main-menu-view.fxml");
}
public void setTicTacToe(ActionEvent actionEvent) throws IOException {
selectedGame = "tic-tac-toe";
navigate(actionEvent, "player-menu-view.fxml");
System.out.println(this);
}
public void setOthello(ActionEvent actionEvent) throws IOException {
selectedGame = "othello";
navigate(actionEvent, "player-menu-view.fxml");
System.out.println(this);
}
// TODO: Remove, will be replaced by a list of choices, see initGame
public void setComputer(ActionEvent actionEvent) throws IOException {
is_cpu = true;
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
initGame(stage);
}
// TODO: Remove, will be replaced by a list of choices, see initGame
public void setPlayer(ActionEvent actionEvent) throws IOException {
is_cpu = false;
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
initGame(stage);
}
public void initGame(Stage stage) {
HashMap<String, String> gameViewMapper = new HashMap<String, String>();
gameViewMapper.put("tic-tac-toe", "tictactoe-view.fxml");
gameViewMapper.put("othello", "othello-view.fxml");
// TODO: Pas aan zodat selectie op frontend zo werkt:
// Als eerst selectie local of remote -> daarna:
// als local: selectie voor zowel player1 als player2 (keuze uit: LOCAL, AI)
// als remote: selectie voor 1 player (keuze uit: LOCAL, AI).
// Wanneer dit gedaan is krijg je iets zoals dit:
//
// EPlayer[] players = new EPlayer[]{player1};
// if (isLocal) {
// players = Arrays.copyOf(players, players.length + 1); // Could refactor to ArrayList?
// players[1] = player2;
// }
// navigateOut(
// stage,
// gameViewMapper.get(selectedGame),
// isLocal ? EGame.LOCAL : EGame.REMOTE,
// players
// );
// Hierbij is het makkelijk om een extra speler te implementeren in de "eventuele" toekomst
if (isLocal) {
this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.LOCAL,
new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL}
);
} else {
this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.REMOTE,
new EPlayer[]{is_cpu ? EPlayer.AI : EPlayer.LOCAL}
);
}
// navigateOut(
// stage,
// gameViewMapper.get(selectedGame),
// this.isLocal ? EGame.LOCAL : EGame.REMOTE,
// new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL}
// );
}
@FXML
public void navigate(ActionEvent actionEvent, String File) throws IOException {
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
Parent root = FXMLLoader.load(MainApplication.class.getResource(File));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
@FXML
public void navigateOut(Stage stage, String view, EGame gameType, EPlayer[] players) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource(view)); // TODO: relative instead
// of absolute gathering of
// resources
Parent root = fxmlLoader.load();
GameController controller = fxmlLoader.getController();
controller.initGame(gameType, players);
Scene scene = new Scene(root);
scene.getStylesheets()
.add(Objects.requireNonNull(MainApplication.class.getResource("style.css")).toExternalForm()); // main
// stylesheet
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| DowneyX/project-ISY | src/main/java/isy/team4/projectisy/controller/HomeController.java | 1,437 | // als local: selectie voor zowel player1 als player2 (keuze uit: LOCAL, AI) | line_comment | nl | package isy.team4.projectisy.controller;
import isy.team4.projectisy.MainApplication;
import isy.team4.projectisy.util.EGame;
import isy.team4.projectisy.util.EPlayer;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import javafx.scene.Node;
public class HomeController extends Controller {
private static String selectedGame;
private static boolean is_cpu;
private static boolean isLocal = true;
private static EPlayer player1;
private static EPlayer player2;
public void navigateOnline(ActionEvent actionEvent) throws IOException {
isLocal = false;
// this.playerMenuText.setText("Kies je speler"); // TODO: temp, see initGame
navigate(actionEvent, "online-menu-view.fxml");
}
public void navigateOffline(ActionEvent actionEvent) throws IOException {
isLocal = true;
// this.playerMenuText.setText("Kies je tegenstander"); // TODO: temp, see initGame
navigate(actionEvent, "offline-menu-view.fxml");
}
public void navigateHome(ActionEvent actionEvent) throws IOException {
navigate(actionEvent, "main-menu-view.fxml");
}
public void navigateOptions(ActionEvent actionEvent) throws IOException {
navigate(actionEvent, "main-menu-view.fxml");
}
public void setTicTacToe(ActionEvent actionEvent) throws IOException {
selectedGame = "tic-tac-toe";
navigate(actionEvent, "player-menu-view.fxml");
System.out.println(this);
}
public void setOthello(ActionEvent actionEvent) throws IOException {
selectedGame = "othello";
navigate(actionEvent, "player-menu-view.fxml");
System.out.println(this);
}
// TODO: Remove, will be replaced by a list of choices, see initGame
public void setComputer(ActionEvent actionEvent) throws IOException {
is_cpu = true;
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
initGame(stage);
}
// TODO: Remove, will be replaced by a list of choices, see initGame
public void setPlayer(ActionEvent actionEvent) throws IOException {
is_cpu = false;
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
initGame(stage);
}
public void initGame(Stage stage) {
HashMap<String, String> gameViewMapper = new HashMap<String, String>();
gameViewMapper.put("tic-tac-toe", "tictactoe-view.fxml");
gameViewMapper.put("othello", "othello-view.fxml");
// TODO: Pas aan zodat selectie op frontend zo werkt:
// Als eerst selectie local of remote -> daarna:
// als local:<SUF>
// als remote: selectie voor 1 player (keuze uit: LOCAL, AI).
// Wanneer dit gedaan is krijg je iets zoals dit:
//
// EPlayer[] players = new EPlayer[]{player1};
// if (isLocal) {
// players = Arrays.copyOf(players, players.length + 1); // Could refactor to ArrayList?
// players[1] = player2;
// }
// navigateOut(
// stage,
// gameViewMapper.get(selectedGame),
// isLocal ? EGame.LOCAL : EGame.REMOTE,
// players
// );
// Hierbij is het makkelijk om een extra speler te implementeren in de "eventuele" toekomst
if (isLocal) {
this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.LOCAL,
new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL}
);
} else {
this.navigateOut(stage, gameViewMapper.get(selectedGame), EGame.REMOTE,
new EPlayer[]{is_cpu ? EPlayer.AI : EPlayer.LOCAL}
);
}
// navigateOut(
// stage,
// gameViewMapper.get(selectedGame),
// this.isLocal ? EGame.LOCAL : EGame.REMOTE,
// new EPlayer[]{EPlayer.LOCAL, is_cpu ? EPlayer.AI : EPlayer.LOCAL}
// );
}
@FXML
public void navigate(ActionEvent actionEvent, String File) throws IOException {
Stage stage = (Stage) ((Node) actionEvent.getSource()).getScene().getWindow();
Parent root = FXMLLoader.load(MainApplication.class.getResource(File));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
@FXML
public void navigateOut(Stage stage, String view, EGame gameType, EPlayer[] players) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource(view)); // TODO: relative instead
// of absolute gathering of
// resources
Parent root = fxmlLoader.load();
GameController controller = fxmlLoader.getController();
controller.initGame(gameType, players);
Scene scene = new Scene(root);
scene.getStylesheets()
.add(Objects.requireNonNull(MainApplication.class.getResource("style.css")).toExternalForm()); // main
// stylesheet
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
25229_4 | package nl.detoren.ijsco.ui.control;
/**
* Copyright (C) 2018 Lars Dam
* 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 version 3.0
* 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.
* See: http://www.gnu.org/licenses/gpl-3.0.html
*
* Problemen in deze code:
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.detoren.ijsco.data.Groep;
import nl.detoren.ijsco.data.Groepen;
import nl.detoren.ijsco.data.GroepsUitslag;
import nl.detoren.ijsco.data.GroepsUitslagen;
import nl.detoren.ijsco.data.Speler;
import nl.detoren.ijsco.data.UitslagSpeler;
import nl.detoren.ijsco.data.Wedstrijd;
import nl.detoren.ijsco.data.WedstrijdUitslag;
/**
*
* Verwerk uitslagen in een nieuwe stand
*
*/
public class Uitslagverwerker {
private final static Logger logger = Logger.getLogger(IJSCOController.class.getName());
/**
* Verwerk de wedstrijduitslagen en maak groepsuitslag
*
* @param spelersgroepen
* De spelersgroepen
* @param wedstrijden
* De gespeelde wedstrijden
* @return Bijgewerkte standen
*/
public GroepsUitslagen verwerkUitslag(Groepen groepen) {
GroepsUitslagen groepsuitslagen = new GroepsUitslagen();
for (Groep groep : groepen) {
logger.log(Level.INFO, "Verwerk uitslag voor groep " + groep.getNaam());
GroepsUitslag uitslag = new GroepsUitslag();
uitslag.setGroepsnaam(groep.getNaam());
for (Speler speler : groep.getSpelers()) {
logger.log(Level.INFO, "Verwerk uitslag voor speler " + speler.getNaam());
if (speler.getNaamHandmatig() != null) {
if (!speler.getNaamHandmatig().equals("Bye")) {
UitslagSpeler update = updateSpeler(speler, groep);
uitslag.addSpeler(update);
uitslag.setAantal(uitslag.getAantal() - 1);
}
} else {
UitslagSpeler update = updateSpeler(speler, groep);
uitslag.addSpeler(update);
}
}
groepsuitslagen.Add(uitslag);
}
return groepsuitslagen;
}
/**
* Return een bijgewerkte versie van een speler. Bijgewerkt zijn aantal
* punten en zijn rating
*
* @param speler
* Speler om bij te werken
* @param wedstrijden
* Alle wedstrijden
* @return Bijgewerkte speler
*/
private UitslagSpeler updateSpeler(Speler speler, Groep groep) {
ArrayList<Wedstrijd> spelerWedstrijden = getWedstrijdenVoorSpeler(speler, groep);
UitslagSpeler updateSpeler = new UitslagSpeler(speler);
int aantalgewonnen = 0;
int aantalremise = 0;
int puntenbij = 0; // puntenbij is 10 * bordpunten ivm halve punten
int ratingbij = 0;
for (Wedstrijd w : spelerWedstrijden) {
//logger.log(Level.INFO, " Wedstrijd :" + w.toString());
int resultaat = -1; // onbekend
Speler tegenstander = w.getWit().gelijkAan(speler) ? w.getZwart() : w.getWit();
Boolean spelerIswit = w.getWit().gelijkAan(speler) ? true : false;
//
// w.getUitslag 1=wit wint 2=zwart wint 3=remise
int uitslagWit = w.getUitslag(); // uitslag vanuit perspectief wit
int uitslagZwart = (w.getUitslag() == 1) ? 2 : ((w.getUitslag() == 2) ? 1 : 3);
int deltaWit;
int deltaZwart;
// PUNTEN
if (uitslagWit == Wedstrijd.UNKNOWN) {
// doe niets
} else if (uitslagWit == Wedstrijd.DRAW) {
puntenbij += 5;
ratingbij +=
aantalremise++;
resultaat = 3;
//logger.log(Level.INFO, " Remise : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.WHITE_WINS) && (w.getWit().gelijkAan(speler))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met wit : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.BLACK_WINS) && (w.getZwart().gelijkAan(speler))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met zwart :" + puntenbij);
} else {
// verlies
resultaat = 2;
//logger.log(Level.INFO, " Verlies :" + puntenbij);
}
if (w.isNietReglementair()) {
Speler wit = w.getWit();
Speler zwart = w.getZwart();
int ratingWit = wit.getRating();
int ratingZwart = zwart.getRating();
//logger.log(Level.INFO, "Startrating wit " + wit.getRating());
//logger.log(Level.INFO, "Startrating zwart " + zwart.getRating());
deltaWit = deltaRatingOSBO(Math.max(ratingWit, 100), Math.max(ratingZwart, 100), uitslagWit);
deltaZwart = deltaRatingOSBO(Math.max(ratingZwart,100), Math.max(ratingWit, 100), uitslagZwart);
ratingbij += spelerIswit ? deltaWit : deltaZwart;
//wit.setRating(Math.max(nieuwWit, 100));
//zwart.setRating(Math.max(nieuwZwart, 100));
//logger.log(Level.INFO, w.toString());
//logger.log(Level.INFO, "Wit: " + wit.getNaam() + " van " + ratingWit + " +/- " + deltaWit + " naar " + (ratingWit + deltaWit));
//logger.log(Level.INFO, "Zwart: " + zwart.getNaam() + " van " + ratingZwart + " +/- " + deltaZwart + " naar " + (ratingZwart +deltaZwart));
} else {
logger.log(Level.INFO, w.toString());
logger.log(Level.INFO, "Niet reglementair, geen aanpassing rating");
}
}
// check is rating will not drop below 100
logger.log(Level.INFO, "new rating would be : " + updateSpeler.getStartrating() + ratingbij);
logger.log(Level.INFO, "100 - newrating : " + (100 - (updateSpeler.getStartrating() + ratingbij)));
logger.log(Level.INFO, "max(100 - newrating, 0) : " + Math.max(0, (100 - (updateSpeler.getStartrating() + ratingbij))));
logger.log(Level.INFO, "ratingbij + max(100 - newrating, 0) : " + (ratingbij + Math.max(0, (100 - (updateSpeler.getStartrating() + ratingbij)))));
ratingbij = ratingbij + (Math.max(100 - (updateSpeler.getStartrating() + ratingbij),0));
//logger.log(Level.INFO, "Punten :" + puntenbij/10);
logger.log(Level.INFO, "DeltaRating :" + ratingbij);
logger.log(Level.INFO, "Rating van " + updateSpeler.getStartrating() + " +/- " + ratingbij + " naar " + (updateSpeler.getStartrating() + ratingbij));
String bijofaf = ratingbij>0 ? "+" : "-";
int startrating = updateSpeler.getStartrating();
logger.log(Level.INFO, updateSpeler.getNaam() + "|" + puntenbij/10 + "|" + startrating + bijofaf + Math.abs(ratingbij) + " naar " + Math.max(100, (startrating + ratingbij)));
//
updateSpeler.setStartrating(speler.getRating());
updateSpeler.setPunten(puntenbij);
updateSpeler.setDeltarating(ratingbij);
return updateSpeler;
}
/**
* Geef voor een specifieke speler alle wedstrijden die hij gespeeld heeft
*
* @param speler
* De speler
* @param wedstrijden
* Alle wedstrijden van een speelavond
* @return wedstrijden gespeeld door speler
*/
private ArrayList<Wedstrijd> getWedstrijdenVoorSpeler(Speler speler, Groep groep) {
logger.log(Level.INFO, "Vind wedstrijden voor speler :" + speler.toString());
ArrayList<Wedstrijd> result = new ArrayList<>();
for (Wedstrijd w : groep.getWedstrijden()) {
if (w !=null) {
if (w.getWit().gelijkAan(speler) || w.getZwart().gelijkAan(speler)) {
result.add(w);
}
}
}
logger.log(Level.INFO, "" + result.size() + " wedstrijden gevonden voor " + speler.toString());
return result;
}
/**
* Geef voor een specifieke speler alle wedstrijden die hij gespeeld heeft
*
* @param speler
* De speler
* @param wedstrijden
* Alle wedstrijden van een speelavond
* @return wedstrijden gespeeld door speler
*/
private List<WedstrijdUitslag> getWedstrijdenVoorSpeler(UitslagSpeler speler, GroepsUitslag groep) {
logger.log(Level.INFO, "Vind wedstrijden voor speler :" + speler.toString());
Iterator<WedstrijdUitslag> iter = groep.getWedstrijden().iterator();
List<WedstrijdUitslag> result = new ArrayList<>();
while (iter.hasNext()) {
//for (WedstrijdUitslag w : result) {
WedstrijdUitslag w = iter.next();
if (w !=null) {
if (w.getWit().gelijkAan(speler) || w.getZwart().gelijkAan(speler)) {
result.add(w);
}
}
}
logger.log(Level.INFO, "" + result.size() + " wedstrijden gevonden voor " + speler.toString());
return result;
}
/**
* Bereken delta rating conform de regels van de OSBO en zoals gebruikt bij
* de interne competitie
*
* @param beginRating
* @param tegenstanderRating
* @param uitslag
* 1 = winst, 2 = verlies, 3 = remise
* @return
*/
public int deltaRatingOSBO(int beginRating, int tegenstanderRating, int uitslag) {
int[] ratingTabel = { 0, 16, 31, 51, 71, 91, 116, 141, 166, 201, 236, 281, 371, 9999 };
int ratingVerschil = Math.abs(beginRating - tegenstanderRating);
boolean ratingHogerDanTegenstander = beginRating > tegenstanderRating;
int index = 0;
while (ratingVerschil >= ratingTabel[index]) {
index++;
}
index--; // iterator goes one to far.
if (index == -1)
index = 0;
// Update rating wit
// Dit gebeurd aan de hand van de volgende OSBO tabel
// Hierin is: W> = winnaar heeft de hoogste rating
// W< = winnaar heeft de laagste rating
// V> = verliezer heeft de hoogste rating
// V< = verliezer heeft de laagste rating
// R> = remise met de hoogste rating
// R< = remise met de laagste rating
//
// In de volgende tabel wordt de aanpassing van de rating weergegeven
// rating
// verschil W> V< W< V> R> R<
// 0- 15 +12 -12 +12 -12 0 0
// 16- 30 +11 -11 +13 -13 - 1 + 1
// 31- 50 +10 -10 +14 -14 - 2 + 2
// 51- 70 + 9 - 9 +15 -15 - 3 + 3
// 71- 90 + 8 - 8 +16 -16 - 4 + 4
// 91-115 + 7 - 7 +17 -17 - 5 + 5
// 116-140 + 6 - 6 +18 -18 - 6 + 6
// 141-165 + 5 - 5 +19 -19 - 7 + 7
// 166-200 + 4 - 4 +20 -20 - 8 + 8
// 201-235 + 3 - 3 +21 -21 - 9 + 9
// 236-280 + 2 - 2 +22 -22 -10 +10
// 281-370 + 1 - 1 +23 -23 -11 +11
// >371 + 0 - 0 +24 -24 -12 +12
int deltaRating;
switch (uitslag) {
case 1: // Winst
deltaRating = 12 + (ratingHogerDanTegenstander ? (-1 * index) : (+1 * index));
return deltaRating;
case 2: // Verlies
deltaRating = 12 + (ratingHogerDanTegenstander ? (+1 * index) : (-1 * index));
return -deltaRating;
case 3: // Remise
deltaRating = (ratingHogerDanTegenstander ? (-1 * index) : (+1 * index));
return deltaRating;
default: // Geen uitstal
logger.log(Level.SEVERE , "Rating update: Uitslag is geen winst, geen verlies en geen remise.");
return 0;
}
}
public GroepsUitslagen verwerkUitslag(GroepsUitslagen groepenuitslagen) {
for (GroepsUitslag groep : groepenuitslagen) {
logger.log(Level.INFO, "Verwerk uitslag voor groep " + groep.getGroepsnaam());
for (Map.Entry<Integer, UitslagSpeler> m : groep.getSpelers().entrySet()) {
UitslagSpeler u = m.getValue();
if (u.getNaam() != null) {
logger.log(Level.INFO, "Verwerk uitslag voor speler " + u.getNaam());
if (!u.getNaam().equals("Bye")) {
u = updateSpeler(u, groep);
//uitslag.addSpeler(update);
//uitslag.setAantal(uitslag.getAantal() - 1);
}
} else {
//UitslagSpeler update = updateSpeler(speler, groep);
//uitslag.addSpeler(update);
}
}
//groepsuitslagen.Add(uitslag);
}
return groepenuitslagen;
}
private UitslagSpeler updateSpeler(UitslagSpeler u, GroepsUitslag groep) {
List<WedstrijdUitslag> spelerWedstrijden = getWedstrijdenVoorSpeler(u, groep);
//UitslagSpeler updateSpeler = new UitslagSpeler(speler);
int aantalgewonnen = 0;
int aantalremise = 0;
int puntenbij = 0; // puntenbij is 10 * bordpunten ivm halve punten
int ratingbij = 0;
for (WedstrijdUitslag w : spelerWedstrijden) {
//logger.log(Level.INFO, " Wedstrijd :" + w.toString());
int resultaat = -1; // onbekend
UitslagSpeler tegenstander = w.getWit().gelijkAan(u) ? w.getZwart() : w.getWit();
Boolean spelerIswit = w.getWit().gelijkAan(u) ? true : false;
//
// w.getUitslag 1=wit wint 2=zwart wint 3=remise
int uitslagWit = w.getUitslag(); // uitslag vanuit perspectief wit
int uitslagZwart = (w.getUitslag() == 1) ? 2 : ((w.getUitslag() == 2) ? 1 : 3);
int deltaWit;
int deltaZwart;
// PUNTEN
if (uitslagWit == Wedstrijd.UNKNOWN) {
// doe niets
} else if (uitslagWit == Wedstrijd.DRAW) {
puntenbij += 5;
ratingbij +=
aantalremise++;
resultaat = 3;
//logger.log(Level.INFO, " Remise : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.WHITE_WINS) && (w.getWit().gelijkAan(u))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met wit : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.BLACK_WINS) && (w.getZwart().gelijkAan(u))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met zwart :" + puntenbij);
} else {
// verlies
resultaat = 2;
//logger.log(Level.INFO, " Verlies :" + puntenbij);
}
if (w.isNietReglementair()) {
UitslagSpeler wit = w.getWit();
UitslagSpeler zwart = w.getZwart();
int ratingWit = wit.getStartrating();
int ratingZwart = zwart.getStartrating();
//logger.log(Level.INFO, "Startrating wit " + wit.getStartrating());
//logger.log(Level.INFO, "Startrating zwart " + zwart.getStartrating());
deltaWit = deltaRatingOSBO(Math.max(ratingWit, 100), Math.max(ratingZwart, 100), uitslagWit);
deltaZwart = deltaRatingOSBO(Math.max(ratingZwart,100), Math.max(ratingWit, 100), uitslagZwart);
ratingbij += spelerIswit ? deltaWit : deltaZwart;
//wit.setRating(Math.max(nieuwWit, 100));
//zwart.setRating(Math.max(nieuwZwart, 100));
//logger.log(Level.INFO, w.toString());
//logger.log(Level.INFO, "Wit: " + wit.getNaam() + " van " + ratingWit + " +/- " + deltaWit + " naar " + (ratingWit + deltaWit));
//logger.log(Level.INFO, "Zwart: " + zwart.getNaam() + " van " + ratingZwart + " +/- " + deltaZwart + " naar " + (ratingZwart +deltaZwart));
} else {
logger.log(Level.INFO, w.toString());
logger.log(Level.INFO, "Niet reglementair, geen aanpassing rating");
}
}
logger.log(Level.INFO, "new rating would be : " + u.getStartrating() + ratingbij);
logger.log(Level.INFO, "100 - newrating : " + (100 - (u.getStartrating() + ratingbij)));
logger.log(Level.INFO, "max(100 - newrating, 0) : " + Math.max(0, (100 - (u.getStartrating() + ratingbij))));
logger.log(Level.INFO, "ratingbij + max(100 - newrating, 0) : " + (ratingbij + Math.max(0, (100 - (u.getStartrating() + ratingbij)))));
ratingbij = ratingbij + (Math.max(100 - (u.getStartrating() + ratingbij),0));
String bijofaf = ratingbij>0 ? "+" : "-";
//int startrating = updateSpeler.getStartrating();
logger.log(Level.INFO, u.getNaam() + "|" + puntenbij/10 + "|" + u.getStartrating() + bijofaf + Math.abs(ratingbij) + " naar " + (u.getStartrating() + ratingbij));
//
//u.setStartrating(speler.getRating());
//updateSpeler.setPunten(puntenbij);
u.setDeltarating(ratingbij);
return u;
}
}
| lmeulen/IJSCO_UI | IJSCO_app/src/nl/detoren/ijsco/ui/control/Uitslagverwerker.java | 5,680 | // puntenbij is 10 * bordpunten ivm halve punten
| line_comment | nl | package nl.detoren.ijsco.ui.control;
/**
* Copyright (C) 2018 Lars Dam
* 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 version 3.0
* 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.
* See: http://www.gnu.org/licenses/gpl-3.0.html
*
* Problemen in deze code:
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.detoren.ijsco.data.Groep;
import nl.detoren.ijsco.data.Groepen;
import nl.detoren.ijsco.data.GroepsUitslag;
import nl.detoren.ijsco.data.GroepsUitslagen;
import nl.detoren.ijsco.data.Speler;
import nl.detoren.ijsco.data.UitslagSpeler;
import nl.detoren.ijsco.data.Wedstrijd;
import nl.detoren.ijsco.data.WedstrijdUitslag;
/**
*
* Verwerk uitslagen in een nieuwe stand
*
*/
public class Uitslagverwerker {
private final static Logger logger = Logger.getLogger(IJSCOController.class.getName());
/**
* Verwerk de wedstrijduitslagen en maak groepsuitslag
*
* @param spelersgroepen
* De spelersgroepen
* @param wedstrijden
* De gespeelde wedstrijden
* @return Bijgewerkte standen
*/
public GroepsUitslagen verwerkUitslag(Groepen groepen) {
GroepsUitslagen groepsuitslagen = new GroepsUitslagen();
for (Groep groep : groepen) {
logger.log(Level.INFO, "Verwerk uitslag voor groep " + groep.getNaam());
GroepsUitslag uitslag = new GroepsUitslag();
uitslag.setGroepsnaam(groep.getNaam());
for (Speler speler : groep.getSpelers()) {
logger.log(Level.INFO, "Verwerk uitslag voor speler " + speler.getNaam());
if (speler.getNaamHandmatig() != null) {
if (!speler.getNaamHandmatig().equals("Bye")) {
UitslagSpeler update = updateSpeler(speler, groep);
uitslag.addSpeler(update);
uitslag.setAantal(uitslag.getAantal() - 1);
}
} else {
UitslagSpeler update = updateSpeler(speler, groep);
uitslag.addSpeler(update);
}
}
groepsuitslagen.Add(uitslag);
}
return groepsuitslagen;
}
/**
* Return een bijgewerkte versie van een speler. Bijgewerkt zijn aantal
* punten en zijn rating
*
* @param speler
* Speler om bij te werken
* @param wedstrijden
* Alle wedstrijden
* @return Bijgewerkte speler
*/
private UitslagSpeler updateSpeler(Speler speler, Groep groep) {
ArrayList<Wedstrijd> spelerWedstrijden = getWedstrijdenVoorSpeler(speler, groep);
UitslagSpeler updateSpeler = new UitslagSpeler(speler);
int aantalgewonnen = 0;
int aantalremise = 0;
int puntenbij = 0; // puntenbij is<SUF>
int ratingbij = 0;
for (Wedstrijd w : spelerWedstrijden) {
//logger.log(Level.INFO, " Wedstrijd :" + w.toString());
int resultaat = -1; // onbekend
Speler tegenstander = w.getWit().gelijkAan(speler) ? w.getZwart() : w.getWit();
Boolean spelerIswit = w.getWit().gelijkAan(speler) ? true : false;
//
// w.getUitslag 1=wit wint 2=zwart wint 3=remise
int uitslagWit = w.getUitslag(); // uitslag vanuit perspectief wit
int uitslagZwart = (w.getUitslag() == 1) ? 2 : ((w.getUitslag() == 2) ? 1 : 3);
int deltaWit;
int deltaZwart;
// PUNTEN
if (uitslagWit == Wedstrijd.UNKNOWN) {
// doe niets
} else if (uitslagWit == Wedstrijd.DRAW) {
puntenbij += 5;
ratingbij +=
aantalremise++;
resultaat = 3;
//logger.log(Level.INFO, " Remise : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.WHITE_WINS) && (w.getWit().gelijkAan(speler))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met wit : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.BLACK_WINS) && (w.getZwart().gelijkAan(speler))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met zwart :" + puntenbij);
} else {
// verlies
resultaat = 2;
//logger.log(Level.INFO, " Verlies :" + puntenbij);
}
if (w.isNietReglementair()) {
Speler wit = w.getWit();
Speler zwart = w.getZwart();
int ratingWit = wit.getRating();
int ratingZwart = zwart.getRating();
//logger.log(Level.INFO, "Startrating wit " + wit.getRating());
//logger.log(Level.INFO, "Startrating zwart " + zwart.getRating());
deltaWit = deltaRatingOSBO(Math.max(ratingWit, 100), Math.max(ratingZwart, 100), uitslagWit);
deltaZwart = deltaRatingOSBO(Math.max(ratingZwart,100), Math.max(ratingWit, 100), uitslagZwart);
ratingbij += spelerIswit ? deltaWit : deltaZwart;
//wit.setRating(Math.max(nieuwWit, 100));
//zwart.setRating(Math.max(nieuwZwart, 100));
//logger.log(Level.INFO, w.toString());
//logger.log(Level.INFO, "Wit: " + wit.getNaam() + " van " + ratingWit + " +/- " + deltaWit + " naar " + (ratingWit + deltaWit));
//logger.log(Level.INFO, "Zwart: " + zwart.getNaam() + " van " + ratingZwart + " +/- " + deltaZwart + " naar " + (ratingZwart +deltaZwart));
} else {
logger.log(Level.INFO, w.toString());
logger.log(Level.INFO, "Niet reglementair, geen aanpassing rating");
}
}
// check is rating will not drop below 100
logger.log(Level.INFO, "new rating would be : " + updateSpeler.getStartrating() + ratingbij);
logger.log(Level.INFO, "100 - newrating : " + (100 - (updateSpeler.getStartrating() + ratingbij)));
logger.log(Level.INFO, "max(100 - newrating, 0) : " + Math.max(0, (100 - (updateSpeler.getStartrating() + ratingbij))));
logger.log(Level.INFO, "ratingbij + max(100 - newrating, 0) : " + (ratingbij + Math.max(0, (100 - (updateSpeler.getStartrating() + ratingbij)))));
ratingbij = ratingbij + (Math.max(100 - (updateSpeler.getStartrating() + ratingbij),0));
//logger.log(Level.INFO, "Punten :" + puntenbij/10);
logger.log(Level.INFO, "DeltaRating :" + ratingbij);
logger.log(Level.INFO, "Rating van " + updateSpeler.getStartrating() + " +/- " + ratingbij + " naar " + (updateSpeler.getStartrating() + ratingbij));
String bijofaf = ratingbij>0 ? "+" : "-";
int startrating = updateSpeler.getStartrating();
logger.log(Level.INFO, updateSpeler.getNaam() + "|" + puntenbij/10 + "|" + startrating + bijofaf + Math.abs(ratingbij) + " naar " + Math.max(100, (startrating + ratingbij)));
//
updateSpeler.setStartrating(speler.getRating());
updateSpeler.setPunten(puntenbij);
updateSpeler.setDeltarating(ratingbij);
return updateSpeler;
}
/**
* Geef voor een specifieke speler alle wedstrijden die hij gespeeld heeft
*
* @param speler
* De speler
* @param wedstrijden
* Alle wedstrijden van een speelavond
* @return wedstrijden gespeeld door speler
*/
private ArrayList<Wedstrijd> getWedstrijdenVoorSpeler(Speler speler, Groep groep) {
logger.log(Level.INFO, "Vind wedstrijden voor speler :" + speler.toString());
ArrayList<Wedstrijd> result = new ArrayList<>();
for (Wedstrijd w : groep.getWedstrijden()) {
if (w !=null) {
if (w.getWit().gelijkAan(speler) || w.getZwart().gelijkAan(speler)) {
result.add(w);
}
}
}
logger.log(Level.INFO, "" + result.size() + " wedstrijden gevonden voor " + speler.toString());
return result;
}
/**
* Geef voor een specifieke speler alle wedstrijden die hij gespeeld heeft
*
* @param speler
* De speler
* @param wedstrijden
* Alle wedstrijden van een speelavond
* @return wedstrijden gespeeld door speler
*/
private List<WedstrijdUitslag> getWedstrijdenVoorSpeler(UitslagSpeler speler, GroepsUitslag groep) {
logger.log(Level.INFO, "Vind wedstrijden voor speler :" + speler.toString());
Iterator<WedstrijdUitslag> iter = groep.getWedstrijden().iterator();
List<WedstrijdUitslag> result = new ArrayList<>();
while (iter.hasNext()) {
//for (WedstrijdUitslag w : result) {
WedstrijdUitslag w = iter.next();
if (w !=null) {
if (w.getWit().gelijkAan(speler) || w.getZwart().gelijkAan(speler)) {
result.add(w);
}
}
}
logger.log(Level.INFO, "" + result.size() + " wedstrijden gevonden voor " + speler.toString());
return result;
}
/**
* Bereken delta rating conform de regels van de OSBO en zoals gebruikt bij
* de interne competitie
*
* @param beginRating
* @param tegenstanderRating
* @param uitslag
* 1 = winst, 2 = verlies, 3 = remise
* @return
*/
public int deltaRatingOSBO(int beginRating, int tegenstanderRating, int uitslag) {
int[] ratingTabel = { 0, 16, 31, 51, 71, 91, 116, 141, 166, 201, 236, 281, 371, 9999 };
int ratingVerschil = Math.abs(beginRating - tegenstanderRating);
boolean ratingHogerDanTegenstander = beginRating > tegenstanderRating;
int index = 0;
while (ratingVerschil >= ratingTabel[index]) {
index++;
}
index--; // iterator goes one to far.
if (index == -1)
index = 0;
// Update rating wit
// Dit gebeurd aan de hand van de volgende OSBO tabel
// Hierin is: W> = winnaar heeft de hoogste rating
// W< = winnaar heeft de laagste rating
// V> = verliezer heeft de hoogste rating
// V< = verliezer heeft de laagste rating
// R> = remise met de hoogste rating
// R< = remise met de laagste rating
//
// In de volgende tabel wordt de aanpassing van de rating weergegeven
// rating
// verschil W> V< W< V> R> R<
// 0- 15 +12 -12 +12 -12 0 0
// 16- 30 +11 -11 +13 -13 - 1 + 1
// 31- 50 +10 -10 +14 -14 - 2 + 2
// 51- 70 + 9 - 9 +15 -15 - 3 + 3
// 71- 90 + 8 - 8 +16 -16 - 4 + 4
// 91-115 + 7 - 7 +17 -17 - 5 + 5
// 116-140 + 6 - 6 +18 -18 - 6 + 6
// 141-165 + 5 - 5 +19 -19 - 7 + 7
// 166-200 + 4 - 4 +20 -20 - 8 + 8
// 201-235 + 3 - 3 +21 -21 - 9 + 9
// 236-280 + 2 - 2 +22 -22 -10 +10
// 281-370 + 1 - 1 +23 -23 -11 +11
// >371 + 0 - 0 +24 -24 -12 +12
int deltaRating;
switch (uitslag) {
case 1: // Winst
deltaRating = 12 + (ratingHogerDanTegenstander ? (-1 * index) : (+1 * index));
return deltaRating;
case 2: // Verlies
deltaRating = 12 + (ratingHogerDanTegenstander ? (+1 * index) : (-1 * index));
return -deltaRating;
case 3: // Remise
deltaRating = (ratingHogerDanTegenstander ? (-1 * index) : (+1 * index));
return deltaRating;
default: // Geen uitstal
logger.log(Level.SEVERE , "Rating update: Uitslag is geen winst, geen verlies en geen remise.");
return 0;
}
}
public GroepsUitslagen verwerkUitslag(GroepsUitslagen groepenuitslagen) {
for (GroepsUitslag groep : groepenuitslagen) {
logger.log(Level.INFO, "Verwerk uitslag voor groep " + groep.getGroepsnaam());
for (Map.Entry<Integer, UitslagSpeler> m : groep.getSpelers().entrySet()) {
UitslagSpeler u = m.getValue();
if (u.getNaam() != null) {
logger.log(Level.INFO, "Verwerk uitslag voor speler " + u.getNaam());
if (!u.getNaam().equals("Bye")) {
u = updateSpeler(u, groep);
//uitslag.addSpeler(update);
//uitslag.setAantal(uitslag.getAantal() - 1);
}
} else {
//UitslagSpeler update = updateSpeler(speler, groep);
//uitslag.addSpeler(update);
}
}
//groepsuitslagen.Add(uitslag);
}
return groepenuitslagen;
}
private UitslagSpeler updateSpeler(UitslagSpeler u, GroepsUitslag groep) {
List<WedstrijdUitslag> spelerWedstrijden = getWedstrijdenVoorSpeler(u, groep);
//UitslagSpeler updateSpeler = new UitslagSpeler(speler);
int aantalgewonnen = 0;
int aantalremise = 0;
int puntenbij = 0; // puntenbij is 10 * bordpunten ivm halve punten
int ratingbij = 0;
for (WedstrijdUitslag w : spelerWedstrijden) {
//logger.log(Level.INFO, " Wedstrijd :" + w.toString());
int resultaat = -1; // onbekend
UitslagSpeler tegenstander = w.getWit().gelijkAan(u) ? w.getZwart() : w.getWit();
Boolean spelerIswit = w.getWit().gelijkAan(u) ? true : false;
//
// w.getUitslag 1=wit wint 2=zwart wint 3=remise
int uitslagWit = w.getUitslag(); // uitslag vanuit perspectief wit
int uitslagZwart = (w.getUitslag() == 1) ? 2 : ((w.getUitslag() == 2) ? 1 : 3);
int deltaWit;
int deltaZwart;
// PUNTEN
if (uitslagWit == Wedstrijd.UNKNOWN) {
// doe niets
} else if (uitslagWit == Wedstrijd.DRAW) {
puntenbij += 5;
ratingbij +=
aantalremise++;
resultaat = 3;
//logger.log(Level.INFO, " Remise : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.WHITE_WINS) && (w.getWit().gelijkAan(u))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met wit : " + puntenbij);
} else if ((uitslagWit == Wedstrijd.BLACK_WINS) && (w.getZwart().gelijkAan(u))) {
puntenbij += 10;
aantalgewonnen++;
resultaat = 1;
//logger.log(Level.INFO, " Winst met zwart :" + puntenbij);
} else {
// verlies
resultaat = 2;
//logger.log(Level.INFO, " Verlies :" + puntenbij);
}
if (w.isNietReglementair()) {
UitslagSpeler wit = w.getWit();
UitslagSpeler zwart = w.getZwart();
int ratingWit = wit.getStartrating();
int ratingZwart = zwart.getStartrating();
//logger.log(Level.INFO, "Startrating wit " + wit.getStartrating());
//logger.log(Level.INFO, "Startrating zwart " + zwart.getStartrating());
deltaWit = deltaRatingOSBO(Math.max(ratingWit, 100), Math.max(ratingZwart, 100), uitslagWit);
deltaZwart = deltaRatingOSBO(Math.max(ratingZwart,100), Math.max(ratingWit, 100), uitslagZwart);
ratingbij += spelerIswit ? deltaWit : deltaZwart;
//wit.setRating(Math.max(nieuwWit, 100));
//zwart.setRating(Math.max(nieuwZwart, 100));
//logger.log(Level.INFO, w.toString());
//logger.log(Level.INFO, "Wit: " + wit.getNaam() + " van " + ratingWit + " +/- " + deltaWit + " naar " + (ratingWit + deltaWit));
//logger.log(Level.INFO, "Zwart: " + zwart.getNaam() + " van " + ratingZwart + " +/- " + deltaZwart + " naar " + (ratingZwart +deltaZwart));
} else {
logger.log(Level.INFO, w.toString());
logger.log(Level.INFO, "Niet reglementair, geen aanpassing rating");
}
}
logger.log(Level.INFO, "new rating would be : " + u.getStartrating() + ratingbij);
logger.log(Level.INFO, "100 - newrating : " + (100 - (u.getStartrating() + ratingbij)));
logger.log(Level.INFO, "max(100 - newrating, 0) : " + Math.max(0, (100 - (u.getStartrating() + ratingbij))));
logger.log(Level.INFO, "ratingbij + max(100 - newrating, 0) : " + (ratingbij + Math.max(0, (100 - (u.getStartrating() + ratingbij)))));
ratingbij = ratingbij + (Math.max(100 - (u.getStartrating() + ratingbij),0));
String bijofaf = ratingbij>0 ? "+" : "-";
//int startrating = updateSpeler.getStartrating();
logger.log(Level.INFO, u.getNaam() + "|" + puntenbij/10 + "|" + u.getStartrating() + bijofaf + Math.abs(ratingbij) + " naar " + (u.getStartrating() + ratingbij));
//
//u.setStartrating(speler.getRating());
//updateSpeler.setPunten(puntenbij);
u.setDeltarating(ratingbij);
return u;
}
}
|
115938_2 | package hellotvxlet;
import java.awt.event.*;
import java.util.*;
import javax.tv.xlet.*;
import org.dvb.event.*;
import org.dvb.ui.*;
import org.havi.ui.*;
import org.havi.ui.event.*;
public class HelloTVXlet implements Xlet, UserEventListener{
MijnComponent mc;
LaserManager laserman=new LaserManager();
HScene scene;
Random rgen=new Random();
Player speler;
Enemy enemy=new Enemy();
int deler=0;
Timer t;
public HelloTVXlet() {
}
public void initXlet(XletContext context)
{
this.startSpel();
}
public void startSpel() {
scene = HSceneFactory.getInstance().getDefaultHScene();
mc = new MijnComponent();
laserman.setScene(scene);
scene.add(mc);
scene.validate();
scene.setVisible(true);
UserEventRepository uev = new UserEventRepository("mijn verzameling");
//voeg toetsen toe aan verzameling
uev.addAllArrowKeys();
//stuur de verzameling naar de EventManager (met link naar dit object)
EventManager.getInstance().addUserEventListener(this, uev);
speler=new Player();
speler.move(300,500);
scene.add(speler);
scene.popToFront(speler);
enemy=new Enemy();
enemy.move(300,10);
scene.add(enemy);
scene.popToFront(enemy);
t = new Timer();
MijnTimerTask mtt = new MijnTimerTask();
mtt.setCallBack(this); //stuur link naar dit object om callback aan te roepen
t.scheduleAtFixedRate(mtt, 0, 10); //start op 0, elke 100 ms
}
void callback() {
//System.out.println("callback()");
mc.verplaatsSterren(0,1);
if (enemy!=null) enemy.verplaatsEnemy(1);
//mc.verplaatsPlayerLaser();
// mc.enemyShoot(mc.enemyX, mc.enemyY);
deler++;
if (rgen.nextInt(20)==10)
{
EnemyLaser eLaser=new EnemyLaser();
eLaser.move(enemy.getX()+32, enemy.getY()+64);
laserman.addEnemyLaser(eLaser);
scene.add(eLaser);
scene.popToFront(eLaser);
deler=0;
}
//mc.verplaatsEnemyLaser();
laserman.moveAllLasers();
if (laserman.testPlayerCollision(speler)) System.out.println("YOU LOSE!!!!!");
if (laserman.testEnemyCollision(enemy)) System.out.println("HIT!!!!!");
}
public void startXlet() {
}
public void pauseXlet() {
}
public void destroyXlet(boolean unconditional) {
}
public void userEventReceived(UserEvent e) {
if (e.getType()==HRcEvent.KEY_PRESSED){ //enkel indrukken, niet loslaten
switch (e.getCode())
{
case HRcEvent.VK_LEFT:
System.out.println("links!!!");
speler.moverel(-10, 0);
scene.dispose();
//timer nog stoppen
t.cancel();
scene = HSceneFactory.getInstance().getDefaultHScene();
scene.add(new HStaticText("hallo",10,10,200,200));
scene.validate();
scene.setVisible(true);
//start
break;
case HRcEvent.VK_RIGHT:
System.out.println("rechts!!!");
speler.moverel(10, 0);
scene.dispose();
this.startSpel();
break;
case HRcEvent.VK_UP:
System.out.println("player shoot!!!");
PlayerLaser pLaser=new PlayerLaser();
pLaser.move(speler.getX()+21, speler.getY()-20);
laserman.addPlayerLaser(pLaser);
scene.add(pLaser);
scene.popToFront(pLaser);
//mc.playerShoot(mc.playerX, mc.playerY);
break;
}
}
}
}
| MTA-Digital-Broadcast-2/V-Clauwaert-Dieter-Boons-Jonah-Project-MHP | SpaceInvaders/src/hellotvxlet/HelloTVXlet.java | 1,135 | //stuur link naar dit object om callback aan te roepen | line_comment | nl | package hellotvxlet;
import java.awt.event.*;
import java.util.*;
import javax.tv.xlet.*;
import org.dvb.event.*;
import org.dvb.ui.*;
import org.havi.ui.*;
import org.havi.ui.event.*;
public class HelloTVXlet implements Xlet, UserEventListener{
MijnComponent mc;
LaserManager laserman=new LaserManager();
HScene scene;
Random rgen=new Random();
Player speler;
Enemy enemy=new Enemy();
int deler=0;
Timer t;
public HelloTVXlet() {
}
public void initXlet(XletContext context)
{
this.startSpel();
}
public void startSpel() {
scene = HSceneFactory.getInstance().getDefaultHScene();
mc = new MijnComponent();
laserman.setScene(scene);
scene.add(mc);
scene.validate();
scene.setVisible(true);
UserEventRepository uev = new UserEventRepository("mijn verzameling");
//voeg toetsen toe aan verzameling
uev.addAllArrowKeys();
//stuur de verzameling naar de EventManager (met link naar dit object)
EventManager.getInstance().addUserEventListener(this, uev);
speler=new Player();
speler.move(300,500);
scene.add(speler);
scene.popToFront(speler);
enemy=new Enemy();
enemy.move(300,10);
scene.add(enemy);
scene.popToFront(enemy);
t = new Timer();
MijnTimerTask mtt = new MijnTimerTask();
mtt.setCallBack(this); //stuur link<SUF>
t.scheduleAtFixedRate(mtt, 0, 10); //start op 0, elke 100 ms
}
void callback() {
//System.out.println("callback()");
mc.verplaatsSterren(0,1);
if (enemy!=null) enemy.verplaatsEnemy(1);
//mc.verplaatsPlayerLaser();
// mc.enemyShoot(mc.enemyX, mc.enemyY);
deler++;
if (rgen.nextInt(20)==10)
{
EnemyLaser eLaser=new EnemyLaser();
eLaser.move(enemy.getX()+32, enemy.getY()+64);
laserman.addEnemyLaser(eLaser);
scene.add(eLaser);
scene.popToFront(eLaser);
deler=0;
}
//mc.verplaatsEnemyLaser();
laserman.moveAllLasers();
if (laserman.testPlayerCollision(speler)) System.out.println("YOU LOSE!!!!!");
if (laserman.testEnemyCollision(enemy)) System.out.println("HIT!!!!!");
}
public void startXlet() {
}
public void pauseXlet() {
}
public void destroyXlet(boolean unconditional) {
}
public void userEventReceived(UserEvent e) {
if (e.getType()==HRcEvent.KEY_PRESSED){ //enkel indrukken, niet loslaten
switch (e.getCode())
{
case HRcEvent.VK_LEFT:
System.out.println("links!!!");
speler.moverel(-10, 0);
scene.dispose();
//timer nog stoppen
t.cancel();
scene = HSceneFactory.getInstance().getDefaultHScene();
scene.add(new HStaticText("hallo",10,10,200,200));
scene.validate();
scene.setVisible(true);
//start
break;
case HRcEvent.VK_RIGHT:
System.out.println("rechts!!!");
speler.moverel(10, 0);
scene.dispose();
this.startSpel();
break;
case HRcEvent.VK_UP:
System.out.println("player shoot!!!");
PlayerLaser pLaser=new PlayerLaser();
pLaser.move(speler.getX()+21, speler.getY()-20);
laserman.addPlayerLaser(pLaser);
scene.add(pLaser);
scene.popToFront(pLaser);
//mc.playerShoot(mc.playerX, mc.playerY);
break;
}
}
}
}
|
132116_5 | package org.jhaws.common.web.wicket.demo;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.lang.Bytes;
import org.jhaws.common.io.FilePath;
import org.jhaws.common.lang.CollectionUtils8;
import org.jhaws.common.web.wicket.bootstrap.DefaultWebPage;
@SuppressWarnings("serial")
public class UploadTestPage extends DefaultWebPage {
private static final String TMP_UPLOAD = "c:/java/tmp";
public UploadTestPage() {
super();
}
public UploadTestPage(PageParameters parameters) {
super(parameters);
}
public static class UploadDTO implements Serializable {
List<UploadItem> existing = new ArrayList<>();
public UploadDTO(List<UploadItem> existing) {
super();
this.existing = existing;
}
public UploadDTO() {
super();
}
public List<UploadItem> getExisting() {
return existing;
}
public void setExisting(List<UploadItem> existing) {
this.existing = existing;
}
}
public static class UploadItem implements Serializable {
String path;
Boolean delete; // markeer om te verwijderen
public UploadItem() {
super();
}
public UploadItem(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Boolean getDelete() {
return delete;
}
public void setDelete(Boolean delete) {
this.delete = delete;
}
@Override
public String toString() {
return (Boolean.TRUE.equals(delete) ? "-" : "") + path;
}
}
IModel<UploadDTO> formModel;
@Override
protected void addComponents(PageParameters parameters, MarkupContainer html) {
Form<Void> hoofdform = new Form<>("hoofdform"); // om form in form te testen
add(hoofdform);
formModel = Model.of(new UploadDTO(new FilePath(TMP_UPLOAD).listFiles().stream().filter(FilePath::isFile).map(FilePath::getFileNameString).map(UploadItem::new).collect(Collectors.toList())));
FileUploadField fileupload = new FileUploadField("fileupload");
Form<UploadDTO> uploadform = new Form<UploadDTO>("uploadform", formModel) { // echte upload form
@Override
protected void onSubmit() {
UploadDTO uploadDTO = getModel().getObject();
CollectionUtils8.streamDetached(uploadDTO.getExisting()).forEach(i -> {
if (Boolean.TRUE.equals(i.getDelete())) {
System.out.println("-" + i.getPath()); // logging
FilePath newFile = new FilePath(TMP_UPLOAD).child(i.getPath());
newFile.delete(); // service toegang
// update model
uploadDTO.getExisting().remove(i);
}
});
List<FileUpload> uploadedFiles = fileupload.getFileUploads();
if (uploadedFiles != null) {
uploadedFiles.forEach(uploadedFile -> {
try {
System.out.println("+" + uploadedFile.getClientFileName()); // logging
FilePath newFile = new FilePath(TMP_UPLOAD).child(uploadedFile.getClientFileName());
newFile.write(uploadedFile.getInputStream());// service toegang
// update model
uploadDTO.getExisting().add(new UploadItem(uploadedFile.getClientFileName()));
} catch (IOException ex) {
ex.printStackTrace();
}
});
}
}
};
uploadform.setFileMaxSize(Bytes.kilobytes(1024l * 10l));// random gekozen om te testen
uploadform.setMultiPart(true); // denk ik niet meer nodig in deze wicket versie
hoofdform.add(uploadform);
WebMarkupContainer fileuploadLabel = new WebMarkupContainer("fileuploadLabel") {
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.put("for", fileupload.getMarkupId());
}
};
uploadform.add(fileupload);
uploadform.add(fileuploadLabel);
// alle bestaande files (zitten al in formmodel DTO als lijst van UploadItem)
uploadform.add(new ListView<UploadItem>("existing", new IModel<List<UploadItem>>() {
@Override
public void detach() {
//
}
@Override
public List<UploadItem> getObject() {
return uploadform.getModel().getObject().getExisting();
}
@Override
public void setObject(List<UploadItem> object) {
uploadform.getModel().getObject().setExisting(object);
}
}) {
@Override
protected void populateItem(ListItem<UploadItem> item) {
CheckBox itemdelete = new CheckBox("itemdelete", new PropertyModel<Boolean>(item.getModel(), "delete"));
itemdelete.setOutputMarkupId(true);
item.add(itemdelete);
Label itemlabel = new Label("itemlabel", Model.of(item.getModelObject().getPath()));
itemlabel.setOutputMarkupId(true);
item.add(itemlabel);
}
});
hoofdform.add(new SubmitLink("submit"));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
}
}
| jurgendl/jhaws | jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/demo/UploadTestPage.java | 1,591 | // alle bestaande files (zitten al in formmodel DTO als lijst van UploadItem) | line_comment | nl | package org.jhaws.common.web.wicket.demo;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.lang.Bytes;
import org.jhaws.common.io.FilePath;
import org.jhaws.common.lang.CollectionUtils8;
import org.jhaws.common.web.wicket.bootstrap.DefaultWebPage;
@SuppressWarnings("serial")
public class UploadTestPage extends DefaultWebPage {
private static final String TMP_UPLOAD = "c:/java/tmp";
public UploadTestPage() {
super();
}
public UploadTestPage(PageParameters parameters) {
super(parameters);
}
public static class UploadDTO implements Serializable {
List<UploadItem> existing = new ArrayList<>();
public UploadDTO(List<UploadItem> existing) {
super();
this.existing = existing;
}
public UploadDTO() {
super();
}
public List<UploadItem> getExisting() {
return existing;
}
public void setExisting(List<UploadItem> existing) {
this.existing = existing;
}
}
public static class UploadItem implements Serializable {
String path;
Boolean delete; // markeer om te verwijderen
public UploadItem() {
super();
}
public UploadItem(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Boolean getDelete() {
return delete;
}
public void setDelete(Boolean delete) {
this.delete = delete;
}
@Override
public String toString() {
return (Boolean.TRUE.equals(delete) ? "-" : "") + path;
}
}
IModel<UploadDTO> formModel;
@Override
protected void addComponents(PageParameters parameters, MarkupContainer html) {
Form<Void> hoofdform = new Form<>("hoofdform"); // om form in form te testen
add(hoofdform);
formModel = Model.of(new UploadDTO(new FilePath(TMP_UPLOAD).listFiles().stream().filter(FilePath::isFile).map(FilePath::getFileNameString).map(UploadItem::new).collect(Collectors.toList())));
FileUploadField fileupload = new FileUploadField("fileupload");
Form<UploadDTO> uploadform = new Form<UploadDTO>("uploadform", formModel) { // echte upload form
@Override
protected void onSubmit() {
UploadDTO uploadDTO = getModel().getObject();
CollectionUtils8.streamDetached(uploadDTO.getExisting()).forEach(i -> {
if (Boolean.TRUE.equals(i.getDelete())) {
System.out.println("-" + i.getPath()); // logging
FilePath newFile = new FilePath(TMP_UPLOAD).child(i.getPath());
newFile.delete(); // service toegang
// update model
uploadDTO.getExisting().remove(i);
}
});
List<FileUpload> uploadedFiles = fileupload.getFileUploads();
if (uploadedFiles != null) {
uploadedFiles.forEach(uploadedFile -> {
try {
System.out.println("+" + uploadedFile.getClientFileName()); // logging
FilePath newFile = new FilePath(TMP_UPLOAD).child(uploadedFile.getClientFileName());
newFile.write(uploadedFile.getInputStream());// service toegang
// update model
uploadDTO.getExisting().add(new UploadItem(uploadedFile.getClientFileName()));
} catch (IOException ex) {
ex.printStackTrace();
}
});
}
}
};
uploadform.setFileMaxSize(Bytes.kilobytes(1024l * 10l));// random gekozen om te testen
uploadform.setMultiPart(true); // denk ik niet meer nodig in deze wicket versie
hoofdform.add(uploadform);
WebMarkupContainer fileuploadLabel = new WebMarkupContainer("fileuploadLabel") {
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.put("for", fileupload.getMarkupId());
}
};
uploadform.add(fileupload);
uploadform.add(fileuploadLabel);
// alle bestaande<SUF>
uploadform.add(new ListView<UploadItem>("existing", new IModel<List<UploadItem>>() {
@Override
public void detach() {
//
}
@Override
public List<UploadItem> getObject() {
return uploadform.getModel().getObject().getExisting();
}
@Override
public void setObject(List<UploadItem> object) {
uploadform.getModel().getObject().setExisting(object);
}
}) {
@Override
protected void populateItem(ListItem<UploadItem> item) {
CheckBox itemdelete = new CheckBox("itemdelete", new PropertyModel<Boolean>(item.getModel(), "delete"));
itemdelete.setOutputMarkupId(true);
item.add(itemdelete);
Label itemlabel = new Label("itemlabel", Model.of(item.getModelObject().getPath()));
itemlabel.setOutputMarkupId(true);
item.add(itemlabel);
}
});
hoofdform.add(new SubmitLink("submit"));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
}
}
|
79576_15 | package com.renderapi;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner; // Import the Scanner class to read text files
import java.net.*;
public class FileTransfer {
// FileTransfe regelt de opslag van de socket
// sock is de geopende socket van de TCP poort
final Socket sock;
// buffer grootte
// DESIGNQUESTION 1KB of zelfs 4KB gaan gebruiken?
// latency?
final static int blockSize = 512;
// File object en file metadata
static File openFile;
String fileName;
long fileSize;
public FileTransfer(Socket sock, int port, String fileName, long size )
{
// open TCP socket
this.sock = sock;
// file metadata
this.fileName = fileName;
this.fileSize = size;
}
public String recvFile(Socket sock, ServerSocket serverSock ) {
String msg = "";
// Maak het file object aan
openFile = new File( this.fileName );
this.fileSize = openFile.length();
// Controleer of het bestand te schrijven is
boolean write;
write = openFile.canRead();
// Stuur error als file niet te schrijven is
if( !write ) {
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Can not read from file: " + this.fileName );
return msg;
}
// File input stream
InputStream inStream;
// Debug log dat er geprobeerd wordt om naar file te schrijven
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Trying to read file: " + this.fileName );
try {
inStream = new FileInputStream( openFile );
} catch(FileNotFoundException e) {
// Handle de File Not Found exceptie
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "File not found: " + this.fileName + " Exception: " + e.getMessage() );
return msg;
}
//hou de bestandsgrootte bij
long totalBytes = 0;
// Schrijf de file size naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File size: " + this.fileSize );
// Transfer buffer
byte[] buffer = new byte[FileTransfer.blockSize];
int bytesRead = 0;
// Output stream wordt niet gebruikt
DataInputStream dataInput;
DataOutputStream outStream;
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Transfer via port: " + serverSock.getLocalPort() );
try {
outStream = new DataOutputStream ( sock.getOutputStream() );
dataInput = new DataInputStream( inStream );
do {
// Lees FileTransfer.blockSize bytes van de stream en hou de totaal grootte bij
bytesRead = dataInput.readNBytes(buffer, 0, FileTransfer.blockSize );
totalBytes += bytesRead;
// Debug hoeveel bytes er al gelezen zijn
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Read from socket bytes: " + totalBytes );
// schrijf de buffer naar de file
if( totalBytes < this.fileSize ) {
outStream.write(buffer, 0, bytesRead);
}
// controleer de grootte
} while( totalBytes < this.fileSize );
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "TotalBytes: " + totalBytes + " FileSize: " + this.fileSize );
long left;
left = this.fileSize - totalBytes + bytesRead;
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Bytes left: " + left );
dataInput.readNBytes(buffer,0,(int)left);
outStream.write(buffer,0,(int)left);
// Struit de outstream
outStream.flush();
outStream.close();
} catch (IOException e ) {
// Handle IO exception en schrijf JSON error als die optreed
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName );
return msg;
}
return msg;
}
public String saveFile() {
// Maak het file object aan
openFile = new File( this.fileName );
try {
// Probeer de file te openen
openFile.createNewFile();
} catch (IOException e) {
// Log de error naar de server log
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
// Stuur de file IO error naar de JSON output.
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.IOERR, "Could not save file: " + this.fileName + " " + e.getMessage() );
return msg;
}
// Controleer of het bestand te schrijven is
boolean write;
write = openFile.canWrite();
// Stuur error als file niet te schrijven is
if( !write ) {
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Can not write to file: " + this.fileName );
return msg;
}
// File output stream
OutputStream outStream;
// Debug log dat er geprobeerd wordt om naar file te schrijven
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Trying to save file: " + this.fileName );
try {
// Open de file output stream
outStream = new FileOutputStream( openFile, false );
} catch(FileNotFoundException e) {
// Handle de File Not Found exceptie
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "File not found: " + this.fileName + " Exception: " + e.getMessage() );
return msg;
}
//hou de bestandsgrootte bij
long totalBytes = 0;
// Schrijf de file size naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File size: " + this.fileSize );
// Transfer buffer
byte[] buffer = new byte[FileTransfer.blockSize];
int bytesRead = 0;
// Output stream wordt niet gebruikt
DataInputStream dataInput;
DataOutputStream dataOutput;
try {
// Open het bestand naar een Stream
dataInput = new DataInputStream(this.sock.getInputStream());
dataOutput = new DataOutputStream(this.sock.getOutputStream());
} catch (IOException e) {
// Handle IO exceptie
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
try {
// Probeer bestand te sluiten
outStream.close();
} catch (IOException ex) {
// Schrijf error naar logfile
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + ex.getMessage() );
}
// Schrijf de file transfer error naar JSON output
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName + " " + e.getMessage() );
return msg;
}
try {
do {
// Lees FileTransfer.blockSize bytes van de stream en hou de totaal grootte bij
bytesRead = dataInput.readNBytes(buffer, 0, FileTransfer.blockSize );
totalBytes += bytesRead;
// Debug hoeveel bytes er al gelezen zijn
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Read from socket bytes: " + totalBytes );
// schrijf de buffer naar de file
if( totalBytes < this.fileSize ) {
outStream.write(buffer, 0, bytesRead);
}
// controleer de grootte
} while( totalBytes < this.fileSize );
// verwijder het laatste blok
totalBytes -= FileTransfer.blockSize;
// bereken de overige bytes
int left =(int)( this.fileSize - totalBytes );
// schrijf deze naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Bytes left: " + left );
//schrijf de laatste bytes
// DESIGNQUESTION volgens mij werkt dit, maar is het handig een MD5 checksum controle te doen
outStream.write(buffer, 0, left);
// Debug.
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "TotalBytes: " + totalBytes + " FileSize: " + this.fileSize );
// Struit de outstream
outStream.flush();
outStream.close();
} catch (IOException e ) {
// Handle IO exception en schrijf JSON error als die optreed
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName );
return msg;
}
// Stuur de save message naar de JSON output
String msg;
msg = MessageHandler.prepareMessage( RenderAPI.NetworkMessageType.FILESAVED, "" + this.fileSize );
return msg;
}
}
| digidagmar/RenderSolution | src/com/renderapi/FileTransfer.java | 2,375 | // Lees FileTransfer.blockSize bytes van de stream en hou de totaal grootte bij | line_comment | nl | package com.renderapi;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner; // Import the Scanner class to read text files
import java.net.*;
public class FileTransfer {
// FileTransfe regelt de opslag van de socket
// sock is de geopende socket van de TCP poort
final Socket sock;
// buffer grootte
// DESIGNQUESTION 1KB of zelfs 4KB gaan gebruiken?
// latency?
final static int blockSize = 512;
// File object en file metadata
static File openFile;
String fileName;
long fileSize;
public FileTransfer(Socket sock, int port, String fileName, long size )
{
// open TCP socket
this.sock = sock;
// file metadata
this.fileName = fileName;
this.fileSize = size;
}
public String recvFile(Socket sock, ServerSocket serverSock ) {
String msg = "";
// Maak het file object aan
openFile = new File( this.fileName );
this.fileSize = openFile.length();
// Controleer of het bestand te schrijven is
boolean write;
write = openFile.canRead();
// Stuur error als file niet te schrijven is
if( !write ) {
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Can not read from file: " + this.fileName );
return msg;
}
// File input stream
InputStream inStream;
// Debug log dat er geprobeerd wordt om naar file te schrijven
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Trying to read file: " + this.fileName );
try {
inStream = new FileInputStream( openFile );
} catch(FileNotFoundException e) {
// Handle de File Not Found exceptie
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "File not found: " + this.fileName + " Exception: " + e.getMessage() );
return msg;
}
//hou de bestandsgrootte bij
long totalBytes = 0;
// Schrijf de file size naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File size: " + this.fileSize );
// Transfer buffer
byte[] buffer = new byte[FileTransfer.blockSize];
int bytesRead = 0;
// Output stream wordt niet gebruikt
DataInputStream dataInput;
DataOutputStream outStream;
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Transfer via port: " + serverSock.getLocalPort() );
try {
outStream = new DataOutputStream ( sock.getOutputStream() );
dataInput = new DataInputStream( inStream );
do {
// Lees FileTransfer.blockSize<SUF>
bytesRead = dataInput.readNBytes(buffer, 0, FileTransfer.blockSize );
totalBytes += bytesRead;
// Debug hoeveel bytes er al gelezen zijn
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Read from socket bytes: " + totalBytes );
// schrijf de buffer naar de file
if( totalBytes < this.fileSize ) {
outStream.write(buffer, 0, bytesRead);
}
// controleer de grootte
} while( totalBytes < this.fileSize );
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "TotalBytes: " + totalBytes + " FileSize: " + this.fileSize );
long left;
left = this.fileSize - totalBytes + bytesRead;
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Bytes left: " + left );
dataInput.readNBytes(buffer,0,(int)left);
outStream.write(buffer,0,(int)left);
// Struit de outstream
outStream.flush();
outStream.close();
} catch (IOException e ) {
// Handle IO exception en schrijf JSON error als die optreed
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName );
return msg;
}
return msg;
}
public String saveFile() {
// Maak het file object aan
openFile = new File( this.fileName );
try {
// Probeer de file te openen
openFile.createNewFile();
} catch (IOException e) {
// Log de error naar de server log
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
// Stuur de file IO error naar de JSON output.
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.IOERR, "Could not save file: " + this.fileName + " " + e.getMessage() );
return msg;
}
// Controleer of het bestand te schrijven is
boolean write;
write = openFile.canWrite();
// Stuur error als file niet te schrijven is
if( !write ) {
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Can not write to file: " + this.fileName );
return msg;
}
// File output stream
OutputStream outStream;
// Debug log dat er geprobeerd wordt om naar file te schrijven
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Trying to save file: " + this.fileName );
try {
// Open de file output stream
outStream = new FileOutputStream( openFile, false );
} catch(FileNotFoundException e) {
// Handle de File Not Found exceptie
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "File not found: " + this.fileName + " Exception: " + e.getMessage() );
return msg;
}
//hou de bestandsgrootte bij
long totalBytes = 0;
// Schrijf de file size naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File size: " + this.fileSize );
// Transfer buffer
byte[] buffer = new byte[FileTransfer.blockSize];
int bytesRead = 0;
// Output stream wordt niet gebruikt
DataInputStream dataInput;
DataOutputStream dataOutput;
try {
// Open het bestand naar een Stream
dataInput = new DataInputStream(this.sock.getInputStream());
dataOutput = new DataOutputStream(this.sock.getOutputStream());
} catch (IOException e) {
// Handle IO exceptie
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
try {
// Probeer bestand te sluiten
outStream.close();
} catch (IOException ex) {
// Schrijf error naar logfile
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + ex.getMessage() );
}
// Schrijf de file transfer error naar JSON output
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName + " " + e.getMessage() );
return msg;
}
try {
do {
// Lees FileTransfer.blockSize bytes van de stream en hou de totaal grootte bij
bytesRead = dataInput.readNBytes(buffer, 0, FileTransfer.blockSize );
totalBytes += bytesRead;
// Debug hoeveel bytes er al gelezen zijn
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Read from socket bytes: " + totalBytes );
// schrijf de buffer naar de file
if( totalBytes < this.fileSize ) {
outStream.write(buffer, 0, bytesRead);
}
// controleer de grootte
} while( totalBytes < this.fileSize );
// verwijder het laatste blok
totalBytes -= FileTransfer.blockSize;
// bereken de overige bytes
int left =(int)( this.fileSize - totalBytes );
// schrijf deze naar de debug log
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Bytes left: " + left );
//schrijf de laatste bytes
// DESIGNQUESTION volgens mij werkt dit, maar is het handig een MD5 checksum controle te doen
outStream.write(buffer, 0, left);
// Debug.
ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "TotalBytes: " + totalBytes + " FileSize: " + this.fileSize );
// Struit de outstream
outStream.flush();
outStream.close();
} catch (IOException e ) {
// Handle IO exception en schrijf JSON error als die optreed
ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IOException: " + e.getMessage() );
String msg;
msg = MessageHandler.prepareError(RenderAPI.NetworkErrorType.FILETRANSFERERR, "Could not save file: " + this.fileName );
return msg;
}
// Stuur de save message naar de JSON output
String msg;
msg = MessageHandler.prepareMessage( RenderAPI.NetworkMessageType.FILESAVED, "" + this.fileSize );
return msg;
}
}
|
146082_22 | /*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.sampling.distribution;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
/**
* List of samplers.
*/
public final class ContinuousSamplersList {
/** List of all RNGs implemented in the library. */
private static final List<ContinuousSamplerTestData> LIST = new ArrayList<>();
static {
try {
// This test uses reference distributions from commons-math3 to compute the expected
// PMF. These distributions have a dual functionality to compute the PMF and perform
// sampling. When no sampling is needed for the created distribution, it is advised
// to pass null as the random generator via the appropriate constructors to avoid the
// additional initialisation overhead.
org.apache.commons.math3.random.RandomGenerator unusedRng = null;
// List of distributions to test.
// Gaussian ("inverse method").
final double meanNormal = -123.45;
final double sigmaNormal = 6.789;
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
RandomSource.KISS.create());
// Gaussian (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
new BoxMullerGaussianSampler(RandomSource.MT.create(), meanNormal, sigmaNormal));
// Gaussian ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new BoxMullerNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Marsaglia").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new MarsagliaNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Ziggurat").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Modified ziggurat").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(ZigguratSampler.NormalizedGaussian.of(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Beta ("inverse method").
final double alphaBeta = 4.3;
final double betaBeta = 2.1;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta),
RandomSource.ISAAC.create());
// Beta ("Cheng").
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta),
ChengBetaSampler.of(RandomSource.MWC_256.create(), alphaBeta, betaBeta));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBeta, alphaBeta),
ChengBetaSampler.of(RandomSource.WELL_19937_A.create(), betaBeta, alphaBeta));
// Beta ("Cheng", alternate algorithm).
final double alphaBetaAlt = 0.5678;
final double betaBetaAlt = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBetaAlt, betaBetaAlt),
ChengBetaSampler.of(RandomSource.WELL_512_A.create(), alphaBetaAlt, betaBetaAlt));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBetaAlt, alphaBetaAlt),
ChengBetaSampler.of(RandomSource.WELL_19937_C.create(), betaBetaAlt, alphaBetaAlt));
// Cauchy ("inverse method").
final double medianCauchy = 0.123;
final double scaleCauchy = 4.5;
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, medianCauchy, scaleCauchy),
RandomSource.WELL_19937_C.create());
// Chi-square ("inverse method").
final int dofChi2 = 12;
add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(unusedRng, dofChi2),
RandomSource.WELL_19937_A.create());
// Exponential ("inverse method").
final double meanExp = 3.45;
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
RandomSource.WELL_44497_A.create());
// Exponential.
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
AhrensDieterExponentialSampler.of(RandomSource.MT.create(), meanExp));
// Exponential ("Modified ziggurat").
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
ZigguratSampler.Exponential.of(RandomSource.XO_RO_SHI_RO_128_SS.create(), meanExp));
// F ("inverse method").
final int numDofF = 4;
final int denomDofF = 7;
add(LIST, new org.apache.commons.math3.distribution.FDistribution(unusedRng, numDofF, denomDofF),
RandomSource.MT_64.create());
// Gamma ("inverse method").
final double alphaGammaSmallerThanOne = 0.1234;
final double alphaGammaLargerThanOne = 2.345;
final double thetaGamma = 3.456;
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma),
RandomSource.SPLIT_MIX_64.create());
// Gamma (alpha < 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaSmallerThanOne, thetaGamma),
AhrensDieterMarsagliaTsangGammaSampler.of(RandomSource.XOR_SHIFT_1024_S_PHI.create(),
alphaGammaSmallerThanOne, thetaGamma));
// Gamma (alpha > 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma),
AhrensDieterMarsagliaTsangGammaSampler.of(RandomSource.WELL_44497_B.create(),
alphaGammaLargerThanOne, thetaGamma));
// Gumbel ("inverse method").
final double muGumbel = -4.56;
final double betaGumbel = 0.123;
add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(unusedRng, muGumbel, betaGumbel),
RandomSource.WELL_1024_A.create());
// Laplace ("inverse method").
final double muLaplace = 12.3;
final double betaLaplace = 5.6;
add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(unusedRng, muLaplace, betaLaplace),
RandomSource.MWC_256.create());
// Levy ("inverse method").
final double muLevy = -1.098;
final double cLevy = 0.76;
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy),
RandomSource.TWO_CMRES.create());
// Levy sampler
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy),
LevySampler.of(RandomSource.JSF_64.create(), muLevy, cLevy));
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, 0.0, 1.0),
LevySampler.of(RandomSource.JSF_64.create(), 0.0, 1.0));
// Log normal ("inverse method").
final double muLogNormal = 2.345;
final double sigmaLogNormal = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
RandomSource.KISS.create());
// Log-normal (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
new BoxMullerLogNormalSampler(RandomSource.XOR_SHIFT_1024_S_PHI.create(), muLogNormal, sigmaLogNormal));
// Log-normal ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new BoxMullerNormalizedGaussianSampler(RandomSource.XOR_SHIFT_1024_S_PHI.create()),
muLogNormal, sigmaLogNormal));
// Log-normal ("Marsaglia").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new MarsagliaNormalizedGaussianSampler(RandomSource.MT_64.create()),
muLogNormal, sigmaLogNormal));
// Log-normal ("Ziggurat").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MWC_256.create()),
muLogNormal, sigmaLogNormal));
// Log-normal negative mean
final double muLogNormal2 = -1.1;
final double sigmaLogNormal2 = 2.3;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal2, sigmaLogNormal2),
LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MWC_256.create()),
muLogNormal2, sigmaLogNormal2));
// Logistic ("inverse method").
final double muLogistic = -123.456;
final double sLogistic = 7.89;
add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(unusedRng, muLogistic, sLogistic),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 2, 6));
// Nakagami ("inverse method").
final double muNakagami = 78.9;
final double omegaNakagami = 23.4;
final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY;
add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(unusedRng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 5, 3));
// Pareto ("inverse method").
final double scalePareto = 23.45;
final double shapePareto = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 9, 11));
// Pareto.
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto),
InverseTransformParetoSampler.of(RandomSource.XOR_SHIFT_1024_S_PHI.create(), scalePareto, shapePareto));
// Stable distributions.
// Gaussian case: alpha=2
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 0, Math.sqrt(2)),
StableSampler.of(RandomSource.MSWS.create(), 2, 0));
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 3.4, 0.75 * Math.sqrt(2)),
StableSampler.of(RandomSource.MSWS.create(), 2, 0, 0.75, 3.4));
// Cauchy case: alpha=1, beta=0, gamma=2.73, delta=0.87
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, 0.87, 2.73),
StableSampler.of(RandomSource.KISS.create(), 1, 0, 2.73, 0.87));
// Levy case: alpha=0.5, beta=0, gamma=5.7, delta=-1.23
// The 0-parameterization requires the reference distribution (1-parameterization) is shifted:
// S0(Z) = S1(Z) + gamma * beta * tan(pi * alpha / 2); gamma = 5.7, beta = -1, alpha = 0.5
// = gamma * -1 * tan(pi/4) = -gamma
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.23 - 5.7, 5.7),
StableSampler.of(RandomSource.JSF_64.create(), 0.5, 1.0, 5.7, -1.23));
// Levy case: alpha=0.5, beta=0.
// The 0-parameterization requires the reference distribution is shifted by -tan(pi/4) = -1
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.0, 1.0),
StableSampler.of(RandomSource.JSF_64.create(), 0.5, 1.0, 1.0, 0.0));
// No Stable distribution in Commons Math: Deciles computed using Nolan's STABLE program:
// https://edspace.american.edu/jpnolan/stable/
// General case (alpha > 1): alpha=1.3, beta=0.4, gamma=1.5, delta=-6.4
add(LIST, new double[] {-8.95069776039550, -7.89186827865320, -7.25070352695719, -6.71497820795024,
-6.19542020516881, -5.63245847779003, -4.94643432673952, -3.95462242999135,
-1.90020994991840, Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.JSF_64.create(), 1.3, 0.4, 1.5, -6.4));
// General case (alpha < 1): alpha=0.8, beta=-0.3, gamma=0.75, delta=3.25
add(LIST, new double[] {-1.60557902637291, 1.45715153372767, 2.39577970333297, 2.86274746879986,
3.15907259287483, 3.38633464572309, 3.60858199662215, 3.96001854555454, 5.16261950198042,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PP.create(), 0.8, -0.3, 0.75, 3.25));
// Alpha 1 case: alpha=1.0, beta=0.3
add(LIST, new double[] {-2.08189340389400, -0.990511737972781, -0.539025554211755, -0.204710171216492,
0.120388569770401, 0.497197960523146, 1.01228394387185, 1.89061920660563, 4.20559140293206,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_SS.create(), 1.0, 0.3));
// Symmetric case (beta=0): alpha=1.3, beta=0.0
add(LIST, new double[] {-2.29713832179280, -1.26781259700375, -0.739212223404616, -0.346771353386198,
0.00000000000000, 0.346771353386198, 0.739212223404616, 1.26781259700376, 2.29713832179280,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PLUS.create(), 1.3, 0.0));
// This is the smallest alpha where the CDF can be reliably computed.
// Small alpha case: alpha=0.1, beta=-0.2
add(LIST, new double[] {-14345498.0855558, -4841.68845914421, -22.6430159400915, -0.194461655962062,
0.299822962206354E-1, 0.316768853375197E-1, 0.519382255860847E-1, 21.8595769961580,
147637.033822552, Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PLUS.create(), 0.1, -0.2));
// T ("inverse method").
final double dofT = 0.76543;
add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT),
RandomSource.ISAAC.create());
// Triangular ("inverse method").
final double aTriangle = -0.76543;
final double cTriangle = -0.65432;
final double bTriangle = -0.54321;
add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(unusedRng, aTriangle, cTriangle, bTriangle),
RandomSource.MT.create());
// Uniform ("inverse method").
final double loUniform = -1.098;
final double hiUniform = 0.76;
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform),
RandomSource.TWO_CMRES.create());
// Uniform.
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform),
ContinuousUniformSampler.of(RandomSource.MT_64.create(), loUniform, hiUniform));
// Weibull ("inverse method").
final double alphaWeibull = 678.9;
final double betaWeibull = 98.76;
add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(unusedRng, alphaWeibull, betaWeibull),
RandomSource.WELL_44497_B.create());
} catch (Exception e) {
// CHECKSTYLE: stop Regexp
System.err.println("Unexpected exception while creating the list of samplers: " + e);
e.printStackTrace(System.err);
// CHECKSTYLE: resume Regexp
throw new RuntimeException(e);
}
}
/**
* Class contains only static methods.
*/
private ContinuousSamplersList() {}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param rng Generator of uniformly distributed sequences.
*/
private static void add(List<ContinuousSamplerTestData> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
UniformRandomProvider rng) {
final ContinuousSampler inverseMethodSampler =
InverseTransformContinuousSampler.of(rng,
new ContinuousInverseCumulativeProbabilityFunction() {
@Override
public double inverseCumulativeProbability(double p) {
return dist.inverseCumulativeProbability(p);
}
@Override
public String toString() {
return dist.toString();
}
});
list.add(new ContinuousSamplerTestData(inverseMethodSampler,
getDeciles(dist)));
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData(sampler,
getDeciles(dist)));
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param deciles Deciles of the given distribution.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData> list,
final double[] deciles,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData(sampler,
deciles));
}
/**
* Subclasses that are "parametric" tests can forward the call to
* the "@Parameters"-annotated method to this method.
*
* @return the list of all generators.
*/
public static Iterable<ContinuousSamplerTestData> list() {
return Collections.unmodifiableList(LIST);
}
/**
* @param dist Distribution.
* @return the deciles of the given distribution.
*/
private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) {
final int last = 9;
final double[] deciles = new double[last];
final double ten = 10;
for (int i = 0; i < last; i++) {
deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten);
}
return deciles;
}
}
| armanbilge/commons-rng | commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java | 6,162 | // Gumbel ("inverse method"). | line_comment | nl | /*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.rng.sampling.distribution;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
/**
* List of samplers.
*/
public final class ContinuousSamplersList {
/** List of all RNGs implemented in the library. */
private static final List<ContinuousSamplerTestData> LIST = new ArrayList<>();
static {
try {
// This test uses reference distributions from commons-math3 to compute the expected
// PMF. These distributions have a dual functionality to compute the PMF and perform
// sampling. When no sampling is needed for the created distribution, it is advised
// to pass null as the random generator via the appropriate constructors to avoid the
// additional initialisation overhead.
org.apache.commons.math3.random.RandomGenerator unusedRng = null;
// List of distributions to test.
// Gaussian ("inverse method").
final double meanNormal = -123.45;
final double sigmaNormal = 6.789;
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
RandomSource.KISS.create());
// Gaussian (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
new BoxMullerGaussianSampler(RandomSource.MT.create(), meanNormal, sigmaNormal));
// Gaussian ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new BoxMullerNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Marsaglia").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new MarsagliaNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Ziggurat").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Gaussian ("Modified ziggurat").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal),
GaussianSampler.of(ZigguratSampler.NormalizedGaussian.of(RandomSource.MT.create()),
meanNormal, sigmaNormal));
// Beta ("inverse method").
final double alphaBeta = 4.3;
final double betaBeta = 2.1;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta),
RandomSource.ISAAC.create());
// Beta ("Cheng").
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta),
ChengBetaSampler.of(RandomSource.MWC_256.create(), alphaBeta, betaBeta));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBeta, alphaBeta),
ChengBetaSampler.of(RandomSource.WELL_19937_A.create(), betaBeta, alphaBeta));
// Beta ("Cheng", alternate algorithm).
final double alphaBetaAlt = 0.5678;
final double betaBetaAlt = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBetaAlt, betaBetaAlt),
ChengBetaSampler.of(RandomSource.WELL_512_A.create(), alphaBetaAlt, betaBetaAlt));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBetaAlt, alphaBetaAlt),
ChengBetaSampler.of(RandomSource.WELL_19937_C.create(), betaBetaAlt, alphaBetaAlt));
// Cauchy ("inverse method").
final double medianCauchy = 0.123;
final double scaleCauchy = 4.5;
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, medianCauchy, scaleCauchy),
RandomSource.WELL_19937_C.create());
// Chi-square ("inverse method").
final int dofChi2 = 12;
add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(unusedRng, dofChi2),
RandomSource.WELL_19937_A.create());
// Exponential ("inverse method").
final double meanExp = 3.45;
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
RandomSource.WELL_44497_A.create());
// Exponential.
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
AhrensDieterExponentialSampler.of(RandomSource.MT.create(), meanExp));
// Exponential ("Modified ziggurat").
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp),
ZigguratSampler.Exponential.of(RandomSource.XO_RO_SHI_RO_128_SS.create(), meanExp));
// F ("inverse method").
final int numDofF = 4;
final int denomDofF = 7;
add(LIST, new org.apache.commons.math3.distribution.FDistribution(unusedRng, numDofF, denomDofF),
RandomSource.MT_64.create());
// Gamma ("inverse method").
final double alphaGammaSmallerThanOne = 0.1234;
final double alphaGammaLargerThanOne = 2.345;
final double thetaGamma = 3.456;
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma),
RandomSource.SPLIT_MIX_64.create());
// Gamma (alpha < 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaSmallerThanOne, thetaGamma),
AhrensDieterMarsagliaTsangGammaSampler.of(RandomSource.XOR_SHIFT_1024_S_PHI.create(),
alphaGammaSmallerThanOne, thetaGamma));
// Gamma (alpha > 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, alphaGammaLargerThanOne, thetaGamma),
AhrensDieterMarsagliaTsangGammaSampler.of(RandomSource.WELL_44497_B.create(),
alphaGammaLargerThanOne, thetaGamma));
// Gumbel ("inverse<SUF>
final double muGumbel = -4.56;
final double betaGumbel = 0.123;
add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(unusedRng, muGumbel, betaGumbel),
RandomSource.WELL_1024_A.create());
// Laplace ("inverse method").
final double muLaplace = 12.3;
final double betaLaplace = 5.6;
add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(unusedRng, muLaplace, betaLaplace),
RandomSource.MWC_256.create());
// Levy ("inverse method").
final double muLevy = -1.098;
final double cLevy = 0.76;
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy),
RandomSource.TWO_CMRES.create());
// Levy sampler
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy),
LevySampler.of(RandomSource.JSF_64.create(), muLevy, cLevy));
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, 0.0, 1.0),
LevySampler.of(RandomSource.JSF_64.create(), 0.0, 1.0));
// Log normal ("inverse method").
final double muLogNormal = 2.345;
final double sigmaLogNormal = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
RandomSource.KISS.create());
// Log-normal (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
new BoxMullerLogNormalSampler(RandomSource.XOR_SHIFT_1024_S_PHI.create(), muLogNormal, sigmaLogNormal));
// Log-normal ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new BoxMullerNormalizedGaussianSampler(RandomSource.XOR_SHIFT_1024_S_PHI.create()),
muLogNormal, sigmaLogNormal));
// Log-normal ("Marsaglia").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new MarsagliaNormalizedGaussianSampler(RandomSource.MT_64.create()),
muLogNormal, sigmaLogNormal));
// Log-normal ("Ziggurat").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal, sigmaLogNormal),
LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MWC_256.create()),
muLogNormal, sigmaLogNormal));
// Log-normal negative mean
final double muLogNormal2 = -1.1;
final double sigmaLogNormal2 = 2.3;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, muLogNormal2, sigmaLogNormal2),
LogNormalSampler.of(new ZigguratNormalizedGaussianSampler(RandomSource.MWC_256.create()),
muLogNormal2, sigmaLogNormal2));
// Logistic ("inverse method").
final double muLogistic = -123.456;
final double sLogistic = 7.89;
add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(unusedRng, muLogistic, sLogistic),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 2, 6));
// Nakagami ("inverse method").
final double muNakagami = 78.9;
final double omegaNakagami = 23.4;
final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY;
add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(unusedRng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 5, 3));
// Pareto ("inverse method").
final double scalePareto = 23.45;
final double shapePareto = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto),
RandomSource.TWO_CMRES_SELECT.create((Object) null, 9, 11));
// Pareto.
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto),
InverseTransformParetoSampler.of(RandomSource.XOR_SHIFT_1024_S_PHI.create(), scalePareto, shapePareto));
// Stable distributions.
// Gaussian case: alpha=2
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 0, Math.sqrt(2)),
StableSampler.of(RandomSource.MSWS.create(), 2, 0));
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, 3.4, 0.75 * Math.sqrt(2)),
StableSampler.of(RandomSource.MSWS.create(), 2, 0, 0.75, 3.4));
// Cauchy case: alpha=1, beta=0, gamma=2.73, delta=0.87
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, 0.87, 2.73),
StableSampler.of(RandomSource.KISS.create(), 1, 0, 2.73, 0.87));
// Levy case: alpha=0.5, beta=0, gamma=5.7, delta=-1.23
// The 0-parameterization requires the reference distribution (1-parameterization) is shifted:
// S0(Z) = S1(Z) + gamma * beta * tan(pi * alpha / 2); gamma = 5.7, beta = -1, alpha = 0.5
// = gamma * -1 * tan(pi/4) = -gamma
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.23 - 5.7, 5.7),
StableSampler.of(RandomSource.JSF_64.create(), 0.5, 1.0, 5.7, -1.23));
// Levy case: alpha=0.5, beta=0.
// The 0-parameterization requires the reference distribution is shifted by -tan(pi/4) = -1
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, -1.0, 1.0),
StableSampler.of(RandomSource.JSF_64.create(), 0.5, 1.0, 1.0, 0.0));
// No Stable distribution in Commons Math: Deciles computed using Nolan's STABLE program:
// https://edspace.american.edu/jpnolan/stable/
// General case (alpha > 1): alpha=1.3, beta=0.4, gamma=1.5, delta=-6.4
add(LIST, new double[] {-8.95069776039550, -7.89186827865320, -7.25070352695719, -6.71497820795024,
-6.19542020516881, -5.63245847779003, -4.94643432673952, -3.95462242999135,
-1.90020994991840, Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.JSF_64.create(), 1.3, 0.4, 1.5, -6.4));
// General case (alpha < 1): alpha=0.8, beta=-0.3, gamma=0.75, delta=3.25
add(LIST, new double[] {-1.60557902637291, 1.45715153372767, 2.39577970333297, 2.86274746879986,
3.15907259287483, 3.38633464572309, 3.60858199662215, 3.96001854555454, 5.16261950198042,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PP.create(), 0.8, -0.3, 0.75, 3.25));
// Alpha 1 case: alpha=1.0, beta=0.3
add(LIST, new double[] {-2.08189340389400, -0.990511737972781, -0.539025554211755, -0.204710171216492,
0.120388569770401, 0.497197960523146, 1.01228394387185, 1.89061920660563, 4.20559140293206,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_SS.create(), 1.0, 0.3));
// Symmetric case (beta=0): alpha=1.3, beta=0.0
add(LIST, new double[] {-2.29713832179280, -1.26781259700375, -0.739212223404616, -0.346771353386198,
0.00000000000000, 0.346771353386198, 0.739212223404616, 1.26781259700376, 2.29713832179280,
Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PLUS.create(), 1.3, 0.0));
// This is the smallest alpha where the CDF can be reliably computed.
// Small alpha case: alpha=0.1, beta=-0.2
add(LIST, new double[] {-14345498.0855558, -4841.68845914421, -22.6430159400915, -0.194461655962062,
0.299822962206354E-1, 0.316768853375197E-1, 0.519382255860847E-1, 21.8595769961580,
147637.033822552, Double.POSITIVE_INFINITY},
StableSampler.of(RandomSource.XO_SHI_RO_512_PLUS.create(), 0.1, -0.2));
// T ("inverse method").
final double dofT = 0.76543;
add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT),
RandomSource.ISAAC.create());
// Triangular ("inverse method").
final double aTriangle = -0.76543;
final double cTriangle = -0.65432;
final double bTriangle = -0.54321;
add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(unusedRng, aTriangle, cTriangle, bTriangle),
RandomSource.MT.create());
// Uniform ("inverse method").
final double loUniform = -1.098;
final double hiUniform = 0.76;
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform),
RandomSource.TWO_CMRES.create());
// Uniform.
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform),
ContinuousUniformSampler.of(RandomSource.MT_64.create(), loUniform, hiUniform));
// Weibull ("inverse method").
final double alphaWeibull = 678.9;
final double betaWeibull = 98.76;
add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(unusedRng, alphaWeibull, betaWeibull),
RandomSource.WELL_44497_B.create());
} catch (Exception e) {
// CHECKSTYLE: stop Regexp
System.err.println("Unexpected exception while creating the list of samplers: " + e);
e.printStackTrace(System.err);
// CHECKSTYLE: resume Regexp
throw new RuntimeException(e);
}
}
/**
* Class contains only static methods.
*/
private ContinuousSamplersList() {}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param rng Generator of uniformly distributed sequences.
*/
private static void add(List<ContinuousSamplerTestData> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
UniformRandomProvider rng) {
final ContinuousSampler inverseMethodSampler =
InverseTransformContinuousSampler.of(rng,
new ContinuousInverseCumulativeProbabilityFunction() {
@Override
public double inverseCumulativeProbability(double p) {
return dist.inverseCumulativeProbability(p);
}
@Override
public String toString() {
return dist.toString();
}
});
list.add(new ContinuousSamplerTestData(inverseMethodSampler,
getDeciles(dist)));
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData(sampler,
getDeciles(dist)));
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param deciles Deciles of the given distribution.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData> list,
final double[] deciles,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData(sampler,
deciles));
}
/**
* Subclasses that are "parametric" tests can forward the call to
* the "@Parameters"-annotated method to this method.
*
* @return the list of all generators.
*/
public static Iterable<ContinuousSamplerTestData> list() {
return Collections.unmodifiableList(LIST);
}
/**
* @param dist Distribution.
* @return the deciles of the given distribution.
*/
private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) {
final int last = 9;
final double[] deciles = new double[last];
final double ten = 10;
for (int i = 0; i < last; i++) {
deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten);
}
return deciles;
}
}
|
8797_9 | /**
* Dies ist ein Git-Test!
*/
package org.exmaralda.coma.root;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.prefs.Preferences;
import org.exmaralda.coma.datatypes.ComaDatatype;
import org.exmaralda.coma.datatypes.ComaTemplate;
import org.exmaralda.coma.filters.ComaFilter;
import org.exmaralda.coma.helpers.ComaTemplates;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
/** @author woerner */
public class ComaData {
private static final int MAX_RECENT_FILES = 5;
public static final String[] TRANSCRIPTION_FORMATS = new String[] { "xml",
"exb", "exs", "tei", "exa" };
public static Preferences prefs = Ui.prefs;
HashMap<String, ComaTemplate> oldTemplates;
private HashSet<Element> basket;
private HashSet<String> roleTypes;
private HashMap<String, ComaFilter> cfilters;
private HashMap<String, ComaFilter> pfilters;
private HashMap<String, ComaFilter> cFilterPresets;
private HashMap<String, ComaFilter> sFilterPresets;
private HashMap<String, String> hiddenKeys;
private Vector<File> recentFiles;
// private Element selectedCorpus;
String defaultTemplateName = "";
private Element dataElement;
private Document document;
private Element rootElement;
private File openFile = new File("");
private String uniqueSpeakerDistinction;
private int schemaVersion = 0;
private ComaTemplates templates;
private File templateFile;
private String searchTerm;
private HashMap<String, Element> selectedCommunications = new HashMap<String, Element>();
private HashMap<String, Element> selectedPersons = new HashMap<String, Element>();
// waren Element-Vektoren
private Coma coma;
private String filterChanged;
public ComaData(Coma c) {
coma = c;
oldTemplates = new HashMap<String, ComaTemplate>();
basket = new HashSet<Element>();
cfilters = new HashMap<String, ComaFilter>();
pfilters = new HashMap<String, ComaFilter>();
templates = new ComaTemplates();
uniqueSpeakerDistinction = "";
openFile = new File("");
initPresets();
createRecentFiles();
}
private void initPresets() {
cFilterPresets = new HashMap<String, ComaFilter>();
cFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter(
coma, "//Corpus/CorpusData/Communication[1>0]"));
cFilterPresets
.put(Ui.getText("filter.commsWithTranscriptions"),
new ComaFilter(coma,
"//Corpus/CorpusData/Communication[count(Transcription)>0]"));
cFilterPresets
.put(Ui.getText("filter.commsWithRecordings"), new ComaFilter(
coma,
"//Corpus/CorpusData/Communication[count(Recording)>0]"));
sFilterPresets = new HashMap<String, ComaFilter>();
sFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter(
coma, "//Corpus/CorpusData/Speaker[1>0]"));
}
private void createRecentFiles() {
recentFiles = new Vector<File>();
String allFiles = prefs.get("recentFiles", "");
String[] files = allFiles.split("\n");
for (String s : files) {
if (s.length() > 0) {
if (recentFiles.size() < MAX_RECENT_FILES) {
recentFiles.add(new File(s));
}
}
}
}
// RECENT FILES (moved from coma.helpers.RecentFiles.java)
public Vector<File> getRecentFiles() {
return recentFiles;
}
public void removeRecentFile(File f) {
recentFiles.remove(f);
recentFilesChanged();
}
private void recentFilesChanged() {
String filesString = "";
for (File f : recentFiles) {
filesString += f.getAbsolutePath() + "\n";
}
prefs.put("recentFiles", filesString);
}
public void clearRecentFiles() {
recentFiles.clear();
recentFilesChanged();
}
private void setRecentFile(File f) {
if (f != null)
if (f.exists()) {
prefs.put("recentDir", f.getParent());
if (recentFiles.contains(f)) {
recentFiles.remove(f);
}
recentFiles.add(0, f);
}
if (recentFiles.size() > MAX_RECENT_FILES) {
recentFiles.remove(recentFiles.size() - 1);
}
recentFilesChanged();
}
// templates for description-panels
public ComaTemplates getTemplates() {
return templates;
}
public void setDefaultTemplateName(String t) {
if (oldTemplates.containsKey(t))
defaultTemplateName = t;
}
public ComaTemplate getTemplate(String s) {
String key = (s == null ? defaultTemplateName : s);
return oldTemplates.get(key);
}
/**
* @param text
* @param keys
*/
public void addTemplate(String name, Vector<String> keys) {
oldTemplates.put(name, new ComaTemplate(name, null, keys));
}
public HashMap<String, ComaFilter> getCfilters() {
return cfilters;
}
public void setCfilters(HashMap<String, ComaFilter> cfilters) {
this.cfilters = cfilters;
}
public HashMap<String, ComaFilter> getPfilters() {
return pfilters;
}
public void addRawCFilter(String xpath) {
ComaFilter filter = new ComaFilter(coma, xpath);
cfilters.put(filter.getXPath(), filter);
}
public void addRawPFilter(String xpath) {
ComaFilter filter = new ComaFilter(coma, xpath);
pfilters.put(filter.getXPath(), filter);
}
public void addcfilter(String xpath) {
String newXPath = xpath.substring(0,
xpath.indexOf("Communication") + 13)
+ "["
+ xpath.substring((xpath.indexOf("Communication") + 14)) + "]";
System.out.println("-->" + newXPath);
ComaFilter filter = new ComaFilter(coma, (newXPath));
cfilters.put(filter.getXPath(), filter);
}
public void addpfilter(String xpath) {
String newXPath = xpath.substring(0, xpath.indexOf("Speaker") + 7)
+ "[" + xpath.substring((xpath.indexOf("Speaker") + 8)) + "]";
ComaFilter filter = new ComaFilter(coma, (newXPath));
pfilters.put(filter.getXPath(), filter);
}
public void removepfilter(String xpath) {
if (xpath == null) {
pfilters.clear();
} else {
pfilters.remove(xpath);
}
}
public void removecfilter(String xpath) {
if (xpath == null) {
cfilters.clear();
} else {
cfilters.remove(xpath);
}
}
public void removeSearchFilters() {
for (String xp : cfilters.keySet()) {
if (xp.contains(searchTerm)) {
removecfilter(xp);
}
}
for (String xp : pfilters.keySet()) {
if (xp.contains(searchTerm)) {
removepfilter(xp);
}
}
}
/** @param string */
/**
* Returns a java.util.list of Communications for a Speaker
*
* @param speakerElmt
* @return
*/
public HashSet<String> getSpeakerIDs(Vector<Element> speakers) {
HashSet<String> ids = new HashSet<String>();
for (Element speaker : speakers) {
ids.add(speaker.getAttributeValue("Id"));
}
return ids;
}
/**
* Returns a java.util.list of Communications for a Speaker
*
* @param speakerElmt
* @return
*/
public List<Element> getCommunicationsForSpeaker(Element speakerElmt,
boolean filtered) {
HashSet<Element> commlist = new HashSet<Element>();
String speakerId = speakerElmt.getAttributeValue("Id");
List<Element> allComms = (filtered ? filterComms() : dataElement
.getChildren("Communication"));
for (Element el : allComms) {
List<Element> spks = el.getChild("Setting").getChildren("Person");
HashMap<String, Element> spkTmp = new HashMap<String, Element>();
for (Element sp : spks) {
if (sp.getText().equals(speakerId)) {
commlist.add(el);
}
}
}
return (new Vector<Element>(commlist).subList(0, commlist.size()));
// return List.(commList);
}
public List<Element> filterComms() {
List<Element> allComms = dataElement.getChildren("Communication");
Vector<Element> independentList = new Vector<Element>();
independentList.addAll(allComms);
int fcount = 0;
for (ComaFilter filter : getCfilters().values()) {
if (filter.isEnabled()) {
try {
XPath xp = XPath.newInstance(filter.isInverted() ? filter
.getXPathInverted() : filter.getXPath());
List nl = xp.selectNodes(dataElement);
if ((filter.isIncluding()) && (fcount > 0)) {
independentList.addAll(nl);
} else {
independentList.retainAll(nl);
}
} catch (JDOMException err) {
err.printStackTrace();
}
}
fcount++;
}
return independentList;
}
public List<Element> filterSpeakers() {
List<Element> allComms = dataElement.getChildren("Speaker");
Vector<Element> independentList = new Vector<Element>();
independentList.addAll(allComms);
int fcount = 0;
for (ComaFilter filter : getPfilters().values()) {
if (filter.isEnabled()) {
try {
XPath xp = XPath.newInstance(filter.isInverted() ? filter
.getXPathInverted() : filter.getXPath());
List nl = xp.selectNodes(dataElement);
if ((filter.isIncluding()) && (fcount > 0)) {
independentList.addAll(nl);
} else {
independentList.retainAll(nl);
}
} catch (JDOMException err) {
err.printStackTrace();
}
}
fcount++;
}
return independentList;
}
public HashMap<String, Element> getAssignedSpeakers(
Element communicationElement) {
HashMap<String, Element> spks = new HashMap<String, Element>();
XPath idx;
try {
idx = XPath.newInstance("//Speaker[role/@target='"
+ communicationElement.getAttributeValue("Id") + "']");
List<Element> roleElements = idx.selectNodes(getDataElement());
for (Element e : roleElements) {
spks.put(e.getAttributeValue("Id"), e);
}
} catch (JDOMException err) {
err.printStackTrace();
}
return spks;
}
/** @param elmt */
// public void setSelectedCorpus(Element elmt) {
// selectedCorpus = elmt;
// dataElement = selectedCorpus.getChild("CorpusData");
// }
public Element getDataElement() {
return dataElement;
}
// public Element getSelectedCorpus() {
// return selectedCorpus;
// }
/**
* sets all communication-filters inactive so a new communication gets
* displayed in any case
*/
public void disableCommFilters() {
for (ComaFilter f : getCfilters().values()) {
f.setEnabled(false);
}
}
/**
* sets all speaker-filters inactive so a new communication gets displayed
* in any case
*/
public void disableSpeakerFilters() {
for (ComaFilter f : getPfilters().values()) {
f.setEnabled(false);
}
}
/** @return */
public String getUniqueSpeakerDistinction() {
return uniqueSpeakerDistinction;
}
/** @param attributeValue */
public void setUniqueSpeakerDistinction(String attributeValue) {
uniqueSpeakerDistinction = attributeValue;
}
/** @param e */
public void setDataElement(Element e) {
dataElement = e;
}
public File getOpenFile() {
return (openFile == null) ? new File("") : openFile;
}
public void setOpenFile(File openFile) {
this.openFile = openFile;
setRecentFile(openFile);
}
/** @param selectedFile */
public void setTemplateFile(File f) {
templates.setFile(f);
templateFile = f;
}
// public String getSelectedCorpusName() {
// return ((getSelectedCorpus() == null)
// ? "no corpus selected"
// : getSelectedCorpus().getAttributeValue("Name"));
// }
public Element getRootElement() {
return document.getRootElement();
}
public Document getDocument() {
return document;
}
public void setDocument(Document d) {
document = d;
setSchemaVersion(0);
}
public HashMap<String, String> getHiddenKeys() {
if (hiddenKeys == null) {
hiddenKeys = new HashMap<String, String>();
if (getRootElement().getChildren("coma").size() > 0) {
for (Element e : (List<Element>) getRootElement()
.getChild("coma").getChild("hidden").getChildren()) {
hiddenKeys.put(e.getAttributeValue("Name"), e.getValue());
}
}
}
return hiddenKeys;
}
public void setRootElement(Element re) {
document.setRootElement(re);
}
public String getCorpusName() {
return document.getRootElement().getAttributeValue("Name");
}
public void removeSubcorpora() {
System.out.print("removing subcorpora...");
XPath spx;
Document newDoc = new Document();
Element cd = new Element("CorpusData");
newDoc.setRootElement(new Element("Corpus").addContent(cd));
newDoc.getRootElement().addContent(new Element("Description"));
for (Attribute a : (List<Attribute>) getRootElement().getAttributes()) {
newDoc.getRootElement().setAttribute(a.getName(), a.getValue());
}
if (getRootElement().getChild("Description") != null) {
for (Element delm : (List<Element>) getRootElement().getChild(
"Description").getChildren()) {
Element dk = new Element("Key");
dk.setAttribute("Name", delm.getAttributeValue("Name"));
dk.setText(delm.getText());
newDoc.getRootElement().getChild("Description").addContent(dk);
}
}
try {
XPath xpsc = XPath.newInstance("//Communication|//Speaker");
List<Element> elements = xpsc.selectNodes(getRootElement());
for (Element sce : elements) {
if (sce.getChild("Description") == null) {
sce.addContent(new Element("Description"));
}
Element d = sce.getChild("Description");
d.addContent(new Element("Key").setAttribute("Name",
"@Coma-Corpus").setText(
sce.getParentElement().getParentElement()
.getAttributeValue("Name")));
cd.addContent((Element) sce.clone());
}
document = newDoc;
System.out.println("removed.");
// setRootElement(newDoc.getRootElement());
} catch (JDOMException e) {
System.out.println("failed.");
}
}
public void addSpeakers(HashSet<Element> speakers) {
for (Element e : speakers) {
dataElement.addContent((Element) e.clone());
}
}
public String getSearchTerm() {
if ((cfilters.size()) + (pfilters.size()) > 0) {
return searchTerm;
} else {
return "";
}
}
public void setSearchTerm(String text) {
searchTerm = text;
// TODO Auto-generated method stub
}
/*
* clears the basket
*/
public void clearBasket() {
basket.clear();
}
/*
* adds a transcription to the basket
*/
public void addToBasket(Element transcription) {
basket.add(transcription);
}
public HashSet<Element> getBasket() {
return basket;
}
//
// public void setSelectedCommunications(Vector<Element>
// selectedCommunications) {
// this.selectedCommunications = selectedCommunications;
// }
public HashMap<String, Element> getSelectedCommunications() {
return selectedCommunications;
}
// public void setSelectedPersons(Vector<Element> selectedPersons) {
// this.selectedPersons = selectedPersons;
// }
public HashMap<String, Element> getSelectedPersons() {
return selectedPersons;
}
public Element getElementById(String target) {
XPath xp;
try {
xp = XPath.newInstance("//.[@Id=\"" + target + "\"]");
// System.out.println("XPath:" + ".[@Id=\"" + target + "\"]");
// System.out.println("FOUND "
// + ((Element) xp.selectSingleNode(dataElement)));
return (Element) xp.selectSingleNode(dataElement);
} catch (JDOMException e) {
e.printStackTrace();
}
return null;
}
public void setcFilterPresets(HashMap<String, ComaFilter> cFilterPresets) {
this.cFilterPresets = cFilterPresets;
}
public HashMap<String, ComaFilter> getcFilterPresets() {
System.out.println(cFilterPresets.size());
return cFilterPresets;
}
public void setsFilterPresets(HashMap<String, ComaFilter> sFilterPresets) {
this.sFilterPresets = sFilterPresets;
}
public HashMap<String, ComaFilter> getsFilterPresets() {
System.out.println(sFilterPresets.size());
return sFilterPresets;
}
public void setSchemaVersion(int schemaVersion) {
this.schemaVersion = schemaVersion;
}
public void setSchemaVersion(String versionString) {
this.schemaVersion = new Integer(versionString);
}
public int getSchemaVersion() {
return schemaVersion;
}
public Set<String> getCommIdsForSelectedSpeakers() {
HashSet<String> ids = new HashSet<String>();
for (String s : selectedPersons.keySet()) {
Element person = selectedPersons.get(s);
if (person.getChild("role") != null) {
for (Element role : (List<Element>) person.getChildren("role")) {
ids.add(role.getAttributeValue("target"));
}
}
}
return ids;
}
public String getSelectedCorpusName() {
return getCorpusName();
}
public HashSet<String> getRoleTypes() {
return roleTypes;
}
public void setRoleTypes(HashSet<String> roleTypes) {
this.roleTypes = roleTypes;
}
public HashSet<String> addRoleType(String rt) {
if (roleTypes == null) {
roleTypes = new HashSet<String>();
}
roleTypes.add(rt);
return roleTypes;
}
public void setFilterChanged(String string) {
filterChanged=string;
}
public String getFilterChanged() {
return filterChanged;
}
}
| upconsulting/exmaralda | src/org/exmaralda/coma/root/ComaData.java | 4,962 | // dataElement = selectedCorpus.getChild("CorpusData"); | line_comment | nl | /**
* Dies ist ein Git-Test!
*/
package org.exmaralda.coma.root;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.prefs.Preferences;
import org.exmaralda.coma.datatypes.ComaDatatype;
import org.exmaralda.coma.datatypes.ComaTemplate;
import org.exmaralda.coma.filters.ComaFilter;
import org.exmaralda.coma.helpers.ComaTemplates;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
/** @author woerner */
public class ComaData {
private static final int MAX_RECENT_FILES = 5;
public static final String[] TRANSCRIPTION_FORMATS = new String[] { "xml",
"exb", "exs", "tei", "exa" };
public static Preferences prefs = Ui.prefs;
HashMap<String, ComaTemplate> oldTemplates;
private HashSet<Element> basket;
private HashSet<String> roleTypes;
private HashMap<String, ComaFilter> cfilters;
private HashMap<String, ComaFilter> pfilters;
private HashMap<String, ComaFilter> cFilterPresets;
private HashMap<String, ComaFilter> sFilterPresets;
private HashMap<String, String> hiddenKeys;
private Vector<File> recentFiles;
// private Element selectedCorpus;
String defaultTemplateName = "";
private Element dataElement;
private Document document;
private Element rootElement;
private File openFile = new File("");
private String uniqueSpeakerDistinction;
private int schemaVersion = 0;
private ComaTemplates templates;
private File templateFile;
private String searchTerm;
private HashMap<String, Element> selectedCommunications = new HashMap<String, Element>();
private HashMap<String, Element> selectedPersons = new HashMap<String, Element>();
// waren Element-Vektoren
private Coma coma;
private String filterChanged;
public ComaData(Coma c) {
coma = c;
oldTemplates = new HashMap<String, ComaTemplate>();
basket = new HashSet<Element>();
cfilters = new HashMap<String, ComaFilter>();
pfilters = new HashMap<String, ComaFilter>();
templates = new ComaTemplates();
uniqueSpeakerDistinction = "";
openFile = new File("");
initPresets();
createRecentFiles();
}
private void initPresets() {
cFilterPresets = new HashMap<String, ComaFilter>();
cFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter(
coma, "//Corpus/CorpusData/Communication[1>0]"));
cFilterPresets
.put(Ui.getText("filter.commsWithTranscriptions"),
new ComaFilter(coma,
"//Corpus/CorpusData/Communication[count(Transcription)>0]"));
cFilterPresets
.put(Ui.getText("filter.commsWithRecordings"), new ComaFilter(
coma,
"//Corpus/CorpusData/Communication[count(Recording)>0]"));
sFilterPresets = new HashMap<String, ComaFilter>();
sFilterPresets.put(Ui.getText("filter.emptyFilter"), new ComaFilter(
coma, "//Corpus/CorpusData/Speaker[1>0]"));
}
private void createRecentFiles() {
recentFiles = new Vector<File>();
String allFiles = prefs.get("recentFiles", "");
String[] files = allFiles.split("\n");
for (String s : files) {
if (s.length() > 0) {
if (recentFiles.size() < MAX_RECENT_FILES) {
recentFiles.add(new File(s));
}
}
}
}
// RECENT FILES (moved from coma.helpers.RecentFiles.java)
public Vector<File> getRecentFiles() {
return recentFiles;
}
public void removeRecentFile(File f) {
recentFiles.remove(f);
recentFilesChanged();
}
private void recentFilesChanged() {
String filesString = "";
for (File f : recentFiles) {
filesString += f.getAbsolutePath() + "\n";
}
prefs.put("recentFiles", filesString);
}
public void clearRecentFiles() {
recentFiles.clear();
recentFilesChanged();
}
private void setRecentFile(File f) {
if (f != null)
if (f.exists()) {
prefs.put("recentDir", f.getParent());
if (recentFiles.contains(f)) {
recentFiles.remove(f);
}
recentFiles.add(0, f);
}
if (recentFiles.size() > MAX_RECENT_FILES) {
recentFiles.remove(recentFiles.size() - 1);
}
recentFilesChanged();
}
// templates for description-panels
public ComaTemplates getTemplates() {
return templates;
}
public void setDefaultTemplateName(String t) {
if (oldTemplates.containsKey(t))
defaultTemplateName = t;
}
public ComaTemplate getTemplate(String s) {
String key = (s == null ? defaultTemplateName : s);
return oldTemplates.get(key);
}
/**
* @param text
* @param keys
*/
public void addTemplate(String name, Vector<String> keys) {
oldTemplates.put(name, new ComaTemplate(name, null, keys));
}
public HashMap<String, ComaFilter> getCfilters() {
return cfilters;
}
public void setCfilters(HashMap<String, ComaFilter> cfilters) {
this.cfilters = cfilters;
}
public HashMap<String, ComaFilter> getPfilters() {
return pfilters;
}
public void addRawCFilter(String xpath) {
ComaFilter filter = new ComaFilter(coma, xpath);
cfilters.put(filter.getXPath(), filter);
}
public void addRawPFilter(String xpath) {
ComaFilter filter = new ComaFilter(coma, xpath);
pfilters.put(filter.getXPath(), filter);
}
public void addcfilter(String xpath) {
String newXPath = xpath.substring(0,
xpath.indexOf("Communication") + 13)
+ "["
+ xpath.substring((xpath.indexOf("Communication") + 14)) + "]";
System.out.println("-->" + newXPath);
ComaFilter filter = new ComaFilter(coma, (newXPath));
cfilters.put(filter.getXPath(), filter);
}
public void addpfilter(String xpath) {
String newXPath = xpath.substring(0, xpath.indexOf("Speaker") + 7)
+ "[" + xpath.substring((xpath.indexOf("Speaker") + 8)) + "]";
ComaFilter filter = new ComaFilter(coma, (newXPath));
pfilters.put(filter.getXPath(), filter);
}
public void removepfilter(String xpath) {
if (xpath == null) {
pfilters.clear();
} else {
pfilters.remove(xpath);
}
}
public void removecfilter(String xpath) {
if (xpath == null) {
cfilters.clear();
} else {
cfilters.remove(xpath);
}
}
public void removeSearchFilters() {
for (String xp : cfilters.keySet()) {
if (xp.contains(searchTerm)) {
removecfilter(xp);
}
}
for (String xp : pfilters.keySet()) {
if (xp.contains(searchTerm)) {
removepfilter(xp);
}
}
}
/** @param string */
/**
* Returns a java.util.list of Communications for a Speaker
*
* @param speakerElmt
* @return
*/
public HashSet<String> getSpeakerIDs(Vector<Element> speakers) {
HashSet<String> ids = new HashSet<String>();
for (Element speaker : speakers) {
ids.add(speaker.getAttributeValue("Id"));
}
return ids;
}
/**
* Returns a java.util.list of Communications for a Speaker
*
* @param speakerElmt
* @return
*/
public List<Element> getCommunicationsForSpeaker(Element speakerElmt,
boolean filtered) {
HashSet<Element> commlist = new HashSet<Element>();
String speakerId = speakerElmt.getAttributeValue("Id");
List<Element> allComms = (filtered ? filterComms() : dataElement
.getChildren("Communication"));
for (Element el : allComms) {
List<Element> spks = el.getChild("Setting").getChildren("Person");
HashMap<String, Element> spkTmp = new HashMap<String, Element>();
for (Element sp : spks) {
if (sp.getText().equals(speakerId)) {
commlist.add(el);
}
}
}
return (new Vector<Element>(commlist).subList(0, commlist.size()));
// return List.(commList);
}
public List<Element> filterComms() {
List<Element> allComms = dataElement.getChildren("Communication");
Vector<Element> independentList = new Vector<Element>();
independentList.addAll(allComms);
int fcount = 0;
for (ComaFilter filter : getCfilters().values()) {
if (filter.isEnabled()) {
try {
XPath xp = XPath.newInstance(filter.isInverted() ? filter
.getXPathInverted() : filter.getXPath());
List nl = xp.selectNodes(dataElement);
if ((filter.isIncluding()) && (fcount > 0)) {
independentList.addAll(nl);
} else {
independentList.retainAll(nl);
}
} catch (JDOMException err) {
err.printStackTrace();
}
}
fcount++;
}
return independentList;
}
public List<Element> filterSpeakers() {
List<Element> allComms = dataElement.getChildren("Speaker");
Vector<Element> independentList = new Vector<Element>();
independentList.addAll(allComms);
int fcount = 0;
for (ComaFilter filter : getPfilters().values()) {
if (filter.isEnabled()) {
try {
XPath xp = XPath.newInstance(filter.isInverted() ? filter
.getXPathInverted() : filter.getXPath());
List nl = xp.selectNodes(dataElement);
if ((filter.isIncluding()) && (fcount > 0)) {
independentList.addAll(nl);
} else {
independentList.retainAll(nl);
}
} catch (JDOMException err) {
err.printStackTrace();
}
}
fcount++;
}
return independentList;
}
public HashMap<String, Element> getAssignedSpeakers(
Element communicationElement) {
HashMap<String, Element> spks = new HashMap<String, Element>();
XPath idx;
try {
idx = XPath.newInstance("//Speaker[role/@target='"
+ communicationElement.getAttributeValue("Id") + "']");
List<Element> roleElements = idx.selectNodes(getDataElement());
for (Element e : roleElements) {
spks.put(e.getAttributeValue("Id"), e);
}
} catch (JDOMException err) {
err.printStackTrace();
}
return spks;
}
/** @param elmt */
// public void setSelectedCorpus(Element elmt) {
// selectedCorpus = elmt;
// dataElement =<SUF>
// }
public Element getDataElement() {
return dataElement;
}
// public Element getSelectedCorpus() {
// return selectedCorpus;
// }
/**
* sets all communication-filters inactive so a new communication gets
* displayed in any case
*/
public void disableCommFilters() {
for (ComaFilter f : getCfilters().values()) {
f.setEnabled(false);
}
}
/**
* sets all speaker-filters inactive so a new communication gets displayed
* in any case
*/
public void disableSpeakerFilters() {
for (ComaFilter f : getPfilters().values()) {
f.setEnabled(false);
}
}
/** @return */
public String getUniqueSpeakerDistinction() {
return uniqueSpeakerDistinction;
}
/** @param attributeValue */
public void setUniqueSpeakerDistinction(String attributeValue) {
uniqueSpeakerDistinction = attributeValue;
}
/** @param e */
public void setDataElement(Element e) {
dataElement = e;
}
public File getOpenFile() {
return (openFile == null) ? new File("") : openFile;
}
public void setOpenFile(File openFile) {
this.openFile = openFile;
setRecentFile(openFile);
}
/** @param selectedFile */
public void setTemplateFile(File f) {
templates.setFile(f);
templateFile = f;
}
// public String getSelectedCorpusName() {
// return ((getSelectedCorpus() == null)
// ? "no corpus selected"
// : getSelectedCorpus().getAttributeValue("Name"));
// }
public Element getRootElement() {
return document.getRootElement();
}
public Document getDocument() {
return document;
}
public void setDocument(Document d) {
document = d;
setSchemaVersion(0);
}
public HashMap<String, String> getHiddenKeys() {
if (hiddenKeys == null) {
hiddenKeys = new HashMap<String, String>();
if (getRootElement().getChildren("coma").size() > 0) {
for (Element e : (List<Element>) getRootElement()
.getChild("coma").getChild("hidden").getChildren()) {
hiddenKeys.put(e.getAttributeValue("Name"), e.getValue());
}
}
}
return hiddenKeys;
}
public void setRootElement(Element re) {
document.setRootElement(re);
}
public String getCorpusName() {
return document.getRootElement().getAttributeValue("Name");
}
public void removeSubcorpora() {
System.out.print("removing subcorpora...");
XPath spx;
Document newDoc = new Document();
Element cd = new Element("CorpusData");
newDoc.setRootElement(new Element("Corpus").addContent(cd));
newDoc.getRootElement().addContent(new Element("Description"));
for (Attribute a : (List<Attribute>) getRootElement().getAttributes()) {
newDoc.getRootElement().setAttribute(a.getName(), a.getValue());
}
if (getRootElement().getChild("Description") != null) {
for (Element delm : (List<Element>) getRootElement().getChild(
"Description").getChildren()) {
Element dk = new Element("Key");
dk.setAttribute("Name", delm.getAttributeValue("Name"));
dk.setText(delm.getText());
newDoc.getRootElement().getChild("Description").addContent(dk);
}
}
try {
XPath xpsc = XPath.newInstance("//Communication|//Speaker");
List<Element> elements = xpsc.selectNodes(getRootElement());
for (Element sce : elements) {
if (sce.getChild("Description") == null) {
sce.addContent(new Element("Description"));
}
Element d = sce.getChild("Description");
d.addContent(new Element("Key").setAttribute("Name",
"@Coma-Corpus").setText(
sce.getParentElement().getParentElement()
.getAttributeValue("Name")));
cd.addContent((Element) sce.clone());
}
document = newDoc;
System.out.println("removed.");
// setRootElement(newDoc.getRootElement());
} catch (JDOMException e) {
System.out.println("failed.");
}
}
public void addSpeakers(HashSet<Element> speakers) {
for (Element e : speakers) {
dataElement.addContent((Element) e.clone());
}
}
public String getSearchTerm() {
if ((cfilters.size()) + (pfilters.size()) > 0) {
return searchTerm;
} else {
return "";
}
}
public void setSearchTerm(String text) {
searchTerm = text;
// TODO Auto-generated method stub
}
/*
* clears the basket
*/
public void clearBasket() {
basket.clear();
}
/*
* adds a transcription to the basket
*/
public void addToBasket(Element transcription) {
basket.add(transcription);
}
public HashSet<Element> getBasket() {
return basket;
}
//
// public void setSelectedCommunications(Vector<Element>
// selectedCommunications) {
// this.selectedCommunications = selectedCommunications;
// }
public HashMap<String, Element> getSelectedCommunications() {
return selectedCommunications;
}
// public void setSelectedPersons(Vector<Element> selectedPersons) {
// this.selectedPersons = selectedPersons;
// }
public HashMap<String, Element> getSelectedPersons() {
return selectedPersons;
}
public Element getElementById(String target) {
XPath xp;
try {
xp = XPath.newInstance("//.[@Id=\"" + target + "\"]");
// System.out.println("XPath:" + ".[@Id=\"" + target + "\"]");
// System.out.println("FOUND "
// + ((Element) xp.selectSingleNode(dataElement)));
return (Element) xp.selectSingleNode(dataElement);
} catch (JDOMException e) {
e.printStackTrace();
}
return null;
}
public void setcFilterPresets(HashMap<String, ComaFilter> cFilterPresets) {
this.cFilterPresets = cFilterPresets;
}
public HashMap<String, ComaFilter> getcFilterPresets() {
System.out.println(cFilterPresets.size());
return cFilterPresets;
}
public void setsFilterPresets(HashMap<String, ComaFilter> sFilterPresets) {
this.sFilterPresets = sFilterPresets;
}
public HashMap<String, ComaFilter> getsFilterPresets() {
System.out.println(sFilterPresets.size());
return sFilterPresets;
}
public void setSchemaVersion(int schemaVersion) {
this.schemaVersion = schemaVersion;
}
public void setSchemaVersion(String versionString) {
this.schemaVersion = new Integer(versionString);
}
public int getSchemaVersion() {
return schemaVersion;
}
public Set<String> getCommIdsForSelectedSpeakers() {
HashSet<String> ids = new HashSet<String>();
for (String s : selectedPersons.keySet()) {
Element person = selectedPersons.get(s);
if (person.getChild("role") != null) {
for (Element role : (List<Element>) person.getChildren("role")) {
ids.add(role.getAttributeValue("target"));
}
}
}
return ids;
}
public String getSelectedCorpusName() {
return getCorpusName();
}
public HashSet<String> getRoleTypes() {
return roleTypes;
}
public void setRoleTypes(HashSet<String> roleTypes) {
this.roleTypes = roleTypes;
}
public HashSet<String> addRoleType(String rt) {
if (roleTypes == null) {
roleTypes = new HashSet<String>();
}
roleTypes.add(rt);
return roleTypes;
}
public void setFilterChanged(String string) {
filterChanged=string;
}
public String getFilterChanged() {
return filterChanged;
}
}
|
11562_1 | package shapes;
import java.awt.Color;
import chartbuilder.ChartBuilder;
/**
* This class represents a shape that can be used to construct graphs. Each shape has its own name and color.
* @author Wout
*
*/
public abstract class Shape {
//TODO Line moet ook overerven van shape denk ik . dan kunt ge da veel gemakkelijker tekenen, gewoon overerven van draw en buildermeegeven
private int xPos;
private int yPos;
private String name;
private Color color;
private double width;
private double height;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
public Shape() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public abstract void draw(ChartBuilder builder);
} | WoutV/OSS_1415 | sonar-polymorphic-views/src/main/java/shapes/Shape.java | 390 | //TODO Line moet ook overerven van shape denk ik . dan kunt ge da veel gemakkelijker tekenen, gewoon overerven van draw en buildermeegeven | line_comment | nl | package shapes;
import java.awt.Color;
import chartbuilder.ChartBuilder;
/**
* This class represents a shape that can be used to construct graphs. Each shape has its own name and color.
* @author Wout
*
*/
public abstract class Shape {
//TODO Line<SUF>
private int xPos;
private int yPos;
private String name;
private Color color;
private double width;
private double height;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
public Shape() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public abstract void draw(ChartBuilder builder);
} |
37742_19 | package com.e.pocketleague;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Database extends AppCompatActivity
{
private static Database databaseInstance;
//const api key
final static private String apiKey = "Your_Riot_API_key";
//interface que en listeners
private static Context context;
private static RequestQueue requestQueue;
private static CustomVolleyListener.CustomVolleyListenerChampion listener = null;
private static CustomVolleyListener.CustomVolleyListenerProfile listener2 = null;
//singelton gebruiken omdat je maar 1 static instnace van het database object wilt hebben
//region singleton
//private constructor.
private Database()
{
//veiligheid check zodat je alleen de instance kan aanspreken
if (databaseInstance != null)
{
throw new RuntimeException("Use getInstance() method ;)");
}
}
//singleton static instance
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerChampion listener)
{
//checken of er al een instance van is
if (databaseInstance == null)
{
synchronized (Database.class)
{
//nieuwe instance aanmaken als er geen is
if (databaseInstance == null) databaseInstance = new Database();
}
}
//listener en que voor volley
Database.context = context;
Database.listener = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//method overloading voor andere interface volley response
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerProfile listener)
{
//checks if there is already an instance
if (databaseInstance == null)
{
synchronized (Database.class)
{
//create new instance when none available
if (databaseInstance == null) databaseInstance = new Database();
}
}
Database.context = context;
Database.listener2 = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//endregion
//Alle champions ophalen
public void getChampions()
{
final String url = "http://ddragon.leagueoflegends.com/cdn/10.7.1/data/en_US/champion.json";
final List<Champion> champions = new ArrayList<Champion>();
//alle champions ophalen uit de leagoe of legends api als jsonObject
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//data opbject ophalen en in object stoppem
JSONObject data = response.getJSONObject("data");
//
//door alle objecten loopen in het data object
for(int i = 0; i < data.names().length(); i++)
{
//alle gegevens invullen, champion van maken en aan de champions lijst toevoegen
JSONObject champJSON = data.getJSONObject(data.names().getString(i));
String sprite = champJSON.getJSONObject("image").getString("full").toLowerCase();
String name = champJSON.getString("name");
String title = champJSON.getString("title");
int key = champJSON.getInt("key");
String[] tags = new String[champJSON.getJSONArray("tags").length()];
//door de tags loopen
for (int j = 0; j < champJSON.getJSONArray("tags").length(); j++)
{
tags[j] = champJSON.getJSONArray("tags").getString(j);
}
champions.add(new Champion(name,key,title,sprite,tags));
}
//System.out.println("In de response");
//aan de interface meegeven zodat ie opgehaald kan worden vanuit een andere Activity
listener.onVolleyResponse(champions);
}
catch (JSONException e)
{
e.printStackTrace();
}
//System.out.println(champions);
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
//System.out.println("voor de return");
//return champions;
}
//profiel ophalen
public void getProfile(String name)
{
//profiel ophalen uit de leagoe of legends API met de naam uit de settings
final String url = "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name;
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//nieuwe gebruiken maken, gegevens invullen terug sturen
User user = new User(
response.getString("name"),
response.getString("id"),
response.getString("profileIconId"),
response.getString("summonerLevel"));
listener2.onVolleyResponseUser(user);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
})
{
//API key meesturen
@Override
public Map getHeaders() throws AuthFailureError
{
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-Riot-Token", apiKey);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String testMe()
{
return "TEST SINGLETON";
}
}
| timonvw/PocketLeague | app/src/main/java/com/e/pocketleague/Database.java | 1,580 | //System.out.println("voor de return"); | line_comment | nl | package com.e.pocketleague;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Database extends AppCompatActivity
{
private static Database databaseInstance;
//const api key
final static private String apiKey = "Your_Riot_API_key";
//interface que en listeners
private static Context context;
private static RequestQueue requestQueue;
private static CustomVolleyListener.CustomVolleyListenerChampion listener = null;
private static CustomVolleyListener.CustomVolleyListenerProfile listener2 = null;
//singelton gebruiken omdat je maar 1 static instnace van het database object wilt hebben
//region singleton
//private constructor.
private Database()
{
//veiligheid check zodat je alleen de instance kan aanspreken
if (databaseInstance != null)
{
throw new RuntimeException("Use getInstance() method ;)");
}
}
//singleton static instance
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerChampion listener)
{
//checken of er al een instance van is
if (databaseInstance == null)
{
synchronized (Database.class)
{
//nieuwe instance aanmaken als er geen is
if (databaseInstance == null) databaseInstance = new Database();
}
}
//listener en que voor volley
Database.context = context;
Database.listener = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//method overloading voor andere interface volley response
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerProfile listener)
{
//checks if there is already an instance
if (databaseInstance == null)
{
synchronized (Database.class)
{
//create new instance when none available
if (databaseInstance == null) databaseInstance = new Database();
}
}
Database.context = context;
Database.listener2 = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//endregion
//Alle champions ophalen
public void getChampions()
{
final String url = "http://ddragon.leagueoflegends.com/cdn/10.7.1/data/en_US/champion.json";
final List<Champion> champions = new ArrayList<Champion>();
//alle champions ophalen uit de leagoe of legends api als jsonObject
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//data opbject ophalen en in object stoppem
JSONObject data = response.getJSONObject("data");
//
//door alle objecten loopen in het data object
for(int i = 0; i < data.names().length(); i++)
{
//alle gegevens invullen, champion van maken en aan de champions lijst toevoegen
JSONObject champJSON = data.getJSONObject(data.names().getString(i));
String sprite = champJSON.getJSONObject("image").getString("full").toLowerCase();
String name = champJSON.getString("name");
String title = champJSON.getString("title");
int key = champJSON.getInt("key");
String[] tags = new String[champJSON.getJSONArray("tags").length()];
//door de tags loopen
for (int j = 0; j < champJSON.getJSONArray("tags").length(); j++)
{
tags[j] = champJSON.getJSONArray("tags").getString(j);
}
champions.add(new Champion(name,key,title,sprite,tags));
}
//System.out.println("In de response");
//aan de interface meegeven zodat ie opgehaald kan worden vanuit een andere Activity
listener.onVolleyResponse(champions);
}
catch (JSONException e)
{
e.printStackTrace();
}
//System.out.println(champions);
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
//System.out.println("voor de<SUF>
//return champions;
}
//profiel ophalen
public void getProfile(String name)
{
//profiel ophalen uit de leagoe of legends API met de naam uit de settings
final String url = "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name;
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//nieuwe gebruiken maken, gegevens invullen terug sturen
User user = new User(
response.getString("name"),
response.getString("id"),
response.getString("profileIconId"),
response.getString("summonerLevel"));
listener2.onVolleyResponseUser(user);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
})
{
//API key meesturen
@Override
public Map getHeaders() throws AuthFailureError
{
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-Riot-Token", apiKey);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String testMe()
{
return "TEST SINGLETON";
}
}
|
185660_10 | package be.mxs.common.util.pdf.official.oc.examinations;
import be.mxs.common.util.pdf.official.PDFOfficialBasic;
import be.mxs.common.util.system.ScreenHelper;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import net.admin.AdminPrivateContact;
public class PDFOfficialPhysioConsultation extends PDFOfficialBasic {
// declarations
private int pageWidth = 100;
//--- ADD HEADER ------------------------------------------------------------------------------
protected void addHeader(){
try{
// get required data
String sUnit = "", sFunction = "", sUnitCode = "";
AdminPrivateContact apc = ScreenHelper.getActivePrivate(patient);
String patientAddress = "";
if (apc!=null){
patientAddress = apc.address+", "+apc.zipcode+" "+apc.city;
}
// put data in tables..
PdfPTable headerTable = new PdfPTable(4);
headerTable.setWidthPercentage(pageWidth);
// ROW 1 - cell 1,2 : left part of title
cell = createTitle(getTran(transactionVO.getTransactionType()),Font.BOLD,10,2);
cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
headerTable.addCell(cell);
// ROW 1 - cell 3,4 : right part of title
cell = createTitle(getTran("web","immatnew")+" "+checkString(patient.getID("immatnew")),Font.BOLD,10,2);
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
headerTable.addCell(cell);
table = new PdfPTable(5);
// ROW 2.1 : werknemer - naam
table.addCell(createValueCell(getTran("web","patient"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(getTran("web","name"),Font.NORMAL,8,1,false));
String patientFullName = patient.lastname+" "+patient.firstname;
table.addCell(createValueCell(patientFullName,Font.BOLD,8,3,false));
// ROW 2.2 : werknemer - adres
table.addCell(emptyCell(1));
table.addCell(createValueCell(getTran("web","address"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(patientAddress,Font.NORMAL,8,3,false));
// ROW 2.3 : onderzochte werknemer - date of birth
table.addCell(emptyCell(1));
table.addCell(createValueCell(getTran("web","dateofbirth"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(patient.dateOfBirth,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 3 : werkgever nr
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","service"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sUnitCode,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 4 : naam en adres werkgever
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","serviceaddress"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sUnit,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 5 : omschrijving functie werkpost of activiteit
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","function"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sFunction,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// spacer below page-header
headerTable.addCell(createBorderlessCell("",10,4));
// add headertable to document
doc.add(headerTable);
}
catch(Exception e){
e.printStackTrace();
}
}
//--- ADD CONTENT -----------------------------------------------------------------------------
protected void addContent(){
try{
table = new PdfPTable(5);
table.setWidthPercentage(pageWidth);
// MEDICAL DIAGNOSIS
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_MEDIC");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_MEDIC"),itemValue);
}
// ANAMNESE
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_ANAMNESE");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_ANAMNESE"),itemValue);
}
// PHYSICAL EXAMINATION
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_EXAM_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_EXAM_PHYS"),itemValue);
}
// PHYSICAL DIAGNOSE
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_PHYS"),itemValue);
}
// PHYSICAL TREATMENT PLAN
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_PLAN_TRAIT_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_PLAN_TRAIT_PHYS"),itemValue);
}
// RE-EVALUATION
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_REEVAL");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_REEVAL"),itemValue);
}
// END OF TREATMENT
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_FIN_TRAIT");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_FIN_TRAIT"),itemValue);
}
doc.add(table);
}
catch(Exception e){
e.printStackTrace();
}
}
}
| freemed/openclinicga-old | src/be/mxs/common/util/pdf/official/oc/examinations/PDFOfficialPhysioConsultation.java | 1,808 | // ROW 5 : omschrijving functie werkpost of activiteit
| line_comment | nl | package be.mxs.common.util.pdf.official.oc.examinations;
import be.mxs.common.util.pdf.official.PDFOfficialBasic;
import be.mxs.common.util.system.ScreenHelper;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import net.admin.AdminPrivateContact;
public class PDFOfficialPhysioConsultation extends PDFOfficialBasic {
// declarations
private int pageWidth = 100;
//--- ADD HEADER ------------------------------------------------------------------------------
protected void addHeader(){
try{
// get required data
String sUnit = "", sFunction = "", sUnitCode = "";
AdminPrivateContact apc = ScreenHelper.getActivePrivate(patient);
String patientAddress = "";
if (apc!=null){
patientAddress = apc.address+", "+apc.zipcode+" "+apc.city;
}
// put data in tables..
PdfPTable headerTable = new PdfPTable(4);
headerTable.setWidthPercentage(pageWidth);
// ROW 1 - cell 1,2 : left part of title
cell = createTitle(getTran(transactionVO.getTransactionType()),Font.BOLD,10,2);
cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
headerTable.addCell(cell);
// ROW 1 - cell 3,4 : right part of title
cell = createTitle(getTran("web","immatnew")+" "+checkString(patient.getID("immatnew")),Font.BOLD,10,2);
cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
headerTable.addCell(cell);
table = new PdfPTable(5);
// ROW 2.1 : werknemer - naam
table.addCell(createValueCell(getTran("web","patient"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(getTran("web","name"),Font.NORMAL,8,1,false));
String patientFullName = patient.lastname+" "+patient.firstname;
table.addCell(createValueCell(patientFullName,Font.BOLD,8,3,false));
// ROW 2.2 : werknemer - adres
table.addCell(emptyCell(1));
table.addCell(createValueCell(getTran("web","address"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(patientAddress,Font.NORMAL,8,3,false));
// ROW 2.3 : onderzochte werknemer - date of birth
table.addCell(emptyCell(1));
table.addCell(createValueCell(getTran("web","dateofbirth"),Font.NORMAL,8,1,false));
table.addCell(createValueCell(patient.dateOfBirth,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 3 : werkgever nr
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","service"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sUnitCode,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 4 : naam en adres werkgever
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","serviceaddress"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sUnit,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// ROW 5<SUF>
table = new PdfPTable(5);
table.addCell(createValueCell(getTran("web","function"),Font.NORMAL,8,2,false));
table.addCell(createValueCell(sFunction,Font.NORMAL,8,3,false));
headerTable.addCell(createCell(new PdfPCell(table),4,PdfPCell.ALIGN_LEFT,PdfPCell.BOX));
// spacer below page-header
headerTable.addCell(createBorderlessCell("",10,4));
// add headertable to document
doc.add(headerTable);
}
catch(Exception e){
e.printStackTrace();
}
}
//--- ADD CONTENT -----------------------------------------------------------------------------
protected void addContent(){
try{
table = new PdfPTable(5);
table.setWidthPercentage(pageWidth);
// MEDICAL DIAGNOSIS
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_MEDIC");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_MEDIC"),itemValue);
}
// ANAMNESE
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_ANAMNESE");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_ANAMNESE"),itemValue);
}
// PHYSICAL EXAMINATION
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_EXAM_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_EXAM_PHYS"),itemValue);
}
// PHYSICAL DIAGNOSE
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_DIAG_PHYS"),itemValue);
}
// PHYSICAL TREATMENT PLAN
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_PLAN_TRAIT_PHYS");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_PLAN_TRAIT_PHYS"),itemValue);
}
// RE-EVALUATION
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_REEVAL");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_REEVAL"),itemValue);
}
// END OF TREATMENT
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_FIN_TRAIT");
if(itemValue.length() > 0){
addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_PHYSIO_CONS_FIN_TRAIT"),itemValue);
}
doc.add(table);
}
catch(Exception e){
e.printStackTrace();
}
}
}
|
12514_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Geeft het aantal levens van de speler weer.
*
* Project 42
*/
public class ControlroomLife extends Actor
{
}
| Project42/game2 | ControlroomLife.java | 61 | /**
* Geeft het aantal levens van de speler weer.
*
* Project 42
*/ | block_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Geeft het aantal<SUF>*/
public class ControlroomLife extends Actor
{
}
|
15351_11 | package spellingvariation;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import trie.Trie;
import trie.Trie.TrieNode;
import util.Options;
import util.StringUtils;
class MatchState implements Comparable<MatchState>
{
TrieNode lexnode;
int position;
int cost;
MatchState parentState;
RuleInfo rule;
MatchState(Trie.TrieNode n, int p)
{
lexnode = n; position = p;
parentState = null; rule = null;
}
public int compareTo(MatchState other)
{
return cost - other.cost;
}
}
/**
* This class tries to find the best matches in a (trie-shaped) word list for a target word, given
* a set of weighted patterns
* <p>Typical usage</p>
* <pre style='font-size:9pt'>
* MemorylessMatcher matcher = new MemorylessMatcher("some_pattern_filename");
* Trie lexicon = new Trie();
* lexicon.loadWordlist("some_wordlist_filename");
* ....
* matcher.matchWordToLexicon(lexicon, s);
* </pre>
* Because there are possibly many different matches,
* you need to implement a callback to get at the matches:
* <pre style='font-size:9pt'>
* MemorylessMatcher.Callback myCallback = new Callback()
* {
* public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
* {
* System.out.printf("%s\t%s\n", targetWord,matchedWord);
* }
* };
* matcher.callback = myCallback;
* </pre>
*/
public class MemorylessMatcher
{
protected static final double costScale = 100.0;
static final int BONUS=0;
int MAX_SUGGESTIONS = 1;
static int MAX_ITEMS=50000;
static int MAX_PENALTY = 3000;
int MAX_PENALTY_INCREMENT=300;
double MIN_JOINT_PROBABILITY=1e-6;
double MIN_CONFIDENCE = 1e-3;
public boolean addWordBoundaries = false;
boolean allowDeletions = true;
boolean allowInsertions = true;
boolean VERBOSE = true;
String targetWord = null;
Trie lextrie;
Trie ruletrie = new Trie();
Vector<MatchState> activeItems = new Vector<MatchState>();
java.util.PriorityQueue<MatchState> queue = new java.util.PriorityQueue<MatchState>();
/**
* You need to override this callback class to retrieve the matching candidates.
* @author jesse
*
*/
public static abstract class Callback
{
/**
*
* @param targetWord the word you submitted to the matcher
* @param matchedWord the match proposed
* @param matchInfo printable representation of alignment of targetWord and matcherWord
* @param cost a discretization of the <i>p</i> parameter according to <i>cost= 100 * -ln(p)</i>
* @param p some probability score, computed from the applied pattern weights
*/
public abstract void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p);
}
protected Callback callback = new Callback()
{
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
if (VERBOSE)
{
System.out.printf("%s-->%s [%s] (%d=%e)\n", targetWord, matchedWord, matchInfo, cost, p);
} else
{
System.out.printf("%s\t%s\n", targetWord,matchedWord);
}
}
};
void init()
{
try
{
String min_joint = Options.getOption("minimumJointProbablity");
if (min_joint != null)
this.MIN_JOINT_PROBABILITY = Double.parseDouble(min_joint);
String min_conf = Options.getOption("minimumConfidence");
if (min_conf != null)
this.MIN_CONFIDENCE = Double.parseDouble(min_conf);
String allow_d = Options.getOption("allowDeletions");
if (allow_d != null)
allowDeletions = Boolean.parseBoolean(allow_d);
String allow_i = Options.getOption("allowInsertions");
if (allow_i != null)
allowInsertions = Boolean.parseBoolean(allow_i);
String maxSuggestions = Options.getOption("maximumSuggestions");
if (maxSuggestions != null)
this.MAX_SUGGESTIONS = Integer.parseInt(maxSuggestions);
String maxPenalty = Options.getOption("maximumPenalty");
if (maxPenalty != null)
MemorylessMatcher.MAX_PENALTY = Integer.parseInt(maxPenalty);
addWordBoundaries = Options.getOptionBoolean("addWordBoundaries", addWordBoundaries);
} catch (Exception e)
{
e.printStackTrace();
}
}
public void setMaxSuggestions(int k)
{
this.MAX_SUGGESTIONS = k;
}
public void setMaxPenaltyIncrement(int x)
{
this.MAX_PENALTY_INCREMENT=x;
}
public MemorylessMatcher(String ruleFileName)
{
init();
try
{
FileInputStream fis = new FileInputStream(ruleFileName);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader f = new BufferedReader(isr);
readRules(f);
} catch (Exception e)
{
}
}
public MemorylessMatcher(MultigramSet set) // not used and unsafe
{
init();
getRulesFromMultigramSet(set);
}
public MemorylessMatcher()
{
}
public void setCallback(Callback c)
{
this.callback = c;
}
@Deprecated
protected boolean readRulesOldVersion(BufferedReader f)
{
String tokens[];
String s;
try
{
while ((s = f.readLine()) != null) // this is silly
{
tokens = s.split("\t");
RuleInfo rule = new RuleInfo(tokens[0], tokens[1], Double.parseDouble(tokens[2]));
storeRule(rule);
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
//System.err.printf( "XXX %d\n", ruletrie.root.nofTransitions());
return true;
}
/**
* Rules are stored in a tab-separated file with format
* modern→historical jointProbability probabilityGivenLHS probabilityGivenRHS
* @param f
* @return
*/
protected boolean readRules(BufferedReader f)
{
String tokens[];
String s;
try
{
while ((s = f.readLine()) != null) // this is silly
{
tokens = s.split("\t");
try
{
String[] lhsrhs = tokens[0].split("→"); // TODO replace this with something safer!
String left,right;
if (tokens[0].startsWith("→"))
{
left=""; right = lhsrhs[1];
} else if (tokens[0].endsWith("→"))
{
left = lhsrhs[0]; right="";
} else
{
left=lhsrhs[0]; right=lhsrhs[1];
}
RuleInfo rule = new RuleInfo(left, right,
Double.parseDouble(tokens[1]),
Double.parseDouble(tokens[2]),
Double.parseDouble(tokens[3])
);
storeRule(rule);
} catch (Exception e)
{
e.printStackTrace();
System.err.println(tokens[0]);
}
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
// System.err.printf( "XXX %d\n", ruletrie.root.nofTransitions());
return true;
}
protected void getRulesFromMultigramSet(MultigramSet set)
{
for (JointMultigram m: set)
{
RuleInfo rule = new RuleInfo(m.lhs, m.rhs, set.getScore(m.id));
storeRule(rule);
}
}
/** Patterns are stored in a trie of tries.
* <ul>
<li> The right hand sides are stored the first level trie
<li> to every final state in the in right hand sides-trie we link the trie consisting of all left hand sides going with this rhs
<li> Rule information (f.i. weight) is stored in the final states of the left-hand-side tries
*</ul>
*/
private void storeRule(RuleInfo rule)
{
if (rule.joint_probability < this.MIN_JOINT_PROBABILITY)
return;
if (!allowDeletions && rule.rhs.equals(""))
return;
if (rule.p_cond_rhs < this.MIN_CONFIDENCE)
return;
if (rule.lhs.endsWith(Alphabet.finalBoundaryString) || rule.rhs.endsWith(Alphabet.finalBoundaryString))
this.addWordBoundaries = true;
if (rule.lhs.startsWith(Alphabet.initialBoundaryString) || rule.rhs.startsWith(Alphabet.initialBoundaryString))
this.addWordBoundaries = true;
TrieNode rnode = ruletrie.root.putWord(rule.rhs);
Trie ltrie = (Trie) rnode.data;
if (ltrie == null) rnode.data = ltrie = new Trie();
TrieNode lnode = ltrie.root.putWord(rule.lhs);
lnode.data = rule;
}
int incrementCost(RuleInfo r, int cost)
{
if (r == null)
{
return cost - BONUS;
}
return cost + r.cost;
}
MatchState findItem(TrieNode lexnode, int pos)
{
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) lexnode.data;
if (items == null)
{
return null;
}
for (int i=0; i < items.size(); i++)
{
if (items.get(i).position == pos) return items.get(i);
}
return null;
}
void additem(TrieNode lexnode, MatchState item)
{
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) lexnode.data;
if (items == null)
{
items = new Vector<MatchState>();
lexnode.data = items;
}
items.addElement(item);
activeItems.addElement(item);
}
// rule=null betekent echo karakter[pos] naar output
void tryNewItem(MatchState item, TrieNode lexnode, int pos, int newCost, RuleInfo rule)
{
MatchState nextitem;
if ((nextitem = findItem(lexnode, pos)) != null) // dit zou toch zo af en toe moeten voorkomen??
{
if (newCost < nextitem.cost)
{
//System.err.printf("decrease cost of item at pos %d from %d to %d\n", pos, nextitem.cost, newCost);
queue.remove(nextitem); nextitem.cost = newCost; queue.offer(nextitem);
nextitem.parentState = item;
nextitem.rule = rule;
nextitem.cost = newCost;
}
} else
{
if (rule != null)
{
//System.err.printf("new item at pos %d, cost %d (%d), rule %s.%s !!!\n", pos, newCost, item.cost, rule.lhs, rule.rhs);
} else
{
//System.err.printf("new item at pos %d, cost %d (%d), character '%c' !!!\n", pos, newCost, item.cost, targetWord[pos-1]);
}
nextitem = new MatchState(lexnode, pos);
nextitem.cost = newCost;
queue.offer(nextitem);
nextitem.parentState = item;
nextitem.rule = rule;
nextitem.cost = newCost;
additem(lexnode, nextitem);
}
}
// try to match the left hand sides of rules in the lexicon
void lhsRecursion(MatchState item, TrieNode lhsNode, TrieNode lexnode, int pos, int cost)
{
if (lhsNode.isFinal) // pas op halve zool lexnode hoeft niet final te zijn
{
RuleInfo rule = (RuleInfo) lhsNode.data;
int newCost = incrementCost(rule, cost);
// System.err.printf("found rule at %d: '%s'->'%s' (%d->%d)\n", pos, rule.lhs, rule.rhs, rule.cost, newCost);
if (rule != null)
{
//if (newCost <= MAX_PENALTY)
tryNewItem(item, lexnode, pos + rule.rhs.length(), newCost, rule);
}
else
{
System.err.println("Fatal error: final node in rule trie without rule information");
System.exit(1);
//tryNewItem(item, lexnode, pos + 1, newCost, rule); // TODO why this?? can this happen?
}
}
int k = lhsNode.nofTransitions();
for (int i=0; i < k; i++)
{
Trie.Transition t = lhsNode.transition(i);
TrieNode nextNodeInLexicon;
if ((nextNodeInLexicon = lexnode.delta(t.character)) != null)
{
lhsRecursion(item, t.node, nextNodeInLexicon, pos, cost);
}
}
}
void relaxTransitions(MatchState item)
{
TrieNode rhsNode = ruletrie.root;
int positionInWord = item.position;
TrieNode nextlexnode;
if ((positionInWord < targetWord.length())
&& (nextlexnode = item.lexnode.delta(targetWord.charAt(positionInWord))) != null)
{
tryNewItem(item, nextlexnode, positionInWord + 1, item.cost - BONUS, null);
}
while (rhsNode != null) // try to find matching right hand sides of rules
{
Trie lhstrie = (Trie) rhsNode.data;
if (lhstrie != null && rhsNode.isFinal) // right hand side of some rule is triggered
{
TrieNode lhsNode = lhstrie.root;
//System.err.printf("recognized right hand side of some rule at %d-%d\n", item.pos, pos);
lhsRecursion(item, lhsNode, item.lexnode, item.position, item.cost); // pos die je door moet geven??
}
if (positionInWord >= targetWord.length()) break;
rhsNode = rhsNode.delta(targetWord.charAt(positionInWord++));
}
}
void outputSuggestion(MatchState item)
{
String matchedWord = "", matchInfo= "";
MatchState theItem = item;
while (theItem != null)
{
if (theItem.rule != null)
{
matchInfo = "[" + theItem.rule.lhs + "->" + theItem.rule.rhs + "]" + matchInfo;
matchedWord = theItem.rule.lhs + matchedWord;
} else if (theItem.position > 0)
{
matchInfo = targetWord.charAt(theItem.position -1) + matchInfo;
matchedWord = targetWord.charAt(theItem.position -1) + matchedWord;
}
theItem = theItem.parentState;
}
double p = Math.exp( (item.cost)/-costScale);
if (callback != null)
{
matchedWord = Alphabet.removeBoundaryMarkers(matchedWord);
callback.handleMatch(targetWord, matchedWord, matchInfo, item.cost, p);
}
}
// Beware: lexicon wordt vervuild met datanodes.
// om het netjes te doen moet je dus eigenlijk kopie trekken
private void removeDataPointersInLexicon()
{
//fprintf(stdout,"Number of items produced: %d\n", activeItems.size);
for (int i=0; i < activeItems.size(); i++)
{
MatchState item = activeItems.get(i);
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) item.lexnode.data;
if (items != null)
{
item.lexnode.data = null;
}
}
activeItems.clear();
}
/**
Main function. Synchronized because:
<ol>
<li> temporary data pointers pollute the lexicon
<li> instance state variables are used
</ol>
*/
synchronized public boolean matchWordToLexicon(Trie lexicon, String target)
{
this.lextrie = lexicon;
this.targetWord = target;
if (this.addWordBoundaries)
this.targetWord = Alphabet.initialBoundaryString + this.targetWord + Alphabet.finalBoundaryString;
//this.queue = fh_makekeyheap();
MatchState startitem = new MatchState(lextrie.root, 0);
activeItems.addElement(startitem);
startitem.cost = 0;
//startitem.heapEl = fh_insertkey(queue, 0, (Object) startitem);
queue.offer(startitem);
boolean stop = false;
int L = targetWord.length();
int nofSuggestions = 0;
int bestCost = 0;
boolean found = false;
while (!stop) // queue empty of 'te duur'
{
//Item item = (Item) fh_extractmin(queue);
MatchState item = queue.poll();
if (item == null) break;
//System.err.printf("######\nextracted item has pos %d of %d, cost %d\n", item.pos, L, item.cost);
//if (item == startitem) { System.err.printf("Hola: weer startitem, DIT KAN NIET\n"); }
int penaltyIncrement = 0;
if (found)
penaltyIncrement = item.cost - bestCost;
else
bestCost = item.cost;
if (item.lexnode.isFinal && item.position == L)
{
// output suggestie
if (item.cost <= MAX_PENALTY && penaltyIncrement <= MAX_PENALTY_INCREMENT)
{
found = true;
outputSuggestion(item);
nofSuggestions++;
}
}
// queue.size() was activeItems.size
if (nofSuggestions >= MAX_SUGGESTIONS || queue.size() > MAX_ITEMS || item.cost > MAX_PENALTY)
{
break;
}
relaxTransitions(item);
//fh_delete(queue, item.heapEl);
// add all transitions for item [moet dan helaas gediscretiseerd]
// evt kan je op reeds bekende items uitkomen
}
removeDataPointersInLexicon();
//fh_deleteheap(queue);
queue.clear();
return found;
//System.err.printf("took %u msec\n", (endUsecs - startUsecs)/1000);
}
public static void usage()
{
System.err.println("Usage: java spellingvariation.MemorylessMatcher <pattern file> <word list> [<input file>]");
}
class Match
{
String target;
String match;
String reference;
String patterns;
boolean correct;
boolean referenceInLexicon;
double score;
public Match(String target, String match,String reference,
boolean correct, boolean referenceInLexicon, double score, String patterns)
{
this.target=target;
this.match=match;
this.reference=reference;
this.correct=correct;
this.referenceInLexicon = referenceInLexicon;
this.score=score;
this.patterns = patterns;
}
String asXML()
{
return String.format("<match value='%s' correct='%s' OOV='%s' score='%f' appliedPatterns='%s'/>",
esc(match), new Boolean(correct).toString(),
new Boolean(!referenceInLexicon).toString(), score, esc(patterns));
}
}
class TestCallback extends Callback
{
int itemsTested=0;
int noMatch = 0;
int correctMatches = 0;
String reference="";
String currentId="";
boolean referenceInLexicon = false;
int nItemsinLexicon = 0;
List<String> targets = new ArrayList<String>();
Map<String,String> id2target = new HashMap<String,String>();
Map<String,String> id2reference = new HashMap<String,String>();
Map<String,List<Match>> matches = new HashMap<String,List<Match>>();
public void addMatch(Match match) // dit is allemaal fout....
{
List<Match> soFar = matches.get(currentId);
if (soFar == null)
{
soFar = new ArrayList<Match>();
matches.put(currentId, soFar);
}
soFar.add(match);
}
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
Match match = new Match(targetWord, matchedWord, reference, matchedWord.equals(reference),
referenceInLexicon, p, matchInfo);
addMatch(match);
if (matchedWord.equals(reference))
{
correctMatches++;
} else
{
//System.err.println("!!Wrong match: " +targetWord + " =~ " + matchedWord + " (reference = " + reference + ")");
}
//System.out.printf("%s -> %s %s %e %d\n" ,targetWord, matchedWord, matchInfo, p, cost);
}
public void dumpResults()
{
System.out.println("<results>");
for (String h: targets)
{
boolean found=false;
List<Match> matchList = matches.get(h);
String mXML="";
if (matchList != null)
{
for (Match m: matchList)
{
mXML += m.asXML();
found |= m.correct;
}
}
String z = String.format("<matching target='%s' reference='%s' found='%s'>%s</matching>",
esc(this.id2target.get(h)) ,
esc(id2reference.get(h)),
new Boolean(found).toString(),
mXML );
System.out.println(z);
}
System.out.println("</results>");
}
}
public static String esc(String s)
{
return StringUtils.xmlSingleQuotedEscape(s);
}
public void test(Trie lexicon, BufferedReader in)
{
this.lextrie = lexicon;
TestCallback cb = new TestCallback();
this.callback = cb;
try
{
String s;
int k=1;
while ((s=in.readLine()) != null)
{
String[] parts = s.split("\\t");
//String lemma=parts[0];
String id = parts[0]; String modern = parts[1]; String historical = parts[2];
cb.reference = modern;
cb.currentId = String.format("%06d",k);
cb.targets.add(cb.currentId);
cb.referenceInLexicon = lexicon.contains(modern, this.addWordBoundaries);
if (cb.referenceInLexicon) cb.nItemsinLexicon++;
cb.id2reference.put(cb.currentId, cb.reference);
cb.id2target.put(cb.currentId, historical);
cb.itemsTested++;
boolean found = this.matchWordToLexicon(lexicon, historical);
if (!found)
{
cb.noMatch++;
}
k++;
}
cb.dumpResults();
double recallOverall = cb.correctMatches / (double) cb.itemsTested;
double modernLexiconCoverage = 0;
double recallInVocabulary = 0;
try
{
recallInVocabulary = cb.correctMatches / (double) cb.nItemsinLexicon;
modernLexiconCoverage = cb.nItemsinLexicon / (double) cb.itemsTested;
} catch (Exception e)
{
}
System.err.println("Items tested: " + cb.itemsTested + "; correct matches: " + cb.correctMatches + "; no match at all: " + cb.noMatch);
System.err.println("Coverage of modern lexicon on modern equivalents: " + modernLexiconCoverage);
System.err.println("Overall recall: " + recallOverall);
System.err.println("Recall of words in modern lexicon: " + recallInVocabulary);
} catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args)
{
new Options(args);
if (args.length < 2)
{
usage();
System.exit(1);
}
MemorylessMatcher matcher = new MemorylessMatcher(Options.getOption("patternInput"));
Trie lexicon = new Trie();
lexicon.loadWordlist(Options.getOption("lexicon"),
false,
Options.getOptionBoolean("addWordBoundaries", false));
boolean found= false;
java.io.BufferedReader stdin = null;
if ((Options.getOption("testFile")) != null)
{
try
{
Reader reader = new InputStreamReader(
new FileInputStream(Options.getOption("testFile")), "UTF-8");
stdin = new BufferedReader(reader);
} catch (Exception e)
{
e.printStackTrace();
stdin = null;
}
} else
{
try
{
stdin = new BufferedReader(new java.io.InputStreamReader(System.in, "UTF-8"));
} catch (Exception e)
{
e.printStackTrace();
}
}
String cmd = Options.getOption("command");
if (cmd != null && cmd.equals("test"))
{
System.err.println("testing on labeled input");
matcher.test(lexicon, stdin);
System.exit(0);
}
MemorylessMatcher.Callback c = new MemorylessMatcher.Callback ()
{
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
System.out.printf("%s -> %s %s %e\n" ,targetWord, matchedWord, matchInfo, p);
}
@SuppressWarnings("unused")
void noMatch(String targetWord)
{
}
};
matcher.callback = c;
String s;
try
{
while ( (s = stdin.readLine()) != null)
{
found = matcher.matchWordToLexicon(lexicon, s);
if (!found)
{
System.out.println("No match " + s);
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
| impactcentre/ImpactIR | src/spellingvariation/MemorylessMatcher.java | 6,913 | // rule=null betekent echo karakter[pos] naar output | line_comment | nl | package spellingvariation;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import trie.Trie;
import trie.Trie.TrieNode;
import util.Options;
import util.StringUtils;
class MatchState implements Comparable<MatchState>
{
TrieNode lexnode;
int position;
int cost;
MatchState parentState;
RuleInfo rule;
MatchState(Trie.TrieNode n, int p)
{
lexnode = n; position = p;
parentState = null; rule = null;
}
public int compareTo(MatchState other)
{
return cost - other.cost;
}
}
/**
* This class tries to find the best matches in a (trie-shaped) word list for a target word, given
* a set of weighted patterns
* <p>Typical usage</p>
* <pre style='font-size:9pt'>
* MemorylessMatcher matcher = new MemorylessMatcher("some_pattern_filename");
* Trie lexicon = new Trie();
* lexicon.loadWordlist("some_wordlist_filename");
* ....
* matcher.matchWordToLexicon(lexicon, s);
* </pre>
* Because there are possibly many different matches,
* you need to implement a callback to get at the matches:
* <pre style='font-size:9pt'>
* MemorylessMatcher.Callback myCallback = new Callback()
* {
* public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
* {
* System.out.printf("%s\t%s\n", targetWord,matchedWord);
* }
* };
* matcher.callback = myCallback;
* </pre>
*/
public class MemorylessMatcher
{
protected static final double costScale = 100.0;
static final int BONUS=0;
int MAX_SUGGESTIONS = 1;
static int MAX_ITEMS=50000;
static int MAX_PENALTY = 3000;
int MAX_PENALTY_INCREMENT=300;
double MIN_JOINT_PROBABILITY=1e-6;
double MIN_CONFIDENCE = 1e-3;
public boolean addWordBoundaries = false;
boolean allowDeletions = true;
boolean allowInsertions = true;
boolean VERBOSE = true;
String targetWord = null;
Trie lextrie;
Trie ruletrie = new Trie();
Vector<MatchState> activeItems = new Vector<MatchState>();
java.util.PriorityQueue<MatchState> queue = new java.util.PriorityQueue<MatchState>();
/**
* You need to override this callback class to retrieve the matching candidates.
* @author jesse
*
*/
public static abstract class Callback
{
/**
*
* @param targetWord the word you submitted to the matcher
* @param matchedWord the match proposed
* @param matchInfo printable representation of alignment of targetWord and matcherWord
* @param cost a discretization of the <i>p</i> parameter according to <i>cost= 100 * -ln(p)</i>
* @param p some probability score, computed from the applied pattern weights
*/
public abstract void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p);
}
protected Callback callback = new Callback()
{
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
if (VERBOSE)
{
System.out.printf("%s-->%s [%s] (%d=%e)\n", targetWord, matchedWord, matchInfo, cost, p);
} else
{
System.out.printf("%s\t%s\n", targetWord,matchedWord);
}
}
};
void init()
{
try
{
String min_joint = Options.getOption("minimumJointProbablity");
if (min_joint != null)
this.MIN_JOINT_PROBABILITY = Double.parseDouble(min_joint);
String min_conf = Options.getOption("minimumConfidence");
if (min_conf != null)
this.MIN_CONFIDENCE = Double.parseDouble(min_conf);
String allow_d = Options.getOption("allowDeletions");
if (allow_d != null)
allowDeletions = Boolean.parseBoolean(allow_d);
String allow_i = Options.getOption("allowInsertions");
if (allow_i != null)
allowInsertions = Boolean.parseBoolean(allow_i);
String maxSuggestions = Options.getOption("maximumSuggestions");
if (maxSuggestions != null)
this.MAX_SUGGESTIONS = Integer.parseInt(maxSuggestions);
String maxPenalty = Options.getOption("maximumPenalty");
if (maxPenalty != null)
MemorylessMatcher.MAX_PENALTY = Integer.parseInt(maxPenalty);
addWordBoundaries = Options.getOptionBoolean("addWordBoundaries", addWordBoundaries);
} catch (Exception e)
{
e.printStackTrace();
}
}
public void setMaxSuggestions(int k)
{
this.MAX_SUGGESTIONS = k;
}
public void setMaxPenaltyIncrement(int x)
{
this.MAX_PENALTY_INCREMENT=x;
}
public MemorylessMatcher(String ruleFileName)
{
init();
try
{
FileInputStream fis = new FileInputStream(ruleFileName);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader f = new BufferedReader(isr);
readRules(f);
} catch (Exception e)
{
}
}
public MemorylessMatcher(MultigramSet set) // not used and unsafe
{
init();
getRulesFromMultigramSet(set);
}
public MemorylessMatcher()
{
}
public void setCallback(Callback c)
{
this.callback = c;
}
@Deprecated
protected boolean readRulesOldVersion(BufferedReader f)
{
String tokens[];
String s;
try
{
while ((s = f.readLine()) != null) // this is silly
{
tokens = s.split("\t");
RuleInfo rule = new RuleInfo(tokens[0], tokens[1], Double.parseDouble(tokens[2]));
storeRule(rule);
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
//System.err.printf( "XXX %d\n", ruletrie.root.nofTransitions());
return true;
}
/**
* Rules are stored in a tab-separated file with format
* modern→historical jointProbability probabilityGivenLHS probabilityGivenRHS
* @param f
* @return
*/
protected boolean readRules(BufferedReader f)
{
String tokens[];
String s;
try
{
while ((s = f.readLine()) != null) // this is silly
{
tokens = s.split("\t");
try
{
String[] lhsrhs = tokens[0].split("→"); // TODO replace this with something safer!
String left,right;
if (tokens[0].startsWith("→"))
{
left=""; right = lhsrhs[1];
} else if (tokens[0].endsWith("→"))
{
left = lhsrhs[0]; right="";
} else
{
left=lhsrhs[0]; right=lhsrhs[1];
}
RuleInfo rule = new RuleInfo(left, right,
Double.parseDouble(tokens[1]),
Double.parseDouble(tokens[2]),
Double.parseDouble(tokens[3])
);
storeRule(rule);
} catch (Exception e)
{
e.printStackTrace();
System.err.println(tokens[0]);
}
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
// System.err.printf( "XXX %d\n", ruletrie.root.nofTransitions());
return true;
}
protected void getRulesFromMultigramSet(MultigramSet set)
{
for (JointMultigram m: set)
{
RuleInfo rule = new RuleInfo(m.lhs, m.rhs, set.getScore(m.id));
storeRule(rule);
}
}
/** Patterns are stored in a trie of tries.
* <ul>
<li> The right hand sides are stored the first level trie
<li> to every final state in the in right hand sides-trie we link the trie consisting of all left hand sides going with this rhs
<li> Rule information (f.i. weight) is stored in the final states of the left-hand-side tries
*</ul>
*/
private void storeRule(RuleInfo rule)
{
if (rule.joint_probability < this.MIN_JOINT_PROBABILITY)
return;
if (!allowDeletions && rule.rhs.equals(""))
return;
if (rule.p_cond_rhs < this.MIN_CONFIDENCE)
return;
if (rule.lhs.endsWith(Alphabet.finalBoundaryString) || rule.rhs.endsWith(Alphabet.finalBoundaryString))
this.addWordBoundaries = true;
if (rule.lhs.startsWith(Alphabet.initialBoundaryString) || rule.rhs.startsWith(Alphabet.initialBoundaryString))
this.addWordBoundaries = true;
TrieNode rnode = ruletrie.root.putWord(rule.rhs);
Trie ltrie = (Trie) rnode.data;
if (ltrie == null) rnode.data = ltrie = new Trie();
TrieNode lnode = ltrie.root.putWord(rule.lhs);
lnode.data = rule;
}
int incrementCost(RuleInfo r, int cost)
{
if (r == null)
{
return cost - BONUS;
}
return cost + r.cost;
}
MatchState findItem(TrieNode lexnode, int pos)
{
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) lexnode.data;
if (items == null)
{
return null;
}
for (int i=0; i < items.size(); i++)
{
if (items.get(i).position == pos) return items.get(i);
}
return null;
}
void additem(TrieNode lexnode, MatchState item)
{
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) lexnode.data;
if (items == null)
{
items = new Vector<MatchState>();
lexnode.data = items;
}
items.addElement(item);
activeItems.addElement(item);
}
// rule=null betekent<SUF>
void tryNewItem(MatchState item, TrieNode lexnode, int pos, int newCost, RuleInfo rule)
{
MatchState nextitem;
if ((nextitem = findItem(lexnode, pos)) != null) // dit zou toch zo af en toe moeten voorkomen??
{
if (newCost < nextitem.cost)
{
//System.err.printf("decrease cost of item at pos %d from %d to %d\n", pos, nextitem.cost, newCost);
queue.remove(nextitem); nextitem.cost = newCost; queue.offer(nextitem);
nextitem.parentState = item;
nextitem.rule = rule;
nextitem.cost = newCost;
}
} else
{
if (rule != null)
{
//System.err.printf("new item at pos %d, cost %d (%d), rule %s.%s !!!\n", pos, newCost, item.cost, rule.lhs, rule.rhs);
} else
{
//System.err.printf("new item at pos %d, cost %d (%d), character '%c' !!!\n", pos, newCost, item.cost, targetWord[pos-1]);
}
nextitem = new MatchState(lexnode, pos);
nextitem.cost = newCost;
queue.offer(nextitem);
nextitem.parentState = item;
nextitem.rule = rule;
nextitem.cost = newCost;
additem(lexnode, nextitem);
}
}
// try to match the left hand sides of rules in the lexicon
void lhsRecursion(MatchState item, TrieNode lhsNode, TrieNode lexnode, int pos, int cost)
{
if (lhsNode.isFinal) // pas op halve zool lexnode hoeft niet final te zijn
{
RuleInfo rule = (RuleInfo) lhsNode.data;
int newCost = incrementCost(rule, cost);
// System.err.printf("found rule at %d: '%s'->'%s' (%d->%d)\n", pos, rule.lhs, rule.rhs, rule.cost, newCost);
if (rule != null)
{
//if (newCost <= MAX_PENALTY)
tryNewItem(item, lexnode, pos + rule.rhs.length(), newCost, rule);
}
else
{
System.err.println("Fatal error: final node in rule trie without rule information");
System.exit(1);
//tryNewItem(item, lexnode, pos + 1, newCost, rule); // TODO why this?? can this happen?
}
}
int k = lhsNode.nofTransitions();
for (int i=0; i < k; i++)
{
Trie.Transition t = lhsNode.transition(i);
TrieNode nextNodeInLexicon;
if ((nextNodeInLexicon = lexnode.delta(t.character)) != null)
{
lhsRecursion(item, t.node, nextNodeInLexicon, pos, cost);
}
}
}
void relaxTransitions(MatchState item)
{
TrieNode rhsNode = ruletrie.root;
int positionInWord = item.position;
TrieNode nextlexnode;
if ((positionInWord < targetWord.length())
&& (nextlexnode = item.lexnode.delta(targetWord.charAt(positionInWord))) != null)
{
tryNewItem(item, nextlexnode, positionInWord + 1, item.cost - BONUS, null);
}
while (rhsNode != null) // try to find matching right hand sides of rules
{
Trie lhstrie = (Trie) rhsNode.data;
if (lhstrie != null && rhsNode.isFinal) // right hand side of some rule is triggered
{
TrieNode lhsNode = lhstrie.root;
//System.err.printf("recognized right hand side of some rule at %d-%d\n", item.pos, pos);
lhsRecursion(item, lhsNode, item.lexnode, item.position, item.cost); // pos die je door moet geven??
}
if (positionInWord >= targetWord.length()) break;
rhsNode = rhsNode.delta(targetWord.charAt(positionInWord++));
}
}
void outputSuggestion(MatchState item)
{
String matchedWord = "", matchInfo= "";
MatchState theItem = item;
while (theItem != null)
{
if (theItem.rule != null)
{
matchInfo = "[" + theItem.rule.lhs + "->" + theItem.rule.rhs + "]" + matchInfo;
matchedWord = theItem.rule.lhs + matchedWord;
} else if (theItem.position > 0)
{
matchInfo = targetWord.charAt(theItem.position -1) + matchInfo;
matchedWord = targetWord.charAt(theItem.position -1) + matchedWord;
}
theItem = theItem.parentState;
}
double p = Math.exp( (item.cost)/-costScale);
if (callback != null)
{
matchedWord = Alphabet.removeBoundaryMarkers(matchedWord);
callback.handleMatch(targetWord, matchedWord, matchInfo, item.cost, p);
}
}
// Beware: lexicon wordt vervuild met datanodes.
// om het netjes te doen moet je dus eigenlijk kopie trekken
private void removeDataPointersInLexicon()
{
//fprintf(stdout,"Number of items produced: %d\n", activeItems.size);
for (int i=0; i < activeItems.size(); i++)
{
MatchState item = activeItems.get(i);
@SuppressWarnings("unchecked")
Vector<MatchState> items = (Vector<MatchState>) item.lexnode.data;
if (items != null)
{
item.lexnode.data = null;
}
}
activeItems.clear();
}
/**
Main function. Synchronized because:
<ol>
<li> temporary data pointers pollute the lexicon
<li> instance state variables are used
</ol>
*/
synchronized public boolean matchWordToLexicon(Trie lexicon, String target)
{
this.lextrie = lexicon;
this.targetWord = target;
if (this.addWordBoundaries)
this.targetWord = Alphabet.initialBoundaryString + this.targetWord + Alphabet.finalBoundaryString;
//this.queue = fh_makekeyheap();
MatchState startitem = new MatchState(lextrie.root, 0);
activeItems.addElement(startitem);
startitem.cost = 0;
//startitem.heapEl = fh_insertkey(queue, 0, (Object) startitem);
queue.offer(startitem);
boolean stop = false;
int L = targetWord.length();
int nofSuggestions = 0;
int bestCost = 0;
boolean found = false;
while (!stop) // queue empty of 'te duur'
{
//Item item = (Item) fh_extractmin(queue);
MatchState item = queue.poll();
if (item == null) break;
//System.err.printf("######\nextracted item has pos %d of %d, cost %d\n", item.pos, L, item.cost);
//if (item == startitem) { System.err.printf("Hola: weer startitem, DIT KAN NIET\n"); }
int penaltyIncrement = 0;
if (found)
penaltyIncrement = item.cost - bestCost;
else
bestCost = item.cost;
if (item.lexnode.isFinal && item.position == L)
{
// output suggestie
if (item.cost <= MAX_PENALTY && penaltyIncrement <= MAX_PENALTY_INCREMENT)
{
found = true;
outputSuggestion(item);
nofSuggestions++;
}
}
// queue.size() was activeItems.size
if (nofSuggestions >= MAX_SUGGESTIONS || queue.size() > MAX_ITEMS || item.cost > MAX_PENALTY)
{
break;
}
relaxTransitions(item);
//fh_delete(queue, item.heapEl);
// add all transitions for item [moet dan helaas gediscretiseerd]
// evt kan je op reeds bekende items uitkomen
}
removeDataPointersInLexicon();
//fh_deleteheap(queue);
queue.clear();
return found;
//System.err.printf("took %u msec\n", (endUsecs - startUsecs)/1000);
}
public static void usage()
{
System.err.println("Usage: java spellingvariation.MemorylessMatcher <pattern file> <word list> [<input file>]");
}
class Match
{
String target;
String match;
String reference;
String patterns;
boolean correct;
boolean referenceInLexicon;
double score;
public Match(String target, String match,String reference,
boolean correct, boolean referenceInLexicon, double score, String patterns)
{
this.target=target;
this.match=match;
this.reference=reference;
this.correct=correct;
this.referenceInLexicon = referenceInLexicon;
this.score=score;
this.patterns = patterns;
}
String asXML()
{
return String.format("<match value='%s' correct='%s' OOV='%s' score='%f' appliedPatterns='%s'/>",
esc(match), new Boolean(correct).toString(),
new Boolean(!referenceInLexicon).toString(), score, esc(patterns));
}
}
class TestCallback extends Callback
{
int itemsTested=0;
int noMatch = 0;
int correctMatches = 0;
String reference="";
String currentId="";
boolean referenceInLexicon = false;
int nItemsinLexicon = 0;
List<String> targets = new ArrayList<String>();
Map<String,String> id2target = new HashMap<String,String>();
Map<String,String> id2reference = new HashMap<String,String>();
Map<String,List<Match>> matches = new HashMap<String,List<Match>>();
public void addMatch(Match match) // dit is allemaal fout....
{
List<Match> soFar = matches.get(currentId);
if (soFar == null)
{
soFar = new ArrayList<Match>();
matches.put(currentId, soFar);
}
soFar.add(match);
}
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
Match match = new Match(targetWord, matchedWord, reference, matchedWord.equals(reference),
referenceInLexicon, p, matchInfo);
addMatch(match);
if (matchedWord.equals(reference))
{
correctMatches++;
} else
{
//System.err.println("!!Wrong match: " +targetWord + " =~ " + matchedWord + " (reference = " + reference + ")");
}
//System.out.printf("%s -> %s %s %e %d\n" ,targetWord, matchedWord, matchInfo, p, cost);
}
public void dumpResults()
{
System.out.println("<results>");
for (String h: targets)
{
boolean found=false;
List<Match> matchList = matches.get(h);
String mXML="";
if (matchList != null)
{
for (Match m: matchList)
{
mXML += m.asXML();
found |= m.correct;
}
}
String z = String.format("<matching target='%s' reference='%s' found='%s'>%s</matching>",
esc(this.id2target.get(h)) ,
esc(id2reference.get(h)),
new Boolean(found).toString(),
mXML );
System.out.println(z);
}
System.out.println("</results>");
}
}
public static String esc(String s)
{
return StringUtils.xmlSingleQuotedEscape(s);
}
public void test(Trie lexicon, BufferedReader in)
{
this.lextrie = lexicon;
TestCallback cb = new TestCallback();
this.callback = cb;
try
{
String s;
int k=1;
while ((s=in.readLine()) != null)
{
String[] parts = s.split("\\t");
//String lemma=parts[0];
String id = parts[0]; String modern = parts[1]; String historical = parts[2];
cb.reference = modern;
cb.currentId = String.format("%06d",k);
cb.targets.add(cb.currentId);
cb.referenceInLexicon = lexicon.contains(modern, this.addWordBoundaries);
if (cb.referenceInLexicon) cb.nItemsinLexicon++;
cb.id2reference.put(cb.currentId, cb.reference);
cb.id2target.put(cb.currentId, historical);
cb.itemsTested++;
boolean found = this.matchWordToLexicon(lexicon, historical);
if (!found)
{
cb.noMatch++;
}
k++;
}
cb.dumpResults();
double recallOverall = cb.correctMatches / (double) cb.itemsTested;
double modernLexiconCoverage = 0;
double recallInVocabulary = 0;
try
{
recallInVocabulary = cb.correctMatches / (double) cb.nItemsinLexicon;
modernLexiconCoverage = cb.nItemsinLexicon / (double) cb.itemsTested;
} catch (Exception e)
{
}
System.err.println("Items tested: " + cb.itemsTested + "; correct matches: " + cb.correctMatches + "; no match at all: " + cb.noMatch);
System.err.println("Coverage of modern lexicon on modern equivalents: " + modernLexiconCoverage);
System.err.println("Overall recall: " + recallOverall);
System.err.println("Recall of words in modern lexicon: " + recallInVocabulary);
} catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args)
{
new Options(args);
if (args.length < 2)
{
usage();
System.exit(1);
}
MemorylessMatcher matcher = new MemorylessMatcher(Options.getOption("patternInput"));
Trie lexicon = new Trie();
lexicon.loadWordlist(Options.getOption("lexicon"),
false,
Options.getOptionBoolean("addWordBoundaries", false));
boolean found= false;
java.io.BufferedReader stdin = null;
if ((Options.getOption("testFile")) != null)
{
try
{
Reader reader = new InputStreamReader(
new FileInputStream(Options.getOption("testFile")), "UTF-8");
stdin = new BufferedReader(reader);
} catch (Exception e)
{
e.printStackTrace();
stdin = null;
}
} else
{
try
{
stdin = new BufferedReader(new java.io.InputStreamReader(System.in, "UTF-8"));
} catch (Exception e)
{
e.printStackTrace();
}
}
String cmd = Options.getOption("command");
if (cmd != null && cmd.equals("test"))
{
System.err.println("testing on labeled input");
matcher.test(lexicon, stdin);
System.exit(0);
}
MemorylessMatcher.Callback c = new MemorylessMatcher.Callback ()
{
public void handleMatch(String targetWord, String matchedWord, String matchInfo, int cost, double p)
{
System.out.printf("%s -> %s %s %e\n" ,targetWord, matchedWord, matchInfo, p);
}
@SuppressWarnings("unused")
void noMatch(String targetWord)
{
}
};
matcher.callback = c;
String s;
try
{
while ( (s = stdin.readLine()) != null)
{
found = matcher.matchWordToLexicon(lexicon, s);
if (!found)
{
System.out.println("No match " + s);
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
|
94298_3 | package masterMind;
public class masterMind7
{
public static void main(String args[])
{
vergelijken check = new vergelijken();
String[] controleVak = new String[4];
String[] codeMaker = check.codeAanMaken();
String[] codeBrekerArray = new String[4];
int poging = 1;
do
{
System.out.println("Dit is poging " + poging);
System.out.println("zet je code er in ");
int kleur = 0;
// hier zet je de code er in
for (int i = 0; i < 4; i++)
{
System.out.println("kleur " + (kleur + 1));
codeBrekerArray[kleur] = check.vraagKeuzpin();
kleur++;
}
// checken voor zwart pin, wit pin of geen pin
controleVak = check.controleren(codeMaker, codeBrekerArray);
// zegt of het zwart pin, wit pin of geen pin is
int i = 0;
for (int cijfers = 1; cijfers < 5; cijfers++)
{
System.out.println(cijfers + " " + controleVak[i]);
i++;
}
// print code uit als je het niet geraden hebt
if (poging == 10)
{
for (int x = 0; x < 4; x++)
{
System.out.println(codeMaker[x]);
}
}
// check win of verlies
poging = poging + 1;
check.winVerlies(controleVak);
}
while (poging <= 10 && check.eindResultaat == false);
if (check.eindResultaat == true)
System.out.println("je hebt gewonnen! :) ");
else
{
System.out.println("je hebt helaas niet gewonnen :( ");
}
}
}
| Ruveydabal/MasterMind | src/masterMind/masterMind7.java | 512 | // print code uit als je het niet geraden hebt | line_comment | nl | package masterMind;
public class masterMind7
{
public static void main(String args[])
{
vergelijken check = new vergelijken();
String[] controleVak = new String[4];
String[] codeMaker = check.codeAanMaken();
String[] codeBrekerArray = new String[4];
int poging = 1;
do
{
System.out.println("Dit is poging " + poging);
System.out.println("zet je code er in ");
int kleur = 0;
// hier zet je de code er in
for (int i = 0; i < 4; i++)
{
System.out.println("kleur " + (kleur + 1));
codeBrekerArray[kleur] = check.vraagKeuzpin();
kleur++;
}
// checken voor zwart pin, wit pin of geen pin
controleVak = check.controleren(codeMaker, codeBrekerArray);
// zegt of het zwart pin, wit pin of geen pin is
int i = 0;
for (int cijfers = 1; cijfers < 5; cijfers++)
{
System.out.println(cijfers + " " + controleVak[i]);
i++;
}
// print code<SUF>
if (poging == 10)
{
for (int x = 0; x < 4; x++)
{
System.out.println(codeMaker[x]);
}
}
// check win of verlies
poging = poging + 1;
check.winVerlies(controleVak);
}
while (poging <= 10 && check.eindResultaat == false);
if (check.eindResultaat == true)
System.out.println("je hebt gewonnen! :) ");
else
{
System.out.println("je hebt helaas niet gewonnen :( ");
}
}
}
|
90641_3 | import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
//test voor push en waarom staat die er nog niet in????? oke hij werkt
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Gamebeheer gamebeheer = new Gamebeheer();
Admin admin = new Admin("Admin", "Admin"); // Maak een Admin object
while (true) {
System.out.println("Welkom bij Retrogames!");
System.out.println("1. User Log In ");
System.out.println("2. Admin Log In");
System.out.print("Vul het nummer in waar u heen wilt navigeren: ");
int login = scanner.nextInt();
scanner.nextLine();
switch (login) {
case 1:
System.out.print("Gebruikersnaam: ");
String gebruikersnaam = scanner.nextLine();
System.out.print("Wachtwoord: ");
String wachtwoord = scanner.nextLine();
Gebruiker gebruiker = new Gebruiker(gebruikersnaam, wachtwoord);
if (gebruiker.checkLogin(gebruiker.getUsername(), gebruiker.getPassword())) {
System.out.println("U bent ingelogd als " + gebruiker.getUsername());
System.out.println("1. Bekijk games op genre");//
System.out.println("2. Bekijk alle games");//
System.out.println("3. Voeg review toe");//
System.out.println("4. Bekijk uitverkoop");
System.out.print("Kies een optie: ");
int userOpties = scanner.nextInt();
scanner.nextLine();
switch (userOpties) {
case 1:
gamebeheer.toonBeschikbareGenres();
System.out.print("Welk genre wilt uw zien: ");
String genre = scanner.nextLine();
gamebeheer.toonGamesOpGenre(genre);
break;
case 2:
gamebeheer.toonRanglijst();
break;
case 3:
gamebeheer.toonRanglijst();
System.out.println("Vul review in");
System.out.print("Game: ");
String reviewgame = scanner.nextLine();
System.out.print("Gameplay Rating: ");
double gameplayrating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Graphics Rating: ");
double graphicsrating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Storyline Rating: ");
double storylinerating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Tekst: ");
String tekst = scanner.nextLine();
gamebeheer.AddReview(reviewgame, gameplayrating, graphicsrating, storylinerating, tekst);
System.out.println("Wilt u de enquête invullen? (ja/nee)");
String keuze = scanner.nextLine();
if (keuze.equalsIgnoreCase("ja")) {
System.out.println("Enquête wordt nu gestart.");
gamebeheer.vulEnqueteIn();
} else {
System.out.println("U heeft ervoor gekozen om de enquête niet in te vullen.");
}
break;
case 4:
System.out.println("Uitverkoop");
gamebeheer.toonUitverkoop();
break;
default:
System.out.println("Ongeldige keuze. Probeer opnieuw.");
}
} else {
System.out.println("Ongeldige gebruikersnaam of wachtwoord. Probeer opnieuw.");
}
break;
case 2:
System.out.print("Admin gebruikersnaam: ");
String adminGebruikersnaam = scanner.nextLine();
System.out.print("Admin wachtwoord: ");
String adminWachtwoord = scanner.nextLine();
if (admin.checkLogin(adminGebruikersnaam, adminWachtwoord)) {
System.out.println("U bent ingelogd als " + adminGebruikersnaam);
System.out.println("1. Voeg game toe aan ranglijst");
System.out.println("2. Voeg game toe aan uitverkoop");
System.out.println("3. Verwijder game uit ranglijst");
System.out.println("4. Verwijder game uit uitverkoop");
System.out.println("5. Wijzig de gameprijs van ranglijst");
System.out.println("6. Wijzig de gameprijs van uitverkoop");
System.out.print("Kies een optie: ");
int adminOptie = scanner.nextInt();
scanner.nextLine();
switch(adminOptie){
case 1:
gamebeheer.toonRanglijst();
System.out.print("Game: ");
String game = scanner.nextLine();
System.out.print("Rating: ");
double rating = scanner.nextDouble();
System.out.print("Genre: ");
scanner.nextLine();
String genre = scanner.nextLine();
System.out.print("Prijs: ");
double prijs = scanner.nextDouble();
scanner.nextLine();
gamebeheer.Addranglijst(game, rating, genre, prijs);
gamebeheer.addGenre(genre);
break;
case 2:
gamebeheer.toonRanglijst();
System.out.print("Voer de naam van de game in voor uitverkoop: ");
String gameNaam = scanner.nextLine();
System.out.print("Korting (%): ");
int korting = scanner.nextInt();
scanner.nextLine();
// Zoek de game in de ranglijst
Game gameInRanglijst = gamebeheer.zoekRanglijst(gameNaam);
if (gameInRanglijst != null) {
// Bereken de nieuwe prijs met korting
double dcprijs = gameInRanglijst.getPrijs() * (korting / 100);
double nieuwePrijs = gameInRanglijst.getPrijs() - dcprijs;
// Update de prijs in de ranglijst
gameInRanglijst.setPrijs(nieuwePrijs);
gamebeheer.saveRanglijst();
// Voeg de game toe aan de uitverkoop
gamebeheer.voegToeAanUitverkoop(gameNaam, korting);
} else {
System.out.println("Game met de naam " + gameNaam + " niet gevonden in de ranglijst.");
}
break;
case 3:
gamebeheer.toonRanglijst();
System.out.print("Gameid om te verwijderen: ");
int gameid = scanner.nextInt();
scanner.nextLine();
gamebeheer.verwijderRanglijst(gameid);
break;
case 4:
gamebeheer.toonUitverkoop();
System.out.print("Uitverkoopid om te verwijderen: ");
int uitverkoopid = scanner.nextInt();
scanner.nextLine();
gamebeheer.verwijderUitverkoop(uitverkoopid);
gamebeheer.toonUitverkoop();
break;
case 5:
gamebeheer.toonRanglijst();
System.out.print("Voer de naam van de game in: ");
String gamenaam = scanner.nextLine();
gameInRanglijst = gamebeheer.zoekRanglijst(gamenaam);
if (gameInRanglijst != null) {
System.out.print("Voer de nieuwe prijs in: ");
double nieuwePrijs = scanner.nextDouble();
scanner.nextLine();
gameInRanglijst.setPrijs(nieuwePrijs);
gamebeheer.saveRanglijst();
System.out.println("Prijs voor " + gamenaam + " is bijgewerkt naar " + nieuwePrijs);
} else {
System.out.println("Game met de naam " + gamenaam + " niet gevonden in de ranglijst.");
}
break;
case 6:
gamebeheer.toonUitverkoop();
System.out.print("Voer de naam van de game in: ");
String gameNaamUitverkoop = scanner.nextLine();
Uitverkoop uitverkoop = gamebeheer.zoekUitverkoop(gameNaamUitverkoop);
if (uitverkoop != null) {
System.out.print("Voer de nieuwe prijs in: ");
double nieuwePrijsUitverkoop = scanner.nextDouble();
scanner.nextLine();
uitverkoop.setNewprijs(nieuwePrijsUitverkoop);
gamebeheer.saveUitverkoop();
System.out.println("Prijs voor " + gameNaamUitverkoop + " in uitverkoop is bijgewerkt naar " + nieuwePrijsUitverkoop);
} else {
System.out.println("Uitverkoop met de naam " + gameNaamUitverkoop + " niet gevonden.");
}
break;
}
// Admin is ingelogd, toon admin opties
} else {
System.out.println("Ongeldige admin gebruikersnaam of wachtwoord. Probeer opnieuw.");
}
break;
}
}
}
}
| Byrott0/PROJ1versie2 | src/Main.java | 2,266 | // Bereken de nieuwe prijs met korting | line_comment | nl | import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
//test voor push en waarom staat die er nog niet in????? oke hij werkt
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Gamebeheer gamebeheer = new Gamebeheer();
Admin admin = new Admin("Admin", "Admin"); // Maak een Admin object
while (true) {
System.out.println("Welkom bij Retrogames!");
System.out.println("1. User Log In ");
System.out.println("2. Admin Log In");
System.out.print("Vul het nummer in waar u heen wilt navigeren: ");
int login = scanner.nextInt();
scanner.nextLine();
switch (login) {
case 1:
System.out.print("Gebruikersnaam: ");
String gebruikersnaam = scanner.nextLine();
System.out.print("Wachtwoord: ");
String wachtwoord = scanner.nextLine();
Gebruiker gebruiker = new Gebruiker(gebruikersnaam, wachtwoord);
if (gebruiker.checkLogin(gebruiker.getUsername(), gebruiker.getPassword())) {
System.out.println("U bent ingelogd als " + gebruiker.getUsername());
System.out.println("1. Bekijk games op genre");//
System.out.println("2. Bekijk alle games");//
System.out.println("3. Voeg review toe");//
System.out.println("4. Bekijk uitverkoop");
System.out.print("Kies een optie: ");
int userOpties = scanner.nextInt();
scanner.nextLine();
switch (userOpties) {
case 1:
gamebeheer.toonBeschikbareGenres();
System.out.print("Welk genre wilt uw zien: ");
String genre = scanner.nextLine();
gamebeheer.toonGamesOpGenre(genre);
break;
case 2:
gamebeheer.toonRanglijst();
break;
case 3:
gamebeheer.toonRanglijst();
System.out.println("Vul review in");
System.out.print("Game: ");
String reviewgame = scanner.nextLine();
System.out.print("Gameplay Rating: ");
double gameplayrating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Graphics Rating: ");
double graphicsrating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Storyline Rating: ");
double storylinerating = scanner.nextDouble();
scanner.nextLine();
System.out.print("Tekst: ");
String tekst = scanner.nextLine();
gamebeheer.AddReview(reviewgame, gameplayrating, graphicsrating, storylinerating, tekst);
System.out.println("Wilt u de enquête invullen? (ja/nee)");
String keuze = scanner.nextLine();
if (keuze.equalsIgnoreCase("ja")) {
System.out.println("Enquête wordt nu gestart.");
gamebeheer.vulEnqueteIn();
} else {
System.out.println("U heeft ervoor gekozen om de enquête niet in te vullen.");
}
break;
case 4:
System.out.println("Uitverkoop");
gamebeheer.toonUitverkoop();
break;
default:
System.out.println("Ongeldige keuze. Probeer opnieuw.");
}
} else {
System.out.println("Ongeldige gebruikersnaam of wachtwoord. Probeer opnieuw.");
}
break;
case 2:
System.out.print("Admin gebruikersnaam: ");
String adminGebruikersnaam = scanner.nextLine();
System.out.print("Admin wachtwoord: ");
String adminWachtwoord = scanner.nextLine();
if (admin.checkLogin(adminGebruikersnaam, adminWachtwoord)) {
System.out.println("U bent ingelogd als " + adminGebruikersnaam);
System.out.println("1. Voeg game toe aan ranglijst");
System.out.println("2. Voeg game toe aan uitverkoop");
System.out.println("3. Verwijder game uit ranglijst");
System.out.println("4. Verwijder game uit uitverkoop");
System.out.println("5. Wijzig de gameprijs van ranglijst");
System.out.println("6. Wijzig de gameprijs van uitverkoop");
System.out.print("Kies een optie: ");
int adminOptie = scanner.nextInt();
scanner.nextLine();
switch(adminOptie){
case 1:
gamebeheer.toonRanglijst();
System.out.print("Game: ");
String game = scanner.nextLine();
System.out.print("Rating: ");
double rating = scanner.nextDouble();
System.out.print("Genre: ");
scanner.nextLine();
String genre = scanner.nextLine();
System.out.print("Prijs: ");
double prijs = scanner.nextDouble();
scanner.nextLine();
gamebeheer.Addranglijst(game, rating, genre, prijs);
gamebeheer.addGenre(genre);
break;
case 2:
gamebeheer.toonRanglijst();
System.out.print("Voer de naam van de game in voor uitverkoop: ");
String gameNaam = scanner.nextLine();
System.out.print("Korting (%): ");
int korting = scanner.nextInt();
scanner.nextLine();
// Zoek de game in de ranglijst
Game gameInRanglijst = gamebeheer.zoekRanglijst(gameNaam);
if (gameInRanglijst != null) {
// Bereken de<SUF>
double dcprijs = gameInRanglijst.getPrijs() * (korting / 100);
double nieuwePrijs = gameInRanglijst.getPrijs() - dcprijs;
// Update de prijs in de ranglijst
gameInRanglijst.setPrijs(nieuwePrijs);
gamebeheer.saveRanglijst();
// Voeg de game toe aan de uitverkoop
gamebeheer.voegToeAanUitverkoop(gameNaam, korting);
} else {
System.out.println("Game met de naam " + gameNaam + " niet gevonden in de ranglijst.");
}
break;
case 3:
gamebeheer.toonRanglijst();
System.out.print("Gameid om te verwijderen: ");
int gameid = scanner.nextInt();
scanner.nextLine();
gamebeheer.verwijderRanglijst(gameid);
break;
case 4:
gamebeheer.toonUitverkoop();
System.out.print("Uitverkoopid om te verwijderen: ");
int uitverkoopid = scanner.nextInt();
scanner.nextLine();
gamebeheer.verwijderUitverkoop(uitverkoopid);
gamebeheer.toonUitverkoop();
break;
case 5:
gamebeheer.toonRanglijst();
System.out.print("Voer de naam van de game in: ");
String gamenaam = scanner.nextLine();
gameInRanglijst = gamebeheer.zoekRanglijst(gamenaam);
if (gameInRanglijst != null) {
System.out.print("Voer de nieuwe prijs in: ");
double nieuwePrijs = scanner.nextDouble();
scanner.nextLine();
gameInRanglijst.setPrijs(nieuwePrijs);
gamebeheer.saveRanglijst();
System.out.println("Prijs voor " + gamenaam + " is bijgewerkt naar " + nieuwePrijs);
} else {
System.out.println("Game met de naam " + gamenaam + " niet gevonden in de ranglijst.");
}
break;
case 6:
gamebeheer.toonUitverkoop();
System.out.print("Voer de naam van de game in: ");
String gameNaamUitverkoop = scanner.nextLine();
Uitverkoop uitverkoop = gamebeheer.zoekUitverkoop(gameNaamUitverkoop);
if (uitverkoop != null) {
System.out.print("Voer de nieuwe prijs in: ");
double nieuwePrijsUitverkoop = scanner.nextDouble();
scanner.nextLine();
uitverkoop.setNewprijs(nieuwePrijsUitverkoop);
gamebeheer.saveUitverkoop();
System.out.println("Prijs voor " + gameNaamUitverkoop + " in uitverkoop is bijgewerkt naar " + nieuwePrijsUitverkoop);
} else {
System.out.println("Uitverkoop met de naam " + gameNaamUitverkoop + " niet gevonden.");
}
break;
}
// Admin is ingelogd, toon admin opties
} else {
System.out.println("Ongeldige admin gebruikersnaam of wachtwoord. Probeer opnieuw.");
}
break;
}
}
}
}
|
132801_12 | /*
* Copyright (C) 2017 B3Partners B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package nl.b3p.jdbc.util.converter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
/**
* @author Matthijs Laan
* @author Meine Toonen
* @author mprins
*/
public abstract class GeometryJdbcConverter {
private static final Log LOG = LogFactory.getLog(GeometryJdbcConverter.class);
protected final WKTReader wkt = new WKTReader();
protected GeometryFactory gf = new GeometryFactory();
public static Object convertToSQLObject(
String stringValue, ColumnMetadata cm, String tableName, String column) {
Object param;
stringValue = stringValue.trim();
switch (cm.getDataType()) {
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
case java.sql.Types.INTEGER:
try {
param = new BigDecimal(stringValue);
} catch (NumberFormatException nfe) {
// try to convert to 1/0 for Oracle boolean
if ("true".equalsIgnoreCase(stringValue)) {
param = BigDecimal.ONE;
} else if ("false".equalsIgnoreCase(stringValue)) {
param = BigDecimal.ZERO;
} else {
throw new NumberFormatException(
String.format(
"Conversie van waarde \"%s\" naar type %s voor %s.%s niet mogelijk",
stringValue, cm.getTypeName(), tableName, cm.getName()));
}
}
break;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.LONGNVARCHAR:
case java.sql.Types.LONGVARCHAR:
param = stringValue;
break;
case java.sql.Types.DATE:
case java.sql.Types.TIMESTAMP:
try {
param = LocalDateTime.parse(stringValue);
} catch (DateTimeParseException e) {
LOG.debug(
"Parsen van waarde "
+ stringValue
+ " als LocalDateTime is mislukt, probeer als "
+ "LocalDate.");
try {
param = LocalDate.parse(stringValue).atTime(0, 0);
} catch (DateTimeParseException e2) {
LOG.error("Fout tijdens parsen van waarde " + stringValue + " als LocalDate", e2);
param = null;
}
}
if (param != null) {
param =
new java.sql.Date(
Date.from(((LocalDateTime) param).atZone(ZoneId.systemDefault()).toInstant())
.getTime());
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
param = Boolean.parseBoolean(stringValue);
break;
// case java.sql.Types.BIT:
// PostgreSQL boolean kolom komt uit de JDBC drivar als BIT / -7 en niet als
// BOOLEAN / 16
// // try to convert to 1/0 for MSSQL boolean
// if ("true".equalsIgnoreCase(stringValue)) {
// param = 1;
// } else if ("false".equalsIgnoreCase(stringValue)) {
// param = 0;
// } else {
// param = Integer.parseInt(stringValue);
// }
// break;
default:
throw new UnsupportedOperationException(
String.format(
"Data type %s (#%d) van kolom \"%s\" wordt niet ondersteund.",
cm.getTypeName(), cm.getDataType(), cm.getName()));
}
return param;
}
// definieer placeholder als ? wanneer object naar native geometry wordt
// geconverteerd
// defineer placeholder via native wkt-import functie als geometry als
// wkt-string wordt doorgegeven
public abstract Object convertToNativeGeometryObject(Geometry param)
throws SQLException, ParseException;
public abstract Object convertToNativeGeometryObject(Geometry param, int srid)
throws SQLException, ParseException;
public abstract Geometry convertToJTSGeometryObject(Object nativeObj);
public String createPSGeometryPlaceholder() throws SQLException {
return "?";
}
public abstract String getSchema();
public abstract String getGeomTypeName();
public abstract boolean isDuplicateKeyViolationMessage(String message);
/**
* bepaal of een melding een constraint violation betreft.
*
* @param message de melding uit de database
* @return {@code true} als de melding een contraint violation betreft
*/
public abstract boolean isFKConstraintViolationMessage(String message);
public abstract String buildPaginationSql(String sql, int offset, int limit);
public abstract StringBuilder buildLimitSql(StringBuilder sql, int limit);
public abstract boolean useSavepoints();
public abstract boolean isPmdKnownBroken();
public abstract String getMViewsSQL();
public abstract String getMViewRefreshSQL(String mview);
/**
* Gets a statement to use in a {@link java.sql.PreparedStatement } to restart a sequence.
*
* @param seqName name of sequence
* @param nextVal the value to restart the sequence, some systems require this to be larger than
* the next value of the sequence.
* @return SQL statement specific for the flavour of database
*/
public String getUpdateSequenceSQL(String seqName, long nextVal) {
// supported for postgres, ms sql, hsqldb, NB return values vary
// https://www.postgresql.org/docs/11/sql-altersequence.html
// https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-sequence-transact-sql?view=sql-server-ver15
return String.format("ALTER SEQUENCE %s RESTART WITH %d", seqName, nextVal);
}
/**
* get the database flavour specific SQL statement to get the next value from a sequence.
*
* @param seqName name of sequence
* @return SQL statement specific for the flavour of database
*/
public abstract String getSelectNextValueFromSequenceSQL(String seqName);
public abstract String getGeotoolsDBTypeName();
public Object convertToNativeGeometryObject(String param) throws ParseException, SQLException {
Geometry o = null;
if (param != null && param.trim().length() > 0) {
o = wkt.read(param);
}
return convertToNativeGeometryObject(o);
}
public Object createNativePoint(double lat, double lon, int srid)
throws SQLException, ParseException {
if (lat == 0 || lon == 0) {
return null;
}
Point p = gf.createPoint(new Coordinate(lon, lat));
return convertToNativeGeometryObject(p, srid);
}
}
| B3Partners/jdbc-util | src/main/java/nl/b3p/jdbc/util/converter/GeometryJdbcConverter.java | 2,007 | // definieer placeholder als ? wanneer object naar native geometry wordt | line_comment | nl | /*
* Copyright (C) 2017 B3Partners B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package nl.b3p.jdbc.util.converter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
/**
* @author Matthijs Laan
* @author Meine Toonen
* @author mprins
*/
public abstract class GeometryJdbcConverter {
private static final Log LOG = LogFactory.getLog(GeometryJdbcConverter.class);
protected final WKTReader wkt = new WKTReader();
protected GeometryFactory gf = new GeometryFactory();
public static Object convertToSQLObject(
String stringValue, ColumnMetadata cm, String tableName, String column) {
Object param;
stringValue = stringValue.trim();
switch (cm.getDataType()) {
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
case java.sql.Types.INTEGER:
try {
param = new BigDecimal(stringValue);
} catch (NumberFormatException nfe) {
// try to convert to 1/0 for Oracle boolean
if ("true".equalsIgnoreCase(stringValue)) {
param = BigDecimal.ONE;
} else if ("false".equalsIgnoreCase(stringValue)) {
param = BigDecimal.ZERO;
} else {
throw new NumberFormatException(
String.format(
"Conversie van waarde \"%s\" naar type %s voor %s.%s niet mogelijk",
stringValue, cm.getTypeName(), tableName, cm.getName()));
}
}
break;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.LONGNVARCHAR:
case java.sql.Types.LONGVARCHAR:
param = stringValue;
break;
case java.sql.Types.DATE:
case java.sql.Types.TIMESTAMP:
try {
param = LocalDateTime.parse(stringValue);
} catch (DateTimeParseException e) {
LOG.debug(
"Parsen van waarde "
+ stringValue
+ " als LocalDateTime is mislukt, probeer als "
+ "LocalDate.");
try {
param = LocalDate.parse(stringValue).atTime(0, 0);
} catch (DateTimeParseException e2) {
LOG.error("Fout tijdens parsen van waarde " + stringValue + " als LocalDate", e2);
param = null;
}
}
if (param != null) {
param =
new java.sql.Date(
Date.from(((LocalDateTime) param).atZone(ZoneId.systemDefault()).toInstant())
.getTime());
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
param = Boolean.parseBoolean(stringValue);
break;
// case java.sql.Types.BIT:
// PostgreSQL boolean kolom komt uit de JDBC drivar als BIT / -7 en niet als
// BOOLEAN / 16
// // try to convert to 1/0 for MSSQL boolean
// if ("true".equalsIgnoreCase(stringValue)) {
// param = 1;
// } else if ("false".equalsIgnoreCase(stringValue)) {
// param = 0;
// } else {
// param = Integer.parseInt(stringValue);
// }
// break;
default:
throw new UnsupportedOperationException(
String.format(
"Data type %s (#%d) van kolom \"%s\" wordt niet ondersteund.",
cm.getTypeName(), cm.getDataType(), cm.getName()));
}
return param;
}
// definieer placeholder<SUF>
// geconverteerd
// defineer placeholder via native wkt-import functie als geometry als
// wkt-string wordt doorgegeven
public abstract Object convertToNativeGeometryObject(Geometry param)
throws SQLException, ParseException;
public abstract Object convertToNativeGeometryObject(Geometry param, int srid)
throws SQLException, ParseException;
public abstract Geometry convertToJTSGeometryObject(Object nativeObj);
public String createPSGeometryPlaceholder() throws SQLException {
return "?";
}
public abstract String getSchema();
public abstract String getGeomTypeName();
public abstract boolean isDuplicateKeyViolationMessage(String message);
/**
* bepaal of een melding een constraint violation betreft.
*
* @param message de melding uit de database
* @return {@code true} als de melding een contraint violation betreft
*/
public abstract boolean isFKConstraintViolationMessage(String message);
public abstract String buildPaginationSql(String sql, int offset, int limit);
public abstract StringBuilder buildLimitSql(StringBuilder sql, int limit);
public abstract boolean useSavepoints();
public abstract boolean isPmdKnownBroken();
public abstract String getMViewsSQL();
public abstract String getMViewRefreshSQL(String mview);
/**
* Gets a statement to use in a {@link java.sql.PreparedStatement } to restart a sequence.
*
* @param seqName name of sequence
* @param nextVal the value to restart the sequence, some systems require this to be larger than
* the next value of the sequence.
* @return SQL statement specific for the flavour of database
*/
public String getUpdateSequenceSQL(String seqName, long nextVal) {
// supported for postgres, ms sql, hsqldb, NB return values vary
// https://www.postgresql.org/docs/11/sql-altersequence.html
// https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-sequence-transact-sql?view=sql-server-ver15
return String.format("ALTER SEQUENCE %s RESTART WITH %d", seqName, nextVal);
}
/**
* get the database flavour specific SQL statement to get the next value from a sequence.
*
* @param seqName name of sequence
* @return SQL statement specific for the flavour of database
*/
public abstract String getSelectNextValueFromSequenceSQL(String seqName);
public abstract String getGeotoolsDBTypeName();
public Object convertToNativeGeometryObject(String param) throws ParseException, SQLException {
Geometry o = null;
if (param != null && param.trim().length() > 0) {
o = wkt.read(param);
}
return convertToNativeGeometryObject(o);
}
public Object createNativePoint(double lat, double lon, int srid)
throws SQLException, ParseException {
if (lat == 0 || lon == 0) {
return null;
}
Point p = gf.createPoint(new Coordinate(lon, lat));
return convertToNativeGeometryObject(p, srid);
}
}
|
13747_11 | package com.company.afvink3;
/**
* Race class
* Class Race maakt gebruik van de class Paard
*
* @author Martijn van der Bruggen
* @version alpha - aanroep van cruciale methodes ontbreekt
* (c) 2009 Hogeschool van Arnhem en Nijmegen
*
* Note: deze code is bewust niet op alle punten generiek
* dit om nog onbekende constructies te vermijden.
*
* Updates
* 2010: verduidelijking van opdrachten in de code MvdB
* 2011: verbetering leesbaarheid code MvdB
* 2012: verbetering layout code en aanpassing commentaar MvdB
* 2013: commentaar aangepast aan nieuwe opdracht MvdB
*
*************************************************
* Afvinkopdracht: werken met methodes en objecten
*************************************************
* Opdrachten zitten verwerkt in de code
* 1) Declaratie constante
* 2) Declaratie van Paard (niet instantiering)
* 3) Declareer een button
* 4) Zet breedte en hoogte van het frame
* 5) Teken een finish streep
* 6) Creatie van 4 paarden
* 7) Pauzeer
* 8) Teken 4 paarden
* 9) Plaats tekst op de button
* 10) Start de race, methode aanroep
*
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Race extends JFrame implements ActionListener {
/** declaratie van variabelen */
private int lengte =500;
Paard h1 = new Paard("h1",Color.gray);
Paard h2 = new Paard("h2",Color.BLUE);
Paard h3 = new Paard("h3",Color.red);
Paard h4 = new Paard("h3",Color.green);
Paard h5 = new Paard("h5",Color.yellow);/* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */
/* (2) Declareer hier h1, h2, h3, h4 van het type Paard
* Deze paarden instantieer je later in het programma
*/
JButton button = new JButton();/* (3) Declareer een button met de naam button van het type JButton */
private JPanel panel;
/** Applicatie - main functie voor runnen applicatie */
public static void main(String[] args) {
Race frame = new Race();
frame.setSize(800,350);/* (4) Geef het frame een breedte van 400 en hoogte van 140 */
frame.createGUI();
frame.setVisible(true);
}
/** Loop de race
*/
private void startRace(Graphics g) {
panel.setBackground(Color.white);
/** Tekenen van de finish streep */
/* (5) Geef de finish streep een rode kleur */
g.setColor(Color.red);
g.fillRect(lengte , 0, 3, 300);
/**(6) Creatie van 4 paarden
* Dit is een instantiering van de 4 paard objecten
* Bij de instantiering geef je de paarden een naam en een kleur mee
* Kijk in de class Paard hoe je de paarden
* kunt initialiseren.
*/
/** Loop tot een paard over de finish is*/
while (h1.getAfstand() < lengte
&& h2.getAfstand() < lengte
&& h3.getAfstand() < lengte
&& h4.getAfstand() < lengte
&& h4.getAfstand() < lengte){
h1.run();
h2.run();
h3.run();
h4.run();
h5.run();
pauzeer(100);
/* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig
* dat er 1 seconde pauze is. De methode pauzeer is onderdeel
* van deze class
*/
tekenPaard(g,h1);
tekenPaard(g,h2);
tekenPaard(g,h3);
tekenPaard(g,h4);
tekenPaard(g,h5);
/* (8) Voeg hier code in om 4 paarden te tekenen die rennen
* Dus een call van de methode tekenPaard
*/
}
/** Kijk welk paard gewonnen heeft
*/
if (h1.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");
}
if (h2.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");
}
if (h3.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");
}
if (h4.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");
}
if (h5.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!");
}
}
/** Creatie van de GUI*/
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 250));
panel.setBackground(Color.white);
window.add(panel);
button.setText("RUN!");/* (9) Zet hier de tekst Run! op de button */
window.add(button);
button.addActionListener(this);
}
/** Teken het paard */
private void tekenPaard(Graphics g, Paard h) {
Image img1 = Toolkit.getDefaultToolkit().getImage("C:\\Users\\brian\\Pictures\\horse.png");
g.setColor(Color.white);
g.fillRect(0, 40 * h.getPaardNummer(), h.getAfstand() + 40 , 44);
g.drawImage(img1,h.getAfstand(),40 * h.getPaardNummer() , this);
}
/** Actie indien de button geklikt is*/
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
/* (10) Roep hier de methode startrace aan met de juiste parameterisering */
startRace (paper);
}
/** Pauzeer gedurende x millisecondes*/
public void pauzeer(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
System.out.println("Pauze interruptie");
}
}
}
| itbc-bin/1819-owe5a-afvinkopdracht3-Brianvanwessel | afvink3/Race.java | 1,677 | /** Loop tot een paard over de finish is*/ | block_comment | nl | package com.company.afvink3;
/**
* Race class
* Class Race maakt gebruik van de class Paard
*
* @author Martijn van der Bruggen
* @version alpha - aanroep van cruciale methodes ontbreekt
* (c) 2009 Hogeschool van Arnhem en Nijmegen
*
* Note: deze code is bewust niet op alle punten generiek
* dit om nog onbekende constructies te vermijden.
*
* Updates
* 2010: verduidelijking van opdrachten in de code MvdB
* 2011: verbetering leesbaarheid code MvdB
* 2012: verbetering layout code en aanpassing commentaar MvdB
* 2013: commentaar aangepast aan nieuwe opdracht MvdB
*
*************************************************
* Afvinkopdracht: werken met methodes en objecten
*************************************************
* Opdrachten zitten verwerkt in de code
* 1) Declaratie constante
* 2) Declaratie van Paard (niet instantiering)
* 3) Declareer een button
* 4) Zet breedte en hoogte van het frame
* 5) Teken een finish streep
* 6) Creatie van 4 paarden
* 7) Pauzeer
* 8) Teken 4 paarden
* 9) Plaats tekst op de button
* 10) Start de race, methode aanroep
*
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Race extends JFrame implements ActionListener {
/** declaratie van variabelen */
private int lengte =500;
Paard h1 = new Paard("h1",Color.gray);
Paard h2 = new Paard("h2",Color.BLUE);
Paard h3 = new Paard("h3",Color.red);
Paard h4 = new Paard("h3",Color.green);
Paard h5 = new Paard("h5",Color.yellow);/* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */
/* (2) Declareer hier h1, h2, h3, h4 van het type Paard
* Deze paarden instantieer je later in het programma
*/
JButton button = new JButton();/* (3) Declareer een button met de naam button van het type JButton */
private JPanel panel;
/** Applicatie - main functie voor runnen applicatie */
public static void main(String[] args) {
Race frame = new Race();
frame.setSize(800,350);/* (4) Geef het frame een breedte van 400 en hoogte van 140 */
frame.createGUI();
frame.setVisible(true);
}
/** Loop de race
*/
private void startRace(Graphics g) {
panel.setBackground(Color.white);
/** Tekenen van de finish streep */
/* (5) Geef de finish streep een rode kleur */
g.setColor(Color.red);
g.fillRect(lengte , 0, 3, 300);
/**(6) Creatie van 4 paarden
* Dit is een instantiering van de 4 paard objecten
* Bij de instantiering geef je de paarden een naam en een kleur mee
* Kijk in de class Paard hoe je de paarden
* kunt initialiseren.
*/
/** Loop tot een<SUF>*/
while (h1.getAfstand() < lengte
&& h2.getAfstand() < lengte
&& h3.getAfstand() < lengte
&& h4.getAfstand() < lengte
&& h4.getAfstand() < lengte){
h1.run();
h2.run();
h3.run();
h4.run();
h5.run();
pauzeer(100);
/* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig
* dat er 1 seconde pauze is. De methode pauzeer is onderdeel
* van deze class
*/
tekenPaard(g,h1);
tekenPaard(g,h2);
tekenPaard(g,h3);
tekenPaard(g,h4);
tekenPaard(g,h5);
/* (8) Voeg hier code in om 4 paarden te tekenen die rennen
* Dus een call van de methode tekenPaard
*/
}
/** Kijk welk paard gewonnen heeft
*/
if (h1.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");
}
if (h2.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");
}
if (h3.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");
}
if (h4.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");
}
if (h5.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!");
}
}
/** Creatie van de GUI*/
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 250));
panel.setBackground(Color.white);
window.add(panel);
button.setText("RUN!");/* (9) Zet hier de tekst Run! op de button */
window.add(button);
button.addActionListener(this);
}
/** Teken het paard */
private void tekenPaard(Graphics g, Paard h) {
Image img1 = Toolkit.getDefaultToolkit().getImage("C:\\Users\\brian\\Pictures\\horse.png");
g.setColor(Color.white);
g.fillRect(0, 40 * h.getPaardNummer(), h.getAfstand() + 40 , 44);
g.drawImage(img1,h.getAfstand(),40 * h.getPaardNummer() , this);
}
/** Actie indien de button geklikt is*/
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
/* (10) Roep hier de methode startrace aan met de juiste parameterisering */
startRace (paper);
}
/** Pauzeer gedurende x millisecondes*/
public void pauzeer(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
System.out.println("Pauze interruptie");
}
}
}
|
11158_3 | import Command.Player;
import FactoryMethod.MediaFactory;
import Media.*;
import Observer.MovieDataService;
import Observer.User;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
System.out.println("Welkom bij NetNix");
// Command pattern demo
Player player = new Player();
// Buttons worden normaal gesproken uitgevoerd door de GUI
player.play();
player.pause();
// Adapter pattern demo
HashMap<String, Integer> ondertitelRegels = new HashMap<>();
ondertitelRegels.put("Deze regel tekst komt voor in de eerste seconde.", 1);
ondertitelRegels.put("Ik heb niks gedaan! Wat gebeurt er???", 24);
ondertitelRegels.put("Inspirationele tekst hier", 15);
StommeOndertiteling stommeOndertiteling = new StommeOndertiteling("Nederlands", "srt", ondertitelRegels);
// Werkt niet!! Stomme ondertiteling werkt niet met Film.
// Film film = new Film("The Shawshank Redemption", null, stommeOndertiteling, 142, "Two imprisoned", Categorie.ACTIE);
StommeOndertitelingAdapter adapter = new StommeOndertitelingAdapter(stommeOndertiteling);
// Werkt wel! Adapter zorgt ervoor dat stomme ondertiteling werkt met Film.
Film film = new Film("The Shawshank Redemption", null, adapter.getOndertiteling(), 142, "Two imprisoned", Categorie.ACTIE);
// Factory method
MediaFactory mediaFactory = new MediaFactory();
// create serie
AbstractMedia serieBreakingBad = mediaFactory.createMedia( "Serie", "Breaking Bad", new Poster("Breaking Bad poster", "breakingbad.jpg", "2008-01-20"),
new ArrayList<>(), "A high school chemistry teacher turned meth producer", null, 50, Categorie.DRAMA);
// create film
AbstractMedia filmTerminator = mediaFactory.createMedia("Film", "Terminator", new Poster("Terminator poster", "terminator.jpg", "1984-01-10"),
new ArrayList<>(), "A cyborg assassin sent back in time to kill Sarah Connor", adapter.getOndertiteling(), 120, Categorie.SCIENCEFICTION);
// MovieObserver pattern demo
User account1 = new User("John Doe");
MovieDataService movieDataService = new MovieDataService();
movieDataService.addObserver(account1);
movieDataService.fetchMovieData(filmTerminator);
}
} | jeffrey0402/NetNix | src/Main.java | 609 | // Werkt niet!! Stomme ondertiteling werkt niet met Film. | line_comment | nl | import Command.Player;
import FactoryMethod.MediaFactory;
import Media.*;
import Observer.MovieDataService;
import Observer.User;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
System.out.println("Welkom bij NetNix");
// Command pattern demo
Player player = new Player();
// Buttons worden normaal gesproken uitgevoerd door de GUI
player.play();
player.pause();
// Adapter pattern demo
HashMap<String, Integer> ondertitelRegels = new HashMap<>();
ondertitelRegels.put("Deze regel tekst komt voor in de eerste seconde.", 1);
ondertitelRegels.put("Ik heb niks gedaan! Wat gebeurt er???", 24);
ondertitelRegels.put("Inspirationele tekst hier", 15);
StommeOndertiteling stommeOndertiteling = new StommeOndertiteling("Nederlands", "srt", ondertitelRegels);
// Werkt niet!!<SUF>
// Film film = new Film("The Shawshank Redemption", null, stommeOndertiteling, 142, "Two imprisoned", Categorie.ACTIE);
StommeOndertitelingAdapter adapter = new StommeOndertitelingAdapter(stommeOndertiteling);
// Werkt wel! Adapter zorgt ervoor dat stomme ondertiteling werkt met Film.
Film film = new Film("The Shawshank Redemption", null, adapter.getOndertiteling(), 142, "Two imprisoned", Categorie.ACTIE);
// Factory method
MediaFactory mediaFactory = new MediaFactory();
// create serie
AbstractMedia serieBreakingBad = mediaFactory.createMedia( "Serie", "Breaking Bad", new Poster("Breaking Bad poster", "breakingbad.jpg", "2008-01-20"),
new ArrayList<>(), "A high school chemistry teacher turned meth producer", null, 50, Categorie.DRAMA);
// create film
AbstractMedia filmTerminator = mediaFactory.createMedia("Film", "Terminator", new Poster("Terminator poster", "terminator.jpg", "1984-01-10"),
new ArrayList<>(), "A cyborg assassin sent back in time to kill Sarah Connor", adapter.getOndertiteling(), 120, Categorie.SCIENCEFICTION);
// MovieObserver pattern demo
User account1 = new User("John Doe");
MovieDataService movieDataService = new MovieDataService();
movieDataService.addObserver(account1);
movieDataService.fetchMovieData(filmTerminator);
}
} |
4790_6 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class Level2 extends World{
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public Level2() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg_night.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,184,184,184,-1,-1,184,184,-1,-1,-1,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{187,-1,-1,-1,-1,187,-1,184,184,184,187,-1,184,184,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,231,232,-1},
{-1,-1,-1,204,208,189,-1,184,184,184,-1,-1,184,184,187,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,32,30,36},
{-1,187,-1,17,17,17,-1,230,230,230,-1,-1,184,184,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,230,230,-1,-1,185,-1,-1,-1,187,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,190,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,187,-1,-1,-1,-1,187,187,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,241,165,165,242,-1,-1,-1,186,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,190,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,187,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,160,150,150,161,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,165,165,242,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,96,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,220,241,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,160,150,150,161,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,96,-1,-1},
{220,219,128,219,-1,-1,-1,-1,-1,-1,-1,-1,221,241,160,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,160,150,150,150,150,242,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,190,189,189,96,-1,194},
{165,165,165,165,242,-1,-1,-1,219,219,190,221,241,150,150,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,165,150,150,150,150,150,161,-1,-1,-1,-1,190,-1,-1,-1,-1,-1,16,16,16,17,17,17,19,19,19},
{150,150,150,150,161,187,187,187,153,165,165,165,160,150,150,150,150,150,150,-1,-1,-1,-1,-1,190,190,-1,-1,-1,160,150,150,150,150,150,150,150,-1,-1,241,165,165,165,242,-1,16,16,185,-1,-1,-1,-1,-1,241,165,165},
{150,150,150,150,150,186,186,186,-1,150,150,150,150,150,150,150,150,150,150,186,186,186,241,165,165,165,165,242,-1,150,150,150,150,150,150,150,150,186,186,160,150,150,150,161,186,186,186,186,186,186,186,186,186,160,150,150},
{150,150,150,150,150,185,185,185,-1,150,150,150,150,150,150,150,150,150,150,185,185,185,160,150,150,150,150,161,185,150,150,150,150,150,150,150,150,185,185,150,150,150,150,150,185,185,185,185,185,185,185,185,185,150,150,150},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero(te);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 100, 600);
addObject(new Enemy(), 600, 705);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
Greenfoot.playSound ("Cannery.mp3");
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-LucaOgier | Level2.java | 2,849 | // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class Level2 extends World{
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public Level2() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg_night.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,184,184,184,-1,-1,184,184,-1,-1,-1,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{187,-1,-1,-1,-1,187,-1,184,184,184,187,-1,184,184,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,231,232,-1},
{-1,-1,-1,204,208,189,-1,184,184,184,-1,-1,184,184,187,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,32,30,36},
{-1,187,-1,17,17,17,-1,230,230,230,-1,-1,184,184,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,187,-1,230,230,-1,-1,185,-1,-1,-1,187,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,190,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,187,-1,-1,-1,-1,187,187,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,241,165,165,242,-1,-1,-1,186,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,190,-1,-1,-1,187,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,187,-1,19,19,19},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,160,150,150,161,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,165,165,242,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,186,-1,-1,-1,-1,-1,-1,96,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,220,241,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,160,150,150,161,-1,-1,-1,-1,-1,185,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,96,-1,-1},
{220,219,128,219,-1,-1,-1,-1,-1,-1,-1,-1,221,241,160,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,160,150,150,150,150,242,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,190,189,189,96,-1,194},
{165,165,165,165,242,-1,-1,-1,219,219,190,221,241,150,150,150,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,241,165,150,150,150,150,150,161,-1,-1,-1,-1,190,-1,-1,-1,-1,-1,16,16,16,17,17,17,19,19,19},
{150,150,150,150,161,187,187,187,153,165,165,165,160,150,150,150,150,150,150,-1,-1,-1,-1,-1,190,190,-1,-1,-1,160,150,150,150,150,150,150,150,-1,-1,241,165,165,165,242,-1,16,16,185,-1,-1,-1,-1,-1,241,165,165},
{150,150,150,150,150,186,186,186,-1,150,150,150,150,150,150,150,150,150,150,186,186,186,241,165,165,165,165,242,-1,150,150,150,150,150,150,150,150,186,186,160,150,150,150,161,186,186,186,186,186,186,186,186,186,160,150,150},
{150,150,150,150,150,185,185,185,-1,150,150,150,150,150,150,150,150,150,150,185,185,185,160,150,150,150,150,161,185,150,150,150,150,150,150,150,150,185,185,150,150,150,150,150,185,185,185,185,185,185,185,185,185,150,150,150},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de<SUF>
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero(te);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 100, 600);
addObject(new Enemy(), 600, 705);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
Greenfoot.playSound ("Cannery.mp3");
}
@Override
public void act() {
ce.update();
}
}
|
45760_41 | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order = 1;
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
| Arodev76/L2Advanced | src/main/java/l2f/gameserver/model/entity/achievements/PlayerCounters.java | 3,235 | // int order = 1; | line_comment | nl | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order<SUF>
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
|
178396_18 | 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.Calendar;
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 = null;
System.out.println("STAP 1");
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst =
persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
// lijst samenvoegen - stap5
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
// 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 null;
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum()))
{//samenvoegen:
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>>
omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return null;
}
//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 null;
}
//Oefening DomeinController:
public String autoMap_ToString() {
//String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
//String res = autoOnderhoudMap.
return null;
}
public String overzicht_ToString() {
overzichtteller = 1;
//String res = overzichtLijstVanAutos.
return null;
}
}
| GuusDb/javaASDoefs | java/herhalingsoefeningen/ASDI_Java_Garage_start/src/domein/Garage.java | 1,052 | //String res = overzichtLijstVanAutos. | 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.Calendar;
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 = null;
System.out.println("STAP 1");
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst =
persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
// lijst samenvoegen - stap5
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
// 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 null;
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum()))
{//samenvoegen:
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>>
omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return null;
}
//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 null;
}
//Oefening DomeinController:
public String autoMap_ToString() {
//String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
//String res = autoOnderhoudMap.
return null;
}
public String overzicht_ToString() {
overzichtteller = 1;
//String res<SUF>
return null;
}
}
|
204525_14 | package week1;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class MiniAktk {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
throw new RuntimeException("Exactly one command line argument (path) required");
}
Path path = Paths.get(args[0]);
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Map<Character, Integer> environment = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
line = removeComment(line);
if (line.startsWith("print ")) { // print järel peab olema tühik
String expression = line.substring(6);
System.out.println(evaluateExpression(expression, environment));
}
else if (line.contains("=")) {
String[] parts = line.split("=");
if (parts.length != 2) {
throw new RuntimeException("Malformed assignment");
}
String trimmed = parts[0].trim();
if (trimmed.length() != 1) {
throw new RuntimeException("Variable name must be 1 character");
}
char variableName = trimmed.charAt(0);
if (!Character.isLetter(variableName)) {
throw new RuntimeException("Variable name must be a letter");
}
String expression = parts[1];
environment.put(variableName, evaluateExpression(expression, environment));
}
else if (!line.trim().isEmpty()) { // tühi rida pole viga
throw new RuntimeException("Malformed line: " + line);
}
}
}
}
/**
* Eemaldab realt kommentaari, kui see seal on.
*/
private static String removeComment(String line) {
if (line.contains("#")) return line.substring(0, line.indexOf('#'));
else return line;
}
private static int evaluateExpression(String expression, Map<Character, Integer> environment) {
// Ümbritseme liitmised tühikutega, asendame lahutamise negatiivse arvu liitmisega,
// näiteks teisendame "a +b-c" kujule "a + b + -c", siis saab arvud lihtsalt kokku liita!
// (Eeldame, et esialgses avaldises on ainult märgita täisarvud)
expression = expression.replace("+", " + ").replace("-", " + -");
String[] summands = expression.split("\\+");
int sum = 0;
for (String summand : summands) {
sum += evaluateSummand(summand.trim(), environment);
}
return sum;
}
/*
* Väärtustab märgita või miinusega täisarvu või muutujanime.
*/
private static int evaluateSummand(String summand, Map<Character, Integer> environment) {
int sign = 1;
summand = summand.trim();
if (summand.startsWith("-")) {
sign = -1;
summand = summand.substring(1).trim();
}
// proovime täisarvuna tõlgendada, kui ei saa, siis peaks olema muutuja
try {
return sign * Integer.parseInt(summand);
} catch (NumberFormatException e) {
char variableName = summand.charAt(0);
if (environment.containsKey(variableName)) {
return sign * environment.get(variableName);
}
else {
throw new RuntimeException("Variable " + variableName + " undefined");
}
}
}
/**
* Alternatiivne lahendus: sümbolhaaval avaldise väärtustamine.
* Võrdle Exercise3 eval näidislahendusega:
* * Miinustega arvestamiseks piisab sign muutuja lisamisest.
* * Vigade tuvastamiseks läheb vaja ebatriviaalseid abimuutujate kombinatsioone.
*/
private static int evaluateExpressionAlt(String expression, Map<Character, Integer> environment) {
// avaldise väärtustamiseks vajalikud muutujad
int sum = 0;
int sign = 1; // "märk" (1 või -1) millega järgmine number/muutuja liidetakse
int current = 0;
// vigaste avaldiste tuvastamiseks vajalikud muutujad
boolean needOperand = true; // kas järgmine sümbol PEAB olema number või muutuja nimi?
boolean acceptDigit = true; // kas järgmine sümbol VÕIB olla number?
for (char c : expression.toCharArray()) {
if (Character.isDigit(c) && acceptDigit) {
current = 10 * current + Character.getNumericValue(c);
needOperand = false;
// endiselt acceptDigit on true
} else if (Character.isLetter(c) && needOperand) {
current = environment.get(c);
acceptDigit = needOperand = false;
} else if ((c == '+' || c == '-') && !needOperand) {
sum += sign * current;
sign = c == '+' ? 1 : -1;
current = 0;
acceptDigit = needOperand = true;
} else if (c == ' ') {
if (!needOperand) {
acceptDigit = false;
}
} else {
// raske öelda, mis nüüd täpselt viga oli
throw new RuntimeException("Malformed expression");
}
}
if (needOperand) {
throw new RuntimeException("Expected operand at the end of expression");
}
return sum + sign * current;
}
}
| sws-lab/akt2024 | sols/week1/MiniAktk.java | 1,466 | // endiselt acceptDigit on true | line_comment | nl | package week1;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class MiniAktk {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
throw new RuntimeException("Exactly one command line argument (path) required");
}
Path path = Paths.get(args[0]);
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Map<Character, Integer> environment = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
line = removeComment(line);
if (line.startsWith("print ")) { // print järel peab olema tühik
String expression = line.substring(6);
System.out.println(evaluateExpression(expression, environment));
}
else if (line.contains("=")) {
String[] parts = line.split("=");
if (parts.length != 2) {
throw new RuntimeException("Malformed assignment");
}
String trimmed = parts[0].trim();
if (trimmed.length() != 1) {
throw new RuntimeException("Variable name must be 1 character");
}
char variableName = trimmed.charAt(0);
if (!Character.isLetter(variableName)) {
throw new RuntimeException("Variable name must be a letter");
}
String expression = parts[1];
environment.put(variableName, evaluateExpression(expression, environment));
}
else if (!line.trim().isEmpty()) { // tühi rida pole viga
throw new RuntimeException("Malformed line: " + line);
}
}
}
}
/**
* Eemaldab realt kommentaari, kui see seal on.
*/
private static String removeComment(String line) {
if (line.contains("#")) return line.substring(0, line.indexOf('#'));
else return line;
}
private static int evaluateExpression(String expression, Map<Character, Integer> environment) {
// Ümbritseme liitmised tühikutega, asendame lahutamise negatiivse arvu liitmisega,
// näiteks teisendame "a +b-c" kujule "a + b + -c", siis saab arvud lihtsalt kokku liita!
// (Eeldame, et esialgses avaldises on ainult märgita täisarvud)
expression = expression.replace("+", " + ").replace("-", " + -");
String[] summands = expression.split("\\+");
int sum = 0;
for (String summand : summands) {
sum += evaluateSummand(summand.trim(), environment);
}
return sum;
}
/*
* Väärtustab märgita või miinusega täisarvu või muutujanime.
*/
private static int evaluateSummand(String summand, Map<Character, Integer> environment) {
int sign = 1;
summand = summand.trim();
if (summand.startsWith("-")) {
sign = -1;
summand = summand.substring(1).trim();
}
// proovime täisarvuna tõlgendada, kui ei saa, siis peaks olema muutuja
try {
return sign * Integer.parseInt(summand);
} catch (NumberFormatException e) {
char variableName = summand.charAt(0);
if (environment.containsKey(variableName)) {
return sign * environment.get(variableName);
}
else {
throw new RuntimeException("Variable " + variableName + " undefined");
}
}
}
/**
* Alternatiivne lahendus: sümbolhaaval avaldise väärtustamine.
* Võrdle Exercise3 eval näidislahendusega:
* * Miinustega arvestamiseks piisab sign muutuja lisamisest.
* * Vigade tuvastamiseks läheb vaja ebatriviaalseid abimuutujate kombinatsioone.
*/
private static int evaluateExpressionAlt(String expression, Map<Character, Integer> environment) {
// avaldise väärtustamiseks vajalikud muutujad
int sum = 0;
int sign = 1; // "märk" (1 või -1) millega järgmine number/muutuja liidetakse
int current = 0;
// vigaste avaldiste tuvastamiseks vajalikud muutujad
boolean needOperand = true; // kas järgmine sümbol PEAB olema number või muutuja nimi?
boolean acceptDigit = true; // kas järgmine sümbol VÕIB olla number?
for (char c : expression.toCharArray()) {
if (Character.isDigit(c) && acceptDigit) {
current = 10 * current + Character.getNumericValue(c);
needOperand = false;
// endiselt acceptDigit<SUF>
} else if (Character.isLetter(c) && needOperand) {
current = environment.get(c);
acceptDigit = needOperand = false;
} else if ((c == '+' || c == '-') && !needOperand) {
sum += sign * current;
sign = c == '+' ? 1 : -1;
current = 0;
acceptDigit = needOperand = true;
} else if (c == ' ') {
if (!needOperand) {
acceptDigit = false;
}
} else {
// raske öelda, mis nüüd täpselt viga oli
throw new RuntimeException("Malformed expression");
}
}
if (needOperand) {
throw new RuntimeException("Expected operand at the end of expression");
}
return sum + sign * current;
}
}
|
18366_3 | package be.vdab.groenetenen.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/* "Performance" als voorbeeld van Around advice: je houdt per Service class method bij hoelang het uitvoeren duurde. */
@Aspect
@Component
@Order(1)
class Performance {
private static final Logger LOGGER = LoggerFactory.getLogger(Performance.class);
/* Je definieert een method als around advice met @Around met een pointcut expressie.
* Elke keer je een method oproept die bij deze pointcut expressie hoort, voert Spring de method schrijfPerformance uit, niet de opgeroepen method zelf.
*/
@Around("be.vdab.groenetenen.aop.PointcutExpressions.services()")
/* 1°) Je geeft de method die het advice voorstelt een ProceedingJoinPoint parameter van het type ProceedingJoinPoint.
* ProceedingJoinPoint erft van JoinPoint en bevat extra functionaliteit die je nodig hebt in around advice.
* Een around advice method moet als returntype Object hebben.
* 2°) De method werpt alle fouten, die het join point eventueel werpt, verder naar de code die oorspronkelijk het join point opgeroepen heeft.
*/
Object schrijfPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
/* Voor je het join point uitvoert, onthoud je het resultaat van System.nanoTime(). Dit geeft je een getal dat daarna per nanoseconde met één verhoogt. */
long voor = System.nanoTime();
try {
/* Bij around advice is het jouw keuze om het join point al of niet uit te voeren.
* Je voert het join point zelf uit met de ProceedingJoinPoint method proceed.
* Je doet deze oproep in een try blok gezien het join point een fout kan werpen.
* De returnwaarde van de proceed method bevat de returnwaarde van het join point zelf.
* Je geeft die door aan de code die het join point oorspronkelijk heeft opgeroepen. */
return joinPoint.proceed();
} finally { // Het finaly blok wordt altijd opgeroepen (ook bij de return van het try blok).
long duurtijd = System.nanoTime() - voor; // Je berekent de duurtijd van het uitvoeren van het join point.
LOGGER.info("{} duurde {} nanoseconden", joinPoint.getSignature().toLongString(), duurtijd);
}
}
}
| LiselotteDes/SPRINGADVgroenetenen | src/main/java/be/vdab/groenetenen/aop/Performance.java | 661 | /* Voor je het join point uitvoert, onthoud je het resultaat van System.nanoTime(). Dit geeft je een getal dat daarna per nanoseconde met één verhoogt. */ | block_comment | nl | package be.vdab.groenetenen.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/* "Performance" als voorbeeld van Around advice: je houdt per Service class method bij hoelang het uitvoeren duurde. */
@Aspect
@Component
@Order(1)
class Performance {
private static final Logger LOGGER = LoggerFactory.getLogger(Performance.class);
/* Je definieert een method als around advice met @Around met een pointcut expressie.
* Elke keer je een method oproept die bij deze pointcut expressie hoort, voert Spring de method schrijfPerformance uit, niet de opgeroepen method zelf.
*/
@Around("be.vdab.groenetenen.aop.PointcutExpressions.services()")
/* 1°) Je geeft de method die het advice voorstelt een ProceedingJoinPoint parameter van het type ProceedingJoinPoint.
* ProceedingJoinPoint erft van JoinPoint en bevat extra functionaliteit die je nodig hebt in around advice.
* Een around advice method moet als returntype Object hebben.
* 2°) De method werpt alle fouten, die het join point eventueel werpt, verder naar de code die oorspronkelijk het join point opgeroepen heeft.
*/
Object schrijfPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
/* Voor je het<SUF>*/
long voor = System.nanoTime();
try {
/* Bij around advice is het jouw keuze om het join point al of niet uit te voeren.
* Je voert het join point zelf uit met de ProceedingJoinPoint method proceed.
* Je doet deze oproep in een try blok gezien het join point een fout kan werpen.
* De returnwaarde van de proceed method bevat de returnwaarde van het join point zelf.
* Je geeft die door aan de code die het join point oorspronkelijk heeft opgeroepen. */
return joinPoint.proceed();
} finally { // Het finaly blok wordt altijd opgeroepen (ook bij de return van het try blok).
long duurtijd = System.nanoTime() - voor; // Je berekent de duurtijd van het uitvoeren van het join point.
LOGGER.info("{} duurde {} nanoseconden", joinPoint.getSignature().toLongString(), duurtijd);
}
}
}
|
100460_2 | package org.example;
public class Berekenaar {
// variable
private double eigenInkomen;
private double partnerInkomen;
private double totaalInkomen;
private double maxLeenBedrag;
private double rente;
private int termijn;
private boolean partner;
private boolean studieSchuld;
private boolean postcode;
private double leenBedragMetRente;
private double aflossingPerMaand;
private double maandBedrag;
private double volledigeLoopTijd;
// get and set
public void setEigenInkomen(double eigenInkomen) {
this.eigenInkomen = eigenInkomen;
this.setTotaalInkomen();
}
public double getEigenInkomen() {
return eigenInkomen;
}
public void setPartnerInkomen(double partnerInkomen) {
this.partnerInkomen = partnerInkomen;
this.setTotaalInkomen();
}
public double getPartnerInkomen() {
return partnerInkomen;
}
public void setTotaalInkomen() {
this.totaalInkomen = this.getEigenInkomen() + this.getPartnerInkomen();
this.setMaxLeenBedrag();
}
public double getTotaalInkomen() {
return totaalInkomen;
}
public void setMaxLeenBedrag() {
if (this.getStudieSchuld()) {
this.maxLeenBedrag = (this.getTotaalInkomen() * 12) * 4.25 * 0.75;
}
else {
this.maxLeenBedrag = (this.getTotaalInkomen() * 12) * 4.25;
}
}
public double getMaxLeenBedrag() {
return maxLeenBedrag;
}
public void setRente(double rente) {
this.rente = rente;
}
public double getRente() {
return rente;
}
public void setTermijn(int termijn) {
this.termijn = termijn;
}
public int getTermijn() {
return termijn;
}
public void setPartner(boolean partner) {
this.partner = partner;
}
public boolean getPartner() {
return partner;
}
public void setStudieSchuld(boolean studieSchuld) {
this.studieSchuld = studieSchuld;
}
public boolean getStudieSchuld() {
return studieSchuld;
}
public void setPostcode(boolean postcode) {
this.postcode = postcode;
}
public boolean getPostcode() {
return postcode;
}
public void setAflossingPerMaand() {
//this.aflossingPerMaand = aflossingPerMaand;
this.getLeenBedragMetRente(); // Calculate leenBedragMetRente
this.aflossingPerMaand = this.getLeenBedragMetRente() / this.getTermijn() / 12;
}
public double getAflossingPerMaand() {
return aflossingPerMaand;
}
public double getMaandBedrag() {
return maandBedrag;
}
public void setMaandBedrag(double maandBedrag) {
this.maandBedrag = maandBedrag;
}
// public void setLeenBedragMetRente(double leenBedragMetRente) {
// this.leenBedragMetRente = this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
// }
//
// public double getLeenBedragMetRente() {
// return leenBedragMetRente;
// }
public void setLeenBedragMetRente(double v) {
this.leenBedragMetRente = this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
}
public double getLeenBedragMetRente() {
return this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
}
public double getVolledigeLoopTijd() {
return volledigeLoopTijd;
}
public void setVolledigeLoopTijd(double volledigeLoopTijd) {
this.volledigeLoopTijd = volledigeLoopTijd;
}
// reset values
public void reset() {
eigenInkomen = 0.0;
partnerInkomen = 0.0;
totaalInkomen = 0.0;
maxLeenBedrag = 0.0;
rente = 0.0;
termijn = 0;
partner = false;
studieSchuld = false;
postcode = false;
leenBedragMetRente = 0.0;
aflossingPerMaand = 0.0;
maandBedrag = 0.0;
volledigeLoopTijd = 0.0;
}
}
| liam-kilsdonk/maven-hypo | src/main/java/org/example/Berekenaar.java | 1,234 | // public void setLeenBedragMetRente(double leenBedragMetRente) { | line_comment | nl | package org.example;
public class Berekenaar {
// variable
private double eigenInkomen;
private double partnerInkomen;
private double totaalInkomen;
private double maxLeenBedrag;
private double rente;
private int termijn;
private boolean partner;
private boolean studieSchuld;
private boolean postcode;
private double leenBedragMetRente;
private double aflossingPerMaand;
private double maandBedrag;
private double volledigeLoopTijd;
// get and set
public void setEigenInkomen(double eigenInkomen) {
this.eigenInkomen = eigenInkomen;
this.setTotaalInkomen();
}
public double getEigenInkomen() {
return eigenInkomen;
}
public void setPartnerInkomen(double partnerInkomen) {
this.partnerInkomen = partnerInkomen;
this.setTotaalInkomen();
}
public double getPartnerInkomen() {
return partnerInkomen;
}
public void setTotaalInkomen() {
this.totaalInkomen = this.getEigenInkomen() + this.getPartnerInkomen();
this.setMaxLeenBedrag();
}
public double getTotaalInkomen() {
return totaalInkomen;
}
public void setMaxLeenBedrag() {
if (this.getStudieSchuld()) {
this.maxLeenBedrag = (this.getTotaalInkomen() * 12) * 4.25 * 0.75;
}
else {
this.maxLeenBedrag = (this.getTotaalInkomen() * 12) * 4.25;
}
}
public double getMaxLeenBedrag() {
return maxLeenBedrag;
}
public void setRente(double rente) {
this.rente = rente;
}
public double getRente() {
return rente;
}
public void setTermijn(int termijn) {
this.termijn = termijn;
}
public int getTermijn() {
return termijn;
}
public void setPartner(boolean partner) {
this.partner = partner;
}
public boolean getPartner() {
return partner;
}
public void setStudieSchuld(boolean studieSchuld) {
this.studieSchuld = studieSchuld;
}
public boolean getStudieSchuld() {
return studieSchuld;
}
public void setPostcode(boolean postcode) {
this.postcode = postcode;
}
public boolean getPostcode() {
return postcode;
}
public void setAflossingPerMaand() {
//this.aflossingPerMaand = aflossingPerMaand;
this.getLeenBedragMetRente(); // Calculate leenBedragMetRente
this.aflossingPerMaand = this.getLeenBedragMetRente() / this.getTermijn() / 12;
}
public double getAflossingPerMaand() {
return aflossingPerMaand;
}
public double getMaandBedrag() {
return maandBedrag;
}
public void setMaandBedrag(double maandBedrag) {
this.maandBedrag = maandBedrag;
}
// public void<SUF>
// this.leenBedragMetRente = this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
// }
//
// public double getLeenBedragMetRente() {
// return leenBedragMetRente;
// }
public void setLeenBedragMetRente(double v) {
this.leenBedragMetRente = this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
}
public double getLeenBedragMetRente() {
return this.getMaxLeenBedrag() + (this.getMaxLeenBedrag() * this.getRente());
}
public double getVolledigeLoopTijd() {
return volledigeLoopTijd;
}
public void setVolledigeLoopTijd(double volledigeLoopTijd) {
this.volledigeLoopTijd = volledigeLoopTijd;
}
// reset values
public void reset() {
eigenInkomen = 0.0;
partnerInkomen = 0.0;
totaalInkomen = 0.0;
maxLeenBedrag = 0.0;
rente = 0.0;
termijn = 0;
partner = false;
studieSchuld = false;
postcode = false;
leenBedragMetRente = 0.0;
aflossingPerMaand = 0.0;
maandBedrag = 0.0;
volledigeLoopTijd = 0.0;
}
}
|
36181_5 | package com.example.ruben.sqlliteinsertruben;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Ruben on 9-11-2017.
*/
public class DbAdapter {
DbHelper helper;
public DbAdapter(Context context)
{
helper = new DbHelper(context);
}
public long insertData(String name, String password)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DbHelper.NAME, name);
contentValues.put(DbHelper.PASSWORD, password);
long id = db.insert(DbHelper.TABLE_NAME, null , contentValues);
return id;
}
static class DbHelper extends SQLiteOpenHelper
{
//velden
private static final String DATABASE_NAME = "myDatabase";
private static final String TABLE_NAME = "myTable";
//als deze hoger wordt gaat die naar onUpgrade
private static final int DATABASE_Version = 1;
private static final String UID="_id";
private static final String NAME = "Name";
private static final String PASSWORD= "Password";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
"( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225), " + PASSWORD+ " VARCHAR(225));";
//private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
Message.message(context,"Started...");
}
@Override
//Als die een nieuwe versie van de database vindt gooit de ouwe weg.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context,"OnUpgrade");
db.execSQL("DROP_TABLE");
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);
}
}
public void onCreate(SQLiteDatabase db) {
//tabel maken in De database.
String SQL_CREATE_WERKNEMER_TABLE = "CREATE TABLE " + Contract.ContractEntry.TABLE_NAME + " ("
+ Contract.ContractEntry.COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " //Wordt automaties een value aan gegeven.
+ Contract.ContractEntry.COLUMN_NAME + " TEXT NOT NULL, "
+ Contract.ContractEntry.COLUMN_PASSWORD + " TEXT NOT NULL, ";
db.execSQL(CREATE_TABLE);
}
}
}
| rubendijkstra02/SqlLiteInsertRuben | app/src/main/java/com/example/ruben/sqlliteinsertruben/DbAdapter.java | 657 | //Wordt automaties een value aan gegeven. | line_comment | nl | package com.example.ruben.sqlliteinsertruben;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Ruben on 9-11-2017.
*/
public class DbAdapter {
DbHelper helper;
public DbAdapter(Context context)
{
helper = new DbHelper(context);
}
public long insertData(String name, String password)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DbHelper.NAME, name);
contentValues.put(DbHelper.PASSWORD, password);
long id = db.insert(DbHelper.TABLE_NAME, null , contentValues);
return id;
}
static class DbHelper extends SQLiteOpenHelper
{
//velden
private static final String DATABASE_NAME = "myDatabase";
private static final String TABLE_NAME = "myTable";
//als deze hoger wordt gaat die naar onUpgrade
private static final int DATABASE_Version = 1;
private static final String UID="_id";
private static final String NAME = "Name";
private static final String PASSWORD= "Password";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
"( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225), " + PASSWORD+ " VARCHAR(225));";
//private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
Message.message(context,"Started...");
}
@Override
//Als die een nieuwe versie van de database vindt gooit de ouwe weg.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context,"OnUpgrade");
db.execSQL("DROP_TABLE");
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);
}
}
public void onCreate(SQLiteDatabase db) {
//tabel maken in De database.
String SQL_CREATE_WERKNEMER_TABLE = "CREATE TABLE " + Contract.ContractEntry.TABLE_NAME + " ("
+ Contract.ContractEntry.COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " //Wordt automaties<SUF>
+ Contract.ContractEntry.COLUMN_NAME + " TEXT NOT NULL, "
+ Contract.ContractEntry.COLUMN_PASSWORD + " TEXT NOT NULL, ";
db.execSQL(CREATE_TABLE);
}
}
}
|
14077_13 | package uml.views.arrow;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import uml.views.umlbox.UMLBox;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
/**
* Amory Hoste
* Bovenklasse - hierin worden de algemene berekeningen gedaan voor de pijl
*/
public abstract class Arrow extends Group {
private double length;
private double angle;
private double x1;
private double x2;
private double y1;
private double y2;
public Arrow(UMLBox from, UMLBox to) {
calculate(from, to);
}
public void calculate(UMLBox from, UMLBox to) {
calculatePoints(from.getBoundsInParent(), to.getBoundsInParent());
double dx = x1 - x2;
double dy = y1 - y2;
length = Math.sqrt(dx * dx + dy * dy);
angle = Math.toDegrees(Math.atan(dy/dx)) + (dx < 0 ? 90 : -90);
}
/**
* Berekent via de methode zoekpunt de x en y coordinaten van de pijl
*/
private void calculatePoints(Bounds vertrekafm, Bounds aankomstafm) {
// Data om eerste punt te berekenen
double x1 = (vertrekafm.getMinX() + vertrekafm.getMaxX())/2;
double y1 = (vertrekafm.getMinY() + vertrekafm.getMaxY())/2;
double minX1 = aankomstafm.getMinX();
double minY1 = aankomstafm.getMinY();
double maxX1 = aankomstafm.getMaxX();
double maxY1 = aankomstafm.getMaxY();
// Data om tweede punt te berekenen
double x2 = (aankomstafm.getMinX() + aankomstafm.getMaxX())/2;
double y2 = (aankomstafm.getMinY() + aankomstafm.getMaxY())/2;
double minX2 = vertrekafm.getMinX();
double minY2 = vertrekafm.getMinY();
double maxX2 = vertrekafm.getMaxX();
double maxY2 = vertrekafm.getMaxY();
// Coordinaatn punt 1 en 2 berekenen
Coordinaat coordinaat1 = zoekPunt(x1, y1, minX1, minY1, maxX1, maxY1);
Coordinaat coordinaat2 = zoekPunt(x2, y2, minX2, minY2, maxX2, maxY2);
// X en Y Coordinaten pijl instellen
this.x1 = coordinaat2.x;
this.x2 = coordinaat1.x;
this.y1 = coordinaat2.y;
this.y2 = coordinaat1.y;
}
/**
* Hulpmethode die gegeven een vertrekpunt en de afmetingen van een vierkant het punt op het vierkant
* waar de lijn uit het vertrekpunt moet aankomen om naar het midden van het vierkant te wijzen berekent
*/
private Coordinaat zoekPunt(double x, double y, double minX, double minY, double maxX, double maxY) {
Coordinaat coordinaat = null;
// Midden vierkant berekenen
double midX = (minX + maxX) / 2;
double midY = (minY + maxY) / 2;
// Breedte en hoogte vierkant berekenen
double height = (maxY - minY);
double width = (maxX - minX);
// Richtingscoëfficiënt berekenen
double m = (midY - y) / (midX - x);
// Coordinaat punt berekenen
if (-height / 2 <= m * width / 2 && m * width / 2 <= height / 2) {
if (x <= midX) {
// Punt aan linkerzijde
double minXy = m * (minX - x) + y;
coordinaat = new Coordinaat(minX, minXy);
} else if (x >= midX) {
// Punt aan rechterzijde
double maxXy = (m * (maxX - x) + y);
coordinaat = new Coordinaat(maxX, maxXy);
}
} else if (-width / 2 <= (height / 2) / m && (height / 2) / m <= width / 2) {
if (y <= midY) {
// Punt aan bovenzijde
double minYx = (minY - y) / m + x;
coordinaat = new Coordinaat(minYx, minY);
} else if (y >= midY) {
// Punt aan onderzijde
double maxYx = (maxY - y) / m + x;
coordinaat = new Coordinaat(maxYx, maxY);
}
}
return coordinaat;
}
protected double getLength() {
return length;
}
protected void setLength(double length) {
this.length = length;
}
protected void setAngle(double angle) {
this.angle = angle;
}
protected double getAngle() {
return angle;
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
public double getY1() {
return y1;
}
public double getY2() {
return y2;
}
public abstract void draw();
public abstract void move();
/**
* Statische binnenklasse die een coordinaat voorsteld
*/
public static class Coordinaat {
public double x;
public double y;
Coordinaat(double x, double y) {
this.x = x;
this.y = y;
}
}
}
| amohoste/UML-Editor | src/uml/views/arrow/Arrow.java | 1,427 | // Punt aan onderzijde | line_comment | nl | package uml.views.arrow;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import uml.views.umlbox.UMLBox;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
/**
* Amory Hoste
* Bovenklasse - hierin worden de algemene berekeningen gedaan voor de pijl
*/
public abstract class Arrow extends Group {
private double length;
private double angle;
private double x1;
private double x2;
private double y1;
private double y2;
public Arrow(UMLBox from, UMLBox to) {
calculate(from, to);
}
public void calculate(UMLBox from, UMLBox to) {
calculatePoints(from.getBoundsInParent(), to.getBoundsInParent());
double dx = x1 - x2;
double dy = y1 - y2;
length = Math.sqrt(dx * dx + dy * dy);
angle = Math.toDegrees(Math.atan(dy/dx)) + (dx < 0 ? 90 : -90);
}
/**
* Berekent via de methode zoekpunt de x en y coordinaten van de pijl
*/
private void calculatePoints(Bounds vertrekafm, Bounds aankomstafm) {
// Data om eerste punt te berekenen
double x1 = (vertrekafm.getMinX() + vertrekafm.getMaxX())/2;
double y1 = (vertrekafm.getMinY() + vertrekafm.getMaxY())/2;
double minX1 = aankomstafm.getMinX();
double minY1 = aankomstafm.getMinY();
double maxX1 = aankomstafm.getMaxX();
double maxY1 = aankomstafm.getMaxY();
// Data om tweede punt te berekenen
double x2 = (aankomstafm.getMinX() + aankomstafm.getMaxX())/2;
double y2 = (aankomstafm.getMinY() + aankomstafm.getMaxY())/2;
double minX2 = vertrekafm.getMinX();
double minY2 = vertrekafm.getMinY();
double maxX2 = vertrekafm.getMaxX();
double maxY2 = vertrekafm.getMaxY();
// Coordinaatn punt 1 en 2 berekenen
Coordinaat coordinaat1 = zoekPunt(x1, y1, minX1, minY1, maxX1, maxY1);
Coordinaat coordinaat2 = zoekPunt(x2, y2, minX2, minY2, maxX2, maxY2);
// X en Y Coordinaten pijl instellen
this.x1 = coordinaat2.x;
this.x2 = coordinaat1.x;
this.y1 = coordinaat2.y;
this.y2 = coordinaat1.y;
}
/**
* Hulpmethode die gegeven een vertrekpunt en de afmetingen van een vierkant het punt op het vierkant
* waar de lijn uit het vertrekpunt moet aankomen om naar het midden van het vierkant te wijzen berekent
*/
private Coordinaat zoekPunt(double x, double y, double minX, double minY, double maxX, double maxY) {
Coordinaat coordinaat = null;
// Midden vierkant berekenen
double midX = (minX + maxX) / 2;
double midY = (minY + maxY) / 2;
// Breedte en hoogte vierkant berekenen
double height = (maxY - minY);
double width = (maxX - minX);
// Richtingscoëfficiënt berekenen
double m = (midY - y) / (midX - x);
// Coordinaat punt berekenen
if (-height / 2 <= m * width / 2 && m * width / 2 <= height / 2) {
if (x <= midX) {
// Punt aan linkerzijde
double minXy = m * (minX - x) + y;
coordinaat = new Coordinaat(minX, minXy);
} else if (x >= midX) {
// Punt aan rechterzijde
double maxXy = (m * (maxX - x) + y);
coordinaat = new Coordinaat(maxX, maxXy);
}
} else if (-width / 2 <= (height / 2) / m && (height / 2) / m <= width / 2) {
if (y <= midY) {
// Punt aan bovenzijde
double minYx = (minY - y) / m + x;
coordinaat = new Coordinaat(minYx, minY);
} else if (y >= midY) {
// Punt aan<SUF>
double maxYx = (maxY - y) / m + x;
coordinaat = new Coordinaat(maxYx, maxY);
}
}
return coordinaat;
}
protected double getLength() {
return length;
}
protected void setLength(double length) {
this.length = length;
}
protected void setAngle(double angle) {
this.angle = angle;
}
protected double getAngle() {
return angle;
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
public double getY1() {
return y1;
}
public double getY2() {
return y2;
}
public abstract void draw();
public abstract void move();
/**
* Statische binnenklasse die een coordinaat voorsteld
*/
public static class Coordinaat {
public double x;
public double y;
Coordinaat(double x, double y) {
this.x = x;
this.y = y;
}
}
}
|
55119_14 | package nl.b3p.geotools.data.linker.blocks;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import nl.b3p.geotools.data.linker.ActionFactory;
import nl.b3p.geotools.data.linker.DataStoreLinker;
import nl.b3p.geotools.data.linker.FeatureException;
import nl.b3p.geotools.data.linker.Status;
import static nl.b3p.geotools.data.linker.blocks.Action.log;
import nl.b3p.geotools.data.linker.feature.EasyFeature;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.geotools.data.DataStore;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.Transaction;
import org.geotools.data.oracle.OracleDialect;
import org.geotools.data.postgis.PostGISDialect;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.factory.Hints;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.JDBCFeatureStore;
import org.geotools.jdbc.PrimaryKey;
import org.geotools.jdbc.PrimaryKeyColumn;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.filter.Filter;
/**
* Write to a datastore (file or JDBC)
*
* @author Gertjan Al, B3Partners
*/
public class ActionDataStore_Writer extends Action {
private boolean initDone = false;//, runOnce = true;
private DataStore dataStore2Write = null;
private Map params;
private final boolean append;
private final boolean dropFirst;
private final boolean modify;
private final boolean modifyGeom;
private final String modifyFilter;
// post collection actions
private boolean postCollectionActionsInitDone = false;
private boolean polygonize = false;
private boolean polygonizeWithAttr = false;
private boolean polygonizeSufLki = false;
private boolean postPointWithinPolygon = false;
private Exception constructorEx;
private List<String> datastoreTypeNames = new ArrayList();
private Map<String, FeatureStore> featureStores = new HashMap();
private Map<String, PrimaryKey> featurePKs = new HashMap();
private List<String> featureTypeNames = new ArrayList();
private Map<String, DefaultFeatureCollection> featureCollectionCache = new HashMap();
private Map<String, Integer> featureBatchSizes = new HashMap();
private Map<String, Integer> featuresWritten = new HashMap();
private Map<String, List<List<String>>> featureErrors = new HashMap();
private Map<String, List<List<String>>> featureNonFatals = new HashMap();
private static final int MAX_CONNECTIONS_NR = 50;
private static final String MAX_CONNECTIONS = "max connections";
private static final int BATCHSIZE = 50;
private static final int MAX_BATCHSIZE = 5000;
private static final int INCREASEFACTOR = 2;
private static final int DECREASEFACTOR = 10;
private ArrayList<CollectionAction> collectionActions = new ArrayList();
private Random generator = new Random((new Date()).getTime());
public ActionDataStore_Writer(Map params, Map properties) {// Boolean append, Boolean dropFirst, Boolean polygonize, String polygonizeClassificationAttribute){
this.params = params;
log.debug(params);
if (ActionFactory.propertyCheck(properties, ActionFactory.APPEND)) {
append = (Boolean) properties.get(ActionFactory.APPEND);
} else {
append = true;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.DROPFIRST)) {
dropFirst = (Boolean) properties.get(ActionFactory.DROPFIRST);
} else {
dropFirst = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.MODIFY)) {
modify = (Boolean) properties.get(ActionFactory.MODIFY);
} else {
modify = false;
}
if(ActionFactory.propertyCheck(properties, ActionFactory.MODIFY_GEOM)){
modifyGeom = (Boolean) properties.get(ActionFactory.MODIFY_GEOM);
} else {
modifyGeom = false;
}
if(ActionFactory.propertyCheck(properties, ActionFactory.ATTRIBUTE_MODIFY_FILTER)){
modifyFilter = (String) properties.get(ActionFactory.ATTRIBUTE_MODIFY_FILTER);
} else {
modifyFilter = null;
}
if (!params.containsKey(MAX_CONNECTIONS)) {
params.put(MAX_CONNECTIONS, MAX_CONNECTIONS_NR);
}
try {
dataStore2Write = DataStoreLinker.openDataStore(params);
if (dataStore2Write != null) {
datastoreTypeNames = Arrays.asList(dataStore2Write.getTypeNames());
initDone = true;
}
} catch (Exception ex) {
constructorEx = ex;
}
initPostCollectionActions(properties);
}
public EasyFeature execute(EasyFeature feature) throws Exception {
if (!initDone) {
throw new Exception("\nOpening dataStore failed; datastore could not be found, missing library or no access to file: "
+ toString() + "\n\n" + constructorEx.getLocalizedMessage());
}
long start = new Date().getTime();
feature = fixFeatureTypeName(feature);
String typename = feature.getFeatureType().getTypeName();
PrimaryKey pks = null;
DefaultFeatureCollection fc = null;
FeatureStore store = null;
List<List<String>> errors = null;
List<List<String>> nonFatals = null;
int batchsize = BATCHSIZE;
int numWritten = 0;
//TODO aanpassen batchsize mogelijk maken
//hiermee kan dan ook (via batch size is -1) in een transactie oude records
//worden verwijderd en nieuwe records worden toegevoegd, zodat een volledige
//rollback gedaan kan worden
if (featureTypeNames.contains(typename)) {
pks = featurePKs.get(typename);
fc = featureCollectionCache.get(typename);
store = featureStores.get(typename);
batchsize = featureBatchSizes.get(typename);
numWritten = featuresWritten.get(typename);
errors = featureErrors.get(typename);
nonFatals = featureNonFatals.get(typename);
} else {
//TODO uitzoeken of drop ook in de transactie kan
boolean delayRemoveUntilFirstCommit = false;
if (batchsize == -1) {
delayRemoveUntilFirstCommit = true;
}
// uitzoeken of tabel al is aangemaakt
// mogelijk wordt de naam van de feature type hierbij nog aangepast
String oldTypeName = typename;
boolean typeExists = datastoreTypeNames.contains(oldTypeName);
typename = checkSchema(feature.getFeatureType(), delayRemoveUntilFirstCommit, typeExists);
if (!typename.equals(oldTypeName)) {
feature.setTypeName(typename);
}
fc = new DefaultFeatureCollection(typename, feature.getFeatureType());
featureCollectionCache.put(typename, fc);
if (dataStore2Write != null) {
if (dataStore2Write instanceof JDBCDataStore) {
FeatureSource fs = ((JDBCDataStore) dataStore2Write).getFeatureSource(typename, Transaction.AUTO_COMMIT);
if (fs instanceof JDBCFeatureStore) {
store = (JDBCFeatureStore) fs;
pks = ((JDBCFeatureStore) fs).getPrimaryKey();
} else {
throw new IllegalStateException("Table cannot be written: no primary key? FeatureSource was not of type JDBCFeatureStore");
}
} else {
store = (FeatureStore) dataStore2Write.getFeatureSource(typename);
}
}
featureStores.put(typename, store);
featurePKs.put(typename, pks);
featureBatchSizes.put(typename, batchsize);
featuresWritten.put(typename, numWritten);
featureErrors.put(typename, new ArrayList<List<String>>());
featureNonFatals.put(typename, new ArrayList<List<String>>());
// remember that typename is processed
featureTypeNames.add(typename);
}
feature.convertGeomTo2D();
prepareWrite(fc, pks, feature);
// start writing when number of features is larger than batch size,
// except when batch size is -1, then always wait for last feature
Integer collectionSize = fc.size();
if ((collectionSize >= batchsize && batchsize != -1)) {
try {
batchsize = writeCollection(fc, store, batchsize);
featureBatchSizes.put(typename, batchsize);
} catch (Exception ex) {
throw new FeatureException("Error writing feature collection. Features not written.", ex);
} finally {
fc.retainAll(new ArrayList());
}
}
long end = new Date().getTime() - start;
log.debug("WRITER BLOCK: " + end);
return feature;
}
private void prepareWrite(DefaultFeatureCollection fc, PrimaryKey pk, EasyFeature feature) throws IOException {
// Bepaal de primary key(s) van record in de doeltabel
PrimaryKey usePk = pk;
// TODO: overnemen van pk uit source en instellen voor target
// kan niet omdat dit niet (gemakkelijk) ondersteund wordt.
// Nu wordt de automatisch gegenereerde primary key gebruikt
// indien er geen doeltabel wordt gebruikt.
// if (dropFirst) {
// if (feature.getUserData().containsKey("sourcePks")) {
// usePk = (PrimaryKey) feature.getUserData().get("sourcePks");
// }
// }
SimpleFeature newFeature = feature.getFeature();
// bouw pk uit gemapte waarden uit bron
StringBuilder oldfid = new StringBuilder();
if (usePk != null) {
List<PrimaryKeyColumn> pkcs = usePk.getColumns();
for (PrimaryKeyColumn pkc : pkcs) {
String cn = pkc.getName();
Object o = feature.getAttribute(cn);
if (o == null) {
// primary is blijkbaar niet gemapt, dan vertrouwen op autonumber
oldfid = null;
break;
}
oldfid.append(o).append(".");
}
if (oldfid != null) {
oldfid.setLength(oldfid.length() - 1);
}
}
if (oldfid != null && oldfid.length() > 0) {
// voeg pk toe aan feature en zeg deze te gebruiken
newFeature = feature.copy(oldfid.toString()).getFeature();
newFeature.getUserData().put(Hints.USE_PROVIDED_FID, true);
}
// Check of feature geskipped moet worden
SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();
if (feature.isSkipped()) {
List<String> message = new ArrayList(
Arrays.asList("Feature uitgefilterd", feature.getID()));
featureNonFatals.get(type.getTypeName()).add(message);
} else {
fc.add(newFeature);
}
}
private int writeCollection(DefaultFeatureCollection fc, FeatureStore store, int batchsize) throws FeatureException, IOException {
// maak nieuwe subcollecties
SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();
int orgbatchsize = batchsize;
int stamp = generator.nextInt(10000);
int orgfcsize = fc.size();
log.info("Starting write out for typename: " + type.getTypeName()
+ " with batch size: " + orgbatchsize
+ " and stamp: " + stamp
+ " and size: " + orgfcsize);
DefaultFeatureCollection currentFc = null;
if (batchsize == -1) {
// alles in een keer
currentFc = fc;
} else {
// splits de collectie zodat in delen geprobeerd kan worden te schrijven
currentFc = new DefaultFeatureCollection(type.getTypeName(), type);
List removeList = new ArrayList();
FeatureIterator fi = fc.features();
int count = 0;
while (fi.hasNext() && count < batchsize) {
SimpleFeature newFeature = (SimpleFeature) fi.next();
currentFc.add(newFeature);
removeList.add(newFeature);
count++;
}
fc.removeAll(removeList);
if (!fc.isEmpty()) {
batchsize = writeCollection(fc, store, batchsize);
featureBatchSizes.put(type.getTypeName(), batchsize);
}
}
Transaction t = new DefaultTransaction("add");
store.setTransaction(t);
try {
if (modify) {
FeatureIterator fi = currentFc.features();
while (fi.hasNext()) {
SimpleFeature newFeature = (SimpleFeature) fi.next();
List<org.opengis.feature.type.AttributeType> properties = newFeature.getFeatureType().getTypes();
Object filterValue = newFeature.getAttribute(modifyFilter);
Filter filter = ECQL.toFilter(modifyFilter+"='" + filterValue + "'");
boolean hasGeom = newFeature.getDefaultGeometryProperty() != null;
for (org.opengis.feature.type.AttributeType property : properties) {
if(hasGeom){
if(newFeature.getDefaultGeometryProperty().getName().equals(property.getName()) && !modifyGeom){
continue;
}
}
if (newFeature.getAttribute(property.getName().toString()) != null) {
store.modifyFeatures(property.getName(), newFeature.getAttribute(property.getName()), filter);
}
}
}
} else {
if (batchsize == -1) {
// als alles in een keer, dan ook pas oude feature weggooien
// als nieuwe insert ok zijn (dus in zelfde transactie)
log.info("Removing all features from: " + type.getTypeName()
+ " within insert transaction.");
store.removeFeatures(Filter.INCLUDE);
}
// schrijf batch aan features
store.addFeatures(currentFc);
}
t.commit();
int numWritten = featuresWritten.get(type.getTypeName());
int numProcessed = currentFc.size();
featuresWritten.put(type.getTypeName(), numWritten + numProcessed);
// indien succesvol dan volgende keer grotere batch
batchsize *= INCREASEFACTOR;
if (batchsize > MAX_BATCHSIZE) {
batchsize = MAX_BATCHSIZE;
}
currentFc.retainAll(new ArrayList());
} catch (Exception ex) {
try {
t.rollback();
} catch (IOException ioex) {
log.error("Error rolling back feature type: " + type.getTypeName()
+ ", retrying after error: " + ioex.getLocalizedMessage());
}
if (batchsize == -1) {
// als batch size is -1 dan is de gehele collectie in een keer
// geschreven en moet niet geprobeerd worden in kleinere delen
// te committen, meteen foutmelding sturen
List<String> message = new ArrayList(
Arrays.asList(ExceptionUtils.getRootCauseMessage(ex), "*"));
featureErrors.get(type.getTypeName()).add(message);
return batchsize;
}
if (batchsize == 1) {
// als slechts een enkele feature niet geprocessed kan worden
// dan opgeven
SimpleFeature f = (SimpleFeature) (currentFc.toArray())[0];
List<String> message = new ArrayList(
Arrays.asList(ExceptionUtils.getRootCauseMessage(ex), f.getID()));
featureErrors.get(type.getTypeName()).add(message);
return batchsize;
}
// probeer opnieuw met aangepast batch size
batchsize /= DECREASEFACTOR;
if (batchsize < 2) {
batchsize = 1;
}
log.info("Rollback for feature type: " + type.getTypeName()
+ ", retry with new batch size: " + batchsize);
batchsize = writeCollection(currentFc, store, batchsize);
featureBatchSizes.put(type.getTypeName(), batchsize);
} finally {
t.close();
}
log.info("finishing write out for typename: " + type.getTypeName()
+ " with batch size: " + orgbatchsize
+ " and stamp: " + stamp
+ " and size: " + orgfcsize);
return batchsize;
}
@Override
public void close() throws Exception {
log.info("Closing ActionDataStore Writer");
if (dataStore2Write != null) {
dataStore2Write.dispose();
}
}
private void initPostCollectionActions(Map properties) {
//slecht een keer init toestaan, ofwel in constructor ofwel in block
//anders wordt het wel erg complex.
if (postCollectionActionsInitDone) {
return;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZE)) {
polygonize = new Boolean(properties.get(ActionFactory.POLYGONIZE).toString());
postCollectionActionsInitDone = true;
} else {
polygonize = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZEWITHATTR)) {
polygonizeWithAttr = new Boolean(properties.get(ActionFactory.POLYGONIZEWITHATTR).toString());
postCollectionActionsInitDone = true;
} else {
polygonizeWithAttr = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZESUFLKI)) {
polygonizeSufLki = new Boolean(properties.get(ActionFactory.POLYGONIZESUFLKI).toString());
postCollectionActionsInitDone = true;
} else {
polygonizeSufLki = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POSTPOINTWITHINPOLYGON)) {
postPointWithinPolygon = new Boolean(properties.get(ActionFactory.POSTPOINTWITHINPOLYGON).toString());
postCollectionActionsInitDone = true;
} else {
postPointWithinPolygon = false;
}
if (this.polygonize) {
log.info("Polygonize is configured as post action");
collectionActions.add(new CollectionAction_Polygonize(new HashMap(properties)));
}
if (this.postPointWithinPolygon) {
log.info("Point_Within_Polygon with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_Point_Within_Polygon(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Cannot create Point_Within_Polygon post action", e);
}
}
if (this.polygonizeWithAttr) {
log.info("Polygonize with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_PolygonizeWithAttr(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create PolygonizeWithAttr post action", e);
}
} else if (this.polygonizeSufLki) {
log.info("Polygonize with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_PolygonizeSufLki(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create PolygonizeWithAttr post action", e);
}
}
if (this.postPointWithinPolygon) {
log.info("Find polygon with point is configured as post action");
try {
collectionActions.add(new CollectionAction_Intersects_XY_Add_Attrib(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create Find polygon with point post action", e);
}
}
}
@Override
public void processPostCollectionActions(Status status, Map properties) {
//deze post actions kunnen ook door een block gezet zijn,
initPostCollectionActions(properties);
log.info("Collect errors from ActionDataStore_Writer");
if (dataStore2Write != null) {
try {
String typeNames[] = dataStore2Write.getTypeNames();
List<List<String>> nonFatals = null;
for (int i = 0; i < typeNames.length; i++) {
nonFatals = featureNonFatals.get(typeNames[i]);
if (nonFatals != null && !nonFatals.isEmpty()) {
for (int j = 0; j < nonFatals.size(); j++) {
List<String> message = nonFatals.get(j);
status.addNonFatalError(message.get(0), message.get(1));
}
}
}
List<List<String>> errors = null;
for (int i = 0; i < typeNames.length; i++) {
errors = featureErrors.get(typeNames[i]);
if (errors != null && !errors.isEmpty()) {
for (int j = 0; j < errors.size(); j++) {
List<String> message = errors.get(j);
status.addWriteError(message.get(0), message.get(1));
}
}
}
for (int i = 0; i < typeNames.length; i++) {
Integer numWritten = featuresWritten.get(typeNames[i]);
if (numWritten!=null) {
int numProcessed = status.getProcessedFeatures();
status.setProcessedFeatures(numProcessed + numWritten.intValue());
}
}
} catch (IOException e) {
status.addWriteError("Error collecting errors/messages from ActionDataStore_Writer", null);
log.error("Error collecting errors/messages from ActionDataStore_Writer.", e);
}
}
for (int i = 0; i < collectionActions.size(); i++) {
log.info("Process Post actions ActionDataStore_Writer");
CollectionAction ca = collectionActions.get(i);
//do the polygonize function
if (ca instanceof CollectionAction_Polygonize) {
for (int s = 0; s < featureTypeNames.size(); s++) {
try {
GeometryDescriptor gd = dataStore2Write.getSchema(featureTypeNames.get(s)).getGeometryDescriptor();
if (gd == null) {
continue;
}
Class geometryTypeBinding = dataStore2Write.getSchema(featureTypeNames.get(s)).getGeometryDescriptor().getType().getBinding();
if (LineString.class == geometryTypeBinding || MultiLineString.class == geometryTypeBinding) {
FeatureSource fs = dataStore2Write.getFeatureSource(featureTypeNames.get(s));
FeatureCollection fc = fs.getFeatures();
ca.execute(fc, this);
}
} catch (Exception e) {
status.addWriteError("Error while polygonizing the lines", "");
log.error("Error while Polygonizing the lines.", e);
}
}
}
if (ca instanceof CollectionAction_Point_Within_Polygon) {
DataStore ds = null;
try {
CollectionAction_Point_Within_Polygon cap = (CollectionAction_Point_Within_Polygon) ca;
FeatureSource fs = dataStore2Write.getFeatureSource(cap.getPointsTable());
DefaultFeatureCollection fc = (DefaultFeatureCollection)fs.getFeatures();
FeatureSource fs2 = dataStore2Write.getFeatureSource(cap.getPolygonTable());
DefaultFeatureCollection fc2 = (DefaultFeatureCollection)fs2.getFeatures();
ds = DataStoreLinker.openDataStore(this.params);
cap.setDataStore2Write(ds);
cap.execute(fc, fc2, this);
} catch (Exception e) {
status.addWriteError("Error while points within polygon with attributes", "");
log.error("Error while Points within Polygon with attributes.", e);
} finally {
if (ds != null) {
ds.dispose();
}
}
}
if (ca instanceof CollectionAction_PolygonizeWithAttr) {
DataStore ds = null;
try {
CollectionAction_PolygonizeWithAttr cap = (CollectionAction_PolygonizeWithAttr) ca;
FeatureSource fs = dataStore2Write.getFeatureSource(cap.getAttributeFeatureName());
FeatureCollection fc = fs.getFeatures();
ds = DataStoreLinker.openDataStore(this.params);
cap.setDataStore2Write(ds);
cap.execute(fc, this);
} catch (Exception e) {
status.addWriteError("Error while polygonizing the lines with attributes", "");
log.error("Error while polygonizing the lines with attributes.", e);
} finally {
if (ds != null) {
ds.dispose();
}
}
}
}
}
/**
* Check the schema and return the name.
*/
private String checkSchema(SimpleFeatureType featureType, boolean delayRemoveUntilFirstCommit, boolean typeExists) throws Exception {
String typename2Write = featureType.getTypeName();
if (dropFirst && typeExists) {
// Check if DataStore is a Database
if (dataStore2Write instanceof JDBCDataStore) {
log.info("Verwijderen van tabel: " + featureType.getTypeName());
try {
dataStore2Write.removeSchema(featureType.getTypeName());
} catch (IOException io) {
log.warn("Verwijderen van " + featureType.getTypeName() + " is niet gelukt, melding: " + io.getLocalizedMessage());
}
}
typeExists = false;
}
// If table does not exist, create new
if (!typeExists) {
log.info("Creating new table with name: " + featureType.getTypeName());
dataStore2Write.createSchema(featureType);
} else if (!append && !modify && !delayRemoveUntilFirstCommit) {
log.info("Removing all features from: " + typename2Write);
boolean deleteSuccess = false;
// Check if DataStore is a Database
if (dataStore2Write instanceof JDBCDataStore) {
// Empty table
JDBCDataStore database = (JDBCDataStore) dataStore2Write;
Connection con = null;
try {
con = database.getConnection(Transaction.AUTO_COMMIT);
// try truncate: fast
removeAllFeaturesWithTruncate(database, con, typename2Write);
deleteSuccess = true;
} catch (Exception e) {
log.debug("Removing using truncate failed: ", e);
Connection con1 = null;
try {
con1 = database.getConnection(Transaction.AUTO_COMMIT);
// try delete from table: mot so fast
removeAllFeaturesWithDelete(database, con, typename2Write);
deleteSuccess = true;
} catch (Exception e2) {
log.debug("Removing using delete from table failed: ", e2);
} finally {
if (con1 != null) {
con1.close();
}
}
} finally {
if (con != null) {
con.close();
}
}
}
if (!deleteSuccess) {
// try using geotools: slowest
removeAllFeatures(dataStore2Write, typename2Write);
log.info("Removing using geotools");
}
}
// lijst van tabellen opnieuw ophalen want er zijn tabellen geschreven
// of verwijderd.
datastoreTypeNames = Arrays.asList(dataStore2Write.getTypeNames());
return typename2Write;
}
/**
* De feature wordt ontdaan van ongeldige waarden en spaties worden
* vervangen door underscrores. Verder wordt gekeken of er al een tabel
* bestaat in de doeldatabase, waarbij hoofdletters worden genegeerd. Als
* dat zo is dat wordt de tabelnaam (featuretype name) goed gezet waarbij
* wel de hoofdletters goed gezet worden. Hierdoor kan later direct in de
* lijst van tabellen worden gecheckt.
*
* @param feature
* @return feature dat gefixt is
* @throws Exception
*/
private EasyFeature fixFeatureTypeName(EasyFeature feature) throws Exception {
String oldTypeName = feature.getTypeName();
boolean isWFS = false;
if(dataStore2Write instanceof WFSDataStore){
isWFS = true;
}
String typename = fixTypename(oldTypeName.replaceAll(" ", "_"), isWFS);
for (String tnn : datastoreTypeNames) {
// hoofdletters gebruik is niet relevant
if (tnn.equalsIgnoreCase(typename)) {
typename = tnn;
break;
}
}
// hoofdletter gebruik is wel relevant
if (!typename.equals(oldTypeName)) {
feature.setTypeName(typename);
}
return feature;
}
public Map getParams() {
return params;
}
public String toString() {
if (params == null) {
return "No datastore params";
}
Map cleanedParams = new HashMap();
for (Object param : params.keySet()) {
if (!param.toString().contains("passw")) {
cleanedParams.put(param, params.get(param));
}
}
return "Datastore params: " + cleanedParams.toString();
}
public static List<List<String>> getConstructors() {
List<List<String>> constructors = new ArrayList<List<String>>();
constructors.add(Arrays.asList(new String[]{
ActionFactory.PARAMS,
ActionFactory.APPEND,
ActionFactory.DROPFIRST
}));
constructors.add(Arrays.asList(new String[]{
ActionFactory.PARAMS
}));
return constructors;
}
public String getDescription_NL() {
return "Schrijf de SimpleFeature weg naar een datastore. Als de datastore een database is, kan de SimpleFeature worden toegevoegd of kan de tabel worden geleegd voor het toevoegen";
}
private void removeAllFeaturesWithTruncate(JDBCDataStore database, Connection con, String typeName) throws SQLException {
PreparedStatement ps = null;
if (database.getSQLDialect() instanceof PostGISDialect) {
ps = con.prepareStatement("TRUNCATE TABLE \"" + typeName + "\" CASCADE");
} else { //if (database.getSQLDialect() instanceof OracleDialect) {
ps = con.prepareStatement("TRUNCATE TABLE \"" + typeName + "\"");
}
ps.execute();
log.info("Removing using truncate");
}
private void removeAllFeaturesWithDelete(JDBCDataStore database, Connection con, String typeName) throws SQLException {
PreparedStatement ps = con.prepareStatement("DELETE FROM \"" + typeName + "\"");
ps.execute();
log.info("Removing using delete from table");
}
private void removeAllFeatures(DataStore datastore, String typeName) throws IOException, Exception {
DefaultTransaction transaction = new DefaultTransaction("removeTransaction");
FeatureStore<SimpleFeatureType, SimpleFeature> store = (FeatureStore<SimpleFeatureType, SimpleFeature>) datastore.getFeatureSource(typeName);
try {
store.removeFeatures(Filter.INCLUDE);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
@Override
public void flush(Status status, Map properties) throws Exception {
for (Map.Entry pairs : featureCollectionCache.entrySet()) {
String key = (String) pairs.getKey();
FeatureStore store = featureStores.get(key);
int batchsize = featureBatchSizes.get(key);
DefaultFeatureCollection fc = (DefaultFeatureCollection) pairs.getValue();
int fcsize = fc.size();
if (fc != null && fcsize > 0) {
batchsize = writeCollection(fc, store, batchsize);
}
log.info("finished flushing cache for typename: " + key
+ " with batch size: " + batchsize
+ " and size: " + fcsize);
}
}
}
| B3Partners/b3p-datastorelinker | src/main/java/nl/b3p/geotools/data/linker/blocks/ActionDataStore_Writer.java | 7,938 | // Bepaal de primary key(s) van record in de doeltabel | line_comment | nl | package nl.b3p.geotools.data.linker.blocks;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import nl.b3p.geotools.data.linker.ActionFactory;
import nl.b3p.geotools.data.linker.DataStoreLinker;
import nl.b3p.geotools.data.linker.FeatureException;
import nl.b3p.geotools.data.linker.Status;
import static nl.b3p.geotools.data.linker.blocks.Action.log;
import nl.b3p.geotools.data.linker.feature.EasyFeature;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.geotools.data.DataStore;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.Transaction;
import org.geotools.data.oracle.OracleDialect;
import org.geotools.data.postgis.PostGISDialect;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.factory.Hints;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.JDBCFeatureStore;
import org.geotools.jdbc.PrimaryKey;
import org.geotools.jdbc.PrimaryKeyColumn;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.filter.Filter;
/**
* Write to a datastore (file or JDBC)
*
* @author Gertjan Al, B3Partners
*/
public class ActionDataStore_Writer extends Action {
private boolean initDone = false;//, runOnce = true;
private DataStore dataStore2Write = null;
private Map params;
private final boolean append;
private final boolean dropFirst;
private final boolean modify;
private final boolean modifyGeom;
private final String modifyFilter;
// post collection actions
private boolean postCollectionActionsInitDone = false;
private boolean polygonize = false;
private boolean polygonizeWithAttr = false;
private boolean polygonizeSufLki = false;
private boolean postPointWithinPolygon = false;
private Exception constructorEx;
private List<String> datastoreTypeNames = new ArrayList();
private Map<String, FeatureStore> featureStores = new HashMap();
private Map<String, PrimaryKey> featurePKs = new HashMap();
private List<String> featureTypeNames = new ArrayList();
private Map<String, DefaultFeatureCollection> featureCollectionCache = new HashMap();
private Map<String, Integer> featureBatchSizes = new HashMap();
private Map<String, Integer> featuresWritten = new HashMap();
private Map<String, List<List<String>>> featureErrors = new HashMap();
private Map<String, List<List<String>>> featureNonFatals = new HashMap();
private static final int MAX_CONNECTIONS_NR = 50;
private static final String MAX_CONNECTIONS = "max connections";
private static final int BATCHSIZE = 50;
private static final int MAX_BATCHSIZE = 5000;
private static final int INCREASEFACTOR = 2;
private static final int DECREASEFACTOR = 10;
private ArrayList<CollectionAction> collectionActions = new ArrayList();
private Random generator = new Random((new Date()).getTime());
public ActionDataStore_Writer(Map params, Map properties) {// Boolean append, Boolean dropFirst, Boolean polygonize, String polygonizeClassificationAttribute){
this.params = params;
log.debug(params);
if (ActionFactory.propertyCheck(properties, ActionFactory.APPEND)) {
append = (Boolean) properties.get(ActionFactory.APPEND);
} else {
append = true;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.DROPFIRST)) {
dropFirst = (Boolean) properties.get(ActionFactory.DROPFIRST);
} else {
dropFirst = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.MODIFY)) {
modify = (Boolean) properties.get(ActionFactory.MODIFY);
} else {
modify = false;
}
if(ActionFactory.propertyCheck(properties, ActionFactory.MODIFY_GEOM)){
modifyGeom = (Boolean) properties.get(ActionFactory.MODIFY_GEOM);
} else {
modifyGeom = false;
}
if(ActionFactory.propertyCheck(properties, ActionFactory.ATTRIBUTE_MODIFY_FILTER)){
modifyFilter = (String) properties.get(ActionFactory.ATTRIBUTE_MODIFY_FILTER);
} else {
modifyFilter = null;
}
if (!params.containsKey(MAX_CONNECTIONS)) {
params.put(MAX_CONNECTIONS, MAX_CONNECTIONS_NR);
}
try {
dataStore2Write = DataStoreLinker.openDataStore(params);
if (dataStore2Write != null) {
datastoreTypeNames = Arrays.asList(dataStore2Write.getTypeNames());
initDone = true;
}
} catch (Exception ex) {
constructorEx = ex;
}
initPostCollectionActions(properties);
}
public EasyFeature execute(EasyFeature feature) throws Exception {
if (!initDone) {
throw new Exception("\nOpening dataStore failed; datastore could not be found, missing library or no access to file: "
+ toString() + "\n\n" + constructorEx.getLocalizedMessage());
}
long start = new Date().getTime();
feature = fixFeatureTypeName(feature);
String typename = feature.getFeatureType().getTypeName();
PrimaryKey pks = null;
DefaultFeatureCollection fc = null;
FeatureStore store = null;
List<List<String>> errors = null;
List<List<String>> nonFatals = null;
int batchsize = BATCHSIZE;
int numWritten = 0;
//TODO aanpassen batchsize mogelijk maken
//hiermee kan dan ook (via batch size is -1) in een transactie oude records
//worden verwijderd en nieuwe records worden toegevoegd, zodat een volledige
//rollback gedaan kan worden
if (featureTypeNames.contains(typename)) {
pks = featurePKs.get(typename);
fc = featureCollectionCache.get(typename);
store = featureStores.get(typename);
batchsize = featureBatchSizes.get(typename);
numWritten = featuresWritten.get(typename);
errors = featureErrors.get(typename);
nonFatals = featureNonFatals.get(typename);
} else {
//TODO uitzoeken of drop ook in de transactie kan
boolean delayRemoveUntilFirstCommit = false;
if (batchsize == -1) {
delayRemoveUntilFirstCommit = true;
}
// uitzoeken of tabel al is aangemaakt
// mogelijk wordt de naam van de feature type hierbij nog aangepast
String oldTypeName = typename;
boolean typeExists = datastoreTypeNames.contains(oldTypeName);
typename = checkSchema(feature.getFeatureType(), delayRemoveUntilFirstCommit, typeExists);
if (!typename.equals(oldTypeName)) {
feature.setTypeName(typename);
}
fc = new DefaultFeatureCollection(typename, feature.getFeatureType());
featureCollectionCache.put(typename, fc);
if (dataStore2Write != null) {
if (dataStore2Write instanceof JDBCDataStore) {
FeatureSource fs = ((JDBCDataStore) dataStore2Write).getFeatureSource(typename, Transaction.AUTO_COMMIT);
if (fs instanceof JDBCFeatureStore) {
store = (JDBCFeatureStore) fs;
pks = ((JDBCFeatureStore) fs).getPrimaryKey();
} else {
throw new IllegalStateException("Table cannot be written: no primary key? FeatureSource was not of type JDBCFeatureStore");
}
} else {
store = (FeatureStore) dataStore2Write.getFeatureSource(typename);
}
}
featureStores.put(typename, store);
featurePKs.put(typename, pks);
featureBatchSizes.put(typename, batchsize);
featuresWritten.put(typename, numWritten);
featureErrors.put(typename, new ArrayList<List<String>>());
featureNonFatals.put(typename, new ArrayList<List<String>>());
// remember that typename is processed
featureTypeNames.add(typename);
}
feature.convertGeomTo2D();
prepareWrite(fc, pks, feature);
// start writing when number of features is larger than batch size,
// except when batch size is -1, then always wait for last feature
Integer collectionSize = fc.size();
if ((collectionSize >= batchsize && batchsize != -1)) {
try {
batchsize = writeCollection(fc, store, batchsize);
featureBatchSizes.put(typename, batchsize);
} catch (Exception ex) {
throw new FeatureException("Error writing feature collection. Features not written.", ex);
} finally {
fc.retainAll(new ArrayList());
}
}
long end = new Date().getTime() - start;
log.debug("WRITER BLOCK: " + end);
return feature;
}
private void prepareWrite(DefaultFeatureCollection fc, PrimaryKey pk, EasyFeature feature) throws IOException {
// Bepaal de<SUF>
PrimaryKey usePk = pk;
// TODO: overnemen van pk uit source en instellen voor target
// kan niet omdat dit niet (gemakkelijk) ondersteund wordt.
// Nu wordt de automatisch gegenereerde primary key gebruikt
// indien er geen doeltabel wordt gebruikt.
// if (dropFirst) {
// if (feature.getUserData().containsKey("sourcePks")) {
// usePk = (PrimaryKey) feature.getUserData().get("sourcePks");
// }
// }
SimpleFeature newFeature = feature.getFeature();
// bouw pk uit gemapte waarden uit bron
StringBuilder oldfid = new StringBuilder();
if (usePk != null) {
List<PrimaryKeyColumn> pkcs = usePk.getColumns();
for (PrimaryKeyColumn pkc : pkcs) {
String cn = pkc.getName();
Object o = feature.getAttribute(cn);
if (o == null) {
// primary is blijkbaar niet gemapt, dan vertrouwen op autonumber
oldfid = null;
break;
}
oldfid.append(o).append(".");
}
if (oldfid != null) {
oldfid.setLength(oldfid.length() - 1);
}
}
if (oldfid != null && oldfid.length() > 0) {
// voeg pk toe aan feature en zeg deze te gebruiken
newFeature = feature.copy(oldfid.toString()).getFeature();
newFeature.getUserData().put(Hints.USE_PROVIDED_FID, true);
}
// Check of feature geskipped moet worden
SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();
if (feature.isSkipped()) {
List<String> message = new ArrayList(
Arrays.asList("Feature uitgefilterd", feature.getID()));
featureNonFatals.get(type.getTypeName()).add(message);
} else {
fc.add(newFeature);
}
}
private int writeCollection(DefaultFeatureCollection fc, FeatureStore store, int batchsize) throws FeatureException, IOException {
// maak nieuwe subcollecties
SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();
int orgbatchsize = batchsize;
int stamp = generator.nextInt(10000);
int orgfcsize = fc.size();
log.info("Starting write out for typename: " + type.getTypeName()
+ " with batch size: " + orgbatchsize
+ " and stamp: " + stamp
+ " and size: " + orgfcsize);
DefaultFeatureCollection currentFc = null;
if (batchsize == -1) {
// alles in een keer
currentFc = fc;
} else {
// splits de collectie zodat in delen geprobeerd kan worden te schrijven
currentFc = new DefaultFeatureCollection(type.getTypeName(), type);
List removeList = new ArrayList();
FeatureIterator fi = fc.features();
int count = 0;
while (fi.hasNext() && count < batchsize) {
SimpleFeature newFeature = (SimpleFeature) fi.next();
currentFc.add(newFeature);
removeList.add(newFeature);
count++;
}
fc.removeAll(removeList);
if (!fc.isEmpty()) {
batchsize = writeCollection(fc, store, batchsize);
featureBatchSizes.put(type.getTypeName(), batchsize);
}
}
Transaction t = new DefaultTransaction("add");
store.setTransaction(t);
try {
if (modify) {
FeatureIterator fi = currentFc.features();
while (fi.hasNext()) {
SimpleFeature newFeature = (SimpleFeature) fi.next();
List<org.opengis.feature.type.AttributeType> properties = newFeature.getFeatureType().getTypes();
Object filterValue = newFeature.getAttribute(modifyFilter);
Filter filter = ECQL.toFilter(modifyFilter+"='" + filterValue + "'");
boolean hasGeom = newFeature.getDefaultGeometryProperty() != null;
for (org.opengis.feature.type.AttributeType property : properties) {
if(hasGeom){
if(newFeature.getDefaultGeometryProperty().getName().equals(property.getName()) && !modifyGeom){
continue;
}
}
if (newFeature.getAttribute(property.getName().toString()) != null) {
store.modifyFeatures(property.getName(), newFeature.getAttribute(property.getName()), filter);
}
}
}
} else {
if (batchsize == -1) {
// als alles in een keer, dan ook pas oude feature weggooien
// als nieuwe insert ok zijn (dus in zelfde transactie)
log.info("Removing all features from: " + type.getTypeName()
+ " within insert transaction.");
store.removeFeatures(Filter.INCLUDE);
}
// schrijf batch aan features
store.addFeatures(currentFc);
}
t.commit();
int numWritten = featuresWritten.get(type.getTypeName());
int numProcessed = currentFc.size();
featuresWritten.put(type.getTypeName(), numWritten + numProcessed);
// indien succesvol dan volgende keer grotere batch
batchsize *= INCREASEFACTOR;
if (batchsize > MAX_BATCHSIZE) {
batchsize = MAX_BATCHSIZE;
}
currentFc.retainAll(new ArrayList());
} catch (Exception ex) {
try {
t.rollback();
} catch (IOException ioex) {
log.error("Error rolling back feature type: " + type.getTypeName()
+ ", retrying after error: " + ioex.getLocalizedMessage());
}
if (batchsize == -1) {
// als batch size is -1 dan is de gehele collectie in een keer
// geschreven en moet niet geprobeerd worden in kleinere delen
// te committen, meteen foutmelding sturen
List<String> message = new ArrayList(
Arrays.asList(ExceptionUtils.getRootCauseMessage(ex), "*"));
featureErrors.get(type.getTypeName()).add(message);
return batchsize;
}
if (batchsize == 1) {
// als slechts een enkele feature niet geprocessed kan worden
// dan opgeven
SimpleFeature f = (SimpleFeature) (currentFc.toArray())[0];
List<String> message = new ArrayList(
Arrays.asList(ExceptionUtils.getRootCauseMessage(ex), f.getID()));
featureErrors.get(type.getTypeName()).add(message);
return batchsize;
}
// probeer opnieuw met aangepast batch size
batchsize /= DECREASEFACTOR;
if (batchsize < 2) {
batchsize = 1;
}
log.info("Rollback for feature type: " + type.getTypeName()
+ ", retry with new batch size: " + batchsize);
batchsize = writeCollection(currentFc, store, batchsize);
featureBatchSizes.put(type.getTypeName(), batchsize);
} finally {
t.close();
}
log.info("finishing write out for typename: " + type.getTypeName()
+ " with batch size: " + orgbatchsize
+ " and stamp: " + stamp
+ " and size: " + orgfcsize);
return batchsize;
}
@Override
public void close() throws Exception {
log.info("Closing ActionDataStore Writer");
if (dataStore2Write != null) {
dataStore2Write.dispose();
}
}
private void initPostCollectionActions(Map properties) {
//slecht een keer init toestaan, ofwel in constructor ofwel in block
//anders wordt het wel erg complex.
if (postCollectionActionsInitDone) {
return;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZE)) {
polygonize = new Boolean(properties.get(ActionFactory.POLYGONIZE).toString());
postCollectionActionsInitDone = true;
} else {
polygonize = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZEWITHATTR)) {
polygonizeWithAttr = new Boolean(properties.get(ActionFactory.POLYGONIZEWITHATTR).toString());
postCollectionActionsInitDone = true;
} else {
polygonizeWithAttr = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POLYGONIZESUFLKI)) {
polygonizeSufLki = new Boolean(properties.get(ActionFactory.POLYGONIZESUFLKI).toString());
postCollectionActionsInitDone = true;
} else {
polygonizeSufLki = false;
}
if (ActionFactory.propertyCheck(properties, ActionFactory.POSTPOINTWITHINPOLYGON)) {
postPointWithinPolygon = new Boolean(properties.get(ActionFactory.POSTPOINTWITHINPOLYGON).toString());
postCollectionActionsInitDone = true;
} else {
postPointWithinPolygon = false;
}
if (this.polygonize) {
log.info("Polygonize is configured as post action");
collectionActions.add(new CollectionAction_Polygonize(new HashMap(properties)));
}
if (this.postPointWithinPolygon) {
log.info("Point_Within_Polygon with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_Point_Within_Polygon(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Cannot create Point_Within_Polygon post action", e);
}
}
if (this.polygonizeWithAttr) {
log.info("Polygonize with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_PolygonizeWithAttr(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create PolygonizeWithAttr post action", e);
}
} else if (this.polygonizeSufLki) {
log.info("Polygonize with attribute is configured as post action");
try {
collectionActions.add(new CollectionAction_PolygonizeSufLki(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create PolygonizeWithAttr post action", e);
}
}
if (this.postPointWithinPolygon) {
log.info("Find polygon with point is configured as post action");
try {
collectionActions.add(new CollectionAction_Intersects_XY_Add_Attrib(dataStore2Write, new HashMap(properties)));
} catch (Exception e) {
log.error("Can not create Find polygon with point post action", e);
}
}
}
@Override
public void processPostCollectionActions(Status status, Map properties) {
//deze post actions kunnen ook door een block gezet zijn,
initPostCollectionActions(properties);
log.info("Collect errors from ActionDataStore_Writer");
if (dataStore2Write != null) {
try {
String typeNames[] = dataStore2Write.getTypeNames();
List<List<String>> nonFatals = null;
for (int i = 0; i < typeNames.length; i++) {
nonFatals = featureNonFatals.get(typeNames[i]);
if (nonFatals != null && !nonFatals.isEmpty()) {
for (int j = 0; j < nonFatals.size(); j++) {
List<String> message = nonFatals.get(j);
status.addNonFatalError(message.get(0), message.get(1));
}
}
}
List<List<String>> errors = null;
for (int i = 0; i < typeNames.length; i++) {
errors = featureErrors.get(typeNames[i]);
if (errors != null && !errors.isEmpty()) {
for (int j = 0; j < errors.size(); j++) {
List<String> message = errors.get(j);
status.addWriteError(message.get(0), message.get(1));
}
}
}
for (int i = 0; i < typeNames.length; i++) {
Integer numWritten = featuresWritten.get(typeNames[i]);
if (numWritten!=null) {
int numProcessed = status.getProcessedFeatures();
status.setProcessedFeatures(numProcessed + numWritten.intValue());
}
}
} catch (IOException e) {
status.addWriteError("Error collecting errors/messages from ActionDataStore_Writer", null);
log.error("Error collecting errors/messages from ActionDataStore_Writer.", e);
}
}
for (int i = 0; i < collectionActions.size(); i++) {
log.info("Process Post actions ActionDataStore_Writer");
CollectionAction ca = collectionActions.get(i);
//do the polygonize function
if (ca instanceof CollectionAction_Polygonize) {
for (int s = 0; s < featureTypeNames.size(); s++) {
try {
GeometryDescriptor gd = dataStore2Write.getSchema(featureTypeNames.get(s)).getGeometryDescriptor();
if (gd == null) {
continue;
}
Class geometryTypeBinding = dataStore2Write.getSchema(featureTypeNames.get(s)).getGeometryDescriptor().getType().getBinding();
if (LineString.class == geometryTypeBinding || MultiLineString.class == geometryTypeBinding) {
FeatureSource fs = dataStore2Write.getFeatureSource(featureTypeNames.get(s));
FeatureCollection fc = fs.getFeatures();
ca.execute(fc, this);
}
} catch (Exception e) {
status.addWriteError("Error while polygonizing the lines", "");
log.error("Error while Polygonizing the lines.", e);
}
}
}
if (ca instanceof CollectionAction_Point_Within_Polygon) {
DataStore ds = null;
try {
CollectionAction_Point_Within_Polygon cap = (CollectionAction_Point_Within_Polygon) ca;
FeatureSource fs = dataStore2Write.getFeatureSource(cap.getPointsTable());
DefaultFeatureCollection fc = (DefaultFeatureCollection)fs.getFeatures();
FeatureSource fs2 = dataStore2Write.getFeatureSource(cap.getPolygonTable());
DefaultFeatureCollection fc2 = (DefaultFeatureCollection)fs2.getFeatures();
ds = DataStoreLinker.openDataStore(this.params);
cap.setDataStore2Write(ds);
cap.execute(fc, fc2, this);
} catch (Exception e) {
status.addWriteError("Error while points within polygon with attributes", "");
log.error("Error while Points within Polygon with attributes.", e);
} finally {
if (ds != null) {
ds.dispose();
}
}
}
if (ca instanceof CollectionAction_PolygonizeWithAttr) {
DataStore ds = null;
try {
CollectionAction_PolygonizeWithAttr cap = (CollectionAction_PolygonizeWithAttr) ca;
FeatureSource fs = dataStore2Write.getFeatureSource(cap.getAttributeFeatureName());
FeatureCollection fc = fs.getFeatures();
ds = DataStoreLinker.openDataStore(this.params);
cap.setDataStore2Write(ds);
cap.execute(fc, this);
} catch (Exception e) {
status.addWriteError("Error while polygonizing the lines with attributes", "");
log.error("Error while polygonizing the lines with attributes.", e);
} finally {
if (ds != null) {
ds.dispose();
}
}
}
}
}
/**
* Check the schema and return the name.
*/
private String checkSchema(SimpleFeatureType featureType, boolean delayRemoveUntilFirstCommit, boolean typeExists) throws Exception {
String typename2Write = featureType.getTypeName();
if (dropFirst && typeExists) {
// Check if DataStore is a Database
if (dataStore2Write instanceof JDBCDataStore) {
log.info("Verwijderen van tabel: " + featureType.getTypeName());
try {
dataStore2Write.removeSchema(featureType.getTypeName());
} catch (IOException io) {
log.warn("Verwijderen van " + featureType.getTypeName() + " is niet gelukt, melding: " + io.getLocalizedMessage());
}
}
typeExists = false;
}
// If table does not exist, create new
if (!typeExists) {
log.info("Creating new table with name: " + featureType.getTypeName());
dataStore2Write.createSchema(featureType);
} else if (!append && !modify && !delayRemoveUntilFirstCommit) {
log.info("Removing all features from: " + typename2Write);
boolean deleteSuccess = false;
// Check if DataStore is a Database
if (dataStore2Write instanceof JDBCDataStore) {
// Empty table
JDBCDataStore database = (JDBCDataStore) dataStore2Write;
Connection con = null;
try {
con = database.getConnection(Transaction.AUTO_COMMIT);
// try truncate: fast
removeAllFeaturesWithTruncate(database, con, typename2Write);
deleteSuccess = true;
} catch (Exception e) {
log.debug("Removing using truncate failed: ", e);
Connection con1 = null;
try {
con1 = database.getConnection(Transaction.AUTO_COMMIT);
// try delete from table: mot so fast
removeAllFeaturesWithDelete(database, con, typename2Write);
deleteSuccess = true;
} catch (Exception e2) {
log.debug("Removing using delete from table failed: ", e2);
} finally {
if (con1 != null) {
con1.close();
}
}
} finally {
if (con != null) {
con.close();
}
}
}
if (!deleteSuccess) {
// try using geotools: slowest
removeAllFeatures(dataStore2Write, typename2Write);
log.info("Removing using geotools");
}
}
// lijst van tabellen opnieuw ophalen want er zijn tabellen geschreven
// of verwijderd.
datastoreTypeNames = Arrays.asList(dataStore2Write.getTypeNames());
return typename2Write;
}
/**
* De feature wordt ontdaan van ongeldige waarden en spaties worden
* vervangen door underscrores. Verder wordt gekeken of er al een tabel
* bestaat in de doeldatabase, waarbij hoofdletters worden genegeerd. Als
* dat zo is dat wordt de tabelnaam (featuretype name) goed gezet waarbij
* wel de hoofdletters goed gezet worden. Hierdoor kan later direct in de
* lijst van tabellen worden gecheckt.
*
* @param feature
* @return feature dat gefixt is
* @throws Exception
*/
private EasyFeature fixFeatureTypeName(EasyFeature feature) throws Exception {
String oldTypeName = feature.getTypeName();
boolean isWFS = false;
if(dataStore2Write instanceof WFSDataStore){
isWFS = true;
}
String typename = fixTypename(oldTypeName.replaceAll(" ", "_"), isWFS);
for (String tnn : datastoreTypeNames) {
// hoofdletters gebruik is niet relevant
if (tnn.equalsIgnoreCase(typename)) {
typename = tnn;
break;
}
}
// hoofdletter gebruik is wel relevant
if (!typename.equals(oldTypeName)) {
feature.setTypeName(typename);
}
return feature;
}
public Map getParams() {
return params;
}
public String toString() {
if (params == null) {
return "No datastore params";
}
Map cleanedParams = new HashMap();
for (Object param : params.keySet()) {
if (!param.toString().contains("passw")) {
cleanedParams.put(param, params.get(param));
}
}
return "Datastore params: " + cleanedParams.toString();
}
public static List<List<String>> getConstructors() {
List<List<String>> constructors = new ArrayList<List<String>>();
constructors.add(Arrays.asList(new String[]{
ActionFactory.PARAMS,
ActionFactory.APPEND,
ActionFactory.DROPFIRST
}));
constructors.add(Arrays.asList(new String[]{
ActionFactory.PARAMS
}));
return constructors;
}
public String getDescription_NL() {
return "Schrijf de SimpleFeature weg naar een datastore. Als de datastore een database is, kan de SimpleFeature worden toegevoegd of kan de tabel worden geleegd voor het toevoegen";
}
private void removeAllFeaturesWithTruncate(JDBCDataStore database, Connection con, String typeName) throws SQLException {
PreparedStatement ps = null;
if (database.getSQLDialect() instanceof PostGISDialect) {
ps = con.prepareStatement("TRUNCATE TABLE \"" + typeName + "\" CASCADE");
} else { //if (database.getSQLDialect() instanceof OracleDialect) {
ps = con.prepareStatement("TRUNCATE TABLE \"" + typeName + "\"");
}
ps.execute();
log.info("Removing using truncate");
}
private void removeAllFeaturesWithDelete(JDBCDataStore database, Connection con, String typeName) throws SQLException {
PreparedStatement ps = con.prepareStatement("DELETE FROM \"" + typeName + "\"");
ps.execute();
log.info("Removing using delete from table");
}
private void removeAllFeatures(DataStore datastore, String typeName) throws IOException, Exception {
DefaultTransaction transaction = new DefaultTransaction("removeTransaction");
FeatureStore<SimpleFeatureType, SimpleFeature> store = (FeatureStore<SimpleFeatureType, SimpleFeature>) datastore.getFeatureSource(typeName);
try {
store.removeFeatures(Filter.INCLUDE);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
throw e;
} finally {
transaction.close();
}
}
@Override
public void flush(Status status, Map properties) throws Exception {
for (Map.Entry pairs : featureCollectionCache.entrySet()) {
String key = (String) pairs.getKey();
FeatureStore store = featureStores.get(key);
int batchsize = featureBatchSizes.get(key);
DefaultFeatureCollection fc = (DefaultFeatureCollection) pairs.getValue();
int fcsize = fc.size();
if (fc != null && fcsize > 0) {
batchsize = writeCollection(fc, store, batchsize);
}
log.info("finished flushing cache for typename: " + key
+ " with batch size: " + batchsize
+ " and size: " + fcsize);
}
}
}
|
43857_1 | package ehb.group5.app.UI.views;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import ehb.group5.app.UI.layouts.CommonLayout;
import ehb.group5.app.backend.data.DatabaseService;
import ehb.group5.app.backend.data.table.CompanyEntity;
import ehb.group5.app.backend.security.PasswordAuthentication;
import lombok.Getter;
@Route("profiel/edit")
@PageTitle("Profiel bewerken")
@CssImport("./styles/ProfielBewerken.css")
public class ProfielBewerkenView extends CommonLayout {
/*
Author: LAMSAKAM Zakaria
email: [email protected]
*/
/*
Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield.
https://vaadin.com/docs/v14/
*/
public ProfielBewerkenView(){
CompanyEntity company = (CompanyEntity) VaadinSession.getCurrent().getAttribute("account");
Div Contentdiv = new Div();
Contentdiv.setId("contentid");
//Titel aanmaken
Contentdiv.add(new H1("Profiel bewerken"));
//Email initialiseren
EmailField emailField = new EmailField("Nieuwe Email");
emailField.setValue(company.getEmail());
emailField.setClearButtonVisible(true);
emailField.setErrorMessage("Please enter a valid email address");
//De maximum limiet van letters implementeren.
emailField.setMaxLength(30);
//Password initialiseren
PasswordField passwordField = new PasswordField();
passwordField.setLabel("Nieuwe Wachtwoord");
passwordField.setClearButtonVisible(true);
passwordField.setErrorMessage("Uw wachtwoord moet minstens 6 characters bevatten");
//De maximum en minimum letters worden hier geinisialiseerd.
passwordField.setMaxLength(50);
passwordField.setMinLength(6);
Button button = new Button("Save");
button.addClickShortcut(Key.ENTER);
//Hier wordt er geinisialiseerd dat je ook met de enter van uw toetsenbord mag drukken.
//Als de emailfield of de passwordfield leeg zijn gaat er niks gebeuren omdat ze dan invalid zijn.
button.addClickListener(buttonClickEvent ->{
if (emailField.getValue()!= null
&& passwordField.getValue() != null
&& !emailField.getValue().isEmpty()
&& !passwordField.getValue().isEmpty()
&& !emailField.isInvalid()
&& !passwordField.isInvalid()
){
// De database wordt hier geüpdatet door de emailfield en de passwordfield te bewerken.
company.setEmail(emailField.getValue());
company.setPassword(new PasswordAuthentication().hash(passwordField.getValue().toCharArray()));
DatabaseService.getCompaniesStore().update(company);
//Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de Route die hier geinisialiseerd word.
UI.getCurrent().getPage().setLocation("profiel");
} else {
Notification.show("Alles is niet correct ingevuld.");
}
});
//Alles in de contentdiv toevoegen.
Contentdiv.add(emailField);
Contentdiv.add(passwordField);
Contentdiv.add(button);
getContainer().add(Contentdiv);
}
}
| EHB-TI/Groep5-Reservingstool_voor_winkeliers | src/main/java/ehb/group5/app/UI/views/ProfielBewerkenView.java | 1,024 | /*
Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield.
https://vaadin.com/docs/v14/
*/ | block_comment | nl | package ehb.group5.app.UI.views;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import ehb.group5.app.UI.layouts.CommonLayout;
import ehb.group5.app.backend.data.DatabaseService;
import ehb.group5.app.backend.data.table.CompanyEntity;
import ehb.group5.app.backend.security.PasswordAuthentication;
import lombok.Getter;
@Route("profiel/edit")
@PageTitle("Profiel bewerken")
@CssImport("./styles/ProfielBewerken.css")
public class ProfielBewerkenView extends CommonLayout {
/*
Author: LAMSAKAM Zakaria
email: [email protected]
*/
/*
Ik heb het<SUF>*/
public ProfielBewerkenView(){
CompanyEntity company = (CompanyEntity) VaadinSession.getCurrent().getAttribute("account");
Div Contentdiv = new Div();
Contentdiv.setId("contentid");
//Titel aanmaken
Contentdiv.add(new H1("Profiel bewerken"));
//Email initialiseren
EmailField emailField = new EmailField("Nieuwe Email");
emailField.setValue(company.getEmail());
emailField.setClearButtonVisible(true);
emailField.setErrorMessage("Please enter a valid email address");
//De maximum limiet van letters implementeren.
emailField.setMaxLength(30);
//Password initialiseren
PasswordField passwordField = new PasswordField();
passwordField.setLabel("Nieuwe Wachtwoord");
passwordField.setClearButtonVisible(true);
passwordField.setErrorMessage("Uw wachtwoord moet minstens 6 characters bevatten");
//De maximum en minimum letters worden hier geinisialiseerd.
passwordField.setMaxLength(50);
passwordField.setMinLength(6);
Button button = new Button("Save");
button.addClickShortcut(Key.ENTER);
//Hier wordt er geinisialiseerd dat je ook met de enter van uw toetsenbord mag drukken.
//Als de emailfield of de passwordfield leeg zijn gaat er niks gebeuren omdat ze dan invalid zijn.
button.addClickListener(buttonClickEvent ->{
if (emailField.getValue()!= null
&& passwordField.getValue() != null
&& !emailField.getValue().isEmpty()
&& !passwordField.getValue().isEmpty()
&& !emailField.isInvalid()
&& !passwordField.isInvalid()
){
// De database wordt hier geüpdatet door de emailfield en de passwordfield te bewerken.
company.setEmail(emailField.getValue());
company.setPassword(new PasswordAuthentication().hash(passwordField.getValue().toCharArray()));
DatabaseService.getCompaniesStore().update(company);
//Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de Route die hier geinisialiseerd word.
UI.getCurrent().getPage().setLocation("profiel");
} else {
Notification.show("Alles is niet correct ingevuld.");
}
});
//Alles in de contentdiv toevoegen.
Contentdiv.add(emailField);
Contentdiv.add(passwordField);
Contentdiv.add(button);
getContainer().add(Contentdiv);
}
}
|
32843_45 | /*
* 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
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axiom.om.impl.dom;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.om.impl.MTOMXMLStreamWriter;
import org.apache.axiom.om.impl.OMNodeEx;
import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.om.util.StAXUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Hashtable;
public abstract class NodeImpl implements Node, NodeList, OMNodeEx, Cloneable {
/** Holds the user data objects */
private Hashtable userData; // Will be initialized in setUserData()
/** Field builder */
public OMXMLParserWrapper builder;
/** Field done */
protected boolean done = false;
protected DocumentImpl ownerNode;
/** Factory that created this node */
protected final OMFactory factory;
// data
protected short flags;
protected final static short OWNED = 0x1 << 1;
protected final static short FIRSTCHILD = 0x1 << 2;
protected final static short READONLY = 0x1 << 3;
protected final static short SPECIFIED = 0x1 << 4;
protected final static short NORMALIZED = 0x1 << 5;
//
// Constructors
//
protected NodeImpl(DocumentImpl ownerDocument, OMFactory factory) {
//this(factory);
this.factory = factory;
this.ownerNode = ownerDocument;
// this.isOwned(true);
}
protected NodeImpl(OMFactory factory) {
this.factory = factory;
}
public void normalize() {
//Parent node should override this
}
public boolean hasAttributes() {
return false; // overridden in ElementImpl
}
public boolean hasChildNodes() {
return false; // Override in ParentNode
}
public String getLocalName() {
return null; // Override in AttrImpl and ElementImpl
}
public String getNamespaceURI() {
return null; // Override in AttrImpl and ElementImpl
}
public String getNodeValue() throws DOMException {
return null;
}
/*
* Overidden in ElementImpl and AttrImpl.
*/
public String getPrefix() {
return null;
}
public void setNodeValue(String arg0) throws DOMException {
// Don't do anything, to be overridden in SOME Child classes
}
public void setPrefix(String prefix) throws DOMException {
throw new DOMException(DOMException.NAMESPACE_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NAMESPACE_ERR,
null));
}
/**
* Finds the document that this Node belongs to (the document in whose context the Node was
* created). The Node may or may not
*/
public Document getOwnerDocument() {
return this.ownerNode;
}
/**
* Returns the collection of attributes associated with this node, or null if none. At this
* writing, Element is the only type of node which will ever have attributes.
*
* @see ElementImpl
*/
public NamedNodeMap getAttributes() {
return null; // overridden in ElementImpl
}
/**
* Gets the first child of this Node, or null if none.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @see ParentNode
*/
public Node getFirstChild() {
return null;
}
/**
* Gets the last child of this Node, or null if none.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @see ParentNode
*/
public Node getLastChild() {
return null;
}
/** Returns the next child of this node's parent, or null if none. */
public Node getNextSibling() {
return null; // default behavior, overriden in ChildNode
}
public Node getParentNode() {
return null; // overriden by ChildNode
// Document, DocumentFragment, and Attribute will never have parents.
}
/*
* Same as getParentNode but returns internal type NodeImpl.
*/
NodeImpl parentNode() {
return null;
}
/** Returns the previous child of this node's parent, or null if none. */
public Node getPreviousSibling() {
return null; // default behavior, overriden in ChildNode
}
// public Node cloneNode(boolean deep) {
// if(this instanceof OMElement) {
// return (Node)((OMElement)this).cloneOMElement();
// } else if(this instanceof OMText ){
// return ((TextImpl)this).cloneText();
// } else {
// throw new UnsupportedOperationException("Only elements can be cloned
// right now");
// }
// }
//
public Node cloneNode(boolean deep) {
NodeImpl newnode;
try {
newnode = (NodeImpl) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("**Internal Error**" + e);
}
newnode.ownerNode = this.ownerNode;
newnode.isOwned(false);
newnode.isReadonly(false);
return newnode;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getChildNodes()
*/
public NodeList getChildNodes() {
return this;
}
public boolean isSupported(String feature, String version) {
throw new UnsupportedOperationException();
// TODO
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
*/
public Node appendChild(Node newChild) throws DOMException {
return insertBefore(newChild, null);
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node)
*/
public Node removeChild(Node oldChild) throws DOMException {
throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_FOUND_ERR,
null));
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
// Overridden in ParentNode
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
//
// NodeList methods
//
/**
* NodeList method: Returns the number of immediate children of this node.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @return Returns int.
* @see ParentNode
*/
public int getLength() {
return 0;
}
/**
* NodeList method: Returns the Nth immediate child of this node, or null if the index is out of
* bounds.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @param index
* @return Returns org.w3c.dom.Node
* @see ParentNode
*/
public Node item(int index) {
return null;
}
/*
* Flags setters and getters
*/
final boolean isOwned() {
return (flags & OWNED) != 0;
}
final void isOwned(boolean value) {
flags = (short) (value ? flags | OWNED : flags & ~OWNED);
}
final boolean isFirstChild() {
return (flags & FIRSTCHILD) != 0;
}
final void isFirstChild(boolean value) {
flags = (short) (value ? flags | FIRSTCHILD : flags & ~FIRSTCHILD);
}
final boolean isReadonly() {
return (flags & READONLY) != 0;
}
final void isReadonly(boolean value) {
flags = (short) (value ? flags | READONLY : flags & ~READONLY);
}
final boolean isSpecified() {
return (flags & SPECIFIED) != 0;
}
final void isSpecified(boolean value) {
flags = (short) (value ? flags | SPECIFIED : flags & ~SPECIFIED);
}
final boolean isNormalized() {
return (flags & NORMALIZED) != 0;
}
final void isNormalized(boolean value) {
// See if flag should propagate to parent.
if (!value && isNormalized() && ownerNode != null) {
ownerNode.isNormalized(false);
}
flags = (short) (value ? flags | NORMALIZED : flags & ~NORMALIZED);
}
// /
// /OM Methods
// /
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#getParent()
*/
public OMContainer getParent() throws OMException {
return null; // overriden by ChildNode
// Document, DocumentFragment, and Attribute will never have parents.
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#isComplete()
*/
public boolean isComplete() {
return this.done;
}
public void setComplete(boolean state) {
this.done = state;
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#insertSiblingAfter
* (org.apache.axis2.om.OMNode)
*/
public void insertSiblingAfter(OMNode sibling) throws OMException {
// Overridden in ChildNode
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#insertSiblingBefore
* (org.apache.axis2.om.OMNode)
*/
public void insertSiblingBefore(OMNode sibling) throws OMException {
// Overridden in ChildNode
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/** Default behavior returns null, overriden in ChildNode. */
public OMNode getPreviousOMSibling() {
return null;
}
/** Default behavior returns null, overriden in ChildNode. */
public OMNode getNextOMSibling() {
return null;
}
public OMNode getNextOMSiblingIfAvailable() {
return null;
}
public void setPreviousOMSibling(OMNode previousSibling) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
public void setNextOMSibling(OMNode previousSibling) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/** Builds next element. */
public void build() {
while (!done)
this.builder.next();
}
/**
* Parses this node and builds the object structure in memory. AXIOM supports two levels of
* deffered building. First is deffered building of AXIOM using StAX. Second level is the deffered
* building of attachments. AXIOM reads in the attachements from the stream only when user asks by
* calling getDataHandler(). build() method builds the OM without the attachments. buildAll()
* builds the OM together with attachement data. This becomes handy when user wants to free the
* input stream.
*/
public void buildWithAttachments() {
if (!this.done) {
this.build();
}
}
public void close(boolean build) {
if (build) {
this.build();
}
this.done = true;
// If this is a StAXBuilder, close it.
if (builder instanceof StAXBuilder &&
!((StAXBuilder) builder).isClosed()) {
((StAXBuilder) builder).releaseParserOnClose(true);
((StAXBuilder) builder).close();
}
}
/**
* Sets the owner document.
*
* @param document
*/
protected void setOwnerDocument(DocumentImpl document) {
this.ownerNode = document;
this.isOwned(true);
}
public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
serialize(xmlWriter, true);
}
public void serializeAndConsume(XMLStreamWriter xmlWriter) throws XMLStreamException {
serialize(xmlWriter, false);
}
public void serialize(XMLStreamWriter xmlWriter, boolean cache) throws XMLStreamException {
MTOMXMLStreamWriter writer = xmlWriter instanceof MTOMXMLStreamWriter ?
(MTOMXMLStreamWriter) xmlWriter :
new MTOMXMLStreamWriter(xmlWriter);
internalSerialize(writer, cache);
writer.flush();
}
public OMNode detach() {
throw new OMException(
"Elements that doesn't have a parent can not be detached");
}
/*
* DOM-Level 3 methods
*/
public String getBaseURI() {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public short compareDocumentPosition(Node other) throws DOMException {
// This is not yet implemented. In the meantime, we throw a DOMException
// and not an UnsupportedOperationException, since this works better with
// some other libraries (such as Saxon 8.9).
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_SUPPORTED_ERR, null));
}
public String getTextContent() throws DOMException {
return getNodeValue(); // overriden in some subclasses
}
// internal method taking a StringBuffer in parameter
void getTextContent(StringBuffer buf) throws DOMException {
String content = getNodeValue();
if (content != null) {
buf.append(content);
}
}
public void setTextContent(String textContent) throws DOMException {
setNodeValue(textContent); // overriden in some subclasses
}
public boolean isSameNode(Node node) {
// TODO : check
return this == node;
}
public String lookupPrefix(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public boolean isDefaultNamespace(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public String lookupNamespaceURI(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
/**
* Tests whether two nodes are equal. <br>This method tests for equality of nodes, not sameness
* (i.e., whether the two nodes are references to the same object) which can be tested with
* <code>Node.isSameNode()</code>. All nodes that are the same will also be equal, though the
* reverse may not be true. <br>Two nodes are equal if and only if the following conditions are
* satisfied: <ul> <li>The two nodes are of the same type. </li> <li>The following string
* attributes are equal: <code>nodeName</code>, <code>localName</code>,
* <code>namespaceURI</code>, <code>prefix</code>, <code>nodeValue</code> . This is: they are
* both <code>null</code>, or they have the same length and are character for character
* identical. </li> <li>The <code>attributes</code> <code>NamedNodeMaps</code> are equal. This
* is: they are both <code>null</code>, or they have the same length and for each node that
* exists in one map there is a node that exists in the other map and is equal, although not
* necessarily at the same index. </li> <li>The <code>childNodes</code> <code>NodeLists</code>
* are equal. This is: they are both <code>null</code>, or they have the same length and contain
* equal nodes at the same index. Note that normalization can affect equality; to avoid this,
* nodes should be normalized before being compared. </li> </ul> <br>For two
* <code>DocumentType</code> nodes to be equal, the following conditions must also be satisfied:
* <ul> <li>The following string attributes are equal: <code>publicId</code>,
* <code>systemId</code>, <code>internalSubset</code>. </li> <li>The <code>entities</code>
* <code>NamedNodeMaps</code> are equal. </li> <li>The <code>notations</code>
* <code>NamedNodeMaps</code> are equal. </li> </ul> <br>On the other hand, the following do not
* affect equality: the <code>ownerDocument</code>, <code>baseURI</code>, and
* <code>parentNode</code> attributes, the <code>specified</code> attribute for
* <code>Attr</code> nodes, the <code>schemaTypeInfo</code> attribute for <code>Attr</code> and
* <code>Element</code> nodes, the <code>Text.isElementContentWhitespace</code> attribute for
* <code>Text</code> nodes, as well as any user data or event listeners registered on the nodes.
* <p ><b>Note:</b> As a general rule, anything not mentioned in the description above is not
* significant in consideration of equality checking. Note that future versions of this
* specification may take into account more attributes and implementations conform to this
* specification are expected to be updated accordingly.
*
* @param node The node to compare equality with.
* @return Returns <code>true</code> if the nodes are equal, <code>false</code> otherwise.
* @since DOM Level 3
*/
//TODO : sumedha, complete
public boolean isEqualNode(Node node) {
final boolean equal = true;
final boolean notEqual = false;
if (this.getNodeType() != node.getNodeType()) {
return notEqual;
}
if (checkStringAttributeEquality(node)) {
if (checkNamedNodeMapEquality(node)) {
} else {
return notEqual;
}
} else {
return notEqual;
}
return equal;
}
private boolean checkStringAttributeEquality(Node node) {
final boolean equal = true;
final boolean notEqual = false;
// null not-null -> true
// not-null null -> true
// null null -> false
// not-null not-null -> false
//NodeName
if (node.getNodeName() == null ^ this.getNodeName() == null) {
return notEqual;
} else {
if (node.getNodeName() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNodeName().equals(this.getNodeName()))) {
return notEqual;
}
}
}
//localName
if (node.getLocalName() == null ^ this.getLocalName() == null) {
return notEqual;
} else {
if (node.getLocalName() == null) {
//This means both are null.do nothing
} else {
if (!(node.getLocalName().equals(this.getLocalName()))) {
return notEqual;
}
}
}
//namespaceURI
if (node.getNamespaceURI() == null ^ this.getNamespaceURI() == null) {
return notEqual;
} else {
if (node.getNamespaceURI() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNamespaceURI().equals(this.getNamespaceURI()))) {
return notEqual;
}
}
}
//prefix
if (node.getPrefix() == null ^ this.getPrefix() == null) {
return notEqual;
} else {
if (node.getPrefix() == null) {
//This means both are null.do nothing
} else {
if (!(node.getPrefix().equals(this.getPrefix()))) {
return notEqual;
}
}
}
//nodeValue
if (node.getNodeValue() == null ^ this.getNodeValue() == null) {
return notEqual;
} else {
if (node.getNodeValue() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNodeValue().equals(this.getNodeValue()))) {
return notEqual;
}
}
}
return equal;
}
private boolean checkNamedNodeMapEquality(Node node) {
final boolean equal = true;
final boolean notEqual = false;
if (node.getAttributes() == null ^ this.getAttributes() == null) {
return notEqual;
}
NamedNodeMap thisNamedNodeMap = this.getAttributes();
NamedNodeMap nodeNamedNodeMap = node.getAttributes();
// null not-null -> true
// not-null null -> true
// null null -> false
// not-null not-null -> false
if (thisNamedNodeMap == null ^ nodeNamedNodeMap == null) {
return notEqual;
} else {
if (thisNamedNodeMap == null) {
//This means both are null.do nothing
} else {
if (thisNamedNodeMap.getLength() != nodeNamedNodeMap.getLength()) {
return notEqual;
} else {
//they have the same length and for each node that exists in one map
//there is a node that exists in the other map and is equal, although
//not necessarily at the same index.
int itemCount = thisNamedNodeMap.getLength();
for (int a = 0; a < itemCount; a++) {
NodeImpl thisNode = (NodeImpl) thisNamedNodeMap.item(a);
NodeImpl tmpNode =
(NodeImpl) nodeNamedNodeMap.getNamedItem(thisNode.getNodeName());
if (tmpNode == null) {
//i.e. no corresponding node
return notEqual;
} else {
if (!(thisNode.isEqualNode(tmpNode))) {
return notEqual;
}
}
}
}
}
}
return equal;
}
public Object getFeature(String arg0, String arg1) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
/* *
* userData storage/hashtable will be called only when the user needs to set user data. Previously, it was done as,
* for every node a new Hashtable created making the excution very inefficient. According to profiles, no. of method
* invocations to setUserData() method is very low, so this implementation is better.
* Another option:
* TODO do a profile and check the times for hashtable initialization. If it's still higher, we have to go to second option
* Create a separate class(UserData) to store key and value pairs. Then put those objects to a array with a reasonable size.
* then grow it accordingly. @ Kasun Gajasinghe
* @param key userData key
* @param value userData value
* @param userDataHandler it seems all invocations sends null for this parameter.
* Kept it for the moment just for being on the safe side.
* @return previous Object if one is set before.
*/
public Object setUserData(String key, Object value, UserDataHandler userDataHandler) {
if (userData == null) {
userData = new Hashtable();
}
return userData.put(key, value);
}
public Object getUserData(String key) {
if (userData != null) {
return userData.get(key);
}
return null;
}
public void serialize(OutputStream output) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output);
try {
serialize(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serialize(Writer writer) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer);
try {
serialize(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serializeAndConsume(OutputStream output)
throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output);
try {
serializeAndConsume(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serializeAndConsume(Writer writer) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer);
try {
serializeAndConsume(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serialize(OutputStream output, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format);
try {
internalSerialize(writer, true);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serialize(Writer writer2, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils
.createXMLStreamWriter(writer2));
writer.setOutputFormat(format);
try {
internalSerialize(writer, true);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serializeAndConsume(OutputStream output, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format);
try {
internalSerialize(writer, false);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serializeAndConsume(Writer writer2, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils
.createXMLStreamWriter(writer2));
try {
writer.setOutputFormat(format);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
internalSerialize(writer, false);
writer.flush();
} finally {
writer.close();
}
}
/** Returns the <code>OMFactory</code> that created this node */
public OMFactory getOMFactory() {
return this.factory;
}
public void internalSerialize(XMLStreamWriter writer) throws XMLStreamException {
internalSerialize(writer, true);
}
public void internalSerializeAndConsume(XMLStreamWriter writer) throws XMLStreamException {
internalSerialize(writer, false);
}
}
| wso2/wso2-axiom | modules/axiom-dom/src/main/java/org/apache/axiom/om/impl/dom/NodeImpl.java | 7,252 | // Overridden in ChildNode | line_comment | nl | /*
* 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
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axiom.om.impl.dom;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.om.impl.MTOMXMLStreamWriter;
import org.apache.axiom.om.impl.OMNodeEx;
import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.om.util.StAXUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Hashtable;
public abstract class NodeImpl implements Node, NodeList, OMNodeEx, Cloneable {
/** Holds the user data objects */
private Hashtable userData; // Will be initialized in setUserData()
/** Field builder */
public OMXMLParserWrapper builder;
/** Field done */
protected boolean done = false;
protected DocumentImpl ownerNode;
/** Factory that created this node */
protected final OMFactory factory;
// data
protected short flags;
protected final static short OWNED = 0x1 << 1;
protected final static short FIRSTCHILD = 0x1 << 2;
protected final static short READONLY = 0x1 << 3;
protected final static short SPECIFIED = 0x1 << 4;
protected final static short NORMALIZED = 0x1 << 5;
//
// Constructors
//
protected NodeImpl(DocumentImpl ownerDocument, OMFactory factory) {
//this(factory);
this.factory = factory;
this.ownerNode = ownerDocument;
// this.isOwned(true);
}
protected NodeImpl(OMFactory factory) {
this.factory = factory;
}
public void normalize() {
//Parent node should override this
}
public boolean hasAttributes() {
return false; // overridden in ElementImpl
}
public boolean hasChildNodes() {
return false; // Override in ParentNode
}
public String getLocalName() {
return null; // Override in AttrImpl and ElementImpl
}
public String getNamespaceURI() {
return null; // Override in AttrImpl and ElementImpl
}
public String getNodeValue() throws DOMException {
return null;
}
/*
* Overidden in ElementImpl and AttrImpl.
*/
public String getPrefix() {
return null;
}
public void setNodeValue(String arg0) throws DOMException {
// Don't do anything, to be overridden in SOME Child classes
}
public void setPrefix(String prefix) throws DOMException {
throw new DOMException(DOMException.NAMESPACE_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NAMESPACE_ERR,
null));
}
/**
* Finds the document that this Node belongs to (the document in whose context the Node was
* created). The Node may or may not
*/
public Document getOwnerDocument() {
return this.ownerNode;
}
/**
* Returns the collection of attributes associated with this node, or null if none. At this
* writing, Element is the only type of node which will ever have attributes.
*
* @see ElementImpl
*/
public NamedNodeMap getAttributes() {
return null; // overridden in ElementImpl
}
/**
* Gets the first child of this Node, or null if none.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @see ParentNode
*/
public Node getFirstChild() {
return null;
}
/**
* Gets the last child of this Node, or null if none.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @see ParentNode
*/
public Node getLastChild() {
return null;
}
/** Returns the next child of this node's parent, or null if none. */
public Node getNextSibling() {
return null; // default behavior, overriden in ChildNode
}
public Node getParentNode() {
return null; // overriden by ChildNode
// Document, DocumentFragment, and Attribute will never have parents.
}
/*
* Same as getParentNode but returns internal type NodeImpl.
*/
NodeImpl parentNode() {
return null;
}
/** Returns the previous child of this node's parent, or null if none. */
public Node getPreviousSibling() {
return null; // default behavior, overriden in ChildNode
}
// public Node cloneNode(boolean deep) {
// if(this instanceof OMElement) {
// return (Node)((OMElement)this).cloneOMElement();
// } else if(this instanceof OMText ){
// return ((TextImpl)this).cloneText();
// } else {
// throw new UnsupportedOperationException("Only elements can be cloned
// right now");
// }
// }
//
public Node cloneNode(boolean deep) {
NodeImpl newnode;
try {
newnode = (NodeImpl) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("**Internal Error**" + e);
}
newnode.ownerNode = this.ownerNode;
newnode.isOwned(false);
newnode.isReadonly(false);
return newnode;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getChildNodes()
*/
public NodeList getChildNodes() {
return this;
}
public boolean isSupported(String feature, String version) {
throw new UnsupportedOperationException();
// TODO
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
*/
public Node appendChild(Node newChild) throws DOMException {
return insertBefore(newChild, null);
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node)
*/
public Node removeChild(Node oldChild) throws DOMException {
throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_FOUND_ERR,
null));
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
// Overridden in ParentNode
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
//
// NodeList methods
//
/**
* NodeList method: Returns the number of immediate children of this node.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @return Returns int.
* @see ParentNode
*/
public int getLength() {
return 0;
}
/**
* NodeList method: Returns the Nth immediate child of this node, or null if the index is out of
* bounds.
* <p/>
* By default we do not have any children, ParentNode overrides this.
*
* @param index
* @return Returns org.w3c.dom.Node
* @see ParentNode
*/
public Node item(int index) {
return null;
}
/*
* Flags setters and getters
*/
final boolean isOwned() {
return (flags & OWNED) != 0;
}
final void isOwned(boolean value) {
flags = (short) (value ? flags | OWNED : flags & ~OWNED);
}
final boolean isFirstChild() {
return (flags & FIRSTCHILD) != 0;
}
final void isFirstChild(boolean value) {
flags = (short) (value ? flags | FIRSTCHILD : flags & ~FIRSTCHILD);
}
final boolean isReadonly() {
return (flags & READONLY) != 0;
}
final void isReadonly(boolean value) {
flags = (short) (value ? flags | READONLY : flags & ~READONLY);
}
final boolean isSpecified() {
return (flags & SPECIFIED) != 0;
}
final void isSpecified(boolean value) {
flags = (short) (value ? flags | SPECIFIED : flags & ~SPECIFIED);
}
final boolean isNormalized() {
return (flags & NORMALIZED) != 0;
}
final void isNormalized(boolean value) {
// See if flag should propagate to parent.
if (!value && isNormalized() && ownerNode != null) {
ownerNode.isNormalized(false);
}
flags = (short) (value ? flags | NORMALIZED : flags & ~NORMALIZED);
}
// /
// /OM Methods
// /
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#getParent()
*/
public OMContainer getParent() throws OMException {
return null; // overriden by ChildNode
// Document, DocumentFragment, and Attribute will never have parents.
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#isComplete()
*/
public boolean isComplete() {
return this.done;
}
public void setComplete(boolean state) {
this.done = state;
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#insertSiblingAfter
* (org.apache.axis2.om.OMNode)
*/
public void insertSiblingAfter(OMNode sibling) throws OMException {
// Overridden in ChildNode
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/*
* (non-Javadoc)
*
* @see org.apache.axis2.om.OMNode#insertSiblingBefore
* (org.apache.axis2.om.OMNode)
*/
public void insertSiblingBefore(OMNode sibling) throws OMException {
// Overridden in<SUF>
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/** Default behavior returns null, overriden in ChildNode. */
public OMNode getPreviousOMSibling() {
return null;
}
/** Default behavior returns null, overriden in ChildNode. */
public OMNode getNextOMSibling() {
return null;
}
public OMNode getNextOMSiblingIfAvailable() {
return null;
}
public void setPreviousOMSibling(OMNode previousSibling) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
public void setNextOMSibling(OMNode previousSibling) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
DOMException.HIERARCHY_REQUEST_ERR, null));
}
/** Builds next element. */
public void build() {
while (!done)
this.builder.next();
}
/**
* Parses this node and builds the object structure in memory. AXIOM supports two levels of
* deffered building. First is deffered building of AXIOM using StAX. Second level is the deffered
* building of attachments. AXIOM reads in the attachements from the stream only when user asks by
* calling getDataHandler(). build() method builds the OM without the attachments. buildAll()
* builds the OM together with attachement data. This becomes handy when user wants to free the
* input stream.
*/
public void buildWithAttachments() {
if (!this.done) {
this.build();
}
}
public void close(boolean build) {
if (build) {
this.build();
}
this.done = true;
// If this is a StAXBuilder, close it.
if (builder instanceof StAXBuilder &&
!((StAXBuilder) builder).isClosed()) {
((StAXBuilder) builder).releaseParserOnClose(true);
((StAXBuilder) builder).close();
}
}
/**
* Sets the owner document.
*
* @param document
*/
protected void setOwnerDocument(DocumentImpl document) {
this.ownerNode = document;
this.isOwned(true);
}
public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
serialize(xmlWriter, true);
}
public void serializeAndConsume(XMLStreamWriter xmlWriter) throws XMLStreamException {
serialize(xmlWriter, false);
}
public void serialize(XMLStreamWriter xmlWriter, boolean cache) throws XMLStreamException {
MTOMXMLStreamWriter writer = xmlWriter instanceof MTOMXMLStreamWriter ?
(MTOMXMLStreamWriter) xmlWriter :
new MTOMXMLStreamWriter(xmlWriter);
internalSerialize(writer, cache);
writer.flush();
}
public OMNode detach() {
throw new OMException(
"Elements that doesn't have a parent can not be detached");
}
/*
* DOM-Level 3 methods
*/
public String getBaseURI() {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public short compareDocumentPosition(Node other) throws DOMException {
// This is not yet implemented. In the meantime, we throw a DOMException
// and not an UnsupportedOperationException, since this works better with
// some other libraries (such as Saxon 8.9).
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, DOMMessageFormatter
.formatMessage(DOMMessageFormatter.DOM_DOMAIN, DOMException.NOT_SUPPORTED_ERR, null));
}
public String getTextContent() throws DOMException {
return getNodeValue(); // overriden in some subclasses
}
// internal method taking a StringBuffer in parameter
void getTextContent(StringBuffer buf) throws DOMException {
String content = getNodeValue();
if (content != null) {
buf.append(content);
}
}
public void setTextContent(String textContent) throws DOMException {
setNodeValue(textContent); // overriden in some subclasses
}
public boolean isSameNode(Node node) {
// TODO : check
return this == node;
}
public String lookupPrefix(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public boolean isDefaultNamespace(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
public String lookupNamespaceURI(String arg0) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
/**
* Tests whether two nodes are equal. <br>This method tests for equality of nodes, not sameness
* (i.e., whether the two nodes are references to the same object) which can be tested with
* <code>Node.isSameNode()</code>. All nodes that are the same will also be equal, though the
* reverse may not be true. <br>Two nodes are equal if and only if the following conditions are
* satisfied: <ul> <li>The two nodes are of the same type. </li> <li>The following string
* attributes are equal: <code>nodeName</code>, <code>localName</code>,
* <code>namespaceURI</code>, <code>prefix</code>, <code>nodeValue</code> . This is: they are
* both <code>null</code>, or they have the same length and are character for character
* identical. </li> <li>The <code>attributes</code> <code>NamedNodeMaps</code> are equal. This
* is: they are both <code>null</code>, or they have the same length and for each node that
* exists in one map there is a node that exists in the other map and is equal, although not
* necessarily at the same index. </li> <li>The <code>childNodes</code> <code>NodeLists</code>
* are equal. This is: they are both <code>null</code>, or they have the same length and contain
* equal nodes at the same index. Note that normalization can affect equality; to avoid this,
* nodes should be normalized before being compared. </li> </ul> <br>For two
* <code>DocumentType</code> nodes to be equal, the following conditions must also be satisfied:
* <ul> <li>The following string attributes are equal: <code>publicId</code>,
* <code>systemId</code>, <code>internalSubset</code>. </li> <li>The <code>entities</code>
* <code>NamedNodeMaps</code> are equal. </li> <li>The <code>notations</code>
* <code>NamedNodeMaps</code> are equal. </li> </ul> <br>On the other hand, the following do not
* affect equality: the <code>ownerDocument</code>, <code>baseURI</code>, and
* <code>parentNode</code> attributes, the <code>specified</code> attribute for
* <code>Attr</code> nodes, the <code>schemaTypeInfo</code> attribute for <code>Attr</code> and
* <code>Element</code> nodes, the <code>Text.isElementContentWhitespace</code> attribute for
* <code>Text</code> nodes, as well as any user data or event listeners registered on the nodes.
* <p ><b>Note:</b> As a general rule, anything not mentioned in the description above is not
* significant in consideration of equality checking. Note that future versions of this
* specification may take into account more attributes and implementations conform to this
* specification are expected to be updated accordingly.
*
* @param node The node to compare equality with.
* @return Returns <code>true</code> if the nodes are equal, <code>false</code> otherwise.
* @since DOM Level 3
*/
//TODO : sumedha, complete
public boolean isEqualNode(Node node) {
final boolean equal = true;
final boolean notEqual = false;
if (this.getNodeType() != node.getNodeType()) {
return notEqual;
}
if (checkStringAttributeEquality(node)) {
if (checkNamedNodeMapEquality(node)) {
} else {
return notEqual;
}
} else {
return notEqual;
}
return equal;
}
private boolean checkStringAttributeEquality(Node node) {
final boolean equal = true;
final boolean notEqual = false;
// null not-null -> true
// not-null null -> true
// null null -> false
// not-null not-null -> false
//NodeName
if (node.getNodeName() == null ^ this.getNodeName() == null) {
return notEqual;
} else {
if (node.getNodeName() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNodeName().equals(this.getNodeName()))) {
return notEqual;
}
}
}
//localName
if (node.getLocalName() == null ^ this.getLocalName() == null) {
return notEqual;
} else {
if (node.getLocalName() == null) {
//This means both are null.do nothing
} else {
if (!(node.getLocalName().equals(this.getLocalName()))) {
return notEqual;
}
}
}
//namespaceURI
if (node.getNamespaceURI() == null ^ this.getNamespaceURI() == null) {
return notEqual;
} else {
if (node.getNamespaceURI() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNamespaceURI().equals(this.getNamespaceURI()))) {
return notEqual;
}
}
}
//prefix
if (node.getPrefix() == null ^ this.getPrefix() == null) {
return notEqual;
} else {
if (node.getPrefix() == null) {
//This means both are null.do nothing
} else {
if (!(node.getPrefix().equals(this.getPrefix()))) {
return notEqual;
}
}
}
//nodeValue
if (node.getNodeValue() == null ^ this.getNodeValue() == null) {
return notEqual;
} else {
if (node.getNodeValue() == null) {
//This means both are null.do nothing
} else {
if (!(node.getNodeValue().equals(this.getNodeValue()))) {
return notEqual;
}
}
}
return equal;
}
private boolean checkNamedNodeMapEquality(Node node) {
final boolean equal = true;
final boolean notEqual = false;
if (node.getAttributes() == null ^ this.getAttributes() == null) {
return notEqual;
}
NamedNodeMap thisNamedNodeMap = this.getAttributes();
NamedNodeMap nodeNamedNodeMap = node.getAttributes();
// null not-null -> true
// not-null null -> true
// null null -> false
// not-null not-null -> false
if (thisNamedNodeMap == null ^ nodeNamedNodeMap == null) {
return notEqual;
} else {
if (thisNamedNodeMap == null) {
//This means both are null.do nothing
} else {
if (thisNamedNodeMap.getLength() != nodeNamedNodeMap.getLength()) {
return notEqual;
} else {
//they have the same length and for each node that exists in one map
//there is a node that exists in the other map and is equal, although
//not necessarily at the same index.
int itemCount = thisNamedNodeMap.getLength();
for (int a = 0; a < itemCount; a++) {
NodeImpl thisNode = (NodeImpl) thisNamedNodeMap.item(a);
NodeImpl tmpNode =
(NodeImpl) nodeNamedNodeMap.getNamedItem(thisNode.getNodeName());
if (tmpNode == null) {
//i.e. no corresponding node
return notEqual;
} else {
if (!(thisNode.isEqualNode(tmpNode))) {
return notEqual;
}
}
}
}
}
}
return equal;
}
public Object getFeature(String arg0, String arg1) {
// TODO TODO
throw new UnsupportedOperationException("TODO");
}
/* *
* userData storage/hashtable will be called only when the user needs to set user data. Previously, it was done as,
* for every node a new Hashtable created making the excution very inefficient. According to profiles, no. of method
* invocations to setUserData() method is very low, so this implementation is better.
* Another option:
* TODO do a profile and check the times for hashtable initialization. If it's still higher, we have to go to second option
* Create a separate class(UserData) to store key and value pairs. Then put those objects to a array with a reasonable size.
* then grow it accordingly. @ Kasun Gajasinghe
* @param key userData key
* @param value userData value
* @param userDataHandler it seems all invocations sends null for this parameter.
* Kept it for the moment just for being on the safe side.
* @return previous Object if one is set before.
*/
public Object setUserData(String key, Object value, UserDataHandler userDataHandler) {
if (userData == null) {
userData = new Hashtable();
}
return userData.put(key, value);
}
public Object getUserData(String key) {
if (userData != null) {
return userData.get(key);
}
return null;
}
public void serialize(OutputStream output) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output);
try {
serialize(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serialize(Writer writer) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer);
try {
serialize(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serializeAndConsume(OutputStream output)
throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(output);
try {
serializeAndConsume(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serializeAndConsume(Writer writer) throws XMLStreamException {
XMLStreamWriter xmlStreamWriter = StAXUtils.createXMLStreamWriter(writer);
try {
serializeAndConsume(xmlStreamWriter);
} finally {
xmlStreamWriter.close();
}
}
public void serialize(OutputStream output, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format);
try {
internalSerialize(writer, true);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serialize(Writer writer2, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils
.createXMLStreamWriter(writer2));
writer.setOutputFormat(format);
try {
internalSerialize(writer, true);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serializeAndConsume(OutputStream output, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(output, format);
try {
internalSerialize(writer, false);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
writer.flush();
} finally {
writer.close();
}
}
public void serializeAndConsume(Writer writer2, OMOutputFormat format)
throws XMLStreamException {
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(StAXUtils
.createXMLStreamWriter(writer2));
try {
writer.setOutputFormat(format);
// TODO: the flush is necessary because of an issue with the lifecycle of MTOMXMLStreamWriter
internalSerialize(writer, false);
writer.flush();
} finally {
writer.close();
}
}
/** Returns the <code>OMFactory</code> that created this node */
public OMFactory getOMFactory() {
return this.factory;
}
public void internalSerialize(XMLStreamWriter writer) throws XMLStreamException {
internalSerialize(writer, true);
}
public void internalSerializeAndConsume(XMLStreamWriter writer) throws XMLStreamException {
internalSerialize(writer, false);
}
}
|
39951_18 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class level5 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class level5 extends World
{
private CollisionEngine ce;
Counter counter = new Counter();
/**
* Constructor for objects of class level5.
*
*/
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
public level5()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
//theCounter = new Counter();
// addObject(theCounter, 0, 0);
//prepare();
int[][] map = {
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,36,-1,172,172,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,36,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,36,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,128,-1,35,36,36,36,36,36,37,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,126,127,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,-1,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,35,36,36,36,36,36,36,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{35,36,36,37,92,92,92,92,92,92,92,92,92,92,36,172,-1,172,-1,172,-1,172,-1,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,61},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,172,-1,172,-1,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,126,60},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,35,37},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 28, 500);
//addObject(new Button(),0,90);
addObject(new ResetButton(), 50,50);
addObject(counter,70,120);
addObject(new Letter('J'), 2804, 433);
addObject(new Letter('A'), 4340, 655);
addObject(new Button(),3330,85);
addObject(new BrownCoin(),3744,780);
addObject(new BrownCoin(),4371,780);
// addObject(new Enemy(), 1250, 770);
//addObject(new enemy2(), 500, 1370);
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
prepare();
}
public Counter getCounter()
{
return counter;
}
public void prepare()
{
addObject(counter,70, 120);
Coin coin = new Coin();
addObject(coin,929,419);
}
@Override
public void act()
{
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-Mathijs01 | level5.java | 4,883 | // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class level5 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class level5 extends World
{
private CollisionEngine ce;
Counter counter = new Counter();
/**
* Constructor for objects of class level5.
*
*/
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
public level5()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
//theCounter = new Counter();
// addObject(theCounter, 0, 0);
//prepare();
int[][] map = {
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,172,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,172,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,36,-1,172,172,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,36,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,172,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,172,-1,-1,-1,-1,-1,172,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,36,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,128,-1,35,36,36,36,36,36,37,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,-1,-1,172,-1,126,127,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,-1,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,35,36,36,36,36,36,36,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,-1,172,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1},
{172,-1,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,172,-1,172,-1,172,-1,172,-1,172,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,172,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{35,36,36,37,92,92,92,92,92,92,92,92,92,92,36,172,-1,172,-1,172,-1,172,-1,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,172,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,61},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,172,-1,172,-1,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,172,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,126,60},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,35,36,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,35,37},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90},
{90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 28, 500);
//addObject(new Button(),0,90);
addObject(new ResetButton(), 50,50);
addObject(counter,70,120);
addObject(new Letter('J'), 2804, 433);
addObject(new Letter('A'), 4340, 655);
addObject(new Button(),3330,85);
addObject(new BrownCoin(),3744,780);
addObject(new BrownCoin(),4371,780);
// addObject(new Enemy(), 1250, 770);
//addObject(new enemy2(), 500, 1370);
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision<SUF>
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
prepare();
}
public Counter getCounter()
{
return counter;
}
public void prepare()
{
addObject(counter,70, 120);
Coin coin = new Coin();
addObject(coin,929,419);
}
@Override
public void act()
{
ce.update();
}
}
|
10446_3 | package com.busenzo.domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Lijn {
private final String id;
private final int nummer;
private final Richting richting;
private final String beschrijving;
private ArrayList<Rit> ritten;
private ArrayList<Halte> haltes;
/**
* Maak een nieuwe lijn aan. Er mag nog geen lijn bestaan met hetzelfde
* nummer, richting en beschrijving.
*
* @param id: LijnID geleverd door ov database
* @param nummer: Het lijnnummer
* @param richting: De richting van de lijn
* @param beschrijving Beschrijving van de lijn.
*/
public Lijn(String id, int nummer, Richting richting, String beschrijving) {
this.id = id;
this.nummer = nummer;
this.richting = richting;
this.beschrijving = beschrijving;
this.haltes = new ArrayList<>();
this.ritten = new ArrayList<>();
}
/**
* Voeg een halte toe aan deze lijn
*
* @param halte: De toe te voegen halte, deze halte mag bij deze lijn nog
* niet bestaan.
* @return true als de halte succesvol is toegevoegd, anders false
*/
public boolean addHalte(Halte halte) {
for (Halte h : haltes) {
if (h.getId().equals(halte.getId())) {
return false;
}
}
this.haltes.add(halte);
return true;
}
/**
* Voeg een lijst van haltes toe aan deze lijn
*
* @param haltes: Een lijst van de toe te voegen haltes, iedere individuele
* halte mag bij deze lijn nog niet bestaan
* @return true als de halte is toegevoegd, anders false
*/
public boolean addHaltes(Halte[] haltes) {
for (Halte h1 : this.haltes) {
for (Halte h2 : haltes) {
if (h1.getId().equals(h2.getId())) {
return false;
}
}
}
this.haltes.addAll(Arrays.asList(haltes));
return true;
}
/**
* Haal de ritten op die bij deze lijn horen.
*
* @return Een lijst van ritten die bij deze lijn horen
*/
public List<Rit> getRitten() {
return this.ritten;
}
public ArrayList<String> getHalteNamen(){
ArrayList<String> halteNamen = new ArrayList<String>();
for (Halte i : haltes){
halteNamen.add(i.getNaam());
}
return halteNamen;
}
/**
* Haal de ritten op die bij deze lijn horen.
*
* @return Een lijst van ritten die bij deze lijn horen
*/
public ArrayList<Halte> getHaltes(){
return haltes;
}
/**
* Voeg een rit toe aan de lijn.
*
* @param rit De toe te voegen rit. Deze rit mag bij deze lijn nog niet
* bestaan, en de rit mag ook niet bij een andere lijn horen.
* @return true als de rit is toegevoegd, anders false
*/
public boolean addRit(Rit rit) {
for(Rit r : ritten)
{
if(r.getLijn().getId().equals(rit.getLijn().getId()) && r.getVerwachteAankomstTijd() == rit.getVerwachteAankomstTijd()) {
return false;
}
}
if(rit.getLijn() != null && !rit.getLijn().getId().equals(this.id)){
return false;
}
this.ritten.add(rit);
return true;
}
/**
* Vraag het lijnnummer op
*
* @return Het lijnnummer van deze lijn
*/
public int getNummer() {
return nummer;
}
public String getId() {
return this.id;
}
/**
* Vraag de richting op van de lijn (heen of terug)
*
* @return De richting van de lijn
*/
public Richting getRichting() {
return richting;
}
/**
* Vraag de beschrijvin van de lijn op
*
* @return De lijnbeschrijving
*/
public String getBeschrijving() {
return beschrijving;
}
/**
* leeg de lijst van ritten
*/
public void clearRitten(){
this.ritten.clear();
}
}
| maartenpeels/Bus-Tracker | src/com/busenzo/domein/Lijn.java | 1,209 | /**
* Haal de ritten op die bij deze lijn horen.
*
* @return Een lijst van ritten die bij deze lijn horen
*/ | block_comment | nl | package com.busenzo.domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Lijn {
private final String id;
private final int nummer;
private final Richting richting;
private final String beschrijving;
private ArrayList<Rit> ritten;
private ArrayList<Halte> haltes;
/**
* Maak een nieuwe lijn aan. Er mag nog geen lijn bestaan met hetzelfde
* nummer, richting en beschrijving.
*
* @param id: LijnID geleverd door ov database
* @param nummer: Het lijnnummer
* @param richting: De richting van de lijn
* @param beschrijving Beschrijving van de lijn.
*/
public Lijn(String id, int nummer, Richting richting, String beschrijving) {
this.id = id;
this.nummer = nummer;
this.richting = richting;
this.beschrijving = beschrijving;
this.haltes = new ArrayList<>();
this.ritten = new ArrayList<>();
}
/**
* Voeg een halte toe aan deze lijn
*
* @param halte: De toe te voegen halte, deze halte mag bij deze lijn nog
* niet bestaan.
* @return true als de halte succesvol is toegevoegd, anders false
*/
public boolean addHalte(Halte halte) {
for (Halte h : haltes) {
if (h.getId().equals(halte.getId())) {
return false;
}
}
this.haltes.add(halte);
return true;
}
/**
* Voeg een lijst van haltes toe aan deze lijn
*
* @param haltes: Een lijst van de toe te voegen haltes, iedere individuele
* halte mag bij deze lijn nog niet bestaan
* @return true als de halte is toegevoegd, anders false
*/
public boolean addHaltes(Halte[] haltes) {
for (Halte h1 : this.haltes) {
for (Halte h2 : haltes) {
if (h1.getId().equals(h2.getId())) {
return false;
}
}
}
this.haltes.addAll(Arrays.asList(haltes));
return true;
}
/**
* Haal de ritten<SUF>*/
public List<Rit> getRitten() {
return this.ritten;
}
public ArrayList<String> getHalteNamen(){
ArrayList<String> halteNamen = new ArrayList<String>();
for (Halte i : haltes){
halteNamen.add(i.getNaam());
}
return halteNamen;
}
/**
* Haal de ritten op die bij deze lijn horen.
*
* @return Een lijst van ritten die bij deze lijn horen
*/
public ArrayList<Halte> getHaltes(){
return haltes;
}
/**
* Voeg een rit toe aan de lijn.
*
* @param rit De toe te voegen rit. Deze rit mag bij deze lijn nog niet
* bestaan, en de rit mag ook niet bij een andere lijn horen.
* @return true als de rit is toegevoegd, anders false
*/
public boolean addRit(Rit rit) {
for(Rit r : ritten)
{
if(r.getLijn().getId().equals(rit.getLijn().getId()) && r.getVerwachteAankomstTijd() == rit.getVerwachteAankomstTijd()) {
return false;
}
}
if(rit.getLijn() != null && !rit.getLijn().getId().equals(this.id)){
return false;
}
this.ritten.add(rit);
return true;
}
/**
* Vraag het lijnnummer op
*
* @return Het lijnnummer van deze lijn
*/
public int getNummer() {
return nummer;
}
public String getId() {
return this.id;
}
/**
* Vraag de richting op van de lijn (heen of terug)
*
* @return De richting van de lijn
*/
public Richting getRichting() {
return richting;
}
/**
* Vraag de beschrijvin van de lijn op
*
* @return De lijnbeschrijving
*/
public String getBeschrijving() {
return beschrijving;
}
/**
* leeg de lijst van ritten
*/
public void clearRitten(){
this.ritten.clear();
}
}
|
112208_3 | package Project1;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class BookApp {
public static void main(String[] args) {
Person person = new Person();//maak en person objecten
//maak een list van person objecten
List<Person> authors = new ArrayList<>();
System.out.println("De naam van authors is :");
authors.add(new Person("Kathryn","Stockett" , LocalDate.of(1969,10,15)));
authors.add(new Person("Sara", "Gruen", LocalDate.of(1962, 8, 17)));
authors.add(new Person("Markus", "Zusak", LocalDate.of(1939, 9, 7)));
authors.add(new Person("Arthur", "Golden", LocalDate.of(1939, 6, 20)));
authors.add(new Person("Yann", "Martel", LocalDate.of(1977, 4, 14)));
for (Person author : authors)
System.out.println(author.getFirstName()+" "+author.getLastName());
System.out.println("***************************");
// Maak een array van Book objecten
Book[] books = new Book[5];
books[0] = new Book("The Help",authors.get(0), LocalDate.of(2009, 2, 10), "Classic");
books[1] = new Book("Water for Elphants", authors.get(1), LocalDate.of(2006,5, 22), "Historical");
books[2] = new Book("The Book Thief", authors.get(2), LocalDate.of(2016, 3, 1), "World War");
books[3] = new Book("Memories of a Geisha", authors.get(3), LocalDate.of(2005, 11, 22), "Asia");
books[4] = new Book("Life of Pi", authors.get(4), LocalDate.of(2001, 9, 11), "Literature");
for (Book book : books){
System.out.println(book.getTitle() + book.getAuthor().firstName +" by "+ book.getAuthor().getLastName()
+" date of publish :"+book.getReleaseDate() +" /genre :"+ book.getGenre());
}
System.out.println("***********************");
//de methoden aanroepen
Book newesteBook = BookInfo.getNewesteBook(books);//moet een object maken omdat niet static is
System.out.println("het nieuweste book is: "+newesteBook.getTitle()+person.getFirstName()+newesteBook.getReleaseDate());
System.out.println("*********************");
BookInfo.printyoungestWriter(books);
//System.out.println("youngest writer"+newesteBook.author);
System.out.println("**********************");
BookInfo.printSortedByTitle(books);
System.out.println("boeken sorted by title");
System.out.println("**********************");
BookInfo.countBooksPerAuthor(books);
//System.out.println("count book per author");
System.out.println("**********************");
System.out.println("print since 2016:");
BookInfo.printBooksReleasedIn2016(books);
}
}
| JananJavdan/Java-Fundamentals | Chapter11_Streams/src/Project1/BookApp.java | 845 | //de methoden aanroepen
| line_comment | nl | package Project1;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class BookApp {
public static void main(String[] args) {
Person person = new Person();//maak en person objecten
//maak een list van person objecten
List<Person> authors = new ArrayList<>();
System.out.println("De naam van authors is :");
authors.add(new Person("Kathryn","Stockett" , LocalDate.of(1969,10,15)));
authors.add(new Person("Sara", "Gruen", LocalDate.of(1962, 8, 17)));
authors.add(new Person("Markus", "Zusak", LocalDate.of(1939, 9, 7)));
authors.add(new Person("Arthur", "Golden", LocalDate.of(1939, 6, 20)));
authors.add(new Person("Yann", "Martel", LocalDate.of(1977, 4, 14)));
for (Person author : authors)
System.out.println(author.getFirstName()+" "+author.getLastName());
System.out.println("***************************");
// Maak een array van Book objecten
Book[] books = new Book[5];
books[0] = new Book("The Help",authors.get(0), LocalDate.of(2009, 2, 10), "Classic");
books[1] = new Book("Water for Elphants", authors.get(1), LocalDate.of(2006,5, 22), "Historical");
books[2] = new Book("The Book Thief", authors.get(2), LocalDate.of(2016, 3, 1), "World War");
books[3] = new Book("Memories of a Geisha", authors.get(3), LocalDate.of(2005, 11, 22), "Asia");
books[4] = new Book("Life of Pi", authors.get(4), LocalDate.of(2001, 9, 11), "Literature");
for (Book book : books){
System.out.println(book.getTitle() + book.getAuthor().firstName +" by "+ book.getAuthor().getLastName()
+" date of publish :"+book.getReleaseDate() +" /genre :"+ book.getGenre());
}
System.out.println("***********************");
//de methoden<SUF>
Book newesteBook = BookInfo.getNewesteBook(books);//moet een object maken omdat niet static is
System.out.println("het nieuweste book is: "+newesteBook.getTitle()+person.getFirstName()+newesteBook.getReleaseDate());
System.out.println("*********************");
BookInfo.printyoungestWriter(books);
//System.out.println("youngest writer"+newesteBook.author);
System.out.println("**********************");
BookInfo.printSortedByTitle(books);
System.out.println("boeken sorted by title");
System.out.println("**********************");
BookInfo.countBooksPerAuthor(books);
//System.out.println("count book per author");
System.out.println("**********************");
System.out.println("print since 2016:");
BookInfo.printBooksReleasedIn2016(books);
}
}
|
167477_3 | package ai.minimax;
import ai.AI;
import game.*;
/**
* Created with IntelliJ IDEA.<br/>
* User: Carlo<br/>
* Date: 17/10/2015<br/>
* Time: 12:39<br/>
*/
public class Minimax implements AI {
private final int maxTreeDepth;
private final char aiPlayer;
private final char opponent;
private TicTacToeNode latestNode;
public Minimax(char aiPlayer, char opponent, int maxTreeDepth) {
this.aiPlayer = aiPlayer;
this.opponent = opponent;
this.maxTreeDepth = maxTreeDepth;
}
@Override
public int move(Board board) {
TicTacToeNode node = new TicTacToeNode(board, opponent, aiPlayer);
minimaxWithAlphaBetaPruning(node, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true, 0);
latestNode = node;
TicTacToeNode chosenNode = node;
while (chosenNode != null) {
chosenNode.setChosen();
chosenNode = chosenNode.getBestNode();
}
return Board.boardsToMove(board.getBoardArray(), node.getBestNode().getBoard().getBoardArray());
}
private double minimaxWithAlphaBetaPruning(TicTacToeNode node, double alpha, double beta, boolean maximizing, int depth) {
Board board = node.getBoard();
double bestScore;
TicTacToeNode bestNode = null;
//Stop searching
if (depth == maxTreeDepth || WinChecker.FIND_WINNER((node.getBoard())).getState() != States.NORMAL) {
bestScore = node.heuristicDriverScore() / depth;
if (maximizing) bestScore = -bestScore;
} else {
//MAX
if (maximizing) {
bestScore = alpha;
for (int pos = 0; pos < board.getBoardSize(); pos++) {
if (board.isFree(pos)) {
//Child maken
TicTacToeNode childNode = new TicTacToeNode(board, node.getOpponentPlayer(), node.getCurrentPlayer());
childNode.getBoard().setPlayer(pos, childNode.getCurrentPlayer());
node.add(childNode);
//Berekening doen
double childScore = minimaxWithAlphaBetaPruning(childNode, bestScore, beta, false, depth + 1);
if (childScore > bestScore) {
//Vervang bestNode door childNode als deze een hoger score teruggeeft
bestScore = childScore;
bestNode = childNode;
}
//Stoppen indien score hoger is als beta
if (bestScore >= beta) return bestScore;
}
}
}
//MIN
else {
bestScore = beta;
for (int pos = 0; pos < board.getBoardSize(); pos++) {
if (board.isFree(pos)) {
//child maken
TicTacToeNode childNode = new TicTacToeNode(board, node.getOpponentPlayer(), node.getCurrentPlayer());
childNode.getBoard().setPlayer(pos, childNode.getCurrentPlayer());
node.add(childNode);
//Berekening doen
double childScore = minimaxWithAlphaBetaPruning(childNode, alpha, bestScore, true, depth + 1);
if (childScore < bestScore) {
//Vervang bestNode door childNode als deze een lager score teruggeeft
bestScore = childScore;
bestNode = childNode;
}
}
//Stoppen indien score lager is als alfa
if (bestScore <= alpha) return bestScore;
}
}
}
node.setBestNode(bestNode);
node.setScore(bestScore);
return bestScore;
}
public TicTacToeNode getLatestNode() {
return latestNode;
}
public char getAiPlayer() {
return aiPlayer;
}
}
| carlo-nomes/TicTacToe | src/AI/minimax/Minimax.java | 946 | //Vervang bestNode door childNode als deze een lager score teruggeeft | line_comment | nl | package ai.minimax;
import ai.AI;
import game.*;
/**
* Created with IntelliJ IDEA.<br/>
* User: Carlo<br/>
* Date: 17/10/2015<br/>
* Time: 12:39<br/>
*/
public class Minimax implements AI {
private final int maxTreeDepth;
private final char aiPlayer;
private final char opponent;
private TicTacToeNode latestNode;
public Minimax(char aiPlayer, char opponent, int maxTreeDepth) {
this.aiPlayer = aiPlayer;
this.opponent = opponent;
this.maxTreeDepth = maxTreeDepth;
}
@Override
public int move(Board board) {
TicTacToeNode node = new TicTacToeNode(board, opponent, aiPlayer);
minimaxWithAlphaBetaPruning(node, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true, 0);
latestNode = node;
TicTacToeNode chosenNode = node;
while (chosenNode != null) {
chosenNode.setChosen();
chosenNode = chosenNode.getBestNode();
}
return Board.boardsToMove(board.getBoardArray(), node.getBestNode().getBoard().getBoardArray());
}
private double minimaxWithAlphaBetaPruning(TicTacToeNode node, double alpha, double beta, boolean maximizing, int depth) {
Board board = node.getBoard();
double bestScore;
TicTacToeNode bestNode = null;
//Stop searching
if (depth == maxTreeDepth || WinChecker.FIND_WINNER((node.getBoard())).getState() != States.NORMAL) {
bestScore = node.heuristicDriverScore() / depth;
if (maximizing) bestScore = -bestScore;
} else {
//MAX
if (maximizing) {
bestScore = alpha;
for (int pos = 0; pos < board.getBoardSize(); pos++) {
if (board.isFree(pos)) {
//Child maken
TicTacToeNode childNode = new TicTacToeNode(board, node.getOpponentPlayer(), node.getCurrentPlayer());
childNode.getBoard().setPlayer(pos, childNode.getCurrentPlayer());
node.add(childNode);
//Berekening doen
double childScore = minimaxWithAlphaBetaPruning(childNode, bestScore, beta, false, depth + 1);
if (childScore > bestScore) {
//Vervang bestNode door childNode als deze een hoger score teruggeeft
bestScore = childScore;
bestNode = childNode;
}
//Stoppen indien score hoger is als beta
if (bestScore >= beta) return bestScore;
}
}
}
//MIN
else {
bestScore = beta;
for (int pos = 0; pos < board.getBoardSize(); pos++) {
if (board.isFree(pos)) {
//child maken
TicTacToeNode childNode = new TicTacToeNode(board, node.getOpponentPlayer(), node.getCurrentPlayer());
childNode.getBoard().setPlayer(pos, childNode.getCurrentPlayer());
node.add(childNode);
//Berekening doen
double childScore = minimaxWithAlphaBetaPruning(childNode, alpha, bestScore, true, depth + 1);
if (childScore < bestScore) {
//Vervang bestNode<SUF>
bestScore = childScore;
bestNode = childNode;
}
}
//Stoppen indien score lager is als alfa
if (bestScore <= alpha) return bestScore;
}
}
}
node.setBestNode(bestNode);
node.setScore(bestScore);
return bestScore;
}
public TicTacToeNode getLatestNode() {
return latestNode;
}
public char getAiPlayer() {
return aiPlayer;
}
}
|
25231_40 | package nl.hu.bep2.casino.blackjack.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.lang.Collections;
import nl.hu.bep2.casino.blackjack.data.GameRepository;
import nl.hu.bep2.casino.blackjack.domain.Card;
import nl.hu.bep2.casino.blackjack.domain.Game;
import nl.hu.bep2.casino.blackjack.domain.GameState;
import nl.hu.bep2.casino.blackjack.domain.Kleur;
import nl.hu.bep2.casino.blackjack.domain.Move;
import nl.hu.bep2.casino.blackjack.domain.MoveChecker;
import nl.hu.bep2.casino.blackjack.domain.Player;
import nl.hu.bep2.casino.blackjack.domain.Waarde;
import nl.hu.bep2.casino.chips.application.Balance;
import nl.hu.bep2.casino.chips.application.ChipsService;
import nl.hu.bep2.casino.chips.data.ChipsRepository;
import nl.hu.bep2.casino.chips.domain.Chips;
import nl.hu.bep2.casino.security.data.UserRepository;
import nl.hu.bep2.casino.security.domain.User;
@Service
public class BlackJackService {
@Autowired
private GameRepository gameRepository;
@Autowired
private ChipsRepository chipsRepository;
@Autowired
private ChipsService chipsService;
@Autowired
private UserRepository userRepository;
//USER BEDENKT SPELERSNAAM, GEEFT AAN MET HOEVEEL DECKS ZE WIL SPELEN EN DOET EEN EERSTE INZET
//ER WORDT DAN SPELER-INSTANTIE AANGEMAAKT, DIE 1OO CHIPS KRIJGT ALS START EN ER WORDT EEN GAME AANGEMAAKT, MET AUTOMATISCH EEN SET GAMECARDS EN EEN DEALERHAND
//SPELER KRIJGT INFORMATIE TERUG:
// HET OBJECT SPELER TERUG WAARIN DE CHIPS EN KAARTEN-OP-DE-HAND ZIJN OPGENOMEN
// EEN KAART VAN DE DEALER (EN EEN TWEEDE GESLOTEN KAART, HANDIG VOOR DE FRONTEND OM TE WETEN DAT ER EEN LEGE KAART GTETEKEND MOET WORDEN)
public BlackJackService() {
}
public List<Object> start(String username,int numberOfDecks, long inzet){
Chips chips = chipsRepository.findByUsername(username).orElse(null);
User user = userRepository.findByUsername(username).orElse(null);
List<Object> gameInfo = new ArrayList<>();
List<Card> dealerCards = new ArrayList<>();
Game game= new Game(user, numberOfDecks, inzet);
chips.withdraw(inzet); // bet plaatsen
game.start() ; // kaarten delen aan speler en dealer
//berekenen wat de stand van zaken is
//we starten de game dus de eerste Move is een bet, die is al ingevuld, eerste inzet was al bekend gemaakt bij creatie van gameobject
// inzet is opgeslagen in een game zodat die ook bewaard is in de databse.
try {
game.setGameState( MoveChecker.checkAndHandleMove(Move.bet,game));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// nu moeten we kijken welke kaarten de speler te zien krijgt, als
//als de speler 21 heeft en de dealer ook eindigt het spel (push)
//als de speler 21 heeft en de dealer niet (blackjack)
// mag de speler toch ook nog even de dealerkaarten zien.
if (game.getGameState() == GameState.push){
dealerCards = game.getDealer().getKaartenOpHand();
chips.deposit(inzet); //speler krijgt inleg terug
}
else if( game.getGameState() == GameState.blackjack) {
dealerCards = game.getDealer().getKaartenOpHand();
chips.deposit((long)(2.5*inzet)); //speler krijgt inzet terug + 1,5 inzet winst totaal 2,5
}
else {
Card blindeKaart = new Card(Kleur.achterkant,Waarde.achterkant);
dealerCards.add(game.getDealer().getFirstDealerCard());
dealerCards.add(blindeKaart);
}
// de hele ronde is nu afgehandeld, speler is betaald, nieuwe game wordt opgeslagen
this.gameRepository.save(game);
// nu heeft de server alles uitgerekend, nu nog aan de gebruiker laten weten wat er gebeurd is.
// we sturen
// - de kaarten op tafel van speler en van de dealer,
// - de inzet(hoewel de speler dat zelf heeft opgegeven)
// - de nieuwe balance
// - de gamestate, ter verklaring van de nieuwe balans
Balance balance = chipsService.findBalance(username);
gameInfo.add(game.getId()); // kaarten op hand speler
gameInfo.add(game.getPlayer().getKaartenOpHand()); // kaarten op hand speler
gameInfo.add(dealerCards); //dealer kaarten een open en een dichte kaart, tenzij spel al is afgelopen
gameInfo.add(game.getInzet());// wat ahd de speler ingezet
gameInfo.add(game.getGameState());//nodig om volgende moves te bepalen
gameInfo.add(balance.getChips()); // chips, naam van de speler, laate maal geupdated, en huidge aantal chips
return gameInfo;
}
public List<Object> makeMove(long gameId,Move move, long inzet){
System.out.println("nu gaan we de game opsnorren");
Game game = this.gameRepository.getGameById(gameId);
if ( game==null) {
throw new IllegalArgumentException("Er is geen game gevonden met deze id: " + gameId);
}
//System.out.println("de dealer is"+ game.getDealer());
String username=null;
try {
username = game.getPlayer().getUser().getUsername();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Chips chips = chipsRepository.findByUsername(username).orElse(null);
List<Object> gameInfo = new ArrayList<>();
List<Card> dealerCards = new ArrayList<>();
//check of een geldige move is gekozen, zo ja, voer uit en retrun de nieuwe gamestate
if (MoveChecker.showMoves(game.getGameState()).contains(move)) {
try {
game.setGameState( MoveChecker.checkAndHandleMove(move,game) );
if (move == Move.doubleDown) {
chips.withdraw(inzet); // bij doubldedown nog een keer de inzet innen
}
else if (move == Move.surrender) {
chips.deposit((long) Math.round(inzet/2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (game.getGameState() == GameState.blackjack){
chips.deposit((long)(1.5*inzet)); //speler krijgt 1,5 x inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.won) {
chips.deposit((long)(2*inzet)); //speler krijgt 2x inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.lost) {
//speler krijgt niks terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.push) {
chips.deposit((long)(inzet)); //speler krijgt inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.bust) {
dealerCards = game.getDealer().getKaartenOpHand(); //speler krijgt geen chips, maar mag wel de dealercards zien
}
else if (game.getGameState() == GameState.playing) {
dealerCards.add(game.getDealer().getFirstDealerCard()); // als nog steeds gewoon playing krijgen we de dealerkaarten nog niet allebei te zien
Card blindeKaart = new Card(Kleur.achterkant,Waarde.achterkant);
dealerCards.add(blindeKaart);
}
Balance balance = chipsService.findBalance(username);
gameInfo.add(game.getPlayer().getKaartenOpHand()); // kaarten op hand speler
gameInfo.add(dealerCards); //dealer kaarten een open en een dichte kaart
gameInfo.add(game.getInzet());// wat ahd de speler ingezet
gameInfo.add(game.getGameState());//nodig om volgende moves te bepalen
gameInfo.add(balance.getChips()); // chips, naam van de speler, laate maal geupdated, en huidge aantal chips
return gameInfo;
}
}
| spook1/U_b2G_maven | src/main/java/nl/hu/bep2/casino/blackjack/application/BlackJackService.java | 2,407 | // kaarten op hand speler | line_comment | nl | package nl.hu.bep2.casino.blackjack.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.lang.Collections;
import nl.hu.bep2.casino.blackjack.data.GameRepository;
import nl.hu.bep2.casino.blackjack.domain.Card;
import nl.hu.bep2.casino.blackjack.domain.Game;
import nl.hu.bep2.casino.blackjack.domain.GameState;
import nl.hu.bep2.casino.blackjack.domain.Kleur;
import nl.hu.bep2.casino.blackjack.domain.Move;
import nl.hu.bep2.casino.blackjack.domain.MoveChecker;
import nl.hu.bep2.casino.blackjack.domain.Player;
import nl.hu.bep2.casino.blackjack.domain.Waarde;
import nl.hu.bep2.casino.chips.application.Balance;
import nl.hu.bep2.casino.chips.application.ChipsService;
import nl.hu.bep2.casino.chips.data.ChipsRepository;
import nl.hu.bep2.casino.chips.domain.Chips;
import nl.hu.bep2.casino.security.data.UserRepository;
import nl.hu.bep2.casino.security.domain.User;
@Service
public class BlackJackService {
@Autowired
private GameRepository gameRepository;
@Autowired
private ChipsRepository chipsRepository;
@Autowired
private ChipsService chipsService;
@Autowired
private UserRepository userRepository;
//USER BEDENKT SPELERSNAAM, GEEFT AAN MET HOEVEEL DECKS ZE WIL SPELEN EN DOET EEN EERSTE INZET
//ER WORDT DAN SPELER-INSTANTIE AANGEMAAKT, DIE 1OO CHIPS KRIJGT ALS START EN ER WORDT EEN GAME AANGEMAAKT, MET AUTOMATISCH EEN SET GAMECARDS EN EEN DEALERHAND
//SPELER KRIJGT INFORMATIE TERUG:
// HET OBJECT SPELER TERUG WAARIN DE CHIPS EN KAARTEN-OP-DE-HAND ZIJN OPGENOMEN
// EEN KAART VAN DE DEALER (EN EEN TWEEDE GESLOTEN KAART, HANDIG VOOR DE FRONTEND OM TE WETEN DAT ER EEN LEGE KAART GTETEKEND MOET WORDEN)
public BlackJackService() {
}
public List<Object> start(String username,int numberOfDecks, long inzet){
Chips chips = chipsRepository.findByUsername(username).orElse(null);
User user = userRepository.findByUsername(username).orElse(null);
List<Object> gameInfo = new ArrayList<>();
List<Card> dealerCards = new ArrayList<>();
Game game= new Game(user, numberOfDecks, inzet);
chips.withdraw(inzet); // bet plaatsen
game.start() ; // kaarten delen aan speler en dealer
//berekenen wat de stand van zaken is
//we starten de game dus de eerste Move is een bet, die is al ingevuld, eerste inzet was al bekend gemaakt bij creatie van gameobject
// inzet is opgeslagen in een game zodat die ook bewaard is in de databse.
try {
game.setGameState( MoveChecker.checkAndHandleMove(Move.bet,game));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// nu moeten we kijken welke kaarten de speler te zien krijgt, als
//als de speler 21 heeft en de dealer ook eindigt het spel (push)
//als de speler 21 heeft en de dealer niet (blackjack)
// mag de speler toch ook nog even de dealerkaarten zien.
if (game.getGameState() == GameState.push){
dealerCards = game.getDealer().getKaartenOpHand();
chips.deposit(inzet); //speler krijgt inleg terug
}
else if( game.getGameState() == GameState.blackjack) {
dealerCards = game.getDealer().getKaartenOpHand();
chips.deposit((long)(2.5*inzet)); //speler krijgt inzet terug + 1,5 inzet winst totaal 2,5
}
else {
Card blindeKaart = new Card(Kleur.achterkant,Waarde.achterkant);
dealerCards.add(game.getDealer().getFirstDealerCard());
dealerCards.add(blindeKaart);
}
// de hele ronde is nu afgehandeld, speler is betaald, nieuwe game wordt opgeslagen
this.gameRepository.save(game);
// nu heeft de server alles uitgerekend, nu nog aan de gebruiker laten weten wat er gebeurd is.
// we sturen
// - de kaarten op tafel van speler en van de dealer,
// - de inzet(hoewel de speler dat zelf heeft opgegeven)
// - de nieuwe balance
// - de gamestate, ter verklaring van de nieuwe balans
Balance balance = chipsService.findBalance(username);
gameInfo.add(game.getId()); // kaarten op hand speler
gameInfo.add(game.getPlayer().getKaartenOpHand()); // kaarten op hand speler
gameInfo.add(dealerCards); //dealer kaarten een open en een dichte kaart, tenzij spel al is afgelopen
gameInfo.add(game.getInzet());// wat ahd de speler ingezet
gameInfo.add(game.getGameState());//nodig om volgende moves te bepalen
gameInfo.add(balance.getChips()); // chips, naam van de speler, laate maal geupdated, en huidge aantal chips
return gameInfo;
}
public List<Object> makeMove(long gameId,Move move, long inzet){
System.out.println("nu gaan we de game opsnorren");
Game game = this.gameRepository.getGameById(gameId);
if ( game==null) {
throw new IllegalArgumentException("Er is geen game gevonden met deze id: " + gameId);
}
//System.out.println("de dealer is"+ game.getDealer());
String username=null;
try {
username = game.getPlayer().getUser().getUsername();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Chips chips = chipsRepository.findByUsername(username).orElse(null);
List<Object> gameInfo = new ArrayList<>();
List<Card> dealerCards = new ArrayList<>();
//check of een geldige move is gekozen, zo ja, voer uit en retrun de nieuwe gamestate
if (MoveChecker.showMoves(game.getGameState()).contains(move)) {
try {
game.setGameState( MoveChecker.checkAndHandleMove(move,game) );
if (move == Move.doubleDown) {
chips.withdraw(inzet); // bij doubldedown nog een keer de inzet innen
}
else if (move == Move.surrender) {
chips.deposit((long) Math.round(inzet/2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (game.getGameState() == GameState.blackjack){
chips.deposit((long)(1.5*inzet)); //speler krijgt 1,5 x inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.won) {
chips.deposit((long)(2*inzet)); //speler krijgt 2x inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.lost) {
//speler krijgt niks terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.push) {
chips.deposit((long)(inzet)); //speler krijgt inzet terug
dealerCards = game.getDealer().getKaartenOpHand();
}
else if (game.getGameState() == GameState.bust) {
dealerCards = game.getDealer().getKaartenOpHand(); //speler krijgt geen chips, maar mag wel de dealercards zien
}
else if (game.getGameState() == GameState.playing) {
dealerCards.add(game.getDealer().getFirstDealerCard()); // als nog steeds gewoon playing krijgen we de dealerkaarten nog niet allebei te zien
Card blindeKaart = new Card(Kleur.achterkant,Waarde.achterkant);
dealerCards.add(blindeKaart);
}
Balance balance = chipsService.findBalance(username);
gameInfo.add(game.getPlayer().getKaartenOpHand()); // kaarten op<SUF>
gameInfo.add(dealerCards); //dealer kaarten een open en een dichte kaart
gameInfo.add(game.getInzet());// wat ahd de speler ingezet
gameInfo.add(game.getGameState());//nodig om volgende moves te bepalen
gameInfo.add(balance.getChips()); // chips, naam van de speler, laate maal geupdated, en huidge aantal chips
return gameInfo;
}
}
|
43962_1 | package be.kuleuven.pccustomizer.controller;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BeheerAttachesController {
@FXML
private TableView tblTips;
public void initialize() {
initTable();
tblTips.setOnMouseClicked(e -> {
if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) {
var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem();
runResource(selectedRow.get(2));
}
});
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
}
private boolean isMac() {
return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0;
}
private void runResource(String resource) {
try {
// TODO dit moet niet van de resource list komen maar van een DB.
var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes();
var path = Paths.get("out-" + resource);
Files.write(path, data);
Thread.sleep(1000);
var process = new ProcessBuilder();
if(isWindows()) {
process.command("cmd.exe", "/c", "start " + path.toRealPath().toString());
} else if(isMac()) {
process.command("open", path.toRealPath().toString());
} else {
throw new RuntimeException("Ik ken uw OS niet jong");
}
process.start();
} catch (Exception e) {
throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e);
}
}
private void initTable() {
tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tblTips.getColumns().clear();
// TODO zijn dit de juiste kolommen?
int colIndex = 0;
for(var colName : new String[]{"Attach beschrijving", "Grootte in KB", "Handle"}) {
TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName);
final int finalColIndex = colIndex;
col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex)));
tblTips.getColumns().add(col);
colIndex++;
}
// TODO verwijderen en "echte data" toevoegen!
tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te gamen", "240", "attach-dubbelklik-op-mij.mp3"));
}
}
| KULeuven-Diepenbeek/db-course | examples/java/project-template-202122/src/main/java/be/kuleuven/pccustomizer/controller/BeheerAttachesController.java | 720 | // TODO zijn dit de juiste kolommen? | line_comment | nl | package be.kuleuven.pccustomizer.controller;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BeheerAttachesController {
@FXML
private TableView tblTips;
public void initialize() {
initTable();
tblTips.setOnMouseClicked(e -> {
if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) {
var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem();
runResource(selectedRow.get(2));
}
});
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
}
private boolean isMac() {
return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0;
}
private void runResource(String resource) {
try {
// TODO dit moet niet van de resource list komen maar van een DB.
var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes();
var path = Paths.get("out-" + resource);
Files.write(path, data);
Thread.sleep(1000);
var process = new ProcessBuilder();
if(isWindows()) {
process.command("cmd.exe", "/c", "start " + path.toRealPath().toString());
} else if(isMac()) {
process.command("open", path.toRealPath().toString());
} else {
throw new RuntimeException("Ik ken uw OS niet jong");
}
process.start();
} catch (Exception e) {
throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e);
}
}
private void initTable() {
tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tblTips.getColumns().clear();
// TODO zijn<SUF>
int colIndex = 0;
for(var colName : new String[]{"Attach beschrijving", "Grootte in KB", "Handle"}) {
TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName);
final int finalColIndex = colIndex;
col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex)));
tblTips.getColumns().add(col);
colIndex++;
}
// TODO verwijderen en "echte data" toevoegen!
tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te gamen", "240", "attach-dubbelklik-op-mij.mp3"));
}
}
|
26086_2 | package singleton;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
/*
De klassen in deze package demonstreren de werking van het Singleton-pattern:
- https://en.wikipedia.org/wiki/Singleton_pattern
Omdat je door gebruik te maken van de een private constructor het aanmaken van objecten
delegeert aan de klasse zelf, kun je ook andere spannende dingen hiermee doen. Zie hiervoor
het commentaar in de klassen StaticFactoryMethodDemo1 en StaticFactoryMethodDemo2, en de
demo-methode hieronder.
*/
public class Demo {
public static void main(String[] args) {
demo2();
}
public static void demo1() {
// twee separate variabelen, maar toch verwijzen ze naar hetzelfde object.
Singleton foo = Singleton.getInstance();
Singleton bar = Singleton.getInstance();
System.out.println(foo.getString());
System.out.println(bar.getString());
System.out.println(bar==foo);
}
/*
Je kunt er op eenzelfde manier ook voor zorgen dat er maar een beperkt aantal objecten
van de klassen kan worden aangemaakt. Zo vragen we hieronder dertig keer dezelfde methode
op, maar de betreffende klasse is zo geprogrammeerd dat er maar tien instanties van het
ding aangemaak kunnen worden. Dus in plaats van de (wellicht) verwachte dertig elementen,
zitten er aan het eind van deze methode maar tien elementen in de HashSet (die verschillende
foo's geven na tien keer een String terug die al in de HashSet zit, en een HashSet kan geen
dubbele waarden bevatten).
*/
public static void demo2() {
Set<String> vals = new HashSet<>();
StaticFactoryMethodDemo2 foo;
for (int i=0; i<30; i++) {
foo = StaticFactoryMethodDemo2.getNextInstance();
vals.add(foo.getDemoString());
}
System.out.println("Aantal elementen in de lijst: " +vals.size());
System.out.println("Hier komen de waarden:");
vals.stream().forEach( v -> System.out.println(v));
}
public static String getRandomString() {
Random r = new Random();
String rv = "";
//loop for fill up 10 characters
for (int i = 0; i < 10; i++) {
char randomadd = (char) (r.nextInt(26) + 'A');
rv += randomadd;
}
return rv;
}
}
| bart314/OOP3 | week3/singleton/Demo.java | 634 | /*
Je kunt er op eenzelfde manier ook voor zorgen dat er maar een beperkt aantal objecten
van de klassen kan worden aangemaakt. Zo vragen we hieronder dertig keer dezelfde methode
op, maar de betreffende klasse is zo geprogrammeerd dat er maar tien instanties van het
ding aangemaak kunnen worden. Dus in plaats van de (wellicht) verwachte dertig elementen,
zitten er aan het eind van deze methode maar tien elementen in de HashSet (die verschillende
foo's geven na tien keer een String terug die al in de HashSet zit, en een HashSet kan geen
dubbele waarden bevatten).
*/ | block_comment | nl | package singleton;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
/*
De klassen in deze package demonstreren de werking van het Singleton-pattern:
- https://en.wikipedia.org/wiki/Singleton_pattern
Omdat je door gebruik te maken van de een private constructor het aanmaken van objecten
delegeert aan de klasse zelf, kun je ook andere spannende dingen hiermee doen. Zie hiervoor
het commentaar in de klassen StaticFactoryMethodDemo1 en StaticFactoryMethodDemo2, en de
demo-methode hieronder.
*/
public class Demo {
public static void main(String[] args) {
demo2();
}
public static void demo1() {
// twee separate variabelen, maar toch verwijzen ze naar hetzelfde object.
Singleton foo = Singleton.getInstance();
Singleton bar = Singleton.getInstance();
System.out.println(foo.getString());
System.out.println(bar.getString());
System.out.println(bar==foo);
}
/*
Je kunt er<SUF>*/
public static void demo2() {
Set<String> vals = new HashSet<>();
StaticFactoryMethodDemo2 foo;
for (int i=0; i<30; i++) {
foo = StaticFactoryMethodDemo2.getNextInstance();
vals.add(foo.getDemoString());
}
System.out.println("Aantal elementen in de lijst: " +vals.size());
System.out.println("Hier komen de waarden:");
vals.stream().forEach( v -> System.out.println(v));
}
public static String getRandomString() {
Random r = new Random();
String rv = "";
//loop for fill up 10 characters
for (int i = 0; i < 10; i++) {
char randomadd = (char) (r.nextInt(26) + 'A');
rv += randomadd;
}
return rv;
}
}
|
16787_19 | package model;
import java.text.ParseException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
private ArrayList<Les> deLessen;
private ArrayList<Vak> deVakken;
private ArrayList<Presentie> dePresenties;
//TODO: Deze commentaar voorzien van actueel commentaar...
/**
* De constructor maakt een set met standaard-data aan. Deze data
* moet nog vervangen worden door gegevens die uit een bestand worden
* ingelezen, maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent en Student. Uiteraard kan dit nog veel
* verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op
* dit moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord)
* Docent getDocent(String gebruikersnaam)
* Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen,
* dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>();
deLessen = new ArrayList<Les>();
deVakken = new ArrayList<Vak>();
deVakken.add(new Vak("TCIF-V1AUI-15", "Analyse en User Interfaces"));
deVakken.add(new Vak("TICT-V1GP-15", "Group Project"));
deVakken.add(new Vak("TICT-V1OODC-15", "Object Oriented Design & Construction"));
dePresenties = new ArrayList<Presentie>();
init();
debug();
}
/**
* De initialisatie methode leest de .csv bestanden uit en maakt aan de hand van diens inhoud de nodige objecten aan.
*/
private void init() {
//
BufferedReader fileReader = null;
String currentLine = "";
// Code voor inlezen klassen.csv
try {
// Creëer de file reader
fileReader = new BufferedReader(new FileReader("data/klassen.csv"));
// Lees het bestand regel voor regel
while((currentLine = fileReader.readLine()) != null) {
// Haal alle tokens uit deze regel
String[] tokens = currentLine.split(",");
// Check of de klas al in deKlassen lijst staat
Klas deKlas = new Klas(tokens[4]);
if(deKlassen.contains(deKlas)) {
deKlas = deKlassen.get(deKlassen.indexOf(deKlas));
}
// Zo niet, voeg deze klas dan aan de lijst toe
else {
deKlassen.add(deKlas);
}
// Check of de student al in deStudenten lijst staat, zo niet, voeg deze dan toe
Student deStudent = new Student(tokens[0], "geheim");
deStudent.setStudentNummer(tokens[0]);
deStudent.setMijnKlas(deKlas);
deStudent.setVoornaam(tokens[3]);
deStudent.setTussenvoegsel(tokens[2]);
deStudent.setAchternaam(tokens[1]);
if(!deStudenten.contains(deStudent)) {
deStudenten.add(deStudent);
}
}
}
catch(Exception e) {
e.printStackTrace();
}
// Code voor inlezen rooster_C.csv
try {
// Creëer de file reader
fileReader = new BufferedReader(new FileReader("data/rooster_C.csv"));
// Lees het bestand regel voor regel
while((currentLine = fileReader.readLine()) != null) {
// Haal alle tokens uit deze regel
String[] tokens = currentLine.split(",");
// Check of het vak al in deVakken lijst staat
Vak hetVak = new Vak(tokens[3], "Cursusnaam onbekend");
if(deVakken.contains(hetVak)) {
hetVak = deVakken.get(deVakken.indexOf(hetVak));
}
// Zo niet, voeg dit vak dan aan de lijst toe
else {
deVakken.add(hetVak);
}
// Same voor de Docent
Docent deDocent = new Docent(tokens[4], "geheim");
if(deDocenten.contains(deDocent)) {
deDocent = deDocenten.get(deDocenten.indexOf(deDocent));
}
else {
deDocenten.add(deDocent);
}
deDocent.voegVakToe(hetVak);
// Same voor de Klas
Klas deKlas = new Klas(tokens[6].replace('_', '-'));
if(deKlassen.contains(deKlas)) {
deKlas = deKlassen.get(deKlassen.indexOf(deKlas));
}
else {
deKlassen.add(deKlas);
}
// Creëer de Les en voeg deze aan de lijst toe
Les deLes = new Les(tokens[0], tokens[1], tokens[2], hetVak, deDocent, tokens[5], deKlas);
deLessen.add(deLes);
// Creëer Presentie objecten voor deze les
for (Student deStudent : getStudentenVanKlas(deKlas.getKlasCode())) {
Presentie dePresentie = new Presentie(deStudent, deLes);
dePresenties.add(dePresentie);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
// Sluit de fileReader
finally {
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Een set for-loops puur bedoelt om te kunnen debuggen.
*/
private void debug() {
System.out.println("- Dit is de inhoud van de studentenlijst -");
for (Student deStudent : deStudenten) {
System.out.println(deStudent);
}
System.out.println("\n- Dit is de inhoud van de klassenlijst -");
for (Klas deKlas : deKlassen) {
System.out.println(deKlas.getKlasCode());
}
System.out.println("\n- Dit is de inhoud van de lessenlijst -");
for (Les deLes : deLessen) {
System.out.println(deLes.toString() + "\n");
}
System.out.println("\n- Dit zijn de lessen van Brian van Yperen op 2016-03-10 -");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
try {
d = dateFormat.parse("2016-03-10");
} catch (ParseException e) {
e.printStackTrace();
}
for (Les deLes : getDeLessenVanStudent(d, "1679084")) {
System.out.println(deLes.toString() + "\n");
}
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersNaam().equals(gebruikersnaam)) {
if (d.controleerWachtwoord(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersNaam().equals(gebruikersnaam)) {
if (s.controleerWachtwoord(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
public Docent getDocent(String gebruikersnaam) {
Docent resultaat = null;
for (Docent d : deDocenten) {
if (d.getGebruikersNaam().equals(gebruikersnaam)) {
resultaat = d;
break;
}
}
return resultaat;
}
public Student getStudent(String gebruikersnaam) {
Student resultaat = null;
for (Student s : deStudenten) {
if (s.getGebruikersNaam().equals(gebruikersnaam)) {
resultaat = s;
break;
}
}
return resultaat;
}
public ArrayList<Student> getStudentenVanKlas(String klasCode) {
ArrayList<Student> resultaat = new ArrayList<Student>();
for (Student s : deStudenten) {
if (s.getMijnKlas().getKlasCode().equals(klasCode)) {
resultaat.add(s);
}
}
return resultaat;
}
public ArrayList<Les> getDeLessenVanStudent(Date d, String nm) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ArrayList<Les> result = new ArrayList<Les>();
// Zoek de klas waarin de Student zich bevindt
Klas k = getStudent(nm).getMijnKlas();
// Vind alle lessen die beginnen op de meegegeven datum en gegeven worden aan de gevonden klas, en voeg deze toe aan de result lijst
for (Les l : deLessen) {
boolean drone = dateFormat.format(d).equals(dateFormat.format(l.getBeginTijd()));
drone = drone && l.getDeKlas().equals(k);
// If this is the drone we're looking for: add it to the list
if (drone) {
result.add(l);
}
}
return result;
}
}
| Gundraub/PrIS | src/model/PrIS.java | 2,667 | // Creëer Presentie objecten voor deze les
| line_comment | nl | package model;
import java.text.ParseException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
private ArrayList<Les> deLessen;
private ArrayList<Vak> deVakken;
private ArrayList<Presentie> dePresenties;
//TODO: Deze commentaar voorzien van actueel commentaar...
/**
* De constructor maakt een set met standaard-data aan. Deze data
* moet nog vervangen worden door gegevens die uit een bestand worden
* ingelezen, maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent en Student. Uiteraard kan dit nog veel
* verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op
* dit moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord)
* Docent getDocent(String gebruikersnaam)
* Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen,
* dat kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>();
deLessen = new ArrayList<Les>();
deVakken = new ArrayList<Vak>();
deVakken.add(new Vak("TCIF-V1AUI-15", "Analyse en User Interfaces"));
deVakken.add(new Vak("TICT-V1GP-15", "Group Project"));
deVakken.add(new Vak("TICT-V1OODC-15", "Object Oriented Design & Construction"));
dePresenties = new ArrayList<Presentie>();
init();
debug();
}
/**
* De initialisatie methode leest de .csv bestanden uit en maakt aan de hand van diens inhoud de nodige objecten aan.
*/
private void init() {
//
BufferedReader fileReader = null;
String currentLine = "";
// Code voor inlezen klassen.csv
try {
// Creëer de file reader
fileReader = new BufferedReader(new FileReader("data/klassen.csv"));
// Lees het bestand regel voor regel
while((currentLine = fileReader.readLine()) != null) {
// Haal alle tokens uit deze regel
String[] tokens = currentLine.split(",");
// Check of de klas al in deKlassen lijst staat
Klas deKlas = new Klas(tokens[4]);
if(deKlassen.contains(deKlas)) {
deKlas = deKlassen.get(deKlassen.indexOf(deKlas));
}
// Zo niet, voeg deze klas dan aan de lijst toe
else {
deKlassen.add(deKlas);
}
// Check of de student al in deStudenten lijst staat, zo niet, voeg deze dan toe
Student deStudent = new Student(tokens[0], "geheim");
deStudent.setStudentNummer(tokens[0]);
deStudent.setMijnKlas(deKlas);
deStudent.setVoornaam(tokens[3]);
deStudent.setTussenvoegsel(tokens[2]);
deStudent.setAchternaam(tokens[1]);
if(!deStudenten.contains(deStudent)) {
deStudenten.add(deStudent);
}
}
}
catch(Exception e) {
e.printStackTrace();
}
// Code voor inlezen rooster_C.csv
try {
// Creëer de file reader
fileReader = new BufferedReader(new FileReader("data/rooster_C.csv"));
// Lees het bestand regel voor regel
while((currentLine = fileReader.readLine()) != null) {
// Haal alle tokens uit deze regel
String[] tokens = currentLine.split(",");
// Check of het vak al in deVakken lijst staat
Vak hetVak = new Vak(tokens[3], "Cursusnaam onbekend");
if(deVakken.contains(hetVak)) {
hetVak = deVakken.get(deVakken.indexOf(hetVak));
}
// Zo niet, voeg dit vak dan aan de lijst toe
else {
deVakken.add(hetVak);
}
// Same voor de Docent
Docent deDocent = new Docent(tokens[4], "geheim");
if(deDocenten.contains(deDocent)) {
deDocent = deDocenten.get(deDocenten.indexOf(deDocent));
}
else {
deDocenten.add(deDocent);
}
deDocent.voegVakToe(hetVak);
// Same voor de Klas
Klas deKlas = new Klas(tokens[6].replace('_', '-'));
if(deKlassen.contains(deKlas)) {
deKlas = deKlassen.get(deKlassen.indexOf(deKlas));
}
else {
deKlassen.add(deKlas);
}
// Creëer de Les en voeg deze aan de lijst toe
Les deLes = new Les(tokens[0], tokens[1], tokens[2], hetVak, deDocent, tokens[5], deKlas);
deLessen.add(deLes);
// Creëer Presentie<SUF>
for (Student deStudent : getStudentenVanKlas(deKlas.getKlasCode())) {
Presentie dePresentie = new Presentie(deStudent, deLes);
dePresenties.add(dePresentie);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
// Sluit de fileReader
finally {
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Een set for-loops puur bedoelt om te kunnen debuggen.
*/
private void debug() {
System.out.println("- Dit is de inhoud van de studentenlijst -");
for (Student deStudent : deStudenten) {
System.out.println(deStudent);
}
System.out.println("\n- Dit is de inhoud van de klassenlijst -");
for (Klas deKlas : deKlassen) {
System.out.println(deKlas.getKlasCode());
}
System.out.println("\n- Dit is de inhoud van de lessenlijst -");
for (Les deLes : deLessen) {
System.out.println(deLes.toString() + "\n");
}
System.out.println("\n- Dit zijn de lessen van Brian van Yperen op 2016-03-10 -");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
try {
d = dateFormat.parse("2016-03-10");
} catch (ParseException e) {
e.printStackTrace();
}
for (Les deLes : getDeLessenVanStudent(d, "1679084")) {
System.out.println(deLes.toString() + "\n");
}
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersNaam().equals(gebruikersnaam)) {
if (d.controleerWachtwoord(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersNaam().equals(gebruikersnaam)) {
if (s.controleerWachtwoord(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
public Docent getDocent(String gebruikersnaam) {
Docent resultaat = null;
for (Docent d : deDocenten) {
if (d.getGebruikersNaam().equals(gebruikersnaam)) {
resultaat = d;
break;
}
}
return resultaat;
}
public Student getStudent(String gebruikersnaam) {
Student resultaat = null;
for (Student s : deStudenten) {
if (s.getGebruikersNaam().equals(gebruikersnaam)) {
resultaat = s;
break;
}
}
return resultaat;
}
public ArrayList<Student> getStudentenVanKlas(String klasCode) {
ArrayList<Student> resultaat = new ArrayList<Student>();
for (Student s : deStudenten) {
if (s.getMijnKlas().getKlasCode().equals(klasCode)) {
resultaat.add(s);
}
}
return resultaat;
}
public ArrayList<Les> getDeLessenVanStudent(Date d, String nm) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ArrayList<Les> result = new ArrayList<Les>();
// Zoek de klas waarin de Student zich bevindt
Klas k = getStudent(nm).getMijnKlas();
// Vind alle lessen die beginnen op de meegegeven datum en gegeven worden aan de gevonden klas, en voeg deze toe aan de result lijst
for (Les l : deLessen) {
boolean drone = dateFormat.format(d).equals(dateFormat.format(l.getBeginTijd()));
drone = drone && l.getDeKlas().equals(k);
// If this is the drone we're looking for: add it to the list
if (drone) {
result.add(l);
}
}
return result;
}
}
|
56112_48 | package bin.view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
import bin.runner.ThreadRunner;
import bin.logic.Counter;
import bin.logic.Field;
import bin.logic.FieldStats;
import bin.main.MainProgram;
import bin.main.Simulator;
import bin.model.Bear;
import bin.model.Fox;
import bin.model.Rabbit;
import bin.model.Wolf;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A graphical view of the simulation grid. The view displays a colored
* rectangle for each location representing its contents. It uses a default
* background color. Colors for each type of species can be defined using the
* setColor method.
*
* @author Ieme, Jermo, Yisong
* @version 2012.01.29
*/
public class SimulatorView extends JFrame {
private static final long serialVersionUID = 277424818342055257L;
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
// view instanties
private FieldView fieldView;
private PieChart pieChart;
private Histogram histogram;
private HistoryView historyView;
private FieldStats stats;
private ThreadRunner threadRunner;
private JFrame settingsFrame;
// A map for storing colors for participants in the simulation
@SuppressWarnings("rawtypes")
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private boolean isReset;
private static final String VERSION = "versie 0.0";
/**
* Create a view of the given width and height.
*
* @param height
* The simulation's height.
* @param width
* The simulation's width.
*/
@SuppressWarnings("rawtypes")
public SimulatorView(int height, int width) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stats = new FieldStats();
threadRunner = new ThreadRunner();
colors = new LinkedHashMap<Class, Color>();
makeFieldView(height, width);
makePieChart(height, width);
makeHistogram(height, width);
makeHistoryView(height, width);
makeMainFrame();
makeMenuBar();
setTitle("Fox and Rabbit Simulation");
}
/**
* Maak main frame aan en al zijn componenten Main frame is de onderste
* laag, daarna komt tweede laag view panel (rechterkant) en toolbar panel
* (linkerkant). Aan de toolbar panel worden knoppen toegevoegd en aan de
* view panel worden meerdere views toegevoegd(piecharts etc.)
*/
public void makeMainFrame() {
// maak main frame (onderste laag) aan, layout en border van main frame.
JPanel mainFrame = new JPanel();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBorder(new EmptyBorder(10, 10, 10, 10));
// maak view panel (tweede laag) aan, layout en border van view panel.
JPanel viewPanel = new JPanel();
viewPanel.setLayout(new GridLayout(2, 2));
viewPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
// maak field panel (bovenste laag) aan, en border van field panel.
JPanel field = new JPanel();
field.setLayout(new BorderLayout());
field.add(stepLabel, BorderLayout.NORTH);
field.add(fieldView, BorderLayout.CENTER);
field.add(population, BorderLayout.SOUTH);
// pieChart panel
JPanel chart = new JPanel();
chart.setLayout(new BorderLayout());
chart.add(pieChart, BorderLayout.CENTER);
// histoGram panel
JPanel diagram = new JPanel();
diagram.setLayout(new BorderLayout());
diagram.add(histogram, BorderLayout.CENTER);
// textArea panel
JTextArea textArea = new JTextArea(20, 20);
historyView.setTextArea(textArea);
// scroll panel voor de textArea
JScrollPane scrollPane = new JScrollPane(textArea);
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
textArea.setEditable(false);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// maak toolbar panel (tweede laag, linkerkant) aan, layout en border
// van toolbar panel
JPanel toolbar = new JPanel();
toolbar.setLayout(new GridLayout(20, 0));
toolbar.setBorder(new EmptyBorder(20, 10, 20, 10));
// labels en knoppen
// voeg ActionListener voor ieder knop en voeg het toe aan toolbar panel
JButton step1 = new JButton("Step 1");
step1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(1);
}
});
toolbar.add(step1);
JButton step100 = new JButton("Step 100");
step100.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(100);
}
});
toolbar.add(step100);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(0);
Component c = (Component)e.getSource();
c.getToolkit().beep();
}
});
toolbar.add(start);
JButton stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.stop();
Component c = (Component)e.getSource();
c.getToolkit().beep();
}
});
toolbar.add(stop);
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
historyView.setStep(0);
MainProgram.getSimulator().reset();
}
});
toolbar.add(reset);
// maak een balk met versie nummer onderaan de frame en voeg toe aan de
// main frame
JLabel statusLabel = new JLabel(VERSION);
mainFrame.add(statusLabel, BorderLayout.SOUTH);
// alles toevoegen aan de frame
this.add(mainFrame);
mainFrame.add(viewPanel, BorderLayout.CENTER);
mainFrame.add(toolbar, BorderLayout.WEST);
viewPanel.add(field);
viewPanel.add(chart);
viewPanel.add(diagram);
viewPanel.add(scrollPane);
// Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setSize(new Dimension(1280, 720));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
/**
* Maak de hoofdmenu aan
*/
private void makeMenuBar() {
// shorcuts kits
final int SHORTCUT_MASK = Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask();
// maak een menubalk aan.
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
// maak de menu en menu items aan
JMenu menu;
JMenuItem item;
// maak menu file aan
menu = new JMenu("File");
menuBar.add(menu);
// maak menu item settings aan en ActionListener
item = new JMenuItem("Settings");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (settingsFrame == null){
makeSettings();
}
settingsFrame.setVisible(true);
}
});
menu.add(item);
menu.addSeparator();
// maak menu item quit aan
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke
.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
// maak help menu aan
menu = new JMenu("Help");
menuBar.add(menu);
}
/**
* maak een pop up settings window, wordt opgeroepen wanneer menu item
* settings wordt gebruikt. Settings wordt gebruikt om gegevens van een
* actoren te kunnen wijzigen
*/
private void makeSettings() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// maak settings frame aan
settingsFrame = new JFrame();
settingsFrame.setTitle("Settings");
// maak settings frame's main tab aan, size, layout en border van
// settings panel
JTabbedPane mainTab = new JTabbedPane();
mainTab.setBorder(new EmptyBorder(10, 10, 10, 10));
mainTab.setPreferredSize(new Dimension(100, 100));
// maak general tab aan, layout en border
JPanel generalTab = new JPanel();
generalTab.setLayout(new GridLayout(8, 1));
generalTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden toe aan general tab
generalTab.add(new JLabel("Animation Speed"));
final JTextField animationSpeed = new JTextField();
generalTab.add(animationSpeed);
generalTab.add(new JLabel("Rabbit creation probability"));
final JTextField rabbitCreationProbability = new JTextField();
generalTab.add(rabbitCreationProbability);
generalTab.add(new JLabel("Fox creation probability"));
final JTextField foxCreationProbability = new JTextField();
generalTab.add(foxCreationProbability);
generalTab.add(new JLabel("Wolf creation probability"));
final JTextField wolfCreationProbability = new JTextField();
generalTab.add(wolfCreationProbability);
generalTab.add(new JLabel("Bear creation probability"));
final JTextField bearCreationProbability = new JTextField();
generalTab.add(bearCreationProbability);
generalTab.add(new JLabel("Hunter creation probability"));
final JTextField hunterCreationProbability = new JTextField();
generalTab.add(hunterCreationProbability);
// change setting button
JButton change = new JButton("change setting");
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Simulator.setAnimationSpeed(stringToInt(animationSpeed));
Simulator.setRabbitCreationProbability(stringToDouble(rabbitCreationProbability));
Simulator.setFoxCreationProbability(stringToDouble(foxCreationProbability));
Simulator.setWolfCreationProbability(stringToDouble(wolfCreationProbability));
Simulator.setBearCreationProbability(stringToDouble(bearCreationProbability));
Simulator.setHunterCreationProbability(stringToDouble(hunterCreationProbability));
}
});
generalTab.add(change);
// set default button
JButton setDefault = new JButton("default");
setDefault.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Simulator.setDefault();
}
});
generalTab.add(setDefault);
// maak rabbits tab aan, layout en border
JPanel rabbitTab = new JPanel();
rabbitTab.setLayout(new GridLayout(8, 0));
rabbitTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan rabbit tab
rabbitTab.add(new JLabel("Breeding age"));
final JTextField rabbitBreedingAge = new JTextField();
rabbitTab.add(rabbitBreedingAge);
rabbitTab.add(new JLabel("Max age"));
final JTextField rabbitMaxAge = new JTextField();
rabbitTab.add(rabbitMaxAge);
rabbitTab.add(new JLabel("Breeding probability"));
final JTextField rabbitBreedingProbability = new JTextField();
rabbitTab.add(rabbitBreedingProbability);
rabbitTab.add(new JLabel("Max litter size"));
final JTextField rabbitMaxLitterSize = new JTextField();
rabbitTab.add(rabbitMaxLitterSize);
// change setting button
JButton changeRabbit = new JButton("change setting");
changeRabbit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rabbit.setBreedingAge(stringToInt(rabbitBreedingAge));
Rabbit.setMaxAge(stringToInt(rabbitMaxAge));
Rabbit.setBreedingProbability(stringToDouble(rabbitBreedingProbability));
Rabbit.setMaxLitterSize(stringToInt(rabbitMaxLitterSize));
}
});
rabbitTab.add(changeRabbit);
// set default button
JButton setDefaultRabbit = new JButton("default");
setDefaultRabbit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rabbit.setDefault();
}
});
rabbitTab.add(setDefaultRabbit);
// maak foxes tab aan, layout en border
JPanel foxTab = new JPanel();
foxTab.setLayout(new GridLayout(8, 0));
foxTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan fox tab
foxTab.add(new JLabel("Breeding age"));
final JTextField foxBreedingAge = new JTextField();
foxTab.add(foxBreedingAge);
foxTab.add(new JLabel("Max age"));
final JTextField foxMaxAge = new JTextField();
foxTab.add(foxMaxAge);
foxTab.add(new JLabel("Breeding probability"));
final JTextField foxBreedingProbability = new JTextField();
foxTab.add(foxBreedingProbability);
foxTab.add(new JLabel("Max litter size"));
final JTextField foxMaxLitterSize = new JTextField();
foxTab.add(foxMaxLitterSize);
// change setting button
JButton changeFox = new JButton("change setting");
changeFox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Fox.setBreedingAge(stringToInt(foxBreedingAge));
Fox.setMaxAge(stringToInt(foxMaxAge));
Fox.setBreedingProbability(stringToDouble(foxBreedingProbability));
Fox.setMaxLitterSize(stringToInt(foxMaxLitterSize));
}
});
foxTab.add(changeFox);
// set default button
JButton setDefaultFox = new JButton("default");
setDefaultFox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Fox.setDefault();
}
});
foxTab.add(setDefaultFox);
// maak wolfs tab aan, layout en border
JPanel wolfTab = new JPanel();
wolfTab.setLayout(new GridLayout(8, 0));
wolfTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan wolf tab
wolfTab.add(new JLabel("Breeding age"));
final JTextField wolfBreedingAge = new JTextField();
wolfTab.add(wolfBreedingAge);
wolfTab.add(new JLabel("Max age"));
final JTextField wolfMaxAge = new JTextField();
wolfTab.add(wolfMaxAge);
wolfTab.add(new JLabel("Breeding probability"));
final JTextField wolfBreedingProbability = new JTextField();
wolfTab.add(wolfBreedingProbability);
wolfTab.add(new JLabel("Max litter size"));
final JTextField wolfMaxLitterSize = new JTextField();
wolfTab.add(wolfMaxLitterSize);
// change setting button
JButton changeWolf = new JButton("change setting");
changeWolf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Wolf.setBreedingAge(stringToInt(wolfBreedingAge));
Wolf.setMaxAge(stringToInt(wolfMaxAge));
Wolf.setBreedingProbability(stringToDouble(wolfBreedingProbability));
Wolf.setMaxLitterSize(stringToInt(wolfMaxLitterSize));
}
});
wolfTab.add(changeWolf);
// set default button
JButton setDefaultWolf = new JButton("default");
setDefaultWolf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Wolf.setDefault();
}
});
wolfTab.add(setDefaultWolf);
// maak bears tab aan, layout en border
JPanel bearTab = new JPanel();
bearTab.setLayout(new GridLayout(8, 0));
bearTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan bear tab
bearTab.add(new JLabel("Breeding age"));
final JTextField bearBreedingAge = new JTextField();
bearTab.add(bearBreedingAge);
bearTab.add(new JLabel("Max age"));
final JTextField bearMaxAge = new JTextField();
bearTab.add(bearMaxAge);
bearTab.add(new JLabel("Breeding probability"));
final JTextField bearBreedingProbability = new JTextField();
bearTab.add(bearBreedingProbability);
bearTab.add(new JLabel("Max litter size"));
final JTextField bearMaxLitterSize = new JTextField();
bearTab.add(bearMaxLitterSize);
// change setting button
JButton changeBear = new JButton("change setting");
changeBear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bear.setBreedingAge(stringToInt(bearBreedingAge));
Bear.setMaxAge(stringToInt(bearMaxAge));
Bear.setBreedingProbability(stringToDouble(bearBreedingProbability));
Bear.setMaxLitterSize(stringToInt(bearMaxLitterSize));
}
});
bearTab.add(changeBear);
// set default button
JButton setDefaultBear = new JButton("default");
setDefaultBear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bear.setDefault();
}
});
bearTab.add(setDefaultBear);
// alle tabs toevoegen aan maintab
// main tab toevoegen aan de settings frame
mainTab.addTab("General", generalTab);
mainTab.addTab("Rabbit", rabbitTab);
mainTab.addTab("Fox", foxTab);
mainTab.addTab("Wolf", wolfTab);
mainTab.addTab("Bear", bearTab);
// mainTab.addTab("Hunter", HunterTab);
settingsFrame.add(mainTab);
settingsFrame.setSize(new Dimension(640, 240));
settingsFrame.setResizable(false);
settingsFrame.setLocationRelativeTo(null); // center de settingsFrame
settingsFrame.setVisible(true);
}
/**
* Quit menu om het programma af te sluiten.
*/
private void quit() {
System.exit(0);
}
/**
* maak fieldView aan
* @param height
* @param width
*/
public void makeFieldView(int height, int width) {
fieldView = new FieldView(height, width);
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
}
/**
* maak pieChart aan
* @param height
* @param width
*/
private void makePieChart(int height, int width) {
pieChart = new PieChart();
pieChart.setSize(height * 2, width * 2);
pieChart.stats(getPopulationDetails());
pieChart.repaint();
}
/**
* maak histogram aan
* @param height
* @param width
*/
private void makeHistogram(int height, int width) {
histogram = new Histogram();
histogram.setSize(height * 2, width * 2);
histogram.stats(getPopulationDetails());
histogram.repaint();
}
/**
* maak historyView aan
* @param height
* @param width
*/
private void makeHistoryView(int height, int width) {
historyView = new HistoryView(height, width);
historyView.setSize(height, width);
historyView.stats(getPopulationDetails());
historyView.history(getIsReset());
}
/**
* Getter om threadRunner object op te halen
* @return threadRunner object van type ThreadRunner
*/
public ThreadRunner getThreadRunner() {
return threadRunner;
}
/**
* getter voor FieldStats stats
* @param stats
*/
public FieldStats getStats() {
return stats;
}
/**
* Getter voor boolean isReset
* @return isReset bepaald of step 0 is voor de historyview
*/
public boolean getIsReset() {
return isReset;
}
/**
* convert text from JTextField to int
* @param number
*/
private int stringToInt(JTextField text) {
int number = 0;
if (!text.getText().equals("")) {
String string = text.getText();
for (int s = 0; s < string.length(); s++) {
if (string.charAt(s) == '0' || string.charAt(s) == '1'
|| string.charAt(s) == '2' || string.charAt(s) == '3'
|| string.charAt(s) == '4' || string.charAt(s) == '5'
|| string.charAt(s) == '6' || string.charAt(s) == '7'
|| string.charAt(s) == '8' || string.charAt(s) == '9') {
number++;
}
}
if (number == string.length()) {
number = Integer.parseInt(text.getText());
} else {
historyView.getTextArea().append(
"Alleen hele getallen zijn toegestaan" + "\r\n");
return number = -1;
}
}
else{
return number = -1;
}
return number;
}
/**
* convert text from JTextField to double
* @param number
*/
private double stringToDouble(JTextField text) {
double number = 0;
int komma = 0;
if (!text.getText().equals(""))
{
String string = text.getText();
for (int s = 0; s < string.length(); s++) {
if (string.charAt(s) == '0' || string.charAt(s) == '1'|| string.charAt(s) == '2' ||
string.charAt(s) == '3' || string.charAt(s) == '4'|| string.charAt(s) == '5' ||
string.charAt(s) == '6' || string.charAt(s) == '7'|| string.charAt(s) == '8' ||
string.charAt(s) == '9' || string.charAt(s) == '.')
{
number++;
}
if (string.charAt(s) == '.')
{
komma++;
}
}
if (number == string.length() && komma <= 1) {
number = Double.parseDouble(text.getText());
} else {
historyView.getTextArea().append(
"Alleen cijfers zijn toegestaan en . getallen" + "\r\n");
return number = -1;
}
}
else{
return number = -1;
}
return number;
}
/**
* Define a color to be used for a given class of animal.
*
* @param animalClass
* The animal's Class object.
* @param color
* The color to be used for the given class.
*/
@SuppressWarnings("rawtypes")
public void setColor(Class animalClass, Color color) {
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
@SuppressWarnings("rawtypes")
private Color getColor(Class animalClass) {
Color col = colors.get(animalClass);
if (col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
} else {
return col;
}
}
/**
* Show the current status of the field.
*
* @param step
* Which iteration step it is.
* @param field
* The field whose status is to be displayed.
*/
public void showStatus(int step, Field field) {
if (!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for (int row = 0; row < field.getDepth(); row++) {
for (int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if (animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
} else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX
+ stats.getPopulationDetails(field));
fieldView.repaint();
pieChart.stats(getPopulationDetails());
pieChart.repaint();
histogram.stats(getPopulationDetails());
histogram.repaint();
historyView.stats(getPopulationDetails());
historyView.history(getIsReset());
}
/**
* retourneert de counter voor ieder kleur
* @return colorStats HashMap die kleur bij houdt en de hoeveelheid
*/
@SuppressWarnings("rawtypes")
public HashMap<Color, Counter> getPopulationDetails() {
HashMap<Class, Counter> classStats = stats.getPopulation();
HashMap<Color, Counter> colorStats = new HashMap<Color, Counter>();
for (Class c : classStats.keySet()) {
colorStats.put(getColor(c), classStats.get(c));
}
return colorStats;
}
/**
* retourneert de counter voor ieder kleur
* @return classStats HashMap die class bij hout en de hoeveelheid
*/
@SuppressWarnings("rawtypes")
public HashMap<Class, Counter> getPopulationDetails2() {
HashMap<Class, Counter> classStats = stats.getPopulation();
return classStats;
}
/**
* Determine whether the simulation should continue to run.
*
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field) {
return stats.isViable(field);
}
}
| X08/Vossen-en-Konijnen | bin/view/SimulatorView.java | 6,591 | // alle tabs toevoegen aan maintab | line_comment | nl | package bin.view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
import bin.runner.ThreadRunner;
import bin.logic.Counter;
import bin.logic.Field;
import bin.logic.FieldStats;
import bin.main.MainProgram;
import bin.main.Simulator;
import bin.model.Bear;
import bin.model.Fox;
import bin.model.Rabbit;
import bin.model.Wolf;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A graphical view of the simulation grid. The view displays a colored
* rectangle for each location representing its contents. It uses a default
* background color. Colors for each type of species can be defined using the
* setColor method.
*
* @author Ieme, Jermo, Yisong
* @version 2012.01.29
*/
public class SimulatorView extends JFrame {
private static final long serialVersionUID = 277424818342055257L;
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
// view instanties
private FieldView fieldView;
private PieChart pieChart;
private Histogram histogram;
private HistoryView historyView;
private FieldStats stats;
private ThreadRunner threadRunner;
private JFrame settingsFrame;
// A map for storing colors for participants in the simulation
@SuppressWarnings("rawtypes")
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private boolean isReset;
private static final String VERSION = "versie 0.0";
/**
* Create a view of the given width and height.
*
* @param height
* The simulation's height.
* @param width
* The simulation's width.
*/
@SuppressWarnings("rawtypes")
public SimulatorView(int height, int width) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stats = new FieldStats();
threadRunner = new ThreadRunner();
colors = new LinkedHashMap<Class, Color>();
makeFieldView(height, width);
makePieChart(height, width);
makeHistogram(height, width);
makeHistoryView(height, width);
makeMainFrame();
makeMenuBar();
setTitle("Fox and Rabbit Simulation");
}
/**
* Maak main frame aan en al zijn componenten Main frame is de onderste
* laag, daarna komt tweede laag view panel (rechterkant) en toolbar panel
* (linkerkant). Aan de toolbar panel worden knoppen toegevoegd en aan de
* view panel worden meerdere views toegevoegd(piecharts etc.)
*/
public void makeMainFrame() {
// maak main frame (onderste laag) aan, layout en border van main frame.
JPanel mainFrame = new JPanel();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBorder(new EmptyBorder(10, 10, 10, 10));
// maak view panel (tweede laag) aan, layout en border van view panel.
JPanel viewPanel = new JPanel();
viewPanel.setLayout(new GridLayout(2, 2));
viewPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
// maak field panel (bovenste laag) aan, en border van field panel.
JPanel field = new JPanel();
field.setLayout(new BorderLayout());
field.add(stepLabel, BorderLayout.NORTH);
field.add(fieldView, BorderLayout.CENTER);
field.add(population, BorderLayout.SOUTH);
// pieChart panel
JPanel chart = new JPanel();
chart.setLayout(new BorderLayout());
chart.add(pieChart, BorderLayout.CENTER);
// histoGram panel
JPanel diagram = new JPanel();
diagram.setLayout(new BorderLayout());
diagram.add(histogram, BorderLayout.CENTER);
// textArea panel
JTextArea textArea = new JTextArea(20, 20);
historyView.setTextArea(textArea);
// scroll panel voor de textArea
JScrollPane scrollPane = new JScrollPane(textArea);
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
textArea.setEditable(false);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// maak toolbar panel (tweede laag, linkerkant) aan, layout en border
// van toolbar panel
JPanel toolbar = new JPanel();
toolbar.setLayout(new GridLayout(20, 0));
toolbar.setBorder(new EmptyBorder(20, 10, 20, 10));
// labels en knoppen
// voeg ActionListener voor ieder knop en voeg het toe aan toolbar panel
JButton step1 = new JButton("Step 1");
step1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(1);
}
});
toolbar.add(step1);
JButton step100 = new JButton("Step 100");
step100.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(100);
}
});
toolbar.add(step100);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.startRun(0);
Component c = (Component)e.getSource();
c.getToolkit().beep();
}
});
toolbar.add(start);
JButton stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadRunner.stop();
Component c = (Component)e.getSource();
c.getToolkit().beep();
}
});
toolbar.add(stop);
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
historyView.setStep(0);
MainProgram.getSimulator().reset();
}
});
toolbar.add(reset);
// maak een balk met versie nummer onderaan de frame en voeg toe aan de
// main frame
JLabel statusLabel = new JLabel(VERSION);
mainFrame.add(statusLabel, BorderLayout.SOUTH);
// alles toevoegen aan de frame
this.add(mainFrame);
mainFrame.add(viewPanel, BorderLayout.CENTER);
mainFrame.add(toolbar, BorderLayout.WEST);
viewPanel.add(field);
viewPanel.add(chart);
viewPanel.add(diagram);
viewPanel.add(scrollPane);
// Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setSize(new Dimension(1280, 720));
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
/**
* Maak de hoofdmenu aan
*/
private void makeMenuBar() {
// shorcuts kits
final int SHORTCUT_MASK = Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask();
// maak een menubalk aan.
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
// maak de menu en menu items aan
JMenu menu;
JMenuItem item;
// maak menu file aan
menu = new JMenu("File");
menuBar.add(menu);
// maak menu item settings aan en ActionListener
item = new JMenuItem("Settings");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (settingsFrame == null){
makeSettings();
}
settingsFrame.setVisible(true);
}
});
menu.add(item);
menu.addSeparator();
// maak menu item quit aan
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke
.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
// maak help menu aan
menu = new JMenu("Help");
menuBar.add(menu);
}
/**
* maak een pop up settings window, wordt opgeroepen wanneer menu item
* settings wordt gebruikt. Settings wordt gebruikt om gegevens van een
* actoren te kunnen wijzigen
*/
private void makeSettings() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// maak settings frame aan
settingsFrame = new JFrame();
settingsFrame.setTitle("Settings");
// maak settings frame's main tab aan, size, layout en border van
// settings panel
JTabbedPane mainTab = new JTabbedPane();
mainTab.setBorder(new EmptyBorder(10, 10, 10, 10));
mainTab.setPreferredSize(new Dimension(100, 100));
// maak general tab aan, layout en border
JPanel generalTab = new JPanel();
generalTab.setLayout(new GridLayout(8, 1));
generalTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden toe aan general tab
generalTab.add(new JLabel("Animation Speed"));
final JTextField animationSpeed = new JTextField();
generalTab.add(animationSpeed);
generalTab.add(new JLabel("Rabbit creation probability"));
final JTextField rabbitCreationProbability = new JTextField();
generalTab.add(rabbitCreationProbability);
generalTab.add(new JLabel("Fox creation probability"));
final JTextField foxCreationProbability = new JTextField();
generalTab.add(foxCreationProbability);
generalTab.add(new JLabel("Wolf creation probability"));
final JTextField wolfCreationProbability = new JTextField();
generalTab.add(wolfCreationProbability);
generalTab.add(new JLabel("Bear creation probability"));
final JTextField bearCreationProbability = new JTextField();
generalTab.add(bearCreationProbability);
generalTab.add(new JLabel("Hunter creation probability"));
final JTextField hunterCreationProbability = new JTextField();
generalTab.add(hunterCreationProbability);
// change setting button
JButton change = new JButton("change setting");
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Simulator.setAnimationSpeed(stringToInt(animationSpeed));
Simulator.setRabbitCreationProbability(stringToDouble(rabbitCreationProbability));
Simulator.setFoxCreationProbability(stringToDouble(foxCreationProbability));
Simulator.setWolfCreationProbability(stringToDouble(wolfCreationProbability));
Simulator.setBearCreationProbability(stringToDouble(bearCreationProbability));
Simulator.setHunterCreationProbability(stringToDouble(hunterCreationProbability));
}
});
generalTab.add(change);
// set default button
JButton setDefault = new JButton("default");
setDefault.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Simulator.setDefault();
}
});
generalTab.add(setDefault);
// maak rabbits tab aan, layout en border
JPanel rabbitTab = new JPanel();
rabbitTab.setLayout(new GridLayout(8, 0));
rabbitTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan rabbit tab
rabbitTab.add(new JLabel("Breeding age"));
final JTextField rabbitBreedingAge = new JTextField();
rabbitTab.add(rabbitBreedingAge);
rabbitTab.add(new JLabel("Max age"));
final JTextField rabbitMaxAge = new JTextField();
rabbitTab.add(rabbitMaxAge);
rabbitTab.add(new JLabel("Breeding probability"));
final JTextField rabbitBreedingProbability = new JTextField();
rabbitTab.add(rabbitBreedingProbability);
rabbitTab.add(new JLabel("Max litter size"));
final JTextField rabbitMaxLitterSize = new JTextField();
rabbitTab.add(rabbitMaxLitterSize);
// change setting button
JButton changeRabbit = new JButton("change setting");
changeRabbit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rabbit.setBreedingAge(stringToInt(rabbitBreedingAge));
Rabbit.setMaxAge(stringToInt(rabbitMaxAge));
Rabbit.setBreedingProbability(stringToDouble(rabbitBreedingProbability));
Rabbit.setMaxLitterSize(stringToInt(rabbitMaxLitterSize));
}
});
rabbitTab.add(changeRabbit);
// set default button
JButton setDefaultRabbit = new JButton("default");
setDefaultRabbit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rabbit.setDefault();
}
});
rabbitTab.add(setDefaultRabbit);
// maak foxes tab aan, layout en border
JPanel foxTab = new JPanel();
foxTab.setLayout(new GridLayout(8, 0));
foxTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan fox tab
foxTab.add(new JLabel("Breeding age"));
final JTextField foxBreedingAge = new JTextField();
foxTab.add(foxBreedingAge);
foxTab.add(new JLabel("Max age"));
final JTextField foxMaxAge = new JTextField();
foxTab.add(foxMaxAge);
foxTab.add(new JLabel("Breeding probability"));
final JTextField foxBreedingProbability = new JTextField();
foxTab.add(foxBreedingProbability);
foxTab.add(new JLabel("Max litter size"));
final JTextField foxMaxLitterSize = new JTextField();
foxTab.add(foxMaxLitterSize);
// change setting button
JButton changeFox = new JButton("change setting");
changeFox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Fox.setBreedingAge(stringToInt(foxBreedingAge));
Fox.setMaxAge(stringToInt(foxMaxAge));
Fox.setBreedingProbability(stringToDouble(foxBreedingProbability));
Fox.setMaxLitterSize(stringToInt(foxMaxLitterSize));
}
});
foxTab.add(changeFox);
// set default button
JButton setDefaultFox = new JButton("default");
setDefaultFox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Fox.setDefault();
}
});
foxTab.add(setDefaultFox);
// maak wolfs tab aan, layout en border
JPanel wolfTab = new JPanel();
wolfTab.setLayout(new GridLayout(8, 0));
wolfTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan wolf tab
wolfTab.add(new JLabel("Breeding age"));
final JTextField wolfBreedingAge = new JTextField();
wolfTab.add(wolfBreedingAge);
wolfTab.add(new JLabel("Max age"));
final JTextField wolfMaxAge = new JTextField();
wolfTab.add(wolfMaxAge);
wolfTab.add(new JLabel("Breeding probability"));
final JTextField wolfBreedingProbability = new JTextField();
wolfTab.add(wolfBreedingProbability);
wolfTab.add(new JLabel("Max litter size"));
final JTextField wolfMaxLitterSize = new JTextField();
wolfTab.add(wolfMaxLitterSize);
// change setting button
JButton changeWolf = new JButton("change setting");
changeWolf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Wolf.setBreedingAge(stringToInt(wolfBreedingAge));
Wolf.setMaxAge(stringToInt(wolfMaxAge));
Wolf.setBreedingProbability(stringToDouble(wolfBreedingProbability));
Wolf.setMaxLitterSize(stringToInt(wolfMaxLitterSize));
}
});
wolfTab.add(changeWolf);
// set default button
JButton setDefaultWolf = new JButton("default");
setDefaultWolf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Wolf.setDefault();
}
});
wolfTab.add(setDefaultWolf);
// maak bears tab aan, layout en border
JPanel bearTab = new JPanel();
bearTab.setLayout(new GridLayout(8, 0));
bearTab.setBorder(new EmptyBorder(10, 10, 10, 10));
// voeg labels, tekstvelden en ActionListener toe aan bear tab
bearTab.add(new JLabel("Breeding age"));
final JTextField bearBreedingAge = new JTextField();
bearTab.add(bearBreedingAge);
bearTab.add(new JLabel("Max age"));
final JTextField bearMaxAge = new JTextField();
bearTab.add(bearMaxAge);
bearTab.add(new JLabel("Breeding probability"));
final JTextField bearBreedingProbability = new JTextField();
bearTab.add(bearBreedingProbability);
bearTab.add(new JLabel("Max litter size"));
final JTextField bearMaxLitterSize = new JTextField();
bearTab.add(bearMaxLitterSize);
// change setting button
JButton changeBear = new JButton("change setting");
changeBear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bear.setBreedingAge(stringToInt(bearBreedingAge));
Bear.setMaxAge(stringToInt(bearMaxAge));
Bear.setBreedingProbability(stringToDouble(bearBreedingProbability));
Bear.setMaxLitterSize(stringToInt(bearMaxLitterSize));
}
});
bearTab.add(changeBear);
// set default button
JButton setDefaultBear = new JButton("default");
setDefaultBear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bear.setDefault();
}
});
bearTab.add(setDefaultBear);
// alle tabs<SUF>
// main tab toevoegen aan de settings frame
mainTab.addTab("General", generalTab);
mainTab.addTab("Rabbit", rabbitTab);
mainTab.addTab("Fox", foxTab);
mainTab.addTab("Wolf", wolfTab);
mainTab.addTab("Bear", bearTab);
// mainTab.addTab("Hunter", HunterTab);
settingsFrame.add(mainTab);
settingsFrame.setSize(new Dimension(640, 240));
settingsFrame.setResizable(false);
settingsFrame.setLocationRelativeTo(null); // center de settingsFrame
settingsFrame.setVisible(true);
}
/**
* Quit menu om het programma af te sluiten.
*/
private void quit() {
System.exit(0);
}
/**
* maak fieldView aan
* @param height
* @param width
*/
public void makeFieldView(int height, int width) {
fieldView = new FieldView(height, width);
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
}
/**
* maak pieChart aan
* @param height
* @param width
*/
private void makePieChart(int height, int width) {
pieChart = new PieChart();
pieChart.setSize(height * 2, width * 2);
pieChart.stats(getPopulationDetails());
pieChart.repaint();
}
/**
* maak histogram aan
* @param height
* @param width
*/
private void makeHistogram(int height, int width) {
histogram = new Histogram();
histogram.setSize(height * 2, width * 2);
histogram.stats(getPopulationDetails());
histogram.repaint();
}
/**
* maak historyView aan
* @param height
* @param width
*/
private void makeHistoryView(int height, int width) {
historyView = new HistoryView(height, width);
historyView.setSize(height, width);
historyView.stats(getPopulationDetails());
historyView.history(getIsReset());
}
/**
* Getter om threadRunner object op te halen
* @return threadRunner object van type ThreadRunner
*/
public ThreadRunner getThreadRunner() {
return threadRunner;
}
/**
* getter voor FieldStats stats
* @param stats
*/
public FieldStats getStats() {
return stats;
}
/**
* Getter voor boolean isReset
* @return isReset bepaald of step 0 is voor de historyview
*/
public boolean getIsReset() {
return isReset;
}
/**
* convert text from JTextField to int
* @param number
*/
private int stringToInt(JTextField text) {
int number = 0;
if (!text.getText().equals("")) {
String string = text.getText();
for (int s = 0; s < string.length(); s++) {
if (string.charAt(s) == '0' || string.charAt(s) == '1'
|| string.charAt(s) == '2' || string.charAt(s) == '3'
|| string.charAt(s) == '4' || string.charAt(s) == '5'
|| string.charAt(s) == '6' || string.charAt(s) == '7'
|| string.charAt(s) == '8' || string.charAt(s) == '9') {
number++;
}
}
if (number == string.length()) {
number = Integer.parseInt(text.getText());
} else {
historyView.getTextArea().append(
"Alleen hele getallen zijn toegestaan" + "\r\n");
return number = -1;
}
}
else{
return number = -1;
}
return number;
}
/**
* convert text from JTextField to double
* @param number
*/
private double stringToDouble(JTextField text) {
double number = 0;
int komma = 0;
if (!text.getText().equals(""))
{
String string = text.getText();
for (int s = 0; s < string.length(); s++) {
if (string.charAt(s) == '0' || string.charAt(s) == '1'|| string.charAt(s) == '2' ||
string.charAt(s) == '3' || string.charAt(s) == '4'|| string.charAt(s) == '5' ||
string.charAt(s) == '6' || string.charAt(s) == '7'|| string.charAt(s) == '8' ||
string.charAt(s) == '9' || string.charAt(s) == '.')
{
number++;
}
if (string.charAt(s) == '.')
{
komma++;
}
}
if (number == string.length() && komma <= 1) {
number = Double.parseDouble(text.getText());
} else {
historyView.getTextArea().append(
"Alleen cijfers zijn toegestaan en . getallen" + "\r\n");
return number = -1;
}
}
else{
return number = -1;
}
return number;
}
/**
* Define a color to be used for a given class of animal.
*
* @param animalClass
* The animal's Class object.
* @param color
* The color to be used for the given class.
*/
@SuppressWarnings("rawtypes")
public void setColor(Class animalClass, Color color) {
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
@SuppressWarnings("rawtypes")
private Color getColor(Class animalClass) {
Color col = colors.get(animalClass);
if (col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
} else {
return col;
}
}
/**
* Show the current status of the field.
*
* @param step
* Which iteration step it is.
* @param field
* The field whose status is to be displayed.
*/
public void showStatus(int step, Field field) {
if (!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for (int row = 0; row < field.getDepth(); row++) {
for (int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if (animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
} else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX
+ stats.getPopulationDetails(field));
fieldView.repaint();
pieChart.stats(getPopulationDetails());
pieChart.repaint();
histogram.stats(getPopulationDetails());
histogram.repaint();
historyView.stats(getPopulationDetails());
historyView.history(getIsReset());
}
/**
* retourneert de counter voor ieder kleur
* @return colorStats HashMap die kleur bij houdt en de hoeveelheid
*/
@SuppressWarnings("rawtypes")
public HashMap<Color, Counter> getPopulationDetails() {
HashMap<Class, Counter> classStats = stats.getPopulation();
HashMap<Color, Counter> colorStats = new HashMap<Color, Counter>();
for (Class c : classStats.keySet()) {
colorStats.put(getColor(c), classStats.get(c));
}
return colorStats;
}
/**
* retourneert de counter voor ieder kleur
* @return classStats HashMap die class bij hout en de hoeveelheid
*/
@SuppressWarnings("rawtypes")
public HashMap<Class, Counter> getPopulationDetails2() {
HashMap<Class, Counter> classStats = stats.getPopulation();
return classStats;
}
/**
* Determine whether the simulation should continue to run.
*
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field) {
return stats.isViable(field);
}
}
|
24386_41 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wad_processor;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TimerTask;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wad.db.DatabaseParameters;
import wad.db.GewensteProces;
import wad.db.PacsDatabaseConnection;
import wad.db.ReadFromIqcDatabase;
import wad.db.WriteResultaten;
import wad.xml.AnalyseModuleResultFile;
import wad.xml.ReadConfigXML;
/**
*
* @author titulaer
*/
public class CheckNewJobs extends TimerTask {
private static Log log = LogFactory.getLog(CheckNewJobs.class);
public int aantalConcurrentJobs = 4;
ArrayList<WAD_ProcessThread> processList = new ArrayList<WAD_ProcessThread>();
int processID = 0;
//Teller om een aantal loops te laten doorlopen voordat afgesloten wordt.
//Dit bouw ik in om te voorkomen dat bij het starten de applicatie niet oneindig blijft lopen, maar egstopt kan worden via een setting in de config.xml
//De teller wordt op nul gezet indien er processen lopen, bij 5 keer doorlopen zonder actieve processen gaat de aplpicatie uit.
public int teller = 0;
public void run() {
//LoggerWrapper loggerWrapper = LoggerWrapper.getInstance();
//LoggerWrapper.myLogger.log(Level.INFO, "");
log.info("Begin cyclus processor.");
teller++;
//RB inlezen db parameters
DatabaseParameters iqcDBParams = new DatabaseParameters();
iqcDBParams = ReadConfigXML.ReadIqcDBParameters(iqcDBParams);
Connection dbConnection = PacsDatabaseConnection.conDb(iqcDBParams);
//Rb Einde inlezen db parameters
Iterator<WAD_ProcessThread> i = null;
WAD_ProcessThread rp = null;
for (i = processList.iterator(); i.hasNext();) {
teller = 0;
rp = i.next();
if (!rp.isRunning()) {
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Thread " + rp.ID() + " stopped, removing from currentJobList");
log.info("Thread " + rp.ID() + " stopped, removing from currentJobList");
// RB BT update process met rp.ID() stopped
GewensteProces gp = new GewensteProces();
gp.getGewensteProcesByKey(dbConnection, Integer.toString(rp.ID()));
if (!rp.stoppedWithError()) {
processFinishedProcess(dbConnection, gp);
} else {
gp.updateStatus(dbConnection, 10);
}
i.remove();
}
}
if (processList.size() < aantalConcurrentJobs) {
GewensteProces gp = new GewensteProces();
//RB Controleren of er processen zijn die eerder niet afgemaakt waren.
//Status 1 en 2 nog geen actie
//Status 3 en 4 nogmaals proberen te importeren
if (gp.getFirstGewensteProcesByStatus(dbConnection, 3)) {
processFinishedProcess(dbConnection, gp);
} else if (gp.getFirstGewensteProcesByStatus(dbConnection, 4)) {
processFinishedProcess(dbConnection, gp);
} else //RB check op nieuw te starten processen met processID, zo ja dan verder
//Pak het eertse item uit de tabel gewenste_processen
if (gp.getFirstGewensteProcesByStatus(dbConnection, 0)) {
//Zet het gewenste process op status 1 (Gestart)
gp.updateStatus(dbConnection, 1);
//Einde code RB
WAD_ProcessThread p = new WAD_ProcessThread();
try {
teller = 0;
//RB update process met id op start zetten
String[] command;
//command = new String[2];
// command[0] = "C:\\WINDOWS\\notepad.exe";
// command[1] = "C:\\temp\\test" + counter + ".txt";
String anaModuleFile = ReadFromIqcDatabase.getAnalyseModuleBySelectorFk(dbConnection, gp.getSelectorKey());
//String anaModuleCfgFile = ReadFromIqcDatabase.getAnalyseModuleCfgBySelectorFk(dbConnection, gp.getSelectorKey());
//aanpassen bij absoluut filepath voor XML in config.xml
String input = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_input", gp.getInputKey());
// String currentDir = System.getProperty("user.dir");
// File dir = new File(currentDir);
// String mainDir = dir.getParent();
// input = input.replace("..", mainDir);
input = input.replace("/", File.separator);
// output folder tbv logging per proces
String outputFolder = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_output", gp.getInputKey());
outputFolder = outputFolder.replace("/", File.separator);
outputFolder = outputFolder.substring(0,outputFolder.lastIndexOf(File.separator));
p.set_outputFolder(outputFolder);
//controle op type extensie, zodat m-files, java-files etc de juiste commandline meekrijgen
//command[0] = "java -jar "+anaModuleFile + " \"" + input +"\"";
//command[1] = anaModuleFile + " " + input;
if (matchExtension(anaModuleFile, "jar")) {
command = new String[4];
command[0] = "java";
command[1] = "-jar";
command[2] = anaModuleFile;
command[3] = input;
} else if (matchExtension(anaModuleFile, "py")) {
command = new String[3];
command[0] = "python";
command[1] = anaModuleFile;
command[2] = input;
} else if (matchExtension(anaModuleFile, "sh") && SystemUtils.IS_OS_LINUX) {
command = new String[3];
command[0] = "bash";
command[1] = anaModuleFile;
command[2] = input;
} else {
command = new String[2];
command[0] = anaModuleFile;
command[1] = input;
}
//Gegevens zijn bekend, nu starten van de analysemodule met input als argument
gp.updateStatus(dbConnection, 2);
this.processID = Integer.parseInt(gp.getKey());
//
p.newProcessThread(command, processID);
processList.add(processList.size(), p);
//zorgen dat service kan herstarten zonder afsluiten dochterprocessen
p.setDaemon(false);
p.start();
//counter += 1;
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Process id: " + processID);
log.info("Process id: " + processID);
} catch (Exception e) {
processList.remove(p);
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Problem starting task: " + e.getMessage());
log.info("Problem starting task: " + e.getMessage());
//Zet het gewenste process op status 10 (Error)
gp.updateStatus(dbConnection, 10);
}
}
} else {
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Cannot add process, current number of processes: " + processList.size());
log.info("Cannot add process, current number of processes: " + processList.size());
}
//RB sluiten van de DBconnectie
PacsDatabaseConnection.closeDb(dbConnection, null, null);
//LoggerWrapper.myLogger.log(Level.INFO, "Einde cyclus processor.");
log.info("Einde cyclus processor.");
//RB
//RB Sluiten applicatie voor testdoeleinden, gebruik setting in config.xml
if (ReadConfigXML.readSettingsElement("stop").equals("1")) {
if (teller == 5) {
//System.out.println(datum+" "+ tijd + ":Afsluiten.");
//LoggerWrapper.myLogger.log(Level.INFO, "Afsluiten processor.");
log.info("Afsluiten processor.");
this.cancel();
System.exit(0);
}
}
//RB Einde afsluiten.
}
private boolean matchExtension(String filename, String ext) {
int dot = filename.lastIndexOf(".");
if (filename.substring(dot + 1).equals(ext)) {
return true;
} else {
return false;
}
}
private void processFinishedProcess(Connection dbConnection, GewensteProces gp) {
// aanpassen bij absoluut filepath voor XML in config.xml
String output = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_output", gp.getOutputKey());
output = output.replace("/", File.separator);
gp.updateStatus(dbConnection, 3);
AnalyseModuleResultFile resultFile = new AnalyseModuleResultFile(output);
Boolean succes = resultFile.read();
if (succes) {
gp.updateStatus(dbConnection, 4);
WriteResultaten writeResultaten = new WriteResultaten(dbConnection, resultFile, Integer.parseInt(gp.getKey()));
gp.updateStatus(dbConnection, 5);
} else {
log.error("Problemen bij het verwerken van result.xml behorende bij proces "+gp.getKey());
gp.updateStatus(dbConnection, 10);
}
// voeg processor.log toe aan DB als object met volgnummer 999 op niveau 2
// FIXME: Hiermee wordt de logfile voor alle exit-statussen opgeslagen.
// Als we deze alleen bij succes=false willen opslaan, deze routine bovenaan
// de functie zetten.
String outputFolder = output.substring(0,output.lastIndexOf(File.separator));
try {
PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO resultaten_object("
+ "niveau, "
+ "gewenste_processen_fk, "
+ "omschrijving, "
+ "volgnummer, "
+ "object_naam_pad) "
+ "values (?,?,?,?,?)");
pstmt.setString(1, "2");
pstmt.setInt(2, Integer.parseInt(gp.getKey()));
pstmt.setString(3, "processor.log");
pstmt.setString(4, "999");
pstmt.setString(5, outputFolder+File.separator+"processor.log");
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException ex) {
log.error(ex);
}
}
}
| wadqc/WAD_Services | WAD_Processor/src/wad_processor/CheckNewJobs.java | 2,763 | //System.out.println(datum+" "+ tijd + ":Afsluiten."); | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wad_processor;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TimerTask;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wad.db.DatabaseParameters;
import wad.db.GewensteProces;
import wad.db.PacsDatabaseConnection;
import wad.db.ReadFromIqcDatabase;
import wad.db.WriteResultaten;
import wad.xml.AnalyseModuleResultFile;
import wad.xml.ReadConfigXML;
/**
*
* @author titulaer
*/
public class CheckNewJobs extends TimerTask {
private static Log log = LogFactory.getLog(CheckNewJobs.class);
public int aantalConcurrentJobs = 4;
ArrayList<WAD_ProcessThread> processList = new ArrayList<WAD_ProcessThread>();
int processID = 0;
//Teller om een aantal loops te laten doorlopen voordat afgesloten wordt.
//Dit bouw ik in om te voorkomen dat bij het starten de applicatie niet oneindig blijft lopen, maar egstopt kan worden via een setting in de config.xml
//De teller wordt op nul gezet indien er processen lopen, bij 5 keer doorlopen zonder actieve processen gaat de aplpicatie uit.
public int teller = 0;
public void run() {
//LoggerWrapper loggerWrapper = LoggerWrapper.getInstance();
//LoggerWrapper.myLogger.log(Level.INFO, "");
log.info("Begin cyclus processor.");
teller++;
//RB inlezen db parameters
DatabaseParameters iqcDBParams = new DatabaseParameters();
iqcDBParams = ReadConfigXML.ReadIqcDBParameters(iqcDBParams);
Connection dbConnection = PacsDatabaseConnection.conDb(iqcDBParams);
//Rb Einde inlezen db parameters
Iterator<WAD_ProcessThread> i = null;
WAD_ProcessThread rp = null;
for (i = processList.iterator(); i.hasNext();) {
teller = 0;
rp = i.next();
if (!rp.isRunning()) {
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Thread " + rp.ID() + " stopped, removing from currentJobList");
log.info("Thread " + rp.ID() + " stopped, removing from currentJobList");
// RB BT update process met rp.ID() stopped
GewensteProces gp = new GewensteProces();
gp.getGewensteProcesByKey(dbConnection, Integer.toString(rp.ID()));
if (!rp.stoppedWithError()) {
processFinishedProcess(dbConnection, gp);
} else {
gp.updateStatus(dbConnection, 10);
}
i.remove();
}
}
if (processList.size() < aantalConcurrentJobs) {
GewensteProces gp = new GewensteProces();
//RB Controleren of er processen zijn die eerder niet afgemaakt waren.
//Status 1 en 2 nog geen actie
//Status 3 en 4 nogmaals proberen te importeren
if (gp.getFirstGewensteProcesByStatus(dbConnection, 3)) {
processFinishedProcess(dbConnection, gp);
} else if (gp.getFirstGewensteProcesByStatus(dbConnection, 4)) {
processFinishedProcess(dbConnection, gp);
} else //RB check op nieuw te starten processen met processID, zo ja dan verder
//Pak het eertse item uit de tabel gewenste_processen
if (gp.getFirstGewensteProcesByStatus(dbConnection, 0)) {
//Zet het gewenste process op status 1 (Gestart)
gp.updateStatus(dbConnection, 1);
//Einde code RB
WAD_ProcessThread p = new WAD_ProcessThread();
try {
teller = 0;
//RB update process met id op start zetten
String[] command;
//command = new String[2];
// command[0] = "C:\\WINDOWS\\notepad.exe";
// command[1] = "C:\\temp\\test" + counter + ".txt";
String anaModuleFile = ReadFromIqcDatabase.getAnalyseModuleBySelectorFk(dbConnection, gp.getSelectorKey());
//String anaModuleCfgFile = ReadFromIqcDatabase.getAnalyseModuleCfgBySelectorFk(dbConnection, gp.getSelectorKey());
//aanpassen bij absoluut filepath voor XML in config.xml
String input = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_input", gp.getInputKey());
// String currentDir = System.getProperty("user.dir");
// File dir = new File(currentDir);
// String mainDir = dir.getParent();
// input = input.replace("..", mainDir);
input = input.replace("/", File.separator);
// output folder tbv logging per proces
String outputFolder = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_output", gp.getInputKey());
outputFolder = outputFolder.replace("/", File.separator);
outputFolder = outputFolder.substring(0,outputFolder.lastIndexOf(File.separator));
p.set_outputFolder(outputFolder);
//controle op type extensie, zodat m-files, java-files etc de juiste commandline meekrijgen
//command[0] = "java -jar "+anaModuleFile + " \"" + input +"\"";
//command[1] = anaModuleFile + " " + input;
if (matchExtension(anaModuleFile, "jar")) {
command = new String[4];
command[0] = "java";
command[1] = "-jar";
command[2] = anaModuleFile;
command[3] = input;
} else if (matchExtension(anaModuleFile, "py")) {
command = new String[3];
command[0] = "python";
command[1] = anaModuleFile;
command[2] = input;
} else if (matchExtension(anaModuleFile, "sh") && SystemUtils.IS_OS_LINUX) {
command = new String[3];
command[0] = "bash";
command[1] = anaModuleFile;
command[2] = input;
} else {
command = new String[2];
command[0] = anaModuleFile;
command[1] = input;
}
//Gegevens zijn bekend, nu starten van de analysemodule met input als argument
gp.updateStatus(dbConnection, 2);
this.processID = Integer.parseInt(gp.getKey());
//
p.newProcessThread(command, processID);
processList.add(processList.size(), p);
//zorgen dat service kan herstarten zonder afsluiten dochterprocessen
p.setDaemon(false);
p.start();
//counter += 1;
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Process id: " + processID);
log.info("Process id: " + processID);
} catch (Exception e) {
processList.remove(p);
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Problem starting task: " + e.getMessage());
log.info("Problem starting task: " + e.getMessage());
//Zet het gewenste process op status 10 (Error)
gp.updateStatus(dbConnection, 10);
}
}
} else {
//LoggerWrapper.myLogger.log(Level.INFO, "{0}", "Cannot add process, current number of processes: " + processList.size());
log.info("Cannot add process, current number of processes: " + processList.size());
}
//RB sluiten van de DBconnectie
PacsDatabaseConnection.closeDb(dbConnection, null, null);
//LoggerWrapper.myLogger.log(Level.INFO, "Einde cyclus processor.");
log.info("Einde cyclus processor.");
//RB
//RB Sluiten applicatie voor testdoeleinden, gebruik setting in config.xml
if (ReadConfigXML.readSettingsElement("stop").equals("1")) {
if (teller == 5) {
//System.out.println(datum+" "+<SUF>
//LoggerWrapper.myLogger.log(Level.INFO, "Afsluiten processor.");
log.info("Afsluiten processor.");
this.cancel();
System.exit(0);
}
}
//RB Einde afsluiten.
}
private boolean matchExtension(String filename, String ext) {
int dot = filename.lastIndexOf(".");
if (filename.substring(dot + 1).equals(ext)) {
return true;
} else {
return false;
}
}
private void processFinishedProcess(Connection dbConnection, GewensteProces gp) {
// aanpassen bij absoluut filepath voor XML in config.xml
String output = ReadConfigXML.readFileElement("XML") + ReadFromIqcDatabase.getFilenameFromTable(dbConnection, "analysemodule_output", gp.getOutputKey());
output = output.replace("/", File.separator);
gp.updateStatus(dbConnection, 3);
AnalyseModuleResultFile resultFile = new AnalyseModuleResultFile(output);
Boolean succes = resultFile.read();
if (succes) {
gp.updateStatus(dbConnection, 4);
WriteResultaten writeResultaten = new WriteResultaten(dbConnection, resultFile, Integer.parseInt(gp.getKey()));
gp.updateStatus(dbConnection, 5);
} else {
log.error("Problemen bij het verwerken van result.xml behorende bij proces "+gp.getKey());
gp.updateStatus(dbConnection, 10);
}
// voeg processor.log toe aan DB als object met volgnummer 999 op niveau 2
// FIXME: Hiermee wordt de logfile voor alle exit-statussen opgeslagen.
// Als we deze alleen bij succes=false willen opslaan, deze routine bovenaan
// de functie zetten.
String outputFolder = output.substring(0,output.lastIndexOf(File.separator));
try {
PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO resultaten_object("
+ "niveau, "
+ "gewenste_processen_fk, "
+ "omschrijving, "
+ "volgnummer, "
+ "object_naam_pad) "
+ "values (?,?,?,?,?)");
pstmt.setString(1, "2");
pstmt.setInt(2, Integer.parseInt(gp.getKey()));
pstmt.setString(3, "processor.log");
pstmt.setString(4, "999");
pstmt.setString(5, outputFolder+File.separator+"processor.log");
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException ex) {
log.error(ex);
}
}
}
|
108717_1 | package DAO.Adres;
import DAO.Reiziger.ReizigerDAO;
import Domein.Adres;
import Domein.Reiziger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AdresDAOsql implements AdresDAO{
private Connection connection;
private ReizigerDAO rdao;
public AdresDAOsql(Connection connection) {
this.connection = connection;
}
public void setRdao(ReizigerDAO rdao) {
this.rdao = rdao;
}
@Override
public boolean save(Adres adres) {
try {
String sqlQuery = "INSERT INTO adres VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, adres.getAdres_id());
ps.setString(2, adres.getPostcode());
ps.setString(3, adres.getHuisnummer());
ps.setString(4, adres.getStraat());
ps.setString(5, adres.getWoonplaats());
ps.setInt(6, adres.getReiziger().getReiziger_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("Something went wrong!\n" + e.getMessage());
return false;
}
}
@Override
public boolean update(Adres adres) {
try {
String sqlQuery = "UPDATE adres SET postcode=?, huisnummer=?, straat=?, woonplaats=? WHERE adres_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setString(1, adres.getPostcode());
ps.setString(2, adres.getHuisnummer());
ps.setString(3, adres.getStraat());
ps.setString(4, adres.getStraat());
ps.setInt(5, adres.getAdres_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("The program failed to update the adres!\n" + e.getMessage());
return false;
}
}
@Override
public boolean delete(Adres adres) {
try {
String sqlQuery = "DELETE FROM adres WHERE adres_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, adres.getAdres_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("The program failed to delete the adres!\n" + e.getMessage());
return false;
}
}
@Override
public Adres findByReiziger(Reiziger reiziger) {
try {
String sqlQuery = "SELECT * FROM adres WHERE reiziger_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, reiziger.getReiziger_id());
ResultSet rs = ps.executeQuery();
rs.next();
// de reiziger werd ten onrechte uit de database gehaald en dat had ik al in een eerdere commit gefixt hetzelfde geld bij findAll
return new Adres(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), reiziger);
} catch (SQLException e) {
if(e.getMessage().equals("ResultSet not positioned properly, perhaps you need to call next.")) {
return null;
}
System.out.println("Couldn't find Adres!\n" + e.getMessage());
return null;
}
}
@Override
public List<Adres> findAll() {
try {
String sqlQuery = "SELECT * FROM adres";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ResultSet rs = ps.executeQuery();
List<Adres> alleAdressen = new ArrayList<>();
while (rs.next()) {
// findAll haalt nu ook de reiziger op bij het adres, hij is toegevoegd aan het einde van de line hieronder
alleAdressen.add(new Adres(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rdao.findById(rs.getInt(6))));
}
return alleAdressen;
} catch (SQLException e) {
System.out.println("Something went wrong!\n" + e.getMessage());
return null;
}
}
}
| BramdeGooijer/DP_OV-Chipkaart | src/main/java/DAO/Adres/AdresDAOsql.java | 1,105 | // findAll haalt nu ook de reiziger op bij het adres, hij is toegevoegd aan het einde van de line hieronder | line_comment | nl | package DAO.Adres;
import DAO.Reiziger.ReizigerDAO;
import Domein.Adres;
import Domein.Reiziger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AdresDAOsql implements AdresDAO{
private Connection connection;
private ReizigerDAO rdao;
public AdresDAOsql(Connection connection) {
this.connection = connection;
}
public void setRdao(ReizigerDAO rdao) {
this.rdao = rdao;
}
@Override
public boolean save(Adres adres) {
try {
String sqlQuery = "INSERT INTO adres VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, adres.getAdres_id());
ps.setString(2, adres.getPostcode());
ps.setString(3, adres.getHuisnummer());
ps.setString(4, adres.getStraat());
ps.setString(5, adres.getWoonplaats());
ps.setInt(6, adres.getReiziger().getReiziger_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("Something went wrong!\n" + e.getMessage());
return false;
}
}
@Override
public boolean update(Adres adres) {
try {
String sqlQuery = "UPDATE adres SET postcode=?, huisnummer=?, straat=?, woonplaats=? WHERE adres_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setString(1, adres.getPostcode());
ps.setString(2, adres.getHuisnummer());
ps.setString(3, adres.getStraat());
ps.setString(4, adres.getStraat());
ps.setInt(5, adres.getAdres_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("The program failed to update the adres!\n" + e.getMessage());
return false;
}
}
@Override
public boolean delete(Adres adres) {
try {
String sqlQuery = "DELETE FROM adres WHERE adres_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, adres.getAdres_id());
ps.execute();
ps.close();
return true;
} catch (SQLException e) {
System.out.println("The program failed to delete the adres!\n" + e.getMessage());
return false;
}
}
@Override
public Adres findByReiziger(Reiziger reiziger) {
try {
String sqlQuery = "SELECT * FROM adres WHERE reiziger_id=?";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ps.setInt(1, reiziger.getReiziger_id());
ResultSet rs = ps.executeQuery();
rs.next();
// de reiziger werd ten onrechte uit de database gehaald en dat had ik al in een eerdere commit gefixt hetzelfde geld bij findAll
return new Adres(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), reiziger);
} catch (SQLException e) {
if(e.getMessage().equals("ResultSet not positioned properly, perhaps you need to call next.")) {
return null;
}
System.out.println("Couldn't find Adres!\n" + e.getMessage());
return null;
}
}
@Override
public List<Adres> findAll() {
try {
String sqlQuery = "SELECT * FROM adres";
PreparedStatement ps = connection.prepareStatement(sqlQuery);
ResultSet rs = ps.executeQuery();
List<Adres> alleAdressen = new ArrayList<>();
while (rs.next()) {
// findAll haalt<SUF>
alleAdressen.add(new Adres(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rdao.findById(rs.getInt(6))));
}
return alleAdressen;
} catch (SQLException e) {
System.out.println("Something went wrong!\n" + e.getMessage());
return null;
}
}
}
|
19024_3 | // dit schrijft onderstaande cell naar een file in de huidige directory
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
// Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{
// hier komt de mapfunctie in
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// map functie leest lijn per lijn
// lijn splitsen in woorden
// hello world
StringTokenizer itr = new StringTokenizer(value.toString());
// itr = [hello, world]
while(itr.hasMoreTokens()){
// hier zitten we woord per woord te lezen
// stuur voor elk woord (woord, 1)
Text word = new Text();
word.set(itr.nextToken());
System.out.println(word.toString());
context.write(word, new IntWritable(1));
// (hello, 1)
// (word, 1)
}
}
}
// Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// key = hello, values = [1, 1, 1, 1]
int sum = 0;
for (IntWritable val: values) {
sum += val.get();
}
System.out.println(sum);
context.write(key, new IntWritable(sum));
}
}
// configure the MapReduce program
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count java");
job.setJarByClass(WordCount.class);
// configure mapper
job.setMapperClass(WCMapper.class);
// configure combiner (soort van reducer die draait op mapping node voor performantie)
job.setCombinerClass(WCReducer.class);
// configure reducer
job.setReducerClass(WCReducer.class);
// set output key-value classes
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// set input file (first argument passed to the program)
FileInputFormat.addInputPath(job, new Path(args[0]));
// set output file (second argument passed to the program)
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// In this case, we wait for completion to get the output/logs and not stop the program to early.
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| OdiseeBigData2223/Leerstof | Week 2/WordCount.java | 838 | // map functie leest lijn per lijn | line_comment | nl | // dit schrijft onderstaande cell naar een file in de huidige directory
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
// Mapper -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCMapper extends Mapper<Object, Text, Text, IntWritable>{
// hier komt de mapfunctie in
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// map functie<SUF>
// lijn splitsen in woorden
// hello world
StringTokenizer itr = new StringTokenizer(value.toString());
// itr = [hello, world]
while(itr.hasMoreTokens()){
// hier zitten we woord per woord te lezen
// stuur voor elk woord (woord, 1)
Text word = new Text();
word.set(itr.nextToken());
System.out.println(word.toString());
context.write(word, new IntWritable(1));
// (hello, 1)
// (word, 1)
}
}
}
// Reducer -> classes tussen <> zijn de classen van de (input key, input_value, output_key, output_value)
public static class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// key = hello, values = [1, 1, 1, 1]
int sum = 0;
for (IntWritable val: values) {
sum += val.get();
}
System.out.println(sum);
context.write(key, new IntWritable(sum));
}
}
// configure the MapReduce program
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count java");
job.setJarByClass(WordCount.class);
// configure mapper
job.setMapperClass(WCMapper.class);
// configure combiner (soort van reducer die draait op mapping node voor performantie)
job.setCombinerClass(WCReducer.class);
// configure reducer
job.setReducerClass(WCReducer.class);
// set output key-value classes
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// set input file (first argument passed to the program)
FileInputFormat.addInputPath(job, new Path(args[0]));
// set output file (second argument passed to the program)
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// In this case, we wait for completion to get the output/logs and not stop the program to early.
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
10496_6 | import java.awt.Color;
import solar.util.Vector3D;
/**
* Balk maakt voorwerpen van type balk aan. Het is een subklasse van Voorwerp.
*
* @Auteurs: Van Damme Wim, Vander Mynsbrugge Jorrit, Vandermeersch Antoine
* @Versie: 11/05/06
*/
public class Balk extends Voorwerp
{
// onthoudt de lengte van de balk
protected int lengte;
// onthoudt de hoogte van de balk
protected int hoogte;
// onthoudt de breedte van de balk
protected int breedte;
// een Vector3D array om de verschillende hoekpunten van de balk bij te houden
protected Vector3D[] hoekpunt;
/**
* Constructor voor objecten van klasse Balk.
*/
public Balk(Vector3D coZon, String kleur, String materiaal, double x, double y, double z, int lengte, int breedte, int hoogte)
{
// Parameters als kleur, locatie ankerpunt, zonrichtings-vector en materiaal worden doorgegeven naar de superklasse.
super(coZon,kleur,materiaal,x,y,z);
// aanmaken van de afmetingen van de balk.
this.lengte = lengte;
this.breedte = breedte;
this.hoogte = hoogte;
// aanmaken van een Vector3D[] Array die de hoekpuntcoordinaten van het prisma zal opslaan.;
hoekpunt = new Vector3D[8];
// initialiseren van de vlakken van de balk.
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
// hoekpunten, vlakken en schduwvlakken worden meteen berekend.
zoekHoekpunten();
maakVlakken();
maakSchaduwVlakken();
}
/**
* zoekHoekPunten - op basis van de locatie (ankerpunt) en de lengte, breedte, hoogte worden de hoekpunten van de balk samengesteld.
*
* @param none
* @return void
*/
public void zoekHoekpunten()
{
hoekpunt[0]= new Vector3D(locatie.getX()-lengte/2,locatie.getY()-breedte/2,locatie.getZ());
hoekpunt[1] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()-breedte/2,locatie.getZ());
hoekpunt[2] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()+breedte/2,locatie.getZ());
hoekpunt[3] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()+breedte/2,locatie.getZ());
hoekpunt[4] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()-breedte/2,locatie.getZ()+hoogte);
hoekpunt[5] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()-breedte/2,locatie.getZ()+hoogte);
hoekpunt[6] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()+breedte/2,locatie.getZ()+hoogte);
hoekpunt[7] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()+breedte/2,locatie.getZ()+hoogte);
}
/**
* maakVlakken - de verschillende vlakken worden rechtstreeks berekend en nadien in de ArrayList van vlakken in de superklasse
* opgeslagen. Om de conventie (juiste richting normaal) te behouden wordt de 'set'-methode van klasse ArrayList aanroepen, en de
* volgorde van de vlakken te garanderen.
*
* @param none
* @return void
*/
public void maakVlakken()
{
// maakt ondervlak en voegt ze toe aan de arraylist vlakken
Vector3D[] vierhoek = new Vector3D[]{hoekpunt[0],hoekpunt[1],hoekpunt[2],hoekpunt[3]};
Vlak ondervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(0,ondervlak);
// maakt bovenvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[4],hoekpunt[5],hoekpunt[6],hoekpunt[7]};
Vlak bovenvlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(1,bovenvlak);
// maakt linkerzijvlak voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[0],hoekpunt[1],hoekpunt[5],hoekpunt[4]};
Vlak linkervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(2,linkervlak);
// maakt rechterzijvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[7],hoekpunt[6],hoekpunt[2],hoekpunt[3]};
Vlak rechtervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(3,rechtervlak);
// maakt voorvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[1],hoekpunt[2],hoekpunt[6],hoekpunt[5]};
Vlak voorvlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(4,voorvlak);
// maakt achtervlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[4],hoekpunt[7],hoekpunt[3],hoekpunt[0]};
Vlak achtervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(5,achtervlak);
}
/**
* setDimensies - wijzigt de huidige afmetingen van de balk.
*
* @param int[] dimensies - nieuwe afmetingen
* @return void
*/
public void setDimensies(int[] dimensies)
{
lengte = dimensies[0];
breedte = dimensies[1];
hoogte = dimensies[2];
}
/**
* getVolume - met behulp van de volume-definitie van een balk en de huidige afmetingen wordt het volume berekend.
*
* @param none
* @return double volume - totaal volume van de balk
*/
public double getVolume()
{
double volume = breedte*lengte*hoogte;
return volume;
}
/**
* getLbh - geeft de afmetingen (lengte-breedte-hoogte) van de balk terug, opgeslagen in een 'intage' array.
*
* @param none
* @return int[] lbh - array met afmetingen van de balk
*/
public int[] getLbh()
{
int[] lbh = new int[3];
lbh[0] = lengte;
lbh[1] = breedte;
lbh[2] = hoogte;
return lbh;
}
} | jorritvm/solar | src/Balk.java | 1,850 | // Parameters als kleur, locatie ankerpunt, zonrichtings-vector en materiaal worden doorgegeven naar de superklasse. | line_comment | nl | import java.awt.Color;
import solar.util.Vector3D;
/**
* Balk maakt voorwerpen van type balk aan. Het is een subklasse van Voorwerp.
*
* @Auteurs: Van Damme Wim, Vander Mynsbrugge Jorrit, Vandermeersch Antoine
* @Versie: 11/05/06
*/
public class Balk extends Voorwerp
{
// onthoudt de lengte van de balk
protected int lengte;
// onthoudt de hoogte van de balk
protected int hoogte;
// onthoudt de breedte van de balk
protected int breedte;
// een Vector3D array om de verschillende hoekpunten van de balk bij te houden
protected Vector3D[] hoekpunt;
/**
* Constructor voor objecten van klasse Balk.
*/
public Balk(Vector3D coZon, String kleur, String materiaal, double x, double y, double z, int lengte, int breedte, int hoogte)
{
// Parameters als<SUF>
super(coZon,kleur,materiaal,x,y,z);
// aanmaken van de afmetingen van de balk.
this.lengte = lengte;
this.breedte = breedte;
this.hoogte = hoogte;
// aanmaken van een Vector3D[] Array die de hoekpuntcoordinaten van het prisma zal opslaan.;
hoekpunt = new Vector3D[8];
// initialiseren van de vlakken van de balk.
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
vlakken.add(null);
// hoekpunten, vlakken en schduwvlakken worden meteen berekend.
zoekHoekpunten();
maakVlakken();
maakSchaduwVlakken();
}
/**
* zoekHoekPunten - op basis van de locatie (ankerpunt) en de lengte, breedte, hoogte worden de hoekpunten van de balk samengesteld.
*
* @param none
* @return void
*/
public void zoekHoekpunten()
{
hoekpunt[0]= new Vector3D(locatie.getX()-lengte/2,locatie.getY()-breedte/2,locatie.getZ());
hoekpunt[1] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()-breedte/2,locatie.getZ());
hoekpunt[2] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()+breedte/2,locatie.getZ());
hoekpunt[3] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()+breedte/2,locatie.getZ());
hoekpunt[4] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()-breedte/2,locatie.getZ()+hoogte);
hoekpunt[5] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()-breedte/2,locatie.getZ()+hoogte);
hoekpunt[6] = new Vector3D(locatie.getX()+lengte/2,locatie.getY()+breedte/2,locatie.getZ()+hoogte);
hoekpunt[7] = new Vector3D(locatie.getX()-lengte/2,locatie.getY()+breedte/2,locatie.getZ()+hoogte);
}
/**
* maakVlakken - de verschillende vlakken worden rechtstreeks berekend en nadien in de ArrayList van vlakken in de superklasse
* opgeslagen. Om de conventie (juiste richting normaal) te behouden wordt de 'set'-methode van klasse ArrayList aanroepen, en de
* volgorde van de vlakken te garanderen.
*
* @param none
* @return void
*/
public void maakVlakken()
{
// maakt ondervlak en voegt ze toe aan de arraylist vlakken
Vector3D[] vierhoek = new Vector3D[]{hoekpunt[0],hoekpunt[1],hoekpunt[2],hoekpunt[3]};
Vlak ondervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(0,ondervlak);
// maakt bovenvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[4],hoekpunt[5],hoekpunt[6],hoekpunt[7]};
Vlak bovenvlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(1,bovenvlak);
// maakt linkerzijvlak voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[0],hoekpunt[1],hoekpunt[5],hoekpunt[4]};
Vlak linkervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(2,linkervlak);
// maakt rechterzijvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[7],hoekpunt[6],hoekpunt[2],hoekpunt[3]};
Vlak rechtervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(3,rechtervlak);
// maakt voorvlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[1],hoekpunt[2],hoekpunt[6],hoekpunt[5]};
Vlak voorvlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(4,voorvlak);
// maakt achtervlak en voegt ze toe aan de arraylist vlakken
vierhoek = new Vector3D[]{hoekpunt[4],hoekpunt[7],hoekpunt[3],hoekpunt[0]};
Vlak achtervlak = new Vlak(hoofdkleur,vierhoek);
vlakken.set(5,achtervlak);
}
/**
* setDimensies - wijzigt de huidige afmetingen van de balk.
*
* @param int[] dimensies - nieuwe afmetingen
* @return void
*/
public void setDimensies(int[] dimensies)
{
lengte = dimensies[0];
breedte = dimensies[1];
hoogte = dimensies[2];
}
/**
* getVolume - met behulp van de volume-definitie van een balk en de huidige afmetingen wordt het volume berekend.
*
* @param none
* @return double volume - totaal volume van de balk
*/
public double getVolume()
{
double volume = breedte*lengte*hoogte;
return volume;
}
/**
* getLbh - geeft de afmetingen (lengte-breedte-hoogte) van de balk terug, opgeslagen in een 'intage' array.
*
* @param none
* @return int[] lbh - array met afmetingen van de balk
*/
public int[] getLbh()
{
int[] lbh = new int[3];
lbh[0] = lengte;
lbh[1] = breedte;
lbh[2] = hoogte;
return lbh;
}
} |
29160_63 | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = -1; // 630;
public static final int ZONE_HEIGHT = 580; // 630;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_include[] = new String[] { "javascript.include", "javascript.src" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
public static final String PROP_createMapCallback[] = new String[] { "createMapCallback" }; // String (JSMap provider JS)
public static final String PROP_postMapInitCallback[] = new String[] { "postMapInitCallback" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
** /
public int getZoneWidth();
*/
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
** /
public int getZoneHeight();
*/
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Gets the default zoom/scale level for this MapProvider when no pushpins are displayed
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getDefaultZoom(int dft);
/**
*** Gets the default zoom/scale level for this MapProvider when displaying pushpins
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getPushpinZoom(int dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
//@Deprecated
//public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
| GBPA/OpenGTS | src/org/opengts/war/tools/MapProvider.java | 5,988 | // dbl/int (default zoom without points) | line_comment | nl | // ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = -1; // 630;
public static final int ZONE_HEIGHT = 580; // 630;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default<SUF>
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_include[] = new String[] { "javascript.include", "javascript.src" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
public static final String PROP_createMapCallback[] = new String[] { "createMapCallback" }; // String (JSMap provider JS)
public static final String PROP_postMapInitCallback[] = new String[] { "postMapInitCallback" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
** /
public int getZoneWidth();
*/
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
** /
public int getZoneHeight();
*/
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Gets the default zoom/scale level for this MapProvider when no pushpins are displayed
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getDefaultZoom(int dft);
/**
*** Gets the default zoom/scale level for this MapProvider when displaying pushpins
*** @param dft The default zoom/scale returned if this MapProvider does not explicitly define a value
*** @return The default zoom level
**/
public int getPushpinZoom(int dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
//@Deprecated
//public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
|
10498_4 | package novi.basics;
import static novi.basics.Main.PLAYERINPUT;
public class Game {
private Field[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
//constructor
public Game(Player player1, Player player2) {
// speelbord opslaan (1 - 9)
// uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven
// zie demo project code voor de andere manier met de for loop
//board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};
board = new Field[9];
for (int fieldIndex = 0; fieldIndex < 9; fieldIndex++) {
board[fieldIndex] = new Field(fieldIndex + 1);
}
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
String activePlayerName = activePlayer.getName();
// actieve speler vragen om een veld te kiezen (1 - 9)
System.out.println(activePlayerName + ", please choose a field");
//setField();
// gekozen veld van de actieve speler opslaan
int chosenField = PLAYERINPUT.nextInt();
int chosenIndex = chosenField - 1;
// als het veld bestaat
if(chosenIndex < 9 && chosenIndex >= 0) {
//als het veld leeg is, wanneer er geen token staat
if(board[chosenIndex].isEmpty()) {
// wanneer de speler een token op het bord kan plaatsen
// de token van de actieve speler op het gekozen veld plaatsen
char token = activePlayer.getToken();
board[chosenIndex].setToken(token);
// het nieuwe speelbord tonen
printBoard();
// als het spel gewonnen is
// tonen wie er gewonnen heeft (de actieve speler)
// de actieve speler krijgt een punt
// de scores van de spelers tonen
// wanneer we in de laatste beurt zijn en niemand gewonnen heeft
// aantal keer gelijk spel ophogen
// aantal keer gelijk spel tonen
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
//changePlayer();
if(activePlayer == player1) {
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
}
// als het veld niet bestaat
else {
// het mamimale aantal beurten verhogen
maxRounds++;
// foutmelding tonen aan de speler
System.out.println("the chosen field does not exist, try again");
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex].getToken() + " ");
// als we het tweede veld geprint hebben of het vijfde veld geprint hebben
// dan gaan we naar de volgende regel
if(fieldIndex == 2 || fieldIndex == 5) {
System.out.println();
}
}
System.out.println();
}
}
| hogeschoolnovi/tic-tac-toe-novidennis | src/novi/basics/Game.java | 1,017 | // maximale aantal rondes opslaan | line_comment | nl | package novi.basics;
import static novi.basics.Main.PLAYERINPUT;
public class Game {
private Field[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
//constructor
public Game(Player player1, Player player2) {
// speelbord opslaan (1 - 9)
// uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven
// zie demo project code voor de andere manier met de for loop
//board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'};
board = new Field[9];
for (int fieldIndex = 0; fieldIndex < 9; fieldIndex++) {
board[fieldIndex] = new Field(fieldIndex + 1);
}
// maximale aantal<SUF>
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
String activePlayerName = activePlayer.getName();
// actieve speler vragen om een veld te kiezen (1 - 9)
System.out.println(activePlayerName + ", please choose a field");
//setField();
// gekozen veld van de actieve speler opslaan
int chosenField = PLAYERINPUT.nextInt();
int chosenIndex = chosenField - 1;
// als het veld bestaat
if(chosenIndex < 9 && chosenIndex >= 0) {
//als het veld leeg is, wanneer er geen token staat
if(board[chosenIndex].isEmpty()) {
// wanneer de speler een token op het bord kan plaatsen
// de token van de actieve speler op het gekozen veld plaatsen
char token = activePlayer.getToken();
board[chosenIndex].setToken(token);
// het nieuwe speelbord tonen
printBoard();
// als het spel gewonnen is
// tonen wie er gewonnen heeft (de actieve speler)
// de actieve speler krijgt een punt
// de scores van de spelers tonen
// wanneer we in de laatste beurt zijn en niemand gewonnen heeft
// aantal keer gelijk spel ophogen
// aantal keer gelijk spel tonen
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
//changePlayer();
if(activePlayer == player1) {
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
}
// als het veld niet bestaat
else {
// het mamimale aantal beurten verhogen
maxRounds++;
// foutmelding tonen aan de speler
System.out.println("the chosen field does not exist, try again");
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex].getToken() + " ");
// als we het tweede veld geprint hebben of het vijfde veld geprint hebben
// dan gaan we naar de volgende regel
if(fieldIndex == 2 || fieldIndex == 5) {
System.out.println();
}
}
System.out.println();
}
}
|
24531_0 | package me.boykev.kitpvp;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class EventManager implements Listener{
public EventManager(Main main) {
this.instance = main;
}
private Main instance;
private ConfigManager cm;
private MapManager mm;
public void onSignClick(PlayerInteractEvent e) {
//Hier moet nog wat mee gebeuren, stop met zeuren dat het nog niet gebruikt wordt, i know the fkng issue. Dankje <3
HashMap<Player, Integer> mapid = instance.mapid;
cm = new ConfigManager(instance);
mm = new MapManager(instance);
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(e.getClickedBlock().getType() == Material.SIGN || e.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign sign = (Sign) e.getClickedBlock().getState();
String signpref = ChatColor.translateAlternateColorCodes('&', cm.getConfig().getString("Sign-Prefix"));
Player p = (Player) e.getPlayer();
if(sign.getLine(0).equalsIgnoreCase(signpref)) {
String mapname = sign.getLine(1).toString().toUpperCase();
if(mm.getConfig().getConfigurationSection(mapname) == null) {
p.sendMessage(ChatColor.RED + "Oeps, deze map lijkt niet te bestaan. Neem contact op met een Developer!");
return;
}
// mapid.put(p, key); < To be inserted if shit is done
//Hier de code die uitgevoerd moet worden als een sign is aangeklikt en de map bestaat (On-Hold voor het ID systeem)
}
return;
}
return;
}
return;
}//end of ClickEvent
public void onSignChange(SignChangeEvent e) {
cm = new ConfigManager(instance);
String signpref = ChatColor.translateAlternateColorCodes('&', cm.getConfig().getString("Sign-Prefix"));
if(!e.getPlayer().hasPermission("kitpvp.sign")) {
e.getPlayer().sendMessage(ChatColor.RED + "Oeps, je hebt niet de permissies om deze signs te maken!");
return;
}
if(e.getLine(0).equalsIgnoreCase("[kitpvp]")) {
if(e.getLine(1).isBlank()) {
e.getPlayer().sendMessage(ChatColor.RED + "Je hebt de sign niet goed opgesteld! Probeer het opnieuw");
return;
}
e.setLine(0, signpref);
e.setLine(1, e.getLine(1).toString().toUpperCase());
return;
}
}
}
| JustBoyke/DDGKitpvp | kitpvp/src/main/java/me/boykev/kitpvp/EventManager.java | 756 | //Hier moet nog wat mee gebeuren, stop met zeuren dat het nog niet gebruikt wordt, i know the fkng issue. Dankje <3
| line_comment | nl | package me.boykev.kitpvp;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class EventManager implements Listener{
public EventManager(Main main) {
this.instance = main;
}
private Main instance;
private ConfigManager cm;
private MapManager mm;
public void onSignClick(PlayerInteractEvent e) {
//Hier moet<SUF>
HashMap<Player, Integer> mapid = instance.mapid;
cm = new ConfigManager(instance);
mm = new MapManager(instance);
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(e.getClickedBlock().getType() == Material.SIGN || e.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign sign = (Sign) e.getClickedBlock().getState();
String signpref = ChatColor.translateAlternateColorCodes('&', cm.getConfig().getString("Sign-Prefix"));
Player p = (Player) e.getPlayer();
if(sign.getLine(0).equalsIgnoreCase(signpref)) {
String mapname = sign.getLine(1).toString().toUpperCase();
if(mm.getConfig().getConfigurationSection(mapname) == null) {
p.sendMessage(ChatColor.RED + "Oeps, deze map lijkt niet te bestaan. Neem contact op met een Developer!");
return;
}
// mapid.put(p, key); < To be inserted if shit is done
//Hier de code die uitgevoerd moet worden als een sign is aangeklikt en de map bestaat (On-Hold voor het ID systeem)
}
return;
}
return;
}
return;
}//end of ClickEvent
public void onSignChange(SignChangeEvent e) {
cm = new ConfigManager(instance);
String signpref = ChatColor.translateAlternateColorCodes('&', cm.getConfig().getString("Sign-Prefix"));
if(!e.getPlayer().hasPermission("kitpvp.sign")) {
e.getPlayer().sendMessage(ChatColor.RED + "Oeps, je hebt niet de permissies om deze signs te maken!");
return;
}
if(e.getLine(0).equalsIgnoreCase("[kitpvp]")) {
if(e.getLine(1).isBlank()) {
e.getPlayer().sendMessage(ChatColor.RED + "Je hebt de sign niet goed opgesteld! Probeer het opnieuw");
return;
}
e.setLine(0, signpref);
e.setLine(1, e.getLine(1).toString().toUpperCase());
return;
}
}
}
|
51844_24 | package com.example.simonjang.activities_excercise1;
import android.app.ActionBar;
import android.hardware.Camera;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextView; // Declareert een private TextView voor in de layout
private Camera mCamera;
private int mCurrentScore;
private int mCurrentLevel;
private final String STATE_SCORE = "playerScore";
private final String STATE_LEVEL = "playerLevel";
// Eerste methode wanneer een activity wordt gestart
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Laadt de savedinstance
setContentView(R.layout.activity_main); // Laadt de layout van de res
mTextView = (TextView) findViewById(R.id.text_message); // Initialiseert de mTextView zodat
// die later kan worden gemanipuleerd
/*
Controleert of de correcte versie wordt gebruikt voor de ActionBar APIs
*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar doesn't behave
// as a button
ActionBar actionbar = getActionBar();
actionbar.setHomeButtonEnabled(false);
}
}
// Wanneer de activity wordt vernietigd
@Override
public void onDestroy() {
super.onDestroy(); // Altijd de superklasse aanroepen
}
// Waneer de huidige activity de focus verliest. De huidige activity is nog steeds half zichtbaar
// Belangrijk om tijdens onPause()
// - Controleren of de app nog steeds zichtbaar is
// - Alle unsaved changes committen, maar enkel permanent opslaan wanneer de gebruiker de activity definitief stopt
// - Alle system resources releasen om battery liffe te sparen
@Override
public void onPause() {
super.onPause(); // Altijd de superklasse methode eerst aanroepen
if(mCamera != null) {
mCamera.release();
mCamera = null;
}
}
// Wordt aangeroepen wanneer een gebruiker een activiteit herneemt die in Paused state was
// Deze methode wordt telkens opnieuw aangeroepen wanneer aan activiteit terug op de voorgrond komt
// Componenten die released werden tijdens onPause() moeten dus opnieuw worden herinitialiseerd
@Override
public void onResume() {
super.onResume(); // Altijd de superklasse methode eerst aanroepen
if(mCamera == null) {
initializeCamera();
}
}
// Lokale methode die initialiseren van de camera tot zich neemt
private void initializeCamera() {
mCamera = Camera.open();
}
// Wordt aangeroepen wanneer de gebruiker een andere activity start
// of
// een nieuwe applicatie opent
@Override
public void onStop() {
super.onStop(); // altijd de superklasse methode eerst aanroepen
}
// Deze methode wordt aangeroepen wanneer de applicatie van Paused state naar Resumed State gaat
@Override
public void onRestart() {
super.onRestart();
}
// Wanneer een activiteit stopt wordt de onSaveInstanceState() methode aangeroepen
// Hierbij heb je dan de mogelijk om informatie in de bundle op te slaan
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Plaatst 2 waarden in de bundle
savedInstanceState.putInt(STATE_SCORE, 100);
savedInstanceState.putInt(STATE_LEVEL, 2);
// Always call the superclass so it can save the view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
}
| SimonJang/AndroidStudioProjects | Activities_Excercise1/app/src/main/java/com/example/simonjang/activities_excercise1/MainActivity.java | 957 | // altijd de superklasse methode eerst aanroepen | line_comment | nl | package com.example.simonjang.activities_excercise1;
import android.app.ActionBar;
import android.hardware.Camera;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextView; // Declareert een private TextView voor in de layout
private Camera mCamera;
private int mCurrentScore;
private int mCurrentLevel;
private final String STATE_SCORE = "playerScore";
private final String STATE_LEVEL = "playerLevel";
// Eerste methode wanneer een activity wordt gestart
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Laadt de savedinstance
setContentView(R.layout.activity_main); // Laadt de layout van de res
mTextView = (TextView) findViewById(R.id.text_message); // Initialiseert de mTextView zodat
// die later kan worden gemanipuleerd
/*
Controleert of de correcte versie wordt gebruikt voor de ActionBar APIs
*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar doesn't behave
// as a button
ActionBar actionbar = getActionBar();
actionbar.setHomeButtonEnabled(false);
}
}
// Wanneer de activity wordt vernietigd
@Override
public void onDestroy() {
super.onDestroy(); // Altijd de superklasse aanroepen
}
// Waneer de huidige activity de focus verliest. De huidige activity is nog steeds half zichtbaar
// Belangrijk om tijdens onPause()
// - Controleren of de app nog steeds zichtbaar is
// - Alle unsaved changes committen, maar enkel permanent opslaan wanneer de gebruiker de activity definitief stopt
// - Alle system resources releasen om battery liffe te sparen
@Override
public void onPause() {
super.onPause(); // Altijd de superklasse methode eerst aanroepen
if(mCamera != null) {
mCamera.release();
mCamera = null;
}
}
// Wordt aangeroepen wanneer een gebruiker een activiteit herneemt die in Paused state was
// Deze methode wordt telkens opnieuw aangeroepen wanneer aan activiteit terug op de voorgrond komt
// Componenten die released werden tijdens onPause() moeten dus opnieuw worden herinitialiseerd
@Override
public void onResume() {
super.onResume(); // Altijd de superklasse methode eerst aanroepen
if(mCamera == null) {
initializeCamera();
}
}
// Lokale methode die initialiseren van de camera tot zich neemt
private void initializeCamera() {
mCamera = Camera.open();
}
// Wordt aangeroepen wanneer de gebruiker een andere activity start
// of
// een nieuwe applicatie opent
@Override
public void onStop() {
super.onStop(); // altijd de<SUF>
}
// Deze methode wordt aangeroepen wanneer de applicatie van Paused state naar Resumed State gaat
@Override
public void onRestart() {
super.onRestart();
}
// Wanneer een activiteit stopt wordt de onSaveInstanceState() methode aangeroepen
// Hierbij heb je dan de mogelijk om informatie in de bundle op te slaan
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Plaatst 2 waarden in de bundle
savedInstanceState.putInt(STATE_SCORE, 100);
savedInstanceState.putInt(STATE_LEVEL, 2);
// Always call the superclass so it can save the view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}
}
|
31221_11 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Candy here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Candy extends World
{
private int score = 0;
private CollisionEngine ce;
Counter counter = new Counter();
/**
* Constructor for objects of class Candy.
*
*/
public Candy()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
//super(600, 400, 1);
super (900, 900, 1, false);
this.setBackground("candy.png");
showText("Wat is het engels woord voor snoep? verzamel de letters om om op het antwoord te komen", 450, 850);
int[][] map3 = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,171,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,165,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,-1,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,188,188,188,-1,-1,-1,-1,165,165,165,165,165,-1,-1,-1,-1,-1,-1,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,165,165,165,-1,-1,165,165,165,165,165,165,165,-1,165,165,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,188,188,-1,188,188,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,188,188,188,188,188,188,188,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,-1,165,165,-1,165,165,-1,-1,165,165,165,165,165,165,165,165,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,150,150,150,150,150,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,188,188,-1,-1,-1,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,188,188,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,188,188,188,-1,-1,-1,-1,188,188,188,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,165,150,150,150,165,-1,-1,-1,-1,165,150,150,150,165,-1,-1,-1,-1,188,188,188,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,127,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{165,165,165,165,165,90,90,165,165,165,165,165,90,90,165,165,165,165,165,90,90,165,165,90,90,165,165,-1,-1,165,165,165,165,165,-1,-1,165,150,150,150,150,150,165,-1,-1,165,150,150,150,150,150,165,-1,-1,165,165,165,165,165,-1,-1,165,150,150,150,165,-1,-1,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, map3);
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
int spawnX = 300;
int spawnY = 3032;
Hero hero = new Hero(181, 1563, 3);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 181, 1563);
addObject(new Enemy(), 1170, 410);
Scoreboard scoreboard = new Scoreboard();
addObject(scoreboard, 69, 29);
addObject(new Letter('C'), 1124, 1423);
addObject(new Letter('A'), 2184, 1423);
addObject(new Letter('N'), 3372, 1353);
addObject(new Letter('D'), 2730, 1003);
addObject(new Letter('Y'), 459, 443);
addObject(new Deur(), 385, 455);
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
public void increaseScore(){
score = score + 1;
}
private void prepare()
{
Hero hero = new Hero(181, 1563, 3);
addObject(counter, 100, 40);
}
public Counter getCounter()
{
return counter;
}
}
| ROCMondriaanTIN/project-greenfoot-game-AnasssArif | Candy.java | 7,967 | // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Candy here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Candy extends World
{
private int score = 0;
private CollisionEngine ce;
Counter counter = new Counter();
/**
* Constructor for objects of class Candy.
*
*/
public Candy()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
//super(600, 400, 1);
super (900, 900, 1, false);
this.setBackground("candy.png");
showText("Wat is het engels woord voor snoep? verzamel de letters om om op het antwoord te komen", 450, 850);
int[][] map3 = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,171,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,165,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,-1,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,188,188,188,-1,-1,-1,-1,165,165,165,165,165,-1,-1,-1,-1,-1,-1,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,165,165,165,-1,-1,165,165,165,165,165,165,165,-1,165,165,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,188,-1,188,188,-1,188,188,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,188,188,188,188,188,188,188,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,165,-1,165,165,-1,165,165,-1,-1,165,165,165,165,165,165,165,165,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,150,150,150,150,150,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,150,150,165,-1,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,188,188,-1,-1,-1,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,188,188,-1,-1,188,188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,188,188,188,-1,-1,-1,-1,188,188,188,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,222,-1,-1,-1,-1,-1,165,150,150,150,165,-1,-1,-1,-1,165,150,150,150,165,-1,-1,-1,-1,188,188,188,-1,-1,-1,-1,165,150,165,-1,-1,-1,-1,127,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{165,165,165,165,165,90,90,165,165,165,165,165,90,90,165,165,165,165,165,90,90,165,165,90,90,165,165,-1,-1,165,165,165,165,165,-1,-1,165,150,150,150,150,150,165,-1,-1,165,150,150,150,150,150,165,-1,-1,165,165,165,165,165,-1,-1,165,150,150,150,165,-1,-1,165,165,165,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,150,150,150,90,90,150,150,90,90,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,150,150,-1,-1,150,150,150,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, map3);
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
int spawnX = 300;
int spawnY = 3032;
Hero hero = new Hero(181, 1563, 3);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 181, 1563);
addObject(new Enemy(), 1170, 410);
Scoreboard scoreboard = new Scoreboard();
addObject(scoreboard, 69, 29);
addObject(new Letter('C'), 1124, 1423);
addObject(new Letter('A'), 2184, 1423);
addObject(new Letter('N'), 3372, 1353);
addObject(new Letter('D'), 2730, 1003);
addObject(new Letter('Y'), 459, 443);
addObject(new Deur(), 385, 455);
// Initialiseren van<SUF>
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
public void increaseScore(){
score = score + 1;
}
private void prepare()
{
Hero hero = new Hero(181, 1563, 3);
addObject(counter, 100, 40);
}
public Counter getCounter()
{
return counter;
}
}
|
62326_10 | /*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.ui;
import java.math.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.debugger.dummy.*;
import sun.jvm.hotspot.utilities.*;
/** A subclass of JPanel which displays a hex dump of memory along
with annotations describing the significance of various
pieces. This can be used to implement either a stack or heap
inspector. */
public class AnnotatedMemoryPanel extends JPanel {
private boolean is64Bit;
private Debugger debugger;
private long addressSize;
private HighPrecisionJScrollBar scrollBar;
private Font font;
private int bytesPerLine;
private int paintCount;
private String unmappedAddrString;
// Type of this is an IntervalTree indexed by Interval<Address> and
// with user data of type Annotation
private IntervalTree annotations =
new IntervalTree(new Comparator<>() {
public int compare(Object o1, Object o2) {
Address a1 = (Address) o1;
Address a2 = (Address) o2;
if ((a1 == null) && (a2 == null)) {
return 0;
} else if (a1 == null) {
return -1;
} else if (a2 == null) {
return 1;
}
if (a1.equals(a2)) {
return 0;
} else if (a1.lessThan(a2)) {
return -1;
}
return 1;
}
});
// Keep track of the last start address at which we painted, so we
// can scroll annotations
private Address lastStartAddr;
// This contains the list of currently-visible IntervalNodes, in
// sorted order by their low endpoint, in the form of a
// List<Annotation>. These annotations have already been laid out.
private java.util.List<Annotation> visibleAnnotations;
// Darker colors than defaults for better readability
private static Color[] colors = {
new Color(0.0f, 0.0f, 0.6f), // blue
new Color(0.6f, 0.0f, 0.6f), // magenta
new Color(0.0f, 0.8f, 0.0f), // green
new Color(0.8f, 0.3f, 0.0f), // orange
new Color(0.0f, 0.6f, 0.8f), // cyan
new Color(0.2f, 0.2f, 0.2f), // dark gray
};
/** Default is 32-bit mode */
public AnnotatedMemoryPanel(Debugger debugger) {
this(debugger, false);
}
public AnnotatedMemoryPanel(Debugger debugger, boolean is64Bit, Address addrValue, Address addrLow, Address addrHigh) {
super();
init(debugger, is64Bit, addressToBigInt(addrValue), addressToBigInt(addrLow), addressToBigInt(addrHigh));
}
public AnnotatedMemoryPanel(Debugger debugger, boolean is64Bit ) {
super();
init(debugger, is64Bit, defaultMemoryLocation(is64Bit), defaultMemoryLow(is64Bit), defaultMemoryHigh(is64Bit));
}
static class AnnoX {
int lineX;
Address highBound;
public AnnoX(int lineX, Address highBound) {
this.lineX = lineX;
this.highBound = highBound;
}
}
public synchronized void paintComponent(Graphics g) {
// System.err.println("AnnotatedMemoryPanel.paintComponent() " + ++paintCount);
super.paintComponent(g);
// Clone the Graphics so we don't screw up its state for Swing
// drawing (as this code otherwise does)
g = g.create();
g.setFont(font);
g.setColor(Color.black);
Rectangle rect = new Rectangle();
getBounds(rect);
String firstAddressString = null;
int lineHeight;
int addrWidth;
{
Rectangle2D bounds = GraphicsUtilities.getStringBounds(unmappedAddrString, g);
lineHeight = (int) bounds.getHeight();
addrWidth = (int) bounds.getWidth();
}
int addrX = (int) (0.25 * addrWidth);
int dataX = (int) (addrX + (1.5 * addrWidth));
int lineStartX = dataX + addrWidth + 5;
int annoStartX = (int) (lineStartX + (0.75 * addrWidth));
int numLines = rect.height / lineHeight;
BigInteger startVal = scrollBar.getValueHP();
BigInteger perLine = new BigInteger(Integer.toString((int) addressSize));
// lineCount and maxLines are both 1 less than expected
BigInteger lineCount = new BigInteger(Integer.toString(numLines - 1));
BigInteger maxLines = scrollBar.getMaximumHP().subtract(scrollBar.getMinimumHP()).divide(perLine);
if (lineCount.compareTo(maxLines) > 0) {
lineCount = maxLines;
}
BigInteger offsetVal = lineCount.multiply(perLine);
BigInteger endVal = startVal.add(offsetVal);
if (endVal.compareTo(scrollBar.getMaximumHP()) > 0) {
startVal = scrollBar.getMaximumHP().subtract(offsetVal);
endVal = scrollBar.getMaximumHP();
// Sure seems like this call will cause us to immediately redraw...
scrollBar.setValueHP(startVal);
}
scrollBar.setVisibleAmountHP(offsetVal.add(perLine));
scrollBar.setBlockIncrementHP(offsetVal);
Address startAddr = bigIntToAddress(startVal);
Address endAddr = bigIntToAddress(endVal);
// Scroll last-known annotations
int scrollOffset = 0;
if (lastStartAddr != null) {
scrollOffset = (int) lastStartAddr.minus(startAddr);
} else {
if (startAddr != null) {
scrollOffset = (int) (-1 * startAddr.minus(lastStartAddr));
}
}
scrollOffset = scrollOffset * lineHeight / (int) addressSize;
scrollAnnotations(scrollOffset);
lastStartAddr = startAddr;
int curY = lineHeight;
Address curAddr = startAddr;
for (int i = 0; i < numLines; i++) {
String s = bigIntToHexString(startVal);
g.drawString(s, addrX, curY);
try {
s = addressToString(startAddr.getAddressAt(i * addressSize));
}
catch (UnmappedAddressException e) {
s = unmappedAddrString;
}
g.drawString(s, dataX, curY);
curY += lineHeight;
startVal = startVal.add(perLine);
}
// Query for visible annotations (little slop to ensure we get the
// top and bottom)
// FIXME: it would be nice to have a more static layout; that is,
// if something scrolls off the bottom of the screen, other
// annotations still visible shouldn't change position
java.util.List<IntervalNode> va =
annotations.findAllNodesIntersecting(new Interval(startAddr.addOffsetTo(-addressSize),
endAddr.addOffsetTo(2 * addressSize)));
// Render them
int curLineX = lineStartX;
int curTextX = annoStartX;
int curColorIdx = 0;
if (g instanceof Graphics2D) {
Stroke stroke = new BasicStroke(3.0f);
((Graphics2D) g).setStroke(stroke);
}
ArrayDeque<AnnoX> drawStack = new ArrayDeque<>();
layoutAnnotations(va, g, curTextX, startAddr, lineHeight);
for (Iterator<Annotation> iter = visibleAnnotations.iterator(); iter.hasNext(); ) {
Annotation anno = iter.next();
Interval interval = anno.getInterval();
if (!drawStack.isEmpty()) {
// See whether we can pop any items off the stack
boolean shouldContinue = true;
do {
AnnoX annoX = drawStack.peek();
if (annoX.highBound.lessThanOrEqual((Address) interval.getLowEndpoint())) {
curLineX = annoX.lineX;
drawStack.pop();
shouldContinue = !drawStack.isEmpty();
} else {
shouldContinue = false;
}
} while (shouldContinue);
}
// Draw a line covering the interval
Address lineStartAddr = (Address) interval.getLowEndpoint();
// Give it a little slop
int lineStartY = (int) (lineStartAddr.minus(startAddr) * lineHeight / addressSize) +
(lineHeight / 3);
Address lineEndAddr = (Address) interval.getHighEndpoint();
drawStack.push(new AnnoX(curLineX, lineEndAddr));
int lineEndY = (int) (lineEndAddr.minus(startAddr) * lineHeight / addressSize);
g.setColor(anno.getColor());
g.drawLine(curLineX, lineStartY, curLineX, lineEndY);
// Draw line to text
g.drawLine(curLineX, lineStartY, curTextX - 10, anno.getY() - (lineHeight / 2));
curLineX += 8;
anno.draw(g);
++curColorIdx;
}
}
/** Add an annotation covering the address range [annotation.lowAddress,
annotation.highAddress); that is, it includes the low address and does not
include the high address. */
public synchronized void addAnnotation(Annotation annotation) {
annotations.insert(annotation.getInterval(), annotation);
}
/** Makes the given address visible somewhere in the window */
public synchronized void makeVisible(Address addr) {
BigInteger bi = addressToBigInt(addr);
scrollBar.setValueHP(bi);
}
public void print() {
printOn(System.out);
}
public void printOn(PrintStream tty) {
annotations.printOn(tty);
}
//----------------------------------------------------------------------
// Internals only below this point
//
private void init(Debugger debugger, boolean is64Bit, BigInteger addrValue, BigInteger addrLow, BigInteger addrHigh) {
this.is64Bit = is64Bit;
this.debugger = debugger;
if (is64Bit) {
addressSize = 8;
unmappedAddrString = "??????????????????";
} else {
addressSize = 4;
unmappedAddrString = "??????????";
}
setLayout(new BorderLayout());
setupScrollBar(addrValue, addrLow, addrHigh);
add(scrollBar, BorderLayout.EAST);
visibleAnnotations = new ArrayList<>();
setBackground(Color.white);
addHierarchyBoundsListener(new HierarchyBoundsListener() {
public void ancestorMoved(HierarchyEvent e) {
}
public void ancestorResized(HierarchyEvent e) {
// FIXME: should perform incremental layout
// System.err.println("Ancestor resized");
}
});
if (font == null) {
font = GraphicsUtilities.getMonospacedFont();
}
if (font == null) {
throw new RuntimeException("Error looking up monospace font Courier");
}
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "PageDown");
getActionMap().put("PageDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().add(scrollBar.getBlockIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "PageUp");
getActionMap().put("PageUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().subtract(scrollBar.getBlockIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
getActionMap().put("Down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().add(scrollBar.getUnitIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
getActionMap().put("Up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().subtract(scrollBar.getUnitIncrementHP()));
}
});
setEnabled(true);
}
private void setupScrollBar(BigInteger value, BigInteger min, BigInteger max) {
scrollBar = new HighPrecisionJScrollBar( Scrollbar.VERTICAL, value, min, max);
if (is64Bit) {
bytesPerLine = 8;
// 64-bit mode
scrollBar.setUnitIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08}));
scrollBar.setBlockIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x40}));
} else {
// 32-bit mode
bytesPerLine = 4;
scrollBar.setUnitIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04}));
scrollBar.setBlockIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20}));
}
scrollBar.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
HighPrecisionJScrollBar h = (HighPrecisionJScrollBar) e.getSource();
repaint();
}
});
}
private static BigInteger defaultMemoryLocation(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
} else {
return new BigInteger(1, new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00});
}
}
private static BigInteger defaultMemoryLow(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
} else {
return new BigInteger(1, new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
}
}
private static BigInteger defaultMemoryHigh(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFC});
} else {
return new BigInteger(1, new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFC});
}
}
private void setupScrollBar() {
setupScrollBar(defaultMemoryLocation(is64Bit),
defaultMemoryLow(is64Bit),
defaultMemoryHigh(is64Bit));
}
private String bigIntToHexString(BigInteger bi) {
StringBuilder buf = new StringBuilder();
buf.append("0x");
String val = bi.toString(16);
for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
buf.append('0');
}
buf.append(val);
return buf.toString();
}
private Address bigIntToAddress(BigInteger i) {
String s = bigIntToHexString(i);
return debugger.parseAddress(s);
}
private BigInteger addressToBigInt(Address a) {
String s = addressToString(a);
if (!s.startsWith("0x")) {
throw new NumberFormatException(s);
}
return new BigInteger(s.substring(2), 16);
}
private String addressToString(Address a) {
if (a == null) {
if (is64Bit) {
return "0x0000000000000000";
} else {
return "0x00000000";
}
}
return a.toString();
}
/** Scrolls the visible annotations by the given Y amount */
private void scrollAnnotations(int y) {
for (Iterator<Annotation> iter = visibleAnnotations.iterator(); iter.hasNext(); ) {
Annotation anno = iter.next();
anno.setY(anno.getY() + y);
}
}
/** Takes the list of currently-visible annotations (in the form of
a List<IntervalNode>) and lays them out given the current
visible position and the already-visible annotations. Does not
perturb the layouts of the currently-visible annotations. */
private void layoutAnnotations(java.util.List<IntervalNode> va,
Graphics g,
int x,
Address startAddr,
int lineHeight) {
// Handle degenerate case early: no visible annotations.
if (va.size() == 0) {
visibleAnnotations.clear();
return;
}
// We have two ranges of visible annotations: the one from the
// last repaint and the currently visible set. We want to preserve
// the layouts of the previously-visible annotations that are
// currently visible (to avoid color flashing, jumping, etc.)
// while making the coloring of the new annotations fit as well as
// possible. Note that annotations may appear and disappear from
// any point in the previously-visible list, but the ordering of
// the visible annotations is always the same.
// This is really a constrained graph-coloring problem. This
// simple algorithm only takes into account half of the
// constraints (for example, the layout of the previous
// annotation, where it should be taking into account the layout
// of the previous and next annotations that were in the
// previously-visible list). There are situations where it can
// generate overlapping annotations and adjacent annotations with
// the same color; generally visible when scrolling line-by-line
// rather than page-by-page. In some of these situations, will
// have to move previously laid-out annotations. FIXME: revisit
// this.
// Index of last annotation which we didn't know how to lay out
int deferredIndex = -1;
// We "lay out after" this one
Annotation constraintAnnotation = null;
// The first constraint annotation
Annotation firstConstraintAnnotation = null;
// The index from which we search forward in the
// visibleAnnotations list. This reduces the amount of work we do.
int searchIndex = 0;
// The new set of annotations
java.util.List<Annotation> newAnnos = new ArrayList<>();
for (Iterator<IntervalNode> iter = va.iterator(); iter.hasNext(); ) {
Annotation anno = (Annotation) iter.next().getData();
// Search forward for this one
boolean found = false;
for (int i = searchIndex; i < visibleAnnotations.size(); i++) {
Annotation el = visibleAnnotations.get(i);
// See whether we can abort the search unsuccessfully because
// we went forward too far
if (el.getLowAddress().greaterThan(anno.getLowAddress())) {
break;
}
if (el == anno) {
// Found successfully.
found = true;
searchIndex = i;
constraintAnnotation = anno;
if (firstConstraintAnnotation == null) {
firstConstraintAnnotation = constraintAnnotation;
}
break;
}
}
if (!found) {
if (constraintAnnotation != null) {
layoutAfter(anno, constraintAnnotation, g, x, startAddr, lineHeight);
constraintAnnotation = anno;
} else {
// Defer layout of this annotation until later
++deferredIndex;
}
}
newAnnos.add(anno);
}
if (firstConstraintAnnotation != null) {
// Go back and lay out deferred annotations
for (int i = deferredIndex; i >= 0; i--) {
Annotation anno = newAnnos.get(i);
layoutBefore(anno, firstConstraintAnnotation, g, x, startAddr, lineHeight);
firstConstraintAnnotation = anno;
}
} else {
// Didn't find any overlap between the old and new annotations.
// Lay out in a feed-forward fashion.
if (Assert.ASSERTS_ENABLED) {
Assert.that(constraintAnnotation == null, "logic error in layout code");
}
for (Iterator iter = newAnnos.iterator(); iter.hasNext(); ) {
Annotation anno = (Annotation) iter.next();
layoutAfter(anno, constraintAnnotation, g, x, startAddr, lineHeight);
constraintAnnotation = anno;
}
}
visibleAnnotations = newAnnos;
}
/** Lays out the given annotation before the optional constraint
annotation, obeying constraints imposed by that annotation if it
is specified. */
private void layoutBefore(Annotation anno, Annotation constraintAnno,
Graphics g, int x,
Address startAddr, int lineHeight) {
anno.computeWidthAndHeight(g);
// Color
if (constraintAnno != null) {
anno.setColor(prevColor(constraintAnno.getColor()));
} else {
anno.setColor(colors[0]);
}
// X
anno.setX(x);
// Tentative Y
anno.setY((int) (((Address) anno.getInterval().getLowEndpoint()).minus(startAddr) * lineHeight / addressSize) +
(5 * lineHeight / 6));
// See whether Y overlaps with last anno's Y; if so, move this one up
if ((constraintAnno != null) && (anno.getY() + anno.getHeight() > constraintAnno.getY())) {
anno.setY(constraintAnno.getY() - anno.getHeight());
}
}
/** Lays out the given annotation after the optional constraint
annotation, obeying constraints imposed by that annotation if it
is specified. */
private void layoutAfter(Annotation anno, Annotation constraintAnno,
Graphics g, int x,
Address startAddr, int lineHeight) {
anno.computeWidthAndHeight(g);
// Color
if (constraintAnno != null) {
anno.setColor(nextColor(constraintAnno.getColor()));
} else {
anno.setColor(colors[0]);
}
// X
anno.setX(x);
// Tentative Y
anno.setY((int) (((Address) anno.getInterval().getLowEndpoint()).minus(startAddr) * lineHeight / addressSize) +
(5 * lineHeight / 6));
// See whether Y overlaps with last anno's Y; if so, move this one down
if ((constraintAnno != null) && (anno.getY() < (constraintAnno.getY() + constraintAnno.getHeight()))) {
anno.setY(constraintAnno.getY() + constraintAnno.getHeight());
}
}
/** Returns previous color in our color palette */
private Color prevColor(Color c) {
int i = findColorIndex(c);
if (i == 0) {
return colors[colors.length - 1];
} else {
return colors[i - 1];
}
}
/** Returns next color in our color palette */
private Color nextColor(Color c) {
return colors[(findColorIndex(c) + 1) % colors.length];
}
private int findColorIndex(Color c) {
for (int i = 0; i < colors.length; i++) {
if (colors[i] == c) {
return i;
}
}
throw new IllegalArgumentException();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
DummyDebugger debugger = new DummyDebugger(new MachineDescriptionIntelX86());
AnnotatedMemoryPanel anno = new AnnotatedMemoryPanel(debugger);
frame.getContentPane().add(anno);
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000000"),
debugger.parseAddress("0x80000040"),
"Stack Frame for \"foo\""));
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000010"),
debugger.parseAddress("0x80000020"),
"Locals for \"foo\""));
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000020"),
debugger.parseAddress("0x80000030"),
"Expression stack for \"foo\""));
frame.setSize(400, 300);
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
| openjdk/jdk | src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/ui/AnnotatedMemoryPanel.java | 6,863 | /** Default is 32-bit mode */ | block_comment | nl | /*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.ui;
import java.math.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.debugger.dummy.*;
import sun.jvm.hotspot.utilities.*;
/** A subclass of JPanel which displays a hex dump of memory along
with annotations describing the significance of various
pieces. This can be used to implement either a stack or heap
inspector. */
public class AnnotatedMemoryPanel extends JPanel {
private boolean is64Bit;
private Debugger debugger;
private long addressSize;
private HighPrecisionJScrollBar scrollBar;
private Font font;
private int bytesPerLine;
private int paintCount;
private String unmappedAddrString;
// Type of this is an IntervalTree indexed by Interval<Address> and
// with user data of type Annotation
private IntervalTree annotations =
new IntervalTree(new Comparator<>() {
public int compare(Object o1, Object o2) {
Address a1 = (Address) o1;
Address a2 = (Address) o2;
if ((a1 == null) && (a2 == null)) {
return 0;
} else if (a1 == null) {
return -1;
} else if (a2 == null) {
return 1;
}
if (a1.equals(a2)) {
return 0;
} else if (a1.lessThan(a2)) {
return -1;
}
return 1;
}
});
// Keep track of the last start address at which we painted, so we
// can scroll annotations
private Address lastStartAddr;
// This contains the list of currently-visible IntervalNodes, in
// sorted order by their low endpoint, in the form of a
// List<Annotation>. These annotations have already been laid out.
private java.util.List<Annotation> visibleAnnotations;
// Darker colors than defaults for better readability
private static Color[] colors = {
new Color(0.0f, 0.0f, 0.6f), // blue
new Color(0.6f, 0.0f, 0.6f), // magenta
new Color(0.0f, 0.8f, 0.0f), // green
new Color(0.8f, 0.3f, 0.0f), // orange
new Color(0.0f, 0.6f, 0.8f), // cyan
new Color(0.2f, 0.2f, 0.2f), // dark gray
};
/** Default is 32-bit<SUF>*/
public AnnotatedMemoryPanel(Debugger debugger) {
this(debugger, false);
}
public AnnotatedMemoryPanel(Debugger debugger, boolean is64Bit, Address addrValue, Address addrLow, Address addrHigh) {
super();
init(debugger, is64Bit, addressToBigInt(addrValue), addressToBigInt(addrLow), addressToBigInt(addrHigh));
}
public AnnotatedMemoryPanel(Debugger debugger, boolean is64Bit ) {
super();
init(debugger, is64Bit, defaultMemoryLocation(is64Bit), defaultMemoryLow(is64Bit), defaultMemoryHigh(is64Bit));
}
static class AnnoX {
int lineX;
Address highBound;
public AnnoX(int lineX, Address highBound) {
this.lineX = lineX;
this.highBound = highBound;
}
}
public synchronized void paintComponent(Graphics g) {
// System.err.println("AnnotatedMemoryPanel.paintComponent() " + ++paintCount);
super.paintComponent(g);
// Clone the Graphics so we don't screw up its state for Swing
// drawing (as this code otherwise does)
g = g.create();
g.setFont(font);
g.setColor(Color.black);
Rectangle rect = new Rectangle();
getBounds(rect);
String firstAddressString = null;
int lineHeight;
int addrWidth;
{
Rectangle2D bounds = GraphicsUtilities.getStringBounds(unmappedAddrString, g);
lineHeight = (int) bounds.getHeight();
addrWidth = (int) bounds.getWidth();
}
int addrX = (int) (0.25 * addrWidth);
int dataX = (int) (addrX + (1.5 * addrWidth));
int lineStartX = dataX + addrWidth + 5;
int annoStartX = (int) (lineStartX + (0.75 * addrWidth));
int numLines = rect.height / lineHeight;
BigInteger startVal = scrollBar.getValueHP();
BigInteger perLine = new BigInteger(Integer.toString((int) addressSize));
// lineCount and maxLines are both 1 less than expected
BigInteger lineCount = new BigInteger(Integer.toString(numLines - 1));
BigInteger maxLines = scrollBar.getMaximumHP().subtract(scrollBar.getMinimumHP()).divide(perLine);
if (lineCount.compareTo(maxLines) > 0) {
lineCount = maxLines;
}
BigInteger offsetVal = lineCount.multiply(perLine);
BigInteger endVal = startVal.add(offsetVal);
if (endVal.compareTo(scrollBar.getMaximumHP()) > 0) {
startVal = scrollBar.getMaximumHP().subtract(offsetVal);
endVal = scrollBar.getMaximumHP();
// Sure seems like this call will cause us to immediately redraw...
scrollBar.setValueHP(startVal);
}
scrollBar.setVisibleAmountHP(offsetVal.add(perLine));
scrollBar.setBlockIncrementHP(offsetVal);
Address startAddr = bigIntToAddress(startVal);
Address endAddr = bigIntToAddress(endVal);
// Scroll last-known annotations
int scrollOffset = 0;
if (lastStartAddr != null) {
scrollOffset = (int) lastStartAddr.minus(startAddr);
} else {
if (startAddr != null) {
scrollOffset = (int) (-1 * startAddr.minus(lastStartAddr));
}
}
scrollOffset = scrollOffset * lineHeight / (int) addressSize;
scrollAnnotations(scrollOffset);
lastStartAddr = startAddr;
int curY = lineHeight;
Address curAddr = startAddr;
for (int i = 0; i < numLines; i++) {
String s = bigIntToHexString(startVal);
g.drawString(s, addrX, curY);
try {
s = addressToString(startAddr.getAddressAt(i * addressSize));
}
catch (UnmappedAddressException e) {
s = unmappedAddrString;
}
g.drawString(s, dataX, curY);
curY += lineHeight;
startVal = startVal.add(perLine);
}
// Query for visible annotations (little slop to ensure we get the
// top and bottom)
// FIXME: it would be nice to have a more static layout; that is,
// if something scrolls off the bottom of the screen, other
// annotations still visible shouldn't change position
java.util.List<IntervalNode> va =
annotations.findAllNodesIntersecting(new Interval(startAddr.addOffsetTo(-addressSize),
endAddr.addOffsetTo(2 * addressSize)));
// Render them
int curLineX = lineStartX;
int curTextX = annoStartX;
int curColorIdx = 0;
if (g instanceof Graphics2D) {
Stroke stroke = new BasicStroke(3.0f);
((Graphics2D) g).setStroke(stroke);
}
ArrayDeque<AnnoX> drawStack = new ArrayDeque<>();
layoutAnnotations(va, g, curTextX, startAddr, lineHeight);
for (Iterator<Annotation> iter = visibleAnnotations.iterator(); iter.hasNext(); ) {
Annotation anno = iter.next();
Interval interval = anno.getInterval();
if (!drawStack.isEmpty()) {
// See whether we can pop any items off the stack
boolean shouldContinue = true;
do {
AnnoX annoX = drawStack.peek();
if (annoX.highBound.lessThanOrEqual((Address) interval.getLowEndpoint())) {
curLineX = annoX.lineX;
drawStack.pop();
shouldContinue = !drawStack.isEmpty();
} else {
shouldContinue = false;
}
} while (shouldContinue);
}
// Draw a line covering the interval
Address lineStartAddr = (Address) interval.getLowEndpoint();
// Give it a little slop
int lineStartY = (int) (lineStartAddr.minus(startAddr) * lineHeight / addressSize) +
(lineHeight / 3);
Address lineEndAddr = (Address) interval.getHighEndpoint();
drawStack.push(new AnnoX(curLineX, lineEndAddr));
int lineEndY = (int) (lineEndAddr.minus(startAddr) * lineHeight / addressSize);
g.setColor(anno.getColor());
g.drawLine(curLineX, lineStartY, curLineX, lineEndY);
// Draw line to text
g.drawLine(curLineX, lineStartY, curTextX - 10, anno.getY() - (lineHeight / 2));
curLineX += 8;
anno.draw(g);
++curColorIdx;
}
}
/** Add an annotation covering the address range [annotation.lowAddress,
annotation.highAddress); that is, it includes the low address and does not
include the high address. */
public synchronized void addAnnotation(Annotation annotation) {
annotations.insert(annotation.getInterval(), annotation);
}
/** Makes the given address visible somewhere in the window */
public synchronized void makeVisible(Address addr) {
BigInteger bi = addressToBigInt(addr);
scrollBar.setValueHP(bi);
}
public void print() {
printOn(System.out);
}
public void printOn(PrintStream tty) {
annotations.printOn(tty);
}
//----------------------------------------------------------------------
// Internals only below this point
//
private void init(Debugger debugger, boolean is64Bit, BigInteger addrValue, BigInteger addrLow, BigInteger addrHigh) {
this.is64Bit = is64Bit;
this.debugger = debugger;
if (is64Bit) {
addressSize = 8;
unmappedAddrString = "??????????????????";
} else {
addressSize = 4;
unmappedAddrString = "??????????";
}
setLayout(new BorderLayout());
setupScrollBar(addrValue, addrLow, addrHigh);
add(scrollBar, BorderLayout.EAST);
visibleAnnotations = new ArrayList<>();
setBackground(Color.white);
addHierarchyBoundsListener(new HierarchyBoundsListener() {
public void ancestorMoved(HierarchyEvent e) {
}
public void ancestorResized(HierarchyEvent e) {
// FIXME: should perform incremental layout
// System.err.println("Ancestor resized");
}
});
if (font == null) {
font = GraphicsUtilities.getMonospacedFont();
}
if (font == null) {
throw new RuntimeException("Error looking up monospace font Courier");
}
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "PageDown");
getActionMap().put("PageDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().add(scrollBar.getBlockIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), "PageUp");
getActionMap().put("PageUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().subtract(scrollBar.getBlockIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
getActionMap().put("Down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().add(scrollBar.getUnitIncrementHP()));
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
getActionMap().put("Up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
scrollBar.setValueHP(scrollBar.getValueHP().subtract(scrollBar.getUnitIncrementHP()));
}
});
setEnabled(true);
}
private void setupScrollBar(BigInteger value, BigInteger min, BigInteger max) {
scrollBar = new HighPrecisionJScrollBar( Scrollbar.VERTICAL, value, min, max);
if (is64Bit) {
bytesPerLine = 8;
// 64-bit mode
scrollBar.setUnitIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08}));
scrollBar.setBlockIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x40}));
} else {
// 32-bit mode
bytesPerLine = 4;
scrollBar.setUnitIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x04}));
scrollBar.setBlockIncrementHP(new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x20}));
}
scrollBar.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
HighPrecisionJScrollBar h = (HighPrecisionJScrollBar) e.getSource();
repaint();
}
});
}
private static BigInteger defaultMemoryLocation(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
} else {
return new BigInteger(1, new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00});
}
}
private static BigInteger defaultMemoryLow(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
} else {
return new BigInteger(1, new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00});
}
}
private static BigInteger defaultMemoryHigh(boolean is64Bit) {
if (is64Bit) {
return new BigInteger(1, new byte[] {
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFC});
} else {
return new BigInteger(1, new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFC});
}
}
private void setupScrollBar() {
setupScrollBar(defaultMemoryLocation(is64Bit),
defaultMemoryLow(is64Bit),
defaultMemoryHigh(is64Bit));
}
private String bigIntToHexString(BigInteger bi) {
StringBuilder buf = new StringBuilder();
buf.append("0x");
String val = bi.toString(16);
for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
buf.append('0');
}
buf.append(val);
return buf.toString();
}
private Address bigIntToAddress(BigInteger i) {
String s = bigIntToHexString(i);
return debugger.parseAddress(s);
}
private BigInteger addressToBigInt(Address a) {
String s = addressToString(a);
if (!s.startsWith("0x")) {
throw new NumberFormatException(s);
}
return new BigInteger(s.substring(2), 16);
}
private String addressToString(Address a) {
if (a == null) {
if (is64Bit) {
return "0x0000000000000000";
} else {
return "0x00000000";
}
}
return a.toString();
}
/** Scrolls the visible annotations by the given Y amount */
private void scrollAnnotations(int y) {
for (Iterator<Annotation> iter = visibleAnnotations.iterator(); iter.hasNext(); ) {
Annotation anno = iter.next();
anno.setY(anno.getY() + y);
}
}
/** Takes the list of currently-visible annotations (in the form of
a List<IntervalNode>) and lays them out given the current
visible position and the already-visible annotations. Does not
perturb the layouts of the currently-visible annotations. */
private void layoutAnnotations(java.util.List<IntervalNode> va,
Graphics g,
int x,
Address startAddr,
int lineHeight) {
// Handle degenerate case early: no visible annotations.
if (va.size() == 0) {
visibleAnnotations.clear();
return;
}
// We have two ranges of visible annotations: the one from the
// last repaint and the currently visible set. We want to preserve
// the layouts of the previously-visible annotations that are
// currently visible (to avoid color flashing, jumping, etc.)
// while making the coloring of the new annotations fit as well as
// possible. Note that annotations may appear and disappear from
// any point in the previously-visible list, but the ordering of
// the visible annotations is always the same.
// This is really a constrained graph-coloring problem. This
// simple algorithm only takes into account half of the
// constraints (for example, the layout of the previous
// annotation, where it should be taking into account the layout
// of the previous and next annotations that were in the
// previously-visible list). There are situations where it can
// generate overlapping annotations and adjacent annotations with
// the same color; generally visible when scrolling line-by-line
// rather than page-by-page. In some of these situations, will
// have to move previously laid-out annotations. FIXME: revisit
// this.
// Index of last annotation which we didn't know how to lay out
int deferredIndex = -1;
// We "lay out after" this one
Annotation constraintAnnotation = null;
// The first constraint annotation
Annotation firstConstraintAnnotation = null;
// The index from which we search forward in the
// visibleAnnotations list. This reduces the amount of work we do.
int searchIndex = 0;
// The new set of annotations
java.util.List<Annotation> newAnnos = new ArrayList<>();
for (Iterator<IntervalNode> iter = va.iterator(); iter.hasNext(); ) {
Annotation anno = (Annotation) iter.next().getData();
// Search forward for this one
boolean found = false;
for (int i = searchIndex; i < visibleAnnotations.size(); i++) {
Annotation el = visibleAnnotations.get(i);
// See whether we can abort the search unsuccessfully because
// we went forward too far
if (el.getLowAddress().greaterThan(anno.getLowAddress())) {
break;
}
if (el == anno) {
// Found successfully.
found = true;
searchIndex = i;
constraintAnnotation = anno;
if (firstConstraintAnnotation == null) {
firstConstraintAnnotation = constraintAnnotation;
}
break;
}
}
if (!found) {
if (constraintAnnotation != null) {
layoutAfter(anno, constraintAnnotation, g, x, startAddr, lineHeight);
constraintAnnotation = anno;
} else {
// Defer layout of this annotation until later
++deferredIndex;
}
}
newAnnos.add(anno);
}
if (firstConstraintAnnotation != null) {
// Go back and lay out deferred annotations
for (int i = deferredIndex; i >= 0; i--) {
Annotation anno = newAnnos.get(i);
layoutBefore(anno, firstConstraintAnnotation, g, x, startAddr, lineHeight);
firstConstraintAnnotation = anno;
}
} else {
// Didn't find any overlap between the old and new annotations.
// Lay out in a feed-forward fashion.
if (Assert.ASSERTS_ENABLED) {
Assert.that(constraintAnnotation == null, "logic error in layout code");
}
for (Iterator iter = newAnnos.iterator(); iter.hasNext(); ) {
Annotation anno = (Annotation) iter.next();
layoutAfter(anno, constraintAnnotation, g, x, startAddr, lineHeight);
constraintAnnotation = anno;
}
}
visibleAnnotations = newAnnos;
}
/** Lays out the given annotation before the optional constraint
annotation, obeying constraints imposed by that annotation if it
is specified. */
private void layoutBefore(Annotation anno, Annotation constraintAnno,
Graphics g, int x,
Address startAddr, int lineHeight) {
anno.computeWidthAndHeight(g);
// Color
if (constraintAnno != null) {
anno.setColor(prevColor(constraintAnno.getColor()));
} else {
anno.setColor(colors[0]);
}
// X
anno.setX(x);
// Tentative Y
anno.setY((int) (((Address) anno.getInterval().getLowEndpoint()).minus(startAddr) * lineHeight / addressSize) +
(5 * lineHeight / 6));
// See whether Y overlaps with last anno's Y; if so, move this one up
if ((constraintAnno != null) && (anno.getY() + anno.getHeight() > constraintAnno.getY())) {
anno.setY(constraintAnno.getY() - anno.getHeight());
}
}
/** Lays out the given annotation after the optional constraint
annotation, obeying constraints imposed by that annotation if it
is specified. */
private void layoutAfter(Annotation anno, Annotation constraintAnno,
Graphics g, int x,
Address startAddr, int lineHeight) {
anno.computeWidthAndHeight(g);
// Color
if (constraintAnno != null) {
anno.setColor(nextColor(constraintAnno.getColor()));
} else {
anno.setColor(colors[0]);
}
// X
anno.setX(x);
// Tentative Y
anno.setY((int) (((Address) anno.getInterval().getLowEndpoint()).minus(startAddr) * lineHeight / addressSize) +
(5 * lineHeight / 6));
// See whether Y overlaps with last anno's Y; if so, move this one down
if ((constraintAnno != null) && (anno.getY() < (constraintAnno.getY() + constraintAnno.getHeight()))) {
anno.setY(constraintAnno.getY() + constraintAnno.getHeight());
}
}
/** Returns previous color in our color palette */
private Color prevColor(Color c) {
int i = findColorIndex(c);
if (i == 0) {
return colors[colors.length - 1];
} else {
return colors[i - 1];
}
}
/** Returns next color in our color palette */
private Color nextColor(Color c) {
return colors[(findColorIndex(c) + 1) % colors.length];
}
private int findColorIndex(Color c) {
for (int i = 0; i < colors.length; i++) {
if (colors[i] == c) {
return i;
}
}
throw new IllegalArgumentException();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
DummyDebugger debugger = new DummyDebugger(new MachineDescriptionIntelX86());
AnnotatedMemoryPanel anno = new AnnotatedMemoryPanel(debugger);
frame.getContentPane().add(anno);
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000000"),
debugger.parseAddress("0x80000040"),
"Stack Frame for \"foo\""));
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000010"),
debugger.parseAddress("0x80000020"),
"Locals for \"foo\""));
anno.addAnnotation(new Annotation(debugger.parseAddress("0x80000020"),
debugger.parseAddress("0x80000030"),
"Expression stack for \"foo\""));
frame.setSize(400, 300);
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
|
108649_0 | package application;
import javafx.fxml.FXML;
import javafx.scene.layout.VBox;
/**
* Klasse "BasisScherm"
*
* Dummy scherm, de basis van alle andere schermen kan hieruit worden gehaald.
*
* @author Martijn Janssen
*
*/
public class BasisScherm {
@FXML
VBox linkbox;
@FXML
private void initialize() {
Linkmenu.setLinks(linkbox);
}
}
| martijnjanssen/Voetbalmanager | src/application/BasisScherm.java | 114 | /**
* Klasse "BasisScherm"
*
* Dummy scherm, de basis van alle andere schermen kan hieruit worden gehaald.
*
* @author Martijn Janssen
*
*/ | block_comment | nl | package application;
import javafx.fxml.FXML;
import javafx.scene.layout.VBox;
/**
* Klasse "BasisScherm"
<SUF>*/
public class BasisScherm {
@FXML
VBox linkbox;
@FXML
private void initialize() {
Linkmenu.setLinks(linkbox);
}
}
|
12459_3 | /*
* Copyright (C) 2017 B3Partners B.V.
*/
package nl.b3p.gds2;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragenresultaat.v20170401.BestandenlijstOpvragenResultaatType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20170401.AfgifteType;
import nl.kadaster.schemas.gds2.imgds.baseurl.v20170401.BaseURLType;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenRequest;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* @author mprins
*/
public class GDS2Util {
private static final Log LOG = LogFactory.getLog(GDS2Util.class);
private static final String PEM_KEY_START = "-----BEGIN PRIVATE KEY-----";
private static final String PEM_KEY_END = "-----END PRIVATE KEY-----";
private static final String PEM_CERT_START = "-----BEGIN CERTIFICATE-----";
private static final String PEM_CERT_END = "-----END CERTIFICATE-----";
public static Certificate getCertificateFromPEM(String pem) throws CertificateException, UnsupportedEncodingException {
if (!pem.startsWith(PEM_CERT_START)) {
throw new IllegalArgumentException("Certificaat moet beginnen met " + PEM_CERT_START);
}
if (!pem.endsWith(PEM_CERT_END)) {
throw new IllegalArgumentException("Certificaat moet eindigen met " + PEM_CERT_END);
}
return CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(pem.getBytes("US-ASCII")));
}
public static PrivateKey getPrivateKeyFromPEM(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException {
if (!pem.startsWith(PEM_KEY_START)) {
throw new IllegalArgumentException("Private key moet beginnen met " + PEM_KEY_START);
}
while (pem.endsWith("\n")) {
pem = pem.substring(0, pem.length() - 1);
}
if (!pem.endsWith(PEM_KEY_END)) {
throw new IllegalArgumentException("Private key moet eindigen met " + PEM_KEY_END);
}
pem = pem.replace(PEM_KEY_START, "").replace(PEM_KEY_END, "");
byte[] decoded = Base64.getMimeDecoder().decode(pem);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
return kf.generatePrivate(spec);
}
/**
* vraagt de bestandenlijst op in maximaal 2 pogingen met 10000 millisec pauze.
*
* @param gds2 afgifte service
* @param request geconfigureerd verzoek
* @return opgevraagde bestanden lijst
* @see #retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401, BestandenlijstOpvragenRequest, int, long)
*/
public static BestandenlijstOpvragenResponse retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401 gds2, BestandenlijstOpvragenRequest request) throws Exception {
return retryBestandenLijstOpvragen(gds2, request, 2, 10000L);
}
/**
* vraagt de bestandenlijst op.
*
* @param gds2 afgifte service
* @param request geconfigureerd verzoek
* @param retries aantal pogingen om verzoek uit te voeren
* @param retryWait te wachten milliseconden tussen retries, wordt vermenigvuldigd met retry poging (dus periode steeds langer)
* @return opgevraagde bestanden lijst
*/
public static BestandenlijstOpvragenResponse retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401 gds2, BestandenlijstOpvragenRequest request, int retries, long retryWait) throws Exception {
int attempt = 0;
while (true) {
try {
return gds2.bestandenlijstOpvragen(request);
} catch (Exception e) {
attempt++;
if (attempt == retries) {
LOG.error("Fout bij laatste poging ophalen bestandenlijst: " + e.getClass().getName() + ": " + e.getMessage());
throw e;
} else {
LOG.warn("Fout bij poging " + attempt + " om bestandenlijst op te halen: " + e.getClass().getName() + ": " + e.getMessage());
Thread.sleep(retryWait * attempt);
LOG.info("Uitvoeren poging " + (attempt + 1) + " om bestandenlijst op te halen...");
}
}
}
}
/**
* bepaal de "certificaat" url, nodig voor BRK download met PKI.
*
* @param antwoord de url
* @return type of {@code null}
*/
public static BaseURLType getCertificaatBaseURL(BestandenlijstOpvragenResultaatType antwoord) {
for (BaseURLType type : antwoord.getBaseURLSet().getBaseURL()) {
if (type.getType().equalsIgnoreCase("certificaat")) {
return type;
}
}
return null;
}
/**
* bepaal de "anoniem" url, nodig voor BAG download zonder PKI.
*
* @param antwoord de url
* @return type of {@code null}
*/
public static BaseURLType getAnoniemBaseURL(BestandenlijstOpvragenResultaatType antwoord) {
for (BaseURLType type : antwoord.getBaseURLSet().getBaseURL()) {
if (type.getType().equalsIgnoreCase("anoniem")) {
return type;
}
}
return null;
}
/**
* bepaal de afgifte url.
*
* @param afgifte de afgifte
* @param type de base url
* @return de afgifte url
*/
public static String getAfgifteURL(AfgifteType afgifte, BaseURLType type) {
return type.getValue() + "/" + afgifte.getAfgifteID();
}
/**
* parse datum uit string.
*
* @param dateStr datum in dd-MM-yyyy formaat (evt. {@code null}
* @return datum (of {@code null} in geval van een parse fout of {@code null} argument)
*/
public static GregorianCalendar getDatumTijd(String dateStr) {
if (dateStr == null) {
return null;
}
Date date;
final DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
if (dateStr.equalsIgnoreCase("nu")) {
date = new Date();
} else {
try {
date = format.parse(dateStr);
} catch (ParseException ex) {
LOG.error(ex);
return null;
}
}
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);
return gregory;
}
/**
* parse datum uit string en verschuif {@code dagen}.
*
* @param refDate datum in dd-MM-yyyy formaat (niet {@code null})
* @param before aantal dagen dat de datum verschoven moet worden, bijvoorbeeld -3 voor 3 dagen eerder
* @return datum (of null in geval van een parse fout)
*/
public static GregorianCalendar getDatumTijd(String refDate, int before) {
GregorianCalendar ref = getDatumTijd(refDate);
ref.add(GregorianCalendar.DAY_OF_YEAR, before);
return ref;
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium, houdt rekening met de juiste maand.
*
* @param year jaartal (4 cijfers, > 2000)
* @param month maand (waarde van 0 t/m 12)
* @param day dag van de maand
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(int year, int month, int day) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(
new GregorianCalendar(
year,
month - 1 /* GregorianCalendar heeft 0-based month */,
day)
);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium.
*
* @param date datum (niet {@code null})
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(Date date) {
final GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium.
*
* @param date datum (niet {@code null})
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(GregorianCalendar date) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(date);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
private GDS2Util() {
}
}
| B3Partners/kadaster-gds2 | src/main/java/nl/b3p/gds2/GDS2Util.java | 2,731 | /**
* vraagt de bestandenlijst op.
*
* @param gds2 afgifte service
* @param request geconfigureerd verzoek
* @param retries aantal pogingen om verzoek uit te voeren
* @param retryWait te wachten milliseconden tussen retries, wordt vermenigvuldigd met retry poging (dus periode steeds langer)
* @return opgevraagde bestanden lijst
*/ | block_comment | nl | /*
* Copyright (C) 2017 B3Partners B.V.
*/
package nl.b3p.gds2;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragenresultaat.v20170401.BestandenlijstOpvragenResultaatType;
import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20170401.AfgifteType;
import nl.kadaster.schemas.gds2.imgds.baseurl.v20170401.BaseURLType;
import nl.kadaster.schemas.gds2.service.afgifte.v20170401.Gds2AfgifteServiceV20170401;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenRequest;
import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20170401.BestandenlijstOpvragenResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* @author mprins
*/
public class GDS2Util {
private static final Log LOG = LogFactory.getLog(GDS2Util.class);
private static final String PEM_KEY_START = "-----BEGIN PRIVATE KEY-----";
private static final String PEM_KEY_END = "-----END PRIVATE KEY-----";
private static final String PEM_CERT_START = "-----BEGIN CERTIFICATE-----";
private static final String PEM_CERT_END = "-----END CERTIFICATE-----";
public static Certificate getCertificateFromPEM(String pem) throws CertificateException, UnsupportedEncodingException {
if (!pem.startsWith(PEM_CERT_START)) {
throw new IllegalArgumentException("Certificaat moet beginnen met " + PEM_CERT_START);
}
if (!pem.endsWith(PEM_CERT_END)) {
throw new IllegalArgumentException("Certificaat moet eindigen met " + PEM_CERT_END);
}
return CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(pem.getBytes("US-ASCII")));
}
public static PrivateKey getPrivateKeyFromPEM(String pem) throws NoSuchAlgorithmException, InvalidKeySpecException {
if (!pem.startsWith(PEM_KEY_START)) {
throw new IllegalArgumentException("Private key moet beginnen met " + PEM_KEY_START);
}
while (pem.endsWith("\n")) {
pem = pem.substring(0, pem.length() - 1);
}
if (!pem.endsWith(PEM_KEY_END)) {
throw new IllegalArgumentException("Private key moet eindigen met " + PEM_KEY_END);
}
pem = pem.replace(PEM_KEY_START, "").replace(PEM_KEY_END, "");
byte[] decoded = Base64.getMimeDecoder().decode(pem);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
return kf.generatePrivate(spec);
}
/**
* vraagt de bestandenlijst op in maximaal 2 pogingen met 10000 millisec pauze.
*
* @param gds2 afgifte service
* @param request geconfigureerd verzoek
* @return opgevraagde bestanden lijst
* @see #retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401, BestandenlijstOpvragenRequest, int, long)
*/
public static BestandenlijstOpvragenResponse retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401 gds2, BestandenlijstOpvragenRequest request) throws Exception {
return retryBestandenLijstOpvragen(gds2, request, 2, 10000L);
}
/**
* vraagt de bestandenlijst<SUF>*/
public static BestandenlijstOpvragenResponse retryBestandenLijstOpvragen(Gds2AfgifteServiceV20170401 gds2, BestandenlijstOpvragenRequest request, int retries, long retryWait) throws Exception {
int attempt = 0;
while (true) {
try {
return gds2.bestandenlijstOpvragen(request);
} catch (Exception e) {
attempt++;
if (attempt == retries) {
LOG.error("Fout bij laatste poging ophalen bestandenlijst: " + e.getClass().getName() + ": " + e.getMessage());
throw e;
} else {
LOG.warn("Fout bij poging " + attempt + " om bestandenlijst op te halen: " + e.getClass().getName() + ": " + e.getMessage());
Thread.sleep(retryWait * attempt);
LOG.info("Uitvoeren poging " + (attempt + 1) + " om bestandenlijst op te halen...");
}
}
}
}
/**
* bepaal de "certificaat" url, nodig voor BRK download met PKI.
*
* @param antwoord de url
* @return type of {@code null}
*/
public static BaseURLType getCertificaatBaseURL(BestandenlijstOpvragenResultaatType antwoord) {
for (BaseURLType type : antwoord.getBaseURLSet().getBaseURL()) {
if (type.getType().equalsIgnoreCase("certificaat")) {
return type;
}
}
return null;
}
/**
* bepaal de "anoniem" url, nodig voor BAG download zonder PKI.
*
* @param antwoord de url
* @return type of {@code null}
*/
public static BaseURLType getAnoniemBaseURL(BestandenlijstOpvragenResultaatType antwoord) {
for (BaseURLType type : antwoord.getBaseURLSet().getBaseURL()) {
if (type.getType().equalsIgnoreCase("anoniem")) {
return type;
}
}
return null;
}
/**
* bepaal de afgifte url.
*
* @param afgifte de afgifte
* @param type de base url
* @return de afgifte url
*/
public static String getAfgifteURL(AfgifteType afgifte, BaseURLType type) {
return type.getValue() + "/" + afgifte.getAfgifteID();
}
/**
* parse datum uit string.
*
* @param dateStr datum in dd-MM-yyyy formaat (evt. {@code null}
* @return datum (of {@code null} in geval van een parse fout of {@code null} argument)
*/
public static GregorianCalendar getDatumTijd(String dateStr) {
if (dateStr == null) {
return null;
}
Date date;
final DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
if (dateStr.equalsIgnoreCase("nu")) {
date = new Date();
} else {
try {
date = format.parse(dateStr);
} catch (ParseException ex) {
LOG.error(ex);
return null;
}
}
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);
return gregory;
}
/**
* parse datum uit string en verschuif {@code dagen}.
*
* @param refDate datum in dd-MM-yyyy formaat (niet {@code null})
* @param before aantal dagen dat de datum verschoven moet worden, bijvoorbeeld -3 voor 3 dagen eerder
* @return datum (of null in geval van een parse fout)
*/
public static GregorianCalendar getDatumTijd(String refDate, int before) {
GregorianCalendar ref = getDatumTijd(refDate);
ref.add(GregorianCalendar.DAY_OF_YEAR, before);
return ref;
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium, houdt rekening met de juiste maand.
*
* @param year jaartal (4 cijfers, > 2000)
* @param month maand (waarde van 0 t/m 12)
* @param day dag van de maand
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(int year, int month, int day) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(
new GregorianCalendar(
year,
month - 1 /* GregorianCalendar heeft 0-based month */,
day)
);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium.
*
* @param date datum (niet {@code null})
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(Date date) {
final GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
/**
* maakt een XML datum die te gebruiken is in een "van" of "tot" criterium.
*
* @param date datum (niet {@code null})
* @return xml datum (of null ingeval van een DatatypeConfigurationException)
*/
public static XMLGregorianCalendar getXMLDatumTijd(GregorianCalendar date) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(date);
} catch (DatatypeConfigurationException e) {
LOG.error(e);
return null;
}
}
private GDS2Util() {
}
}
|
22223_4 | 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();
}
/**
* 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.nanoTime();
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.nanoTime(), 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) + " ns.";
}
}
/**
* 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();
}
}
| timgoes1997/jsf32kochfractal | src/timeutil/TimeStamp.java | 1,114 | /**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/ | 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 met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* 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.nanoTime();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik<SUF>*/
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.nanoTime(), 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) + " ns.";
}
}
/**
* 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();
}
}
|
54823_9 | package hsleiden.stenentijdperk.stenentijdperk.Controllers;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Beschavingskaarten.Kaart;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Dobbelsteen;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.StaticHut;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Tool;
import hsleiden.stenentijdperk.stenentijdperk.Managers.ViewManager;
import hsleiden.stenentijdperk.stenentijdperk.Models.BoardModel;
import hsleiden.stenentijdperk.stenentijdperk.Models.PlayerModel;
import hsleiden.stenentijdperk.stenentijdperk.Views.ResourceView;
import hsleiden.stenentijdperk.stenentijdperk.Views.TableauView;
import hsleiden.stenentijdperk.stenentijdperk.observers.BoardObserver;
import java.util.ArrayList;
import java.util.List;
public class BoardController {
private PlayerController playercontroller;
private BoardModel boardmodel;
// TODO naar boardmodel en dan firebase
private ArrayList<PlayerModel> players = new ArrayList<PlayerModel>();
private int[] gegooideWorp;
public BoardController() {
// TODO all references naar temp players moet naar firebase vragen.
PlayerModel matt = new PlayerModel("Matt");
PlayerModel jake = new PlayerModel("Jake");
PlayerModel lucas = new PlayerModel("Lucas");
PlayerModel carlos = new PlayerModel("Carlos");
players.add(matt);
players.add(jake);
players.add(lucas);
players.add(carlos);
playercontroller = new PlayerController();
boardmodel = new BoardModel();
boardmodel.setPlayer(players.get(0)); // Begin van het spel turn eerste speler bepalen.
gegooideWorp = new int[3];
}
public void registerObserver(BoardObserver boardobserver) {
this.boardmodel.register(boardobserver);
}
public Kaart getKaart(int index) {
return this.boardmodel.getKaart(index);
}
public List<Kaart> getKaarten() {
return this.boardmodel.getKaarten();
}
public StaticHut getHut(int stapel) {
return this.boardmodel.getHut(stapel);
}
public List<StaticHut> getHutStapel(int stapel) {
return this.boardmodel.getHutStapel(stapel);
}
public void onResourceButtonClick(int index, int input) {
if (!boardmodel.getPlaced() && boardmodel.requestCap(index) - boardmodel.requestVillagers(index) != 0
&& playercontroller.getPositie(boardmodel.getPlayer(), index) == 0) {
// Dit veranderd de hoeveelheid stamleden van een speler
boardmodel.decreaseVillagers(index, input);
plaatsenStamleden(index, input);
}
}
public boolean stamledenCheck(int index, int input) {
return (input > 0 && input <= playercontroller.getVillagers(boardmodel.getPlayer())
&& input <= (boardmodel.requestCap(index) - boardmodel.requestVillagers(index)));
}
public void onButtonClick(int index) {
if (vraagPhase() == 1) {
buttonCheckPhase1(index);
} else {
buttonCheckPhase2(index);
}
}
// Hier is het rollen voor resources.
public void resolveResource(int index) {
gegooideWorp[0] = index;
int stamleden = playercontroller.getPositie(boardmodel.getPlayer(), index);
if (stamleden != 0) {
Dobbelsteen roll = new Dobbelsteen(stamleden);
roll.worp();
roll.berekenTotaal();
gegooideWorp[1] = roll.getTotaal();
gegooideWorp[2] = stamleden;
if (playercontroller.getTools(boardmodel.getPlayer()).size() != 0 && checkTools()) {
ViewManager.loadPopupWindow(new TableauView(boardmodel.getPlayer(), this, gegooideWorp[1]).setScene());
} else {
toolsGebruiken(0);
}
}
}
public void toolsGebruiken(int waarde) {
int index = gegooideWorp[0];
int roltotaal = gegooideWorp[1] + waarde;
int stamleden = gegooideWorp[2];
int resources = roltotaal / boardmodel.getResource(index).getWaarde();
if (resources > boardmodel.getResource(index).getHoeveelheid()) {
resources = boardmodel.getResource(index).getHoeveelheid();
}
boardmodel.reduceResources(index, resources);
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
boardmodel.getPlayer().addResources(index, resources);
boardmodel.getLocaties().get(index).reduceVillager(stamleden);
}
private boolean checkTools() {
boolean toolsLeft = false;
for (Tool tool : playercontroller.getTools(boardmodel.getPlayer())) {
if (tool.getStatus()) {
toolsLeft = true;
}
}
return toolsLeft;
}
private void gainTools(int index) {
if ((playercontroller.getPositie(boardmodel.getPlayer(), index) != 0)) {
ArrayList<Tool> tools = playercontroller.getTools(boardmodel.getPlayer());
if (tools.size() < 3) {
playercontroller.addTool(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
} else if (tools.get(2).getLevel() != 4) {
for (int i = 0; i < 3; i++) {
if (tools.get(i).getLevel() == tools.get(2).getLevel()) {
tools.get(i).increaseLevel();
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
break;
}
}
}
}
}
public void endTurn() {
if (boardmodel.getPlaced()) { // checkt of de speler stamleden heeft geplaast.
boolean villagersLeft = true;
int i = checkPlayer();
switch (i) { // Verschillede loops bepaalt door welke speler aan de beurt was
case 0: // Spelers 1, 2 en 3
case 1:
case 2:
villagersLeft = loopPlayers(i, players);
boardmodel.setPlaced(false);
if (!villagersLeft) { // Als de vorige loop niks gevonden heeft dan komt deze pas
villagersLeft = loopPlayers(-1, players.subList(0, i + 1));
}
break;
case 3:
villagersLeft = loopPlayers(i - 4, players);
boardmodel.setPlaced(false);
break;
}
if (!villagersLeft) {
boardmodel.setPhase(2);
int turnCheck = (boardmodel.getTurn() - 1) % 4;
boardmodel.setPlayer(players.get(turnCheck));
// TODO Dit moet een soort pop up worden.
System.out.println("Nu komen de acties");
}
}
}
public boolean EndTurnPhase2() {
boolean eindeSpel = false;
List<Integer> posities = playercontroller.vraagPosities(boardmodel.getPlayer());
if (posities.stream().allMatch(n -> n == 0)) {
int i = checkPlayer();
if (i == 3) {
boardmodel.setPlayer(players.get(0));
} else {
i++;
boardmodel.setPlayer(players.get(i));
}
posities = playercontroller.vraagPosities(boardmodel.getPlayer());
}
if (posities.stream().allMatch(n -> n == 0)) {
System.out.println("Einde Ronde");
boardmodel.setPhase(1);
for (PlayerModel player : players) {
List<Integer> resources = playercontroller.vraagResources(player);
int remaining = voedselBetalen(player);
for (int j = 1; j < resources.size(); j++) {
if (remaining != 0 && !(resources.stream().allMatch(n -> n == 0))) {
for (int k = resources.get(j); k > 0; k--) {
if (remaining != 0) {
remaining -= 1;
playercontroller.reduceResource(player, j, 1);
boardmodel.addResources(j, 1);
} else {
break;
}
}
} else if (resources.stream().allMatch(n -> n == 0)) {
player.setPunten(player.getPunten() - 10);
break;
} else {
break;
}
}
playercontroller.setVillagers(player, playercontroller.getMaxVillagers(player));
for (Tool tool : playercontroller.getTools(player)) {
tool.setStatus(true);
}
}
boardmodel.notifyAllObservers();
if (checkWincondition()) {
eindeSpel = true;
endGame();
}
}
return eindeSpel;
}
public int vraagPhase() {
return boardmodel.getPhase();
}
private void moreAgriculture(int index) {
if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0
&& playercontroller.vraagGraan(boardmodel.getPlayer()) != 10) {
playercontroller.addGraan(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
}
}
private void moreVillagerHut(int index) {
if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0
&& playercontroller.getMaxVillagers(boardmodel.getPlayer()) != 10) {
playercontroller.addMaxVillagers(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
}
}
private void buttonCheckPhase1(int index) {
if (locatieVrij(index) && !boardmodel.getPlaced()) {
if (index == 6 && playercontroller.getVillagers(boardmodel.getPlayer()) >= 2) {
plaatsenStamleden(index, 2);
} else if (index != 6) {
plaatsenStamleden(index, 1);
}
}
}
private void buttonCheckPhase2(int index) {
switch (index) {
case 5:
moreAgriculture(index);
break;
case 6:
moreVillagerHut(index);
break;
case 7:
gainTools(index);
break;
case 8:
case 9:
case 10:
case 11:
hutActie(index - 8);
break;
case 12:
case 13:
case 14:
case 15:
beschavingsKaarActie(index - 12);
break;
}
}
private void beschavingsKaarActie(int index) {
if ((playercontroller.getPositie(boardmodel.getPlayer(), (index + 12)) != 0)) {
ViewManager.loadPopupWindow(new ResourceView(boardmodel.getPlayer(), this.playercontroller, this,
(index + 1), 0, index, "beschavingskaart"));
}
}
public void kaartGekocht(int index, List<Integer> resources, String type) {
if (type.equals("beschavingskaart")) {
if (resourcesBetalen(resources)) {
this.boardmodel.getPlayer().addKaarten(this.boardmodel.getKaart(index));
this.boardmodel.getKaart(index).uitvoerenActie(this.boardmodel.getPlayer());
this.boardmodel.updatePunten();
this.boardmodel.removeKaart(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0);
} else {
if (resourcesBetalen(resources)) {
int punten = (resources.get(0) * 3) + (resources.get(1) * 4) + (resources.get(2) * 5)
+ (resources.get(3) * 6);
this.boardmodel.getPlayer().increasePunten(punten);
this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index));
this.boardmodel.updatePunten();
this.boardmodel.removeHut(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
public void kaartAnnuleer(int index, String type) {
if (type.equals("beschavingskaart")) {
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0);
} else {
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
private void hutActie(int index) {
if ((this.playercontroller.getPositie(this.boardmodel.getPlayer(), (index + 8)) != 0)) {
if (this.boardmodel.getHut(index).getPunten() == 0) {
ViewManager.loadPopupWindow(new ResourceView(this.boardmodel.getPlayer(), this.playercontroller, this,
this.boardmodel.getHut(index).getKosten().get(0),
this.boardmodel.getHut(index).getKosten().get(1), index, "hutkaart"));
} else {
if (resourcesBetalen(this.boardmodel.getHut(index).getKosten())) {
this.boardmodel.getPlayer().increasePunten(this.boardmodel.getHut(index).getPunten());
this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index));
this.boardmodel.updatePunten();
this.boardmodel.removeHut(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
}
private int voedselBetalen(PlayerModel player) {
int remaining = 0;
int voedselNodig = playercontroller.getMaxVillagers(player) - playercontroller.vraagGraan(player);
int voedselSpeler = playercontroller.vraagResources(player).get(0);
if (voedselSpeler >= voedselNodig) {
playercontroller.reduceResource(player, 0, voedselNodig);
boardmodel.addResources(0, voedselNodig);
} else {
playercontroller.reduceResource(player, 0, voedselSpeler);
remaining = voedselNodig - voedselSpeler;
boardmodel.addResources(0, voedselSpeler);
}
return remaining;
}
// Methode om door lijsten spelers te loopen.
private boolean loopPlayers(int start, List<PlayerModel> player) {
boolean found = false;
for (int j = start + 1; j < player.size(); j++) {
if (playercontroller.getVillagers(player.get(j)) != 0) {
boardmodel.setPlayer(player.get(j)); // Veranderd de huidige speler
found = true;
break;
}
}
return found;
}
private int checkPlayer() {
int i = 0;
for (int j = 0; j < 4; j++) {
if (boardmodel.getPlayer().equals(players.get(j))) { // Bepaling welke player aan de beurt is
i = j;
break;
}
}
return i;
}
private boolean checkResourceKost(int resource, List<Integer> kost) {
return boardmodel.getPlayer().getResource(resource + 1) >= kost.get(resource);
}
private boolean locatieVrij(int index) {
boolean status = true;
for (PlayerModel player : players) {
if (player.getPositie(index) != 0) {
status = false;
}
}
return status;
}
private void plaatsenStamleden(int index, int stamleden) {
boardmodel.setPlaced(true);
playercontroller.setVillagers(boardmodel.getPlayer(),
(playercontroller.getVillagers(boardmodel.getPlayer()) - stamleden));
playercontroller.setPositie(boardmodel.getPlayer(), index, stamleden);
}
private boolean resourcesBetalen(List<Integer> kost) {
if (checkResourceKost(0, kost) && checkResourceKost(1, kost) && checkResourceKost(2, kost)
&& checkResourceKost(3, kost)) {
int i = 1;
for (Integer amount : kost) {
playercontroller.reduceResource(boardmodel.getPlayer(), i, amount);
boardmodel.changeHoeveelheid(i, amount);
i++;
}
return true;
} else {
return false;
}
}
private void endGame() {
for (PlayerModel player : players) {
finalPuntenCount(player);
}
}
private boolean checkWincondition() {
boolean endGame = false;
for (int i = 0; i < 4; i++) {
if (boardmodel.getHutStapel(i).size() == 0) {
endGame = true;
}
}
if (boardmodel.getKaarten().size() < 4) {
endGame = true;
}
return endGame;
}
private void finalPuntenCount(PlayerModel player) {
List<Integer> multipliers = playercontroller.getMultiplier(player);
for (Tool tool : playercontroller.getTools(player)) {
this.playercontroller.increasePunten(player, multipliers.get(0) * tool.getLevel());
}
this.playercontroller.increasePunten(player,
multipliers.get(1) * this.playercontroller.getHutjes(player).size());
this.playercontroller.increasePunten(player,
multipliers.get(2) * this.playercontroller.getMaxVillagers(player));
this.playercontroller.increasePunten(player, multipliers.get(3) * this.playercontroller.vraagGraan(player));
this.playercontroller.increasePunten(player,
this.playercontroller.getTreasures(player).size() * this.playercontroller.getTreasures(player).size());
this.boardmodel.updatePunten();
}
// TODO tijdelijk
public ArrayList<PlayerModel> getPlayers() {
return this.players;
}
public PlayerModel getPlayer() {
return boardmodel.getPlayer();
}
}
| DankGaming/stenentijdperk | src/main/java/hsleiden/stenentijdperk/stenentijdperk/Controllers/BoardController.java | 4,776 | // TODO Dit moet een soort pop up worden. | line_comment | nl | package hsleiden.stenentijdperk.stenentijdperk.Controllers;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Beschavingskaarten.Kaart;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Dobbelsteen;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.StaticHut;
import hsleiden.stenentijdperk.stenentijdperk.Helpers.Tool;
import hsleiden.stenentijdperk.stenentijdperk.Managers.ViewManager;
import hsleiden.stenentijdperk.stenentijdperk.Models.BoardModel;
import hsleiden.stenentijdperk.stenentijdperk.Models.PlayerModel;
import hsleiden.stenentijdperk.stenentijdperk.Views.ResourceView;
import hsleiden.stenentijdperk.stenentijdperk.Views.TableauView;
import hsleiden.stenentijdperk.stenentijdperk.observers.BoardObserver;
import java.util.ArrayList;
import java.util.List;
public class BoardController {
private PlayerController playercontroller;
private BoardModel boardmodel;
// TODO naar boardmodel en dan firebase
private ArrayList<PlayerModel> players = new ArrayList<PlayerModel>();
private int[] gegooideWorp;
public BoardController() {
// TODO all references naar temp players moet naar firebase vragen.
PlayerModel matt = new PlayerModel("Matt");
PlayerModel jake = new PlayerModel("Jake");
PlayerModel lucas = new PlayerModel("Lucas");
PlayerModel carlos = new PlayerModel("Carlos");
players.add(matt);
players.add(jake);
players.add(lucas);
players.add(carlos);
playercontroller = new PlayerController();
boardmodel = new BoardModel();
boardmodel.setPlayer(players.get(0)); // Begin van het spel turn eerste speler bepalen.
gegooideWorp = new int[3];
}
public void registerObserver(BoardObserver boardobserver) {
this.boardmodel.register(boardobserver);
}
public Kaart getKaart(int index) {
return this.boardmodel.getKaart(index);
}
public List<Kaart> getKaarten() {
return this.boardmodel.getKaarten();
}
public StaticHut getHut(int stapel) {
return this.boardmodel.getHut(stapel);
}
public List<StaticHut> getHutStapel(int stapel) {
return this.boardmodel.getHutStapel(stapel);
}
public void onResourceButtonClick(int index, int input) {
if (!boardmodel.getPlaced() && boardmodel.requestCap(index) - boardmodel.requestVillagers(index) != 0
&& playercontroller.getPositie(boardmodel.getPlayer(), index) == 0) {
// Dit veranderd de hoeveelheid stamleden van een speler
boardmodel.decreaseVillagers(index, input);
plaatsenStamleden(index, input);
}
}
public boolean stamledenCheck(int index, int input) {
return (input > 0 && input <= playercontroller.getVillagers(boardmodel.getPlayer())
&& input <= (boardmodel.requestCap(index) - boardmodel.requestVillagers(index)));
}
public void onButtonClick(int index) {
if (vraagPhase() == 1) {
buttonCheckPhase1(index);
} else {
buttonCheckPhase2(index);
}
}
// Hier is het rollen voor resources.
public void resolveResource(int index) {
gegooideWorp[0] = index;
int stamleden = playercontroller.getPositie(boardmodel.getPlayer(), index);
if (stamleden != 0) {
Dobbelsteen roll = new Dobbelsteen(stamleden);
roll.worp();
roll.berekenTotaal();
gegooideWorp[1] = roll.getTotaal();
gegooideWorp[2] = stamleden;
if (playercontroller.getTools(boardmodel.getPlayer()).size() != 0 && checkTools()) {
ViewManager.loadPopupWindow(new TableauView(boardmodel.getPlayer(), this, gegooideWorp[1]).setScene());
} else {
toolsGebruiken(0);
}
}
}
public void toolsGebruiken(int waarde) {
int index = gegooideWorp[0];
int roltotaal = gegooideWorp[1] + waarde;
int stamleden = gegooideWorp[2];
int resources = roltotaal / boardmodel.getResource(index).getWaarde();
if (resources > boardmodel.getResource(index).getHoeveelheid()) {
resources = boardmodel.getResource(index).getHoeveelheid();
}
boardmodel.reduceResources(index, resources);
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
boardmodel.getPlayer().addResources(index, resources);
boardmodel.getLocaties().get(index).reduceVillager(stamleden);
}
private boolean checkTools() {
boolean toolsLeft = false;
for (Tool tool : playercontroller.getTools(boardmodel.getPlayer())) {
if (tool.getStatus()) {
toolsLeft = true;
}
}
return toolsLeft;
}
private void gainTools(int index) {
if ((playercontroller.getPositie(boardmodel.getPlayer(), index) != 0)) {
ArrayList<Tool> tools = playercontroller.getTools(boardmodel.getPlayer());
if (tools.size() < 3) {
playercontroller.addTool(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
} else if (tools.get(2).getLevel() != 4) {
for (int i = 0; i < 3; i++) {
if (tools.get(i).getLevel() == tools.get(2).getLevel()) {
tools.get(i).increaseLevel();
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
break;
}
}
}
}
}
public void endTurn() {
if (boardmodel.getPlaced()) { // checkt of de speler stamleden heeft geplaast.
boolean villagersLeft = true;
int i = checkPlayer();
switch (i) { // Verschillede loops bepaalt door welke speler aan de beurt was
case 0: // Spelers 1, 2 en 3
case 1:
case 2:
villagersLeft = loopPlayers(i, players);
boardmodel.setPlaced(false);
if (!villagersLeft) { // Als de vorige loop niks gevonden heeft dan komt deze pas
villagersLeft = loopPlayers(-1, players.subList(0, i + 1));
}
break;
case 3:
villagersLeft = loopPlayers(i - 4, players);
boardmodel.setPlaced(false);
break;
}
if (!villagersLeft) {
boardmodel.setPhase(2);
int turnCheck = (boardmodel.getTurn() - 1) % 4;
boardmodel.setPlayer(players.get(turnCheck));
// TODO Dit<SUF>
System.out.println("Nu komen de acties");
}
}
}
public boolean EndTurnPhase2() {
boolean eindeSpel = false;
List<Integer> posities = playercontroller.vraagPosities(boardmodel.getPlayer());
if (posities.stream().allMatch(n -> n == 0)) {
int i = checkPlayer();
if (i == 3) {
boardmodel.setPlayer(players.get(0));
} else {
i++;
boardmodel.setPlayer(players.get(i));
}
posities = playercontroller.vraagPosities(boardmodel.getPlayer());
}
if (posities.stream().allMatch(n -> n == 0)) {
System.out.println("Einde Ronde");
boardmodel.setPhase(1);
for (PlayerModel player : players) {
List<Integer> resources = playercontroller.vraagResources(player);
int remaining = voedselBetalen(player);
for (int j = 1; j < resources.size(); j++) {
if (remaining != 0 && !(resources.stream().allMatch(n -> n == 0))) {
for (int k = resources.get(j); k > 0; k--) {
if (remaining != 0) {
remaining -= 1;
playercontroller.reduceResource(player, j, 1);
boardmodel.addResources(j, 1);
} else {
break;
}
}
} else if (resources.stream().allMatch(n -> n == 0)) {
player.setPunten(player.getPunten() - 10);
break;
} else {
break;
}
}
playercontroller.setVillagers(player, playercontroller.getMaxVillagers(player));
for (Tool tool : playercontroller.getTools(player)) {
tool.setStatus(true);
}
}
boardmodel.notifyAllObservers();
if (checkWincondition()) {
eindeSpel = true;
endGame();
}
}
return eindeSpel;
}
public int vraagPhase() {
return boardmodel.getPhase();
}
private void moreAgriculture(int index) {
if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0
&& playercontroller.vraagGraan(boardmodel.getPlayer()) != 10) {
playercontroller.addGraan(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
}
}
private void moreVillagerHut(int index) {
if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0
&& playercontroller.getMaxVillagers(boardmodel.getPlayer()) != 10) {
playercontroller.addMaxVillagers(boardmodel.getPlayer());
playercontroller.setPositie(boardmodel.getPlayer(), index, 0);
}
}
private void buttonCheckPhase1(int index) {
if (locatieVrij(index) && !boardmodel.getPlaced()) {
if (index == 6 && playercontroller.getVillagers(boardmodel.getPlayer()) >= 2) {
plaatsenStamleden(index, 2);
} else if (index != 6) {
plaatsenStamleden(index, 1);
}
}
}
private void buttonCheckPhase2(int index) {
switch (index) {
case 5:
moreAgriculture(index);
break;
case 6:
moreVillagerHut(index);
break;
case 7:
gainTools(index);
break;
case 8:
case 9:
case 10:
case 11:
hutActie(index - 8);
break;
case 12:
case 13:
case 14:
case 15:
beschavingsKaarActie(index - 12);
break;
}
}
private void beschavingsKaarActie(int index) {
if ((playercontroller.getPositie(boardmodel.getPlayer(), (index + 12)) != 0)) {
ViewManager.loadPopupWindow(new ResourceView(boardmodel.getPlayer(), this.playercontroller, this,
(index + 1), 0, index, "beschavingskaart"));
}
}
public void kaartGekocht(int index, List<Integer> resources, String type) {
if (type.equals("beschavingskaart")) {
if (resourcesBetalen(resources)) {
this.boardmodel.getPlayer().addKaarten(this.boardmodel.getKaart(index));
this.boardmodel.getKaart(index).uitvoerenActie(this.boardmodel.getPlayer());
this.boardmodel.updatePunten();
this.boardmodel.removeKaart(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0);
} else {
if (resourcesBetalen(resources)) {
int punten = (resources.get(0) * 3) + (resources.get(1) * 4) + (resources.get(2) * 5)
+ (resources.get(3) * 6);
this.boardmodel.getPlayer().increasePunten(punten);
this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index));
this.boardmodel.updatePunten();
this.boardmodel.removeHut(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
public void kaartAnnuleer(int index, String type) {
if (type.equals("beschavingskaart")) {
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0);
} else {
this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
private void hutActie(int index) {
if ((this.playercontroller.getPositie(this.boardmodel.getPlayer(), (index + 8)) != 0)) {
if (this.boardmodel.getHut(index).getPunten() == 0) {
ViewManager.loadPopupWindow(new ResourceView(this.boardmodel.getPlayer(), this.playercontroller, this,
this.boardmodel.getHut(index).getKosten().get(0),
this.boardmodel.getHut(index).getKosten().get(1), index, "hutkaart"));
} else {
if (resourcesBetalen(this.boardmodel.getHut(index).getKosten())) {
this.boardmodel.getPlayer().increasePunten(this.boardmodel.getHut(index).getPunten());
this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index));
this.boardmodel.updatePunten();
this.boardmodel.removeHut(index);
} else {
System.out.println("niet genoeg resources");
// TODO deze else verbeteren
}
playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0);
}
}
}
private int voedselBetalen(PlayerModel player) {
int remaining = 0;
int voedselNodig = playercontroller.getMaxVillagers(player) - playercontroller.vraagGraan(player);
int voedselSpeler = playercontroller.vraagResources(player).get(0);
if (voedselSpeler >= voedselNodig) {
playercontroller.reduceResource(player, 0, voedselNodig);
boardmodel.addResources(0, voedselNodig);
} else {
playercontroller.reduceResource(player, 0, voedselSpeler);
remaining = voedselNodig - voedselSpeler;
boardmodel.addResources(0, voedselSpeler);
}
return remaining;
}
// Methode om door lijsten spelers te loopen.
private boolean loopPlayers(int start, List<PlayerModel> player) {
boolean found = false;
for (int j = start + 1; j < player.size(); j++) {
if (playercontroller.getVillagers(player.get(j)) != 0) {
boardmodel.setPlayer(player.get(j)); // Veranderd de huidige speler
found = true;
break;
}
}
return found;
}
private int checkPlayer() {
int i = 0;
for (int j = 0; j < 4; j++) {
if (boardmodel.getPlayer().equals(players.get(j))) { // Bepaling welke player aan de beurt is
i = j;
break;
}
}
return i;
}
private boolean checkResourceKost(int resource, List<Integer> kost) {
return boardmodel.getPlayer().getResource(resource + 1) >= kost.get(resource);
}
private boolean locatieVrij(int index) {
boolean status = true;
for (PlayerModel player : players) {
if (player.getPositie(index) != 0) {
status = false;
}
}
return status;
}
private void plaatsenStamleden(int index, int stamleden) {
boardmodel.setPlaced(true);
playercontroller.setVillagers(boardmodel.getPlayer(),
(playercontroller.getVillagers(boardmodel.getPlayer()) - stamleden));
playercontroller.setPositie(boardmodel.getPlayer(), index, stamleden);
}
private boolean resourcesBetalen(List<Integer> kost) {
if (checkResourceKost(0, kost) && checkResourceKost(1, kost) && checkResourceKost(2, kost)
&& checkResourceKost(3, kost)) {
int i = 1;
for (Integer amount : kost) {
playercontroller.reduceResource(boardmodel.getPlayer(), i, amount);
boardmodel.changeHoeveelheid(i, amount);
i++;
}
return true;
} else {
return false;
}
}
private void endGame() {
for (PlayerModel player : players) {
finalPuntenCount(player);
}
}
private boolean checkWincondition() {
boolean endGame = false;
for (int i = 0; i < 4; i++) {
if (boardmodel.getHutStapel(i).size() == 0) {
endGame = true;
}
}
if (boardmodel.getKaarten().size() < 4) {
endGame = true;
}
return endGame;
}
private void finalPuntenCount(PlayerModel player) {
List<Integer> multipliers = playercontroller.getMultiplier(player);
for (Tool tool : playercontroller.getTools(player)) {
this.playercontroller.increasePunten(player, multipliers.get(0) * tool.getLevel());
}
this.playercontroller.increasePunten(player,
multipliers.get(1) * this.playercontroller.getHutjes(player).size());
this.playercontroller.increasePunten(player,
multipliers.get(2) * this.playercontroller.getMaxVillagers(player));
this.playercontroller.increasePunten(player, multipliers.get(3) * this.playercontroller.vraagGraan(player));
this.playercontroller.increasePunten(player,
this.playercontroller.getTreasures(player).size() * this.playercontroller.getTreasures(player).size());
this.boardmodel.updatePunten();
}
// TODO tijdelijk
public ArrayList<PlayerModel> getPlayers() {
return this.players;
}
public PlayerModel getPlayer() {
return boardmodel.getPlayer();
}
}
|
138203_30 | package agendaStarter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import domein.Appointment;
import domein.Contact;
import domein.Location;
import exception.InformationRequiredException;
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
//
//private Scheduler scheduler = new Scheduler();
//
//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 = scheduler.createAppointment(new AppointmentBuilder(), LocalDateTime.of(2022, 7, 22, 12, 30)
// , null, "Project Demo", createAttendees(4), new Location("Hogeschool Gent, D2.014"));
appt = new Appointment.Builder().startDate(LocalDateTime.of(2022, 7, 22, 12, 30))
.description("projectDemo")
.attendees(createAttendees(4))
.location( new Location("Hogeschool Gent, D2.014"))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
//
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().startDate(LocalDateTime.of(2022, 3, 21, 12, 30))
.location(new Location("Hogeschool Gent, B3.020"))
.description("OOO II")
.attendees(createAttendees(4))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
//
// System.out.println("Meeting : all items are provided");
// //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 = scheduler.createAppointment(new MeetingBuilder(), LocalDateTime.of(2022, 4, 1, 10, 00),
// LocalDateTime.of(2022, 4, 1, 11, 30), "Project II Meeting",
// createAttendees(2) ,new Location("Hogeschool Gent, B1.032"));
appt = new Appointment.MeetingBuilder().startDate(LocalDateTime.of(2022, 4, 1, 10, 00))
.endDate(LocalDateTime.of(2022, 4, 1, 11, 30))
.description("Project II Meeting")
.attendees(createAttendees(2))
.location(new Location("Hogeschool Gent, B1.032"))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
}
// //TODO een printmethode voor bij fouten : wat er voor de constructie ontbreekt
// //
// //public void print...
//
private void printExceptions(InformationRequiredException ex) {
System.out.println(ex.getMessage());
ex.getInformationRequired().forEach(System.out::println);
System.out.println();
}
//
//
//
//
//
// //
// //END TODO printmethode wat ontbreekt
//
} | GuusDb/ASDII | DesignPatterns/Builder/ASDII_AgendaStarter_NL/src/agendaStarter/TestDrive.java | 1,678 | // //TODO een printmethode voor bij fouten : wat er voor de constructie ontbreekt | line_comment | nl | package agendaStarter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import domein.Appointment;
import domein.Contact;
import domein.Location;
import exception.InformationRequiredException;
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
//
//private Scheduler scheduler = new Scheduler();
//
//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 = scheduler.createAppointment(new AppointmentBuilder(), LocalDateTime.of(2022, 7, 22, 12, 30)
// , null, "Project Demo", createAttendees(4), new Location("Hogeschool Gent, D2.014"));
appt = new Appointment.Builder().startDate(LocalDateTime.of(2022, 7, 22, 12, 30))
.description("projectDemo")
.attendees(createAttendees(4))
.location( new Location("Hogeschool Gent, D2.014"))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
//
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().startDate(LocalDateTime.of(2022, 3, 21, 12, 30))
.location(new Location("Hogeschool Gent, B3.020"))
.description("OOO II")
.attendees(createAttendees(4))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
//
// System.out.println("Meeting : all items are provided");
// //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 = scheduler.createAppointment(new MeetingBuilder(), LocalDateTime.of(2022, 4, 1, 10, 00),
// LocalDateTime.of(2022, 4, 1, 11, 30), "Project II Meeting",
// createAttendees(2) ,new Location("Hogeschool Gent, B1.032"));
appt = new Appointment.MeetingBuilder().startDate(LocalDateTime.of(2022, 4, 1, 10, 00))
.endDate(LocalDateTime.of(2022, 4, 1, 11, 30))
.description("Project II Meeting")
.attendees(createAttendees(2))
.location(new Location("Hogeschool Gent, B1.032"))
.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 ex) {
// TODO: handle exception
printExceptions(ex);
}
}
// //TODO een<SUF>
// //
// //public void print...
//
private void printExceptions(InformationRequiredException ex) {
System.out.println(ex.getMessage());
ex.getInformationRequired().forEach(System.out::println);
System.out.println();
}
//
//
//
//
//
// //
// //END TODO printmethode wat ontbreekt
//
} |
56062_0 | package nl.hsleiden.idepa.simplefactory.linebreaker;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextEditorView extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Linebreaker with Factory Pattern");
GridPane grid = new GridPane();
primaryStage.setX(550);
primaryStage.setY(133);
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Scene scene = new Scene(grid, 500, 275);
primaryStage.setScene(scene);
Text scenetitle = new Text("Linebreaker with Factory Pattern");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
grid.add(scenetitle, 0, 0, 2, 1);
final TextArea textArea = new TextArea();
textArea.setEditable(false);
/* Tekst uit het TextElement wordt op de TextArea gezet. */
TextElement textElement = new TextElement(LineBreakerFactory.getInstance().getDefaultLineBreaker());
textArea.setText(textElement.getText());
grid.add(textArea, 1, 4);
/*
* Verschillende linebreaker mogelijkheden worden toegevoegd aan de
* choicebox
*/
List<String> lineBreakerNames = LineBreakerFactory.getInstance().getLineBreakerNames();
ChoiceBox<String> cb = new ChoiceBox<String>(FXCollections.observableArrayList(lineBreakerNames));
grid.add(cb, 1, 1);
cb.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/*
* Op basis van de gekozen linebreaker wordt deze aangemaakt
* door de factory. Daarna wordt deze gebruikt om de tekst te
* formateren en te tonen op het scherm
*/
String lineBreakerChoice = cb.getValue();
LineBreaker createLineBreaker = LineBreakerFactory.getInstance().createLineBreaker(lineBreakerChoice);
textElement.setLineBreaker(createLineBreaker);
String breakLines = createLineBreaker.breakLines(textElement.getText());
textArea.setText(breakLines);
}
});
primaryStage.show();
}
} | alexvanmanen/idepa | src/nl/hsleiden/idepa/simplefactory/linebreaker/TextEditorView.java | 720 | /* Tekst uit het TextElement wordt op de TextArea gezet. */ | block_comment | nl | package nl.hsleiden.idepa.simplefactory.linebreaker;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextEditorView extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Linebreaker with Factory Pattern");
GridPane grid = new GridPane();
primaryStage.setX(550);
primaryStage.setY(133);
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Scene scene = new Scene(grid, 500, 275);
primaryStage.setScene(scene);
Text scenetitle = new Text("Linebreaker with Factory Pattern");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
grid.add(scenetitle, 0, 0, 2, 1);
final TextArea textArea = new TextArea();
textArea.setEditable(false);
/* Tekst uit het<SUF>*/
TextElement textElement = new TextElement(LineBreakerFactory.getInstance().getDefaultLineBreaker());
textArea.setText(textElement.getText());
grid.add(textArea, 1, 4);
/*
* Verschillende linebreaker mogelijkheden worden toegevoegd aan de
* choicebox
*/
List<String> lineBreakerNames = LineBreakerFactory.getInstance().getLineBreakerNames();
ChoiceBox<String> cb = new ChoiceBox<String>(FXCollections.observableArrayList(lineBreakerNames));
grid.add(cb, 1, 1);
cb.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/*
* Op basis van de gekozen linebreaker wordt deze aangemaakt
* door de factory. Daarna wordt deze gebruikt om de tekst te
* formateren en te tonen op het scherm
*/
String lineBreakerChoice = cb.getValue();
LineBreaker createLineBreaker = LineBreakerFactory.getInstance().createLineBreaker(lineBreakerChoice);
textElement.setLineBreaker(createLineBreaker);
String breakLines = createLineBreaker.breakLines(textElement.getText());
textArea.setText(breakLines);
}
});
primaryStage.show();
}
} |
8374_0 | package memory;
import java.util.ArrayList;
import java.util.Random;
public class Memory {
/**
* Klass om het memory spel te beheren.
*
* @author Koen
*/
// moeilijkhied moet altijd de helft van het aantal vakjes in het spelersveld zijn.
private int moeilijkheid = 8;
// zou gevuld moeten worden met de arraylist kaarten voor de gui.
private Kaarten[][] memoryVeld;
ArrayList<Kaarten> kaarten = new ArrayList<Kaarten>();
public Memory() {
}
/**Maakt een nieuw spel en vult de ArrayList kaarten met kaartsoort en een random uniek nummer voor elke kaart welke afhankelijk is van de moeilijkheid. Elke kaart komt twee keer voor.
*
* @param kaartsoort
* @param <code>moeilijkheid</code> mag zijn 8, 18, 32.
*/
public void nieuwSpel(String kaartsoort, int moeilijkheid){
kaarten.clear();
this.moeilijkheid = moeilijkheid;
ArrayList<Integer> rnummers1 = randomNummers(moeilijkheid);
ArrayList<Integer> rnummers2 = randomNummers(moeilijkheid);
for(int i = 1; i <=moeilijkheid; i++){
int randomTijdelijk = rnummers1.get(i -1);
kaarten.add(new Kaarten(kaartsoort, randomTijdelijk));
int randomTijdelijk2 = rnummers2.get(i-1);
kaarten.add(new Kaarten(kaartsoort, randomTijdelijk2));
}
//memoryVeld = new Kaarten[4][4];
}
public ArrayList<Kaarten> getKaarten(){
return kaarten;
}
/**
* Stel de moelijkhied in van het spel. Mogelijke invoeringen 8, 18, 32.
* @param moeilijkheid
*/
public void setMoeilijkheid(int moeilijkheid) {
this.moeilijkheid = moeilijkheid;
}
/**
* Kijkt of twee kaarten gelijk zijn aan elkaar.
* @param kaart1
* @param kaart2
* @return <code>false</code> als het niet dezelfde kaarten zijn, <code>true</code> als het wel dezelfde kaarten zijn.
*/
public boolean zijnGelijk(Kaarten kaart1, Kaarten kaart2){
if (kaart1.getNummer() == kaart2.getNummer()){
return true;
}
return false;
}
/**Maakt een Arraylist met random unieke nummers tussen 1 en en moeilijkheid van lengte moeilijkheid.
*
* @author Koen
* @param moeilijkheid
* @return een Arraylist gevult met unieke random nummers van de lengte moeilijkheid.
*/
public ArrayList<Integer> randomNummers(int moeilijkheid){
ArrayList<Integer> nummers = new ArrayList<Integer>();
Random random = new Random();
while(nummers.size() < moeilijkheid){
int hulp = 1 + random.nextInt(moeilijkheid);
if(!nummers.contains(hulp)){
nummers.add(hulp);
}
}
return nummers;
}
}
| Mandiax/GameSuite | GameSuiteMain/src/memory/Memory.java | 855 | /**
* Klass om het memory spel te beheren.
*
* @author Koen
*/ | block_comment | nl | package memory;
import java.util.ArrayList;
import java.util.Random;
public class Memory {
/**
* Klass om het<SUF>*/
// moeilijkhied moet altijd de helft van het aantal vakjes in het spelersveld zijn.
private int moeilijkheid = 8;
// zou gevuld moeten worden met de arraylist kaarten voor de gui.
private Kaarten[][] memoryVeld;
ArrayList<Kaarten> kaarten = new ArrayList<Kaarten>();
public Memory() {
}
/**Maakt een nieuw spel en vult de ArrayList kaarten met kaartsoort en een random uniek nummer voor elke kaart welke afhankelijk is van de moeilijkheid. Elke kaart komt twee keer voor.
*
* @param kaartsoort
* @param <code>moeilijkheid</code> mag zijn 8, 18, 32.
*/
public void nieuwSpel(String kaartsoort, int moeilijkheid){
kaarten.clear();
this.moeilijkheid = moeilijkheid;
ArrayList<Integer> rnummers1 = randomNummers(moeilijkheid);
ArrayList<Integer> rnummers2 = randomNummers(moeilijkheid);
for(int i = 1; i <=moeilijkheid; i++){
int randomTijdelijk = rnummers1.get(i -1);
kaarten.add(new Kaarten(kaartsoort, randomTijdelijk));
int randomTijdelijk2 = rnummers2.get(i-1);
kaarten.add(new Kaarten(kaartsoort, randomTijdelijk2));
}
//memoryVeld = new Kaarten[4][4];
}
public ArrayList<Kaarten> getKaarten(){
return kaarten;
}
/**
* Stel de moelijkhied in van het spel. Mogelijke invoeringen 8, 18, 32.
* @param moeilijkheid
*/
public void setMoeilijkheid(int moeilijkheid) {
this.moeilijkheid = moeilijkheid;
}
/**
* Kijkt of twee kaarten gelijk zijn aan elkaar.
* @param kaart1
* @param kaart2
* @return <code>false</code> als het niet dezelfde kaarten zijn, <code>true</code> als het wel dezelfde kaarten zijn.
*/
public boolean zijnGelijk(Kaarten kaart1, Kaarten kaart2){
if (kaart1.getNummer() == kaart2.getNummer()){
return true;
}
return false;
}
/**Maakt een Arraylist met random unieke nummers tussen 1 en en moeilijkheid van lengte moeilijkheid.
*
* @author Koen
* @param moeilijkheid
* @return een Arraylist gevult met unieke random nummers van de lengte moeilijkheid.
*/
public ArrayList<Integer> randomNummers(int moeilijkheid){
ArrayList<Integer> nummers = new ArrayList<Integer>();
Random random = new Random();
while(nummers.size() < moeilijkheid){
int hulp = 1 + random.nextInt(moeilijkheid);
if(!nummers.contains(hulp)){
nummers.add(hulp);
}
}
return nummers;
}
}
|
14955_11 | import java.awt.Label;
public class Opdracht2WEEE
{
public static void main(String[] args)
{
// MAAK ALLE ONDERDELEN AF OM DE OPDRACHT TE VOLTOOIEN!
OnderdeelEen();
OnderdeelTwee();
OnderdeelDrie();
}
public static void OnderdeelEen()
{
/*
* ################## VARIABELEN MAKEN ##################
*
* Maak twee variabelen en print de waarde van deze variabelen uit.
* De eerste variabele moet een "boolean" zijn en de tweede variabele
* moet een "String" zijn. (Zorg ervoor dat de String gevuld is. ;D )
*
*/
System.out.println("################## VARIABELEN MAKEN ##################");
// Maak hier de variabelen:
// VERVANG DE COMMENT (inclusief /* en */ ) MET JOUW VARIABELEN!
System.out.println( /* HIER KOMT VARIABELE A */ );
System.out.println( /* HIER KOMT VARIABELE B */ );
}
public static void OnderdeelTwee()
{
/*
* ################## DATATYPES ##################
*
* Zorg ervoor dat de correcte soort waarde in de getypeerde variabelen terecht komt.
*
*/
// Vul de correcte waarde bij deze variabelen in:
String variabeleA;
boolean variabeleB;
int variabeleC;
Label variabeleD = new Label("Naam van het Label"); // Deze klopt al.
char variabeleE;
double variabeleF;
float variabeleG;
// Hier worden de resultaten geprint:
System.out.println("################## DATATYPES ##################");
System.out.println(variabeleA);
System.out.println(variabeleB);
System.out.println(variabeleC);
System.out.println(variabeleD.getText());
System.out.println(variabeleE);
System.out.println(variabeleF);
System.out.println(variabeleG);
}
public static void OnderdeelDrie()
{
/*
* ################## VARIABELEN IN VARIABELEN ##################
*
* Maak 8 variabelen in totaal, waarvan 2 een "boolean" zijn, 3 een "int" en 3 een "String".
*
* Boolean 1 heeft een ja/nee waarde.
* Boolean 2 heeft een referentie naar boolean 1.
*
* Int 1 heeft een getallenwaarde.
* Int 2 heeft een getallenwaarde.
* Int 3 heeft de waarde: int 1 - int 2. (int 1 MINUS int 2)
*
* String 1 heeft een tekstwaarde.
* String 2 heeft een tekstwaarde.
* String 3 heeft de waarde: String 1 + String 2. (String 1 PLUS String 2)
*
*
* Vervolgens print je boolean 2, int 3 en String 3 uit.
*
*/
System.out.println("################## VARIABELEN IN VARIABELEN ##################");
// Maak hier de variabelen:
// VERVANG DE COMMENT (inclusief /* en */ ) MET JOUW VARIABELEN!
System.out.println( /* HIER KOMT BOOLEAN 2 */ );
System.out.println( /* HIER KOMT INT 3 */ );
System.out.println( /* HIER KOMT STRING 3 */ );
}
}
| FloortjeTjeertes/TPR | Periode 1/Les 2/Opdracht2WEEE.java | 967 | // Maak hier de variabelen: | line_comment | nl | import java.awt.Label;
public class Opdracht2WEEE
{
public static void main(String[] args)
{
// MAAK ALLE ONDERDELEN AF OM DE OPDRACHT TE VOLTOOIEN!
OnderdeelEen();
OnderdeelTwee();
OnderdeelDrie();
}
public static void OnderdeelEen()
{
/*
* ################## VARIABELEN MAKEN ##################
*
* Maak twee variabelen en print de waarde van deze variabelen uit.
* De eerste variabele moet een "boolean" zijn en de tweede variabele
* moet een "String" zijn. (Zorg ervoor dat de String gevuld is. ;D )
*
*/
System.out.println("################## VARIABELEN MAKEN ##################");
// Maak hier de variabelen:
// VERVANG DE COMMENT (inclusief /* en */ ) MET JOUW VARIABELEN!
System.out.println( /* HIER KOMT VARIABELE A */ );
System.out.println( /* HIER KOMT VARIABELE B */ );
}
public static void OnderdeelTwee()
{
/*
* ################## DATATYPES ##################
*
* Zorg ervoor dat de correcte soort waarde in de getypeerde variabelen terecht komt.
*
*/
// Vul de correcte waarde bij deze variabelen in:
String variabeleA;
boolean variabeleB;
int variabeleC;
Label variabeleD = new Label("Naam van het Label"); // Deze klopt al.
char variabeleE;
double variabeleF;
float variabeleG;
// Hier worden de resultaten geprint:
System.out.println("################## DATATYPES ##################");
System.out.println(variabeleA);
System.out.println(variabeleB);
System.out.println(variabeleC);
System.out.println(variabeleD.getText());
System.out.println(variabeleE);
System.out.println(variabeleF);
System.out.println(variabeleG);
}
public static void OnderdeelDrie()
{
/*
* ################## VARIABELEN IN VARIABELEN ##################
*
* Maak 8 variabelen in totaal, waarvan 2 een "boolean" zijn, 3 een "int" en 3 een "String".
*
* Boolean 1 heeft een ja/nee waarde.
* Boolean 2 heeft een referentie naar boolean 1.
*
* Int 1 heeft een getallenwaarde.
* Int 2 heeft een getallenwaarde.
* Int 3 heeft de waarde: int 1 - int 2. (int 1 MINUS int 2)
*
* String 1 heeft een tekstwaarde.
* String 2 heeft een tekstwaarde.
* String 3 heeft de waarde: String 1 + String 2. (String 1 PLUS String 2)
*
*
* Vervolgens print je boolean 2, int 3 en String 3 uit.
*
*/
System.out.println("################## VARIABELEN IN VARIABELEN ##################");
// Maak hier<SUF>
// VERVANG DE COMMENT (inclusief /* en */ ) MET JOUW VARIABELEN!
System.out.println( /* HIER KOMT BOOLEAN 2 */ );
System.out.println( /* HIER KOMT INT 3 */ );
System.out.println( /* HIER KOMT STRING 3 */ );
}
}
|
139351_21 | /***
* Heavily modified code from the provided framework (UvA Netcentric 2013/2014 course)
*/
package uva.nc.app;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.pm.ActivityInfo;
import java.io.IOException;
import java.lang.Math;
import java.nio.charset.Charset;
import java.util.UUID;
import uva.nc.ServiceActivity;
import uva.nc.bluetooth.BluetoothService;
import uva.nc.mbed.MbedManager;
import uva.nc.mbed.MbedRequest;
import uva.nc.mbed.MbedResponse;
import uva.nc.mbed.MbedService;
import android.widget.FrameLayout;
import android.view.View.OnClickListener;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
/* Import ZBar Class files */
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;
public class MainActivity extends ServiceActivity {
private static final String TAG = MainActivity.class.getName();
// Receiver implemented in separate class, see bottom of file.
private final MainActivityReceiver receiver = new MainActivityReceiver();
// ID's for commands on mBed.
private static final int COMMAND_DRIVE = 1;
// BT Controls.
private TextView listenerStatusText;
private TextView ownAddressText;
private Button connectButton;
private Button disconnectButton;
// mBed Controls.
private TextView mbedConnectedText;
// Layout Controls
private Button showCameraLayout;
private Button showMbedLayout;
private Button showDebugLayout;
private Button showManualLayout;
// Layout Frames
private LinearLayout cameraLayout;
private LinearLayout mbedLayout;
private LinearLayout debugLayout;
private LinearLayout manualLayout;
// Manual Drive Controls
private Button driveForward;
private Button driveBackward;
private Button driveLeft;
private Button driveRight;
// Logging TextView
private TextView logComm;
// Accessory to connect to when service is connected.
private UsbAccessory toConnect;
// Camera Variables
private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;
// QR scanner Variables
ImageScanner scanner;
private boolean barcodeScanned = false;
private boolean previewing = true;
private boolean connected = false;
// Load QR scanner library
static {
System.loadLibrary("iconv");
}
// QR scanner Controls
TextView scanText;
Button scanButton;
// Initialize variables for bluetooth connection
/****
* Device address Floris: 44:6D:57:96:64:F7
* Device address Matthijs: 00:15:83:15:A3:10
* Device address Mike: 44:6D:57:4A:81:D4
* Device address Patrick: A4:17:31:ED:18:F8
* Device address Xander: 00:09:DD:50:8D:2A
*/
private String deviceAddress = "00:15:83:15:A3:10";
private UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
private BluetoothAdapter BA;
private BluetoothThread connection;
BluetoothDevice device;
BluetoothSocket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
attachControls();
//Bluetooth initialize
device = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice(deviceAddress);
// If this intent was started with an accessory, store it temporarily and clear once connected.
UsbAccessory accessory = getIntent().getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (accessory != null) {
this.toConnect = accessory;
}
/***
* Code for QR scanner
* Source: ZBarAndroidSDK-0.2 example
* http://sourceforge.net/projects/zbar/
**/
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
/* Instance barcode scanner */
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
// Add camera preview to layout
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
preview.addView(mPreview);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, receiver.getIntentFilter());
refreshBluetoothControls();
refreshMbedControls();
}
@Override
protected void onPause() {
super.onPause();
releaseCamera();
unregisterReceiver(receiver);
}
@Override
protected void onBluetoothReady(BluetoothService bluetooth) {
refreshBluetoothControls();
}
@Override
protected void onMbedReady(MbedService mbed) {
if (toConnect != null) {
mbed.manager.attach(toConnect);
toConnect = null;
}
refreshMbedControls();
}
private void attachControls() {
// Bluetooth controls.
ownAddressText = (TextView)findViewById(R.id.own_address);
listenerStatusText = (TextView)findViewById(R.id.listener_status);
connectButton = (Button)findViewById(R.id.listener);
disconnectButton = (Button)findViewById(R.id.disconnect);
// Mbed controls
mbedConnectedText = (TextView)findViewById(R.id.mbed_connected);
// Logging TextView
logComm = (TextView)findViewById(R.id.log_comm);
// Layout controls
cameraLayout = (LinearLayout)findViewById(R.id.camera_layout);
showCameraLayout = (Button)findViewById(R.id.show_camera_layout);
showCameraLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cameraLayout.getVisibility() == View.VISIBLE) {
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
} else {
cameraLayout.setVisibility(View.VISIBLE);
showCameraLayout.setText("Hide Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
mbedLayout = (LinearLayout)findViewById(R.id.mbed_layout);
showMbedLayout = (Button)findViewById(R.id.show_mbed_layout);
showMbedLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mbedLayout.getVisibility() == View.VISIBLE) {
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
} else {
mbedLayout.setVisibility(View.VISIBLE);
showMbedLayout.setText("Hide Connections");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
debugLayout = (LinearLayout)findViewById(R.id.debug_layout);
showDebugLayout = (Button)findViewById(R.id.show_debug_layout);
showDebugLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(debugLayout.getVisibility() == View.VISIBLE) {
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
} else {
debugLayout.setVisibility(View.VISIBLE);
showDebugLayout.setText("Hide Monitoring");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
manualLayout = (LinearLayout)findViewById(R.id.manual_layout);
showManualLayout = (Button)findViewById(R.id.show_manual_layout);
showManualLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(manualLayout.getVisibility() == View.VISIBLE) {
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
} else {
manualLayout.setVisibility(View.VISIBLE);
showManualLayout.setText("Hide Manual Controls");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
}
}
});
// QRscanner controls
scanText = (TextView)findViewById(R.id.scanText);
scanButton = (Button)findViewById(R.id.ScanButton);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (barcodeScanned) {
barcodeScanned = false;
scanText.setText("Scanning...");
mCamera.setPreviewCallback(previewCb);
mCamera.startPreview();
previewing = true;
mCamera.autoFocus(autoFocusCB);
}
}
});
// Manual robot controls
driveForward = (Button)findViewById(R.id.forward);
driveForward.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 1.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive forward message to mbed\n");
}
});
driveBackward = (Button)findViewById(R.id.backward);
driveBackward.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 2.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive backward message to mbed\n");
}
});
driveLeft = (Button)findViewById(R.id.left);
driveLeft.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 3.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive left message to mbed\n");
}
});
driveRight = (Button)findViewById(R.id.right);
driveRight.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 4.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive right message to mbed\n");
}
});
}
// Controls to connect and disconnect to Bluetooth server
private void refreshBluetoothControls() {
String slaveStatus = "Status not available";
String ownAddress = "Not available";
boolean slaveButtonEnabled = false;
// Well it's not pretty, but it (barely) avoids duplicate logic.
final BluetoothService bluetooth = getBluetooth();
if (bluetooth != null) {
slaveButtonEnabled = true;
slaveStatus = "Master connecting";
ownAddress = bluetooth.utility.getOwnAddress();
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Log.i("Masterserver", "Connected");
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
//socket.connect();
} catch (IOException e) {
Log.e("Masterserver", "Error" + e);
}
connection = BluetoothThread.newInstance(socket, bluetoothListener);
}
});
disconnectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
connection.cancel();
Log.i("Masterserver", "Disconnected");
connected = false;
} catch(IOException e) {
Log.e("Masterserver", "Error" + e);
}
}
});
}
listenerStatusText.setText(slaveStatus);
connectButton.setEnabled(slaveButtonEnabled);
disconnectButton.setEnabled(slaveButtonEnabled);
ownAddressText.setText(ownAddress);
}
private void refreshMbedControls() {
String connText = getString(R.string.not_connected); // if you want to localize
MbedService mbed = getMbed();
if (mbed != null && mbed.manager.areChannelsOpen()) {
connText = getString(R.string.connected);
}
mbedConnectedText.setText(connText);
}
// Function receives message from Bluetooth server
private BluetoothThread.Listener bluetoothListener = new BluetoothThread.Listener() {
String currentLocation = "[0, 0]";
String finalDestination = "[0, 0]";
String direction = "None";
String confirmation = "False";
boolean roaming = true;
public void onConnected() {
Log.i("Masterserver", "Connected bluetooth 12");
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.i("Masterserver", "Connected bluetooth");
connected = true;
//MainActivity.this.onConnected(true);
}
});
}
public void onDisconnected() {
Log.i("Masterserver", "Disconnected bluetooth 12");
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.i("Masterserver", "Disconnected bluetooth");
//MainActivity.this.onConnected(false);
}
});
}
public void onError(IOException e) {
}
public void onReceived(byte[] buffer, int length) {
Log.i("Masterserver", "received message with length" + length);
final String Input = new String(buffer, 0, length);
Log.i("Masterserver", "received message = " + Input);
// Hier wordt de finalDestination ontvangen.
if (Input.contains("finalDestination: ")) {
finalDestination = Input.replace("finalDestination: ", "");
roaming = false;
logComm.append("* Received Final Destination\n");
// Hier word de current location ontvangen
} else if (Input.contains("currentLocation: ")) {
currentLocation = Input.replace("currentLocation: ", "");
Log.i("Masterserver", "currenLocation: " + currentLocation);
//scanText.setText("Current Location: " + currentLocation);
//TODO: niet meer locatie/ richting gebruiken die al afgekeurd is
if (roaming) {
direction = RandomDirection();
Log.i("Masterserver", "RandomDirection");
} else {
direction = KortstePadSolver(currentLocation, finalDestination);
Log.i("Masterserver", "KorstePadSolver");
}
SendMessage("direction: " + direction);
// Hier wordt de confirmation ontvangen.
} else if (Input.contains("confirmation: ")) {
confirmation = Input.replace("confirmation: ", "");
logComm.append("* Direction is free\n");
if (confirmation.equals("True")) {
float[] args = new float[1];
logComm.append("* Driving direction: " + direction + "\n");
if(direction.equals("North")) {
args[0] = 1.0f;
} else if(direction.equals("South")) {
args[0] = 2.0f;
} else if(direction.equals("West")) {
args[0] = 3.0f;
} else if(direction.equals("East")) {
args[0] = 4.0f;
}
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
}
}
runOnUiThread(new Runnable() {
public void run() {
}
});
}
public void onMessage(String message) {
Log.i("Masterserver", "Message: " + message);
}
// Function for choosing a random direction to drive to
public String RandomDirection() {
int direction = 1 + (int)(Math.random() * ((4 - 1) + 1));
if (direction == 1)
return "North";
else if (direction == 2)
return "East";
else if (direction == 3)
return "South";
else if (direction == 4)
return "West";
return "None";
}
// Function for finding the shortest path to the final destination of the omnibot
public String KortstePadSolver(String currentLocation, String finalDestination) {
/* currentLocation -> "[x, y]" */
/* finalDestination -> "[x, y]" */
int currentX = Integer.valueOf(String.valueOf(currentLocation.charAt(1)));
int currentY = Integer.valueOf(String.valueOf(currentLocation.charAt(4)));
int finalX = Integer.valueOf(String.valueOf(finalDestination.charAt(1)));
int finalY = Integer.valueOf(String.valueOf(finalDestination.charAt(4)));
if (Math.abs(finalX - currentX) == 0 && Math.abs(finalY - currentY) == 0) {
return "Done";
}
if (Math.abs(finalX - currentX) > Math.abs(finalY - currentY)) {
if (finalX > currentX)
return "East";
else
return "West";
} else {
if (finalY > currentY)
return "North";
else
return "South";
}
}
// Sends message to Bluetooth server
public void SendMessage(String Message) {
byte[] b = Message.getBytes(Charset.forName("UTF-8"));
try {
connection.write(b);
logComm.append("* Sent " + Message + " to master\n");
} catch (IOException e) {
Log.e("Masterserver", "Error with write");
}
}
};
/***
* Functions for QR scanner
* Source: ZBarAndroidSDK-0.2 example
* http://sourceforge.net/projects/zbar/
*
* Copied:
* getCamerainstance()
* releaseCamera()
* doAutoFocus()
* autoFocusCB()
*
* Modified:
* previewCb()
**/
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
} catch (Exception e){
}
return c;
}
private void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (previewing)
mCamera.autoFocus(autoFocusCB);
}
};
// QR scanner automatically sends message to Bluetooth server after scanning a QR code
// and pauses the scanner
PreviewCallback previewCb = new PreviewCallback() {
public void SendMessage(String Message) {
byte[] b = Message.getBytes(Charset.forName("UTF-8"));
try {
Log.i("message", Message);
connection.write(b);
logComm.append("* Sent " + Message + " to master\n");
} catch (IOException e) {
Log.e("Masterserver", "Error with write");
}
}
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = scanner.scanImage(barcode);
if (result != 0 && connected) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms) {
String QRdata = sym.getData();
Log.i("message", QRdata);
scanText.setText("QR-Code: " + QRdata);
SendMessage("QRdata: " + QRdata);
barcodeScanned = true;
}
} else if(result != 0 && !connected) {
Log.i("Bluetooth", "Scanned while not connected!");
}
}
};
// Mimic continuous auto-focusing
AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
autoFocusHandler.postDelayed(doAutoFocus, 1000);
}
};
// Broadcast receiver which handles incoming events. If it were smaller, inline it.
private class MainActivityReceiver extends BroadcastReceiver {
// Refresh Mbed controls on these events.
private final String MBED_REFRESH_ON[] = { MbedManager.DEVICE_ATTACHED,
MbedManager.DEVICE_DETACHED };
// Returns intents this receiver responds to.
protected IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
// Notification updates.
for (String action : MBED_REFRESH_ON) {
filter.addAction(action);
}
// Data received events.
filter.addAction(MbedManager.DATA_READ);
return filter;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Refresh on most mBed events.
for (String update : MBED_REFRESH_ON) {
if (action.equals(update)) {
refreshMbedControls();
break;
}
}
// Process received data from Mbed
if (action.equals(MbedManager.DATA_READ)) {
// mBed data received.
MbedResponse response = intent.getParcelableExtra(MbedManager.EXTRA_DATA);
if (response != null) {
// Errors handled as separate case, but this is just sample code.
if (response.hasError()) {
toastLong("Error! " + response);
return;
}
float[] values = response.getValues();
if (response.getCommandId() == COMMAND_DRIVE) {
if (values == null || values.length != 1) {
toastShort("Error!");
} else {
// Resumes QR scanner when omnibot finished driving
logComm.append("* Finished driving, activate QR scanner\n");
if((int)values[0] == 0) {
if (barcodeScanned) {
barcodeScanned = false;
scanText.setText("Scanning...");
mCamera.setPreviewCallback(previewCb);
mCamera.startPreview();
previewing = true;
mCamera.autoFocus(autoFocusCB);
}
}
}
}
}
}
}
}
}
| matthijsthoolen/netcentric-2 | RobotApp/app/src/main/java/uva/nc/app/MainActivity.java | 6,004 | // Hier word de current location ontvangen | line_comment | nl | /***
* Heavily modified code from the provided framework (UvA Netcentric 2013/2014 course)
*/
package uva.nc.app;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.pm.ActivityInfo;
import java.io.IOException;
import java.lang.Math;
import java.nio.charset.Charset;
import java.util.UUID;
import uva.nc.ServiceActivity;
import uva.nc.bluetooth.BluetoothService;
import uva.nc.mbed.MbedManager;
import uva.nc.mbed.MbedRequest;
import uva.nc.mbed.MbedResponse;
import uva.nc.mbed.MbedService;
import android.widget.FrameLayout;
import android.view.View.OnClickListener;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
/* Import ZBar Class files */
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.Config;
public class MainActivity extends ServiceActivity {
private static final String TAG = MainActivity.class.getName();
// Receiver implemented in separate class, see bottom of file.
private final MainActivityReceiver receiver = new MainActivityReceiver();
// ID's for commands on mBed.
private static final int COMMAND_DRIVE = 1;
// BT Controls.
private TextView listenerStatusText;
private TextView ownAddressText;
private Button connectButton;
private Button disconnectButton;
// mBed Controls.
private TextView mbedConnectedText;
// Layout Controls
private Button showCameraLayout;
private Button showMbedLayout;
private Button showDebugLayout;
private Button showManualLayout;
// Layout Frames
private LinearLayout cameraLayout;
private LinearLayout mbedLayout;
private LinearLayout debugLayout;
private LinearLayout manualLayout;
// Manual Drive Controls
private Button driveForward;
private Button driveBackward;
private Button driveLeft;
private Button driveRight;
// Logging TextView
private TextView logComm;
// Accessory to connect to when service is connected.
private UsbAccessory toConnect;
// Camera Variables
private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;
// QR scanner Variables
ImageScanner scanner;
private boolean barcodeScanned = false;
private boolean previewing = true;
private boolean connected = false;
// Load QR scanner library
static {
System.loadLibrary("iconv");
}
// QR scanner Controls
TextView scanText;
Button scanButton;
// Initialize variables for bluetooth connection
/****
* Device address Floris: 44:6D:57:96:64:F7
* Device address Matthijs: 00:15:83:15:A3:10
* Device address Mike: 44:6D:57:4A:81:D4
* Device address Patrick: A4:17:31:ED:18:F8
* Device address Xander: 00:09:DD:50:8D:2A
*/
private String deviceAddress = "00:15:83:15:A3:10";
private UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
private BluetoothAdapter BA;
private BluetoothThread connection;
BluetoothDevice device;
BluetoothSocket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
attachControls();
//Bluetooth initialize
device = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice(deviceAddress);
// If this intent was started with an accessory, store it temporarily and clear once connected.
UsbAccessory accessory = getIntent().getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
if (accessory != null) {
this.toConnect = accessory;
}
/***
* Code for QR scanner
* Source: ZBarAndroidSDK-0.2 example
* http://sourceforge.net/projects/zbar/
**/
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
/* Instance barcode scanner */
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
// Add camera preview to layout
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
preview.addView(mPreview);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, receiver.getIntentFilter());
refreshBluetoothControls();
refreshMbedControls();
}
@Override
protected void onPause() {
super.onPause();
releaseCamera();
unregisterReceiver(receiver);
}
@Override
protected void onBluetoothReady(BluetoothService bluetooth) {
refreshBluetoothControls();
}
@Override
protected void onMbedReady(MbedService mbed) {
if (toConnect != null) {
mbed.manager.attach(toConnect);
toConnect = null;
}
refreshMbedControls();
}
private void attachControls() {
// Bluetooth controls.
ownAddressText = (TextView)findViewById(R.id.own_address);
listenerStatusText = (TextView)findViewById(R.id.listener_status);
connectButton = (Button)findViewById(R.id.listener);
disconnectButton = (Button)findViewById(R.id.disconnect);
// Mbed controls
mbedConnectedText = (TextView)findViewById(R.id.mbed_connected);
// Logging TextView
logComm = (TextView)findViewById(R.id.log_comm);
// Layout controls
cameraLayout = (LinearLayout)findViewById(R.id.camera_layout);
showCameraLayout = (Button)findViewById(R.id.show_camera_layout);
showCameraLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cameraLayout.getVisibility() == View.VISIBLE) {
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
} else {
cameraLayout.setVisibility(View.VISIBLE);
showCameraLayout.setText("Hide Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
mbedLayout = (LinearLayout)findViewById(R.id.mbed_layout);
showMbedLayout = (Button)findViewById(R.id.show_mbed_layout);
showMbedLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mbedLayout.getVisibility() == View.VISIBLE) {
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
} else {
mbedLayout.setVisibility(View.VISIBLE);
showMbedLayout.setText("Hide Connections");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
debugLayout = (LinearLayout)findViewById(R.id.debug_layout);
showDebugLayout = (Button)findViewById(R.id.show_debug_layout);
showDebugLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(debugLayout.getVisibility() == View.VISIBLE) {
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
} else {
debugLayout.setVisibility(View.VISIBLE);
showDebugLayout.setText("Hide Monitoring");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
}
}
});
manualLayout = (LinearLayout)findViewById(R.id.manual_layout);
showManualLayout = (Button)findViewById(R.id.show_manual_layout);
showManualLayout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(manualLayout.getVisibility() == View.VISIBLE) {
manualLayout.setVisibility(View.GONE);
showManualLayout.setText("Show Manual Controls");
} else {
manualLayout.setVisibility(View.VISIBLE);
showManualLayout.setText("Hide Manual Controls");
cameraLayout.setVisibility(View.GONE);
showCameraLayout.setText("Show Camera Preview");
mbedLayout.setVisibility(View.GONE);
showMbedLayout.setText("Show Connections");
debugLayout.setVisibility(View.GONE);
showDebugLayout.setText("Show Monitoring");
}
}
});
// QRscanner controls
scanText = (TextView)findViewById(R.id.scanText);
scanButton = (Button)findViewById(R.id.ScanButton);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (barcodeScanned) {
barcodeScanned = false;
scanText.setText("Scanning...");
mCamera.setPreviewCallback(previewCb);
mCamera.startPreview();
previewing = true;
mCamera.autoFocus(autoFocusCB);
}
}
});
// Manual robot controls
driveForward = (Button)findViewById(R.id.forward);
driveForward.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 1.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive forward message to mbed\n");
}
});
driveBackward = (Button)findViewById(R.id.backward);
driveBackward.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 2.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive backward message to mbed\n");
}
});
driveLeft = (Button)findViewById(R.id.left);
driveLeft.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 3.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive left message to mbed\n");
}
});
driveRight = (Button)findViewById(R.id.right);
driveRight.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
float[] args = new float[1];
args[0] = 4.0f;
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
logComm.append("* Sent Drive right message to mbed\n");
}
});
}
// Controls to connect and disconnect to Bluetooth server
private void refreshBluetoothControls() {
String slaveStatus = "Status not available";
String ownAddress = "Not available";
boolean slaveButtonEnabled = false;
// Well it's not pretty, but it (barely) avoids duplicate logic.
final BluetoothService bluetooth = getBluetooth();
if (bluetooth != null) {
slaveButtonEnabled = true;
slaveStatus = "Master connecting";
ownAddress = bluetooth.utility.getOwnAddress();
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Log.i("Masterserver", "Connected");
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
//socket.connect();
} catch (IOException e) {
Log.e("Masterserver", "Error" + e);
}
connection = BluetoothThread.newInstance(socket, bluetoothListener);
}
});
disconnectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
connection.cancel();
Log.i("Masterserver", "Disconnected");
connected = false;
} catch(IOException e) {
Log.e("Masterserver", "Error" + e);
}
}
});
}
listenerStatusText.setText(slaveStatus);
connectButton.setEnabled(slaveButtonEnabled);
disconnectButton.setEnabled(slaveButtonEnabled);
ownAddressText.setText(ownAddress);
}
private void refreshMbedControls() {
String connText = getString(R.string.not_connected); // if you want to localize
MbedService mbed = getMbed();
if (mbed != null && mbed.manager.areChannelsOpen()) {
connText = getString(R.string.connected);
}
mbedConnectedText.setText(connText);
}
// Function receives message from Bluetooth server
private BluetoothThread.Listener bluetoothListener = new BluetoothThread.Listener() {
String currentLocation = "[0, 0]";
String finalDestination = "[0, 0]";
String direction = "None";
String confirmation = "False";
boolean roaming = true;
public void onConnected() {
Log.i("Masterserver", "Connected bluetooth 12");
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.i("Masterserver", "Connected bluetooth");
connected = true;
//MainActivity.this.onConnected(true);
}
});
}
public void onDisconnected() {
Log.i("Masterserver", "Disconnected bluetooth 12");
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.i("Masterserver", "Disconnected bluetooth");
//MainActivity.this.onConnected(false);
}
});
}
public void onError(IOException e) {
}
public void onReceived(byte[] buffer, int length) {
Log.i("Masterserver", "received message with length" + length);
final String Input = new String(buffer, 0, length);
Log.i("Masterserver", "received message = " + Input);
// Hier wordt de finalDestination ontvangen.
if (Input.contains("finalDestination: ")) {
finalDestination = Input.replace("finalDestination: ", "");
roaming = false;
logComm.append("* Received Final Destination\n");
// Hier word<SUF>
} else if (Input.contains("currentLocation: ")) {
currentLocation = Input.replace("currentLocation: ", "");
Log.i("Masterserver", "currenLocation: " + currentLocation);
//scanText.setText("Current Location: " + currentLocation);
//TODO: niet meer locatie/ richting gebruiken die al afgekeurd is
if (roaming) {
direction = RandomDirection();
Log.i("Masterserver", "RandomDirection");
} else {
direction = KortstePadSolver(currentLocation, finalDestination);
Log.i("Masterserver", "KorstePadSolver");
}
SendMessage("direction: " + direction);
// Hier wordt de confirmation ontvangen.
} else if (Input.contains("confirmation: ")) {
confirmation = Input.replace("confirmation: ", "");
logComm.append("* Direction is free\n");
if (confirmation.equals("True")) {
float[] args = new float[1];
logComm.append("* Driving direction: " + direction + "\n");
if(direction.equals("North")) {
args[0] = 1.0f;
} else if(direction.equals("South")) {
args[0] = 2.0f;
} else if(direction.equals("West")) {
args[0] = 3.0f;
} else if(direction.equals("East")) {
args[0] = 4.0f;
}
getMbed().manager.write(new MbedRequest(COMMAND_DRIVE, args));
}
}
runOnUiThread(new Runnable() {
public void run() {
}
});
}
public void onMessage(String message) {
Log.i("Masterserver", "Message: " + message);
}
// Function for choosing a random direction to drive to
public String RandomDirection() {
int direction = 1 + (int)(Math.random() * ((4 - 1) + 1));
if (direction == 1)
return "North";
else if (direction == 2)
return "East";
else if (direction == 3)
return "South";
else if (direction == 4)
return "West";
return "None";
}
// Function for finding the shortest path to the final destination of the omnibot
public String KortstePadSolver(String currentLocation, String finalDestination) {
/* currentLocation -> "[x, y]" */
/* finalDestination -> "[x, y]" */
int currentX = Integer.valueOf(String.valueOf(currentLocation.charAt(1)));
int currentY = Integer.valueOf(String.valueOf(currentLocation.charAt(4)));
int finalX = Integer.valueOf(String.valueOf(finalDestination.charAt(1)));
int finalY = Integer.valueOf(String.valueOf(finalDestination.charAt(4)));
if (Math.abs(finalX - currentX) == 0 && Math.abs(finalY - currentY) == 0) {
return "Done";
}
if (Math.abs(finalX - currentX) > Math.abs(finalY - currentY)) {
if (finalX > currentX)
return "East";
else
return "West";
} else {
if (finalY > currentY)
return "North";
else
return "South";
}
}
// Sends message to Bluetooth server
public void SendMessage(String Message) {
byte[] b = Message.getBytes(Charset.forName("UTF-8"));
try {
connection.write(b);
logComm.append("* Sent " + Message + " to master\n");
} catch (IOException e) {
Log.e("Masterserver", "Error with write");
}
}
};
/***
* Functions for QR scanner
* Source: ZBarAndroidSDK-0.2 example
* http://sourceforge.net/projects/zbar/
*
* Copied:
* getCamerainstance()
* releaseCamera()
* doAutoFocus()
* autoFocusCB()
*
* Modified:
* previewCb()
**/
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
} catch (Exception e){
}
return c;
}
private void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (previewing)
mCamera.autoFocus(autoFocusCB);
}
};
// QR scanner automatically sends message to Bluetooth server after scanning a QR code
// and pauses the scanner
PreviewCallback previewCb = new PreviewCallback() {
public void SendMessage(String Message) {
byte[] b = Message.getBytes(Charset.forName("UTF-8"));
try {
Log.i("message", Message);
connection.write(b);
logComm.append("* Sent " + Message + " to master\n");
} catch (IOException e) {
Log.e("Masterserver", "Error with write");
}
}
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = scanner.scanImage(barcode);
if (result != 0 && connected) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms) {
String QRdata = sym.getData();
Log.i("message", QRdata);
scanText.setText("QR-Code: " + QRdata);
SendMessage("QRdata: " + QRdata);
barcodeScanned = true;
}
} else if(result != 0 && !connected) {
Log.i("Bluetooth", "Scanned while not connected!");
}
}
};
// Mimic continuous auto-focusing
AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
autoFocusHandler.postDelayed(doAutoFocus, 1000);
}
};
// Broadcast receiver which handles incoming events. If it were smaller, inline it.
private class MainActivityReceiver extends BroadcastReceiver {
// Refresh Mbed controls on these events.
private final String MBED_REFRESH_ON[] = { MbedManager.DEVICE_ATTACHED,
MbedManager.DEVICE_DETACHED };
// Returns intents this receiver responds to.
protected IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
// Notification updates.
for (String action : MBED_REFRESH_ON) {
filter.addAction(action);
}
// Data received events.
filter.addAction(MbedManager.DATA_READ);
return filter;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Refresh on most mBed events.
for (String update : MBED_REFRESH_ON) {
if (action.equals(update)) {
refreshMbedControls();
break;
}
}
// Process received data from Mbed
if (action.equals(MbedManager.DATA_READ)) {
// mBed data received.
MbedResponse response = intent.getParcelableExtra(MbedManager.EXTRA_DATA);
if (response != null) {
// Errors handled as separate case, but this is just sample code.
if (response.hasError()) {
toastLong("Error! " + response);
return;
}
float[] values = response.getValues();
if (response.getCommandId() == COMMAND_DRIVE) {
if (values == null || values.length != 1) {
toastShort("Error!");
} else {
// Resumes QR scanner when omnibot finished driving
logComm.append("* Finished driving, activate QR scanner\n");
if((int)values[0] == 0) {
if (barcodeScanned) {
barcodeScanned = false;
scanText.setText("Scanning...");
mCamera.setPreviewCallback(previewCb);
mCamera.startPreview();
previewing = true;
mCamera.autoFocus(autoFocusCB);
}
}
}
}
}
}
}
}
}
|
39039_10 | /**
* KAR Geo Tool - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kar;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.kar.hibernate.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.securityfilter.realm.SecurityRealmInterface;
import org.stripesstuff.stripersist.Stripersist;
/**
* SecurityRealm implementatie voor SecurityFilter 2.0.
*
* Deze realm gebruikt "Gebruiker" objecten als Principal.
*
* Wachtwoorden worden gehashed opgeslagen in de database en er wordt gebruik
* gemaakt van een salt. De salt en het wachtwoord geconcateneerd worden
* gehashed met SHA-1. De salt en hash worden als hex in de database opgeslagen
* in een varchar kolom omdat dit wat handzamer is dan een blob/bytea kolom.
*
* Wachtwoorden worden gehashed in UTF8 encoding, dus
* salt = 00 11 22 33, wachtwoord = "test", hash phrase = 00 11 22 33 74 65 73 74
* sha-1 hash = af30b67b3c0e3fcd1d80ba679770f3947f6edd8d
* salt = 00 11 22 33, wachtwoord = "tëst", hash phrase = 00 11 22 33 74 c3 ab 73 74
* sha-1 hash = d49a8431ec274a1433b7fdda34e4de0b2784b812
*/
public class SecurityRealm implements SecurityRealmInterface {
private static final Log auditLog = LogFactory.getLog("audit");
private static final int SALT_SIZE = 4;
/**
* Methode om random salt tbv hash te genereren
*
* @param request gebruikt voor initialisatie PRNG met IP en poort van client
* @return salt in hex string
*/
public static String generateHexSalt(HttpServletRequest request) {
long seed = System.currentTimeMillis();
long ip = 1;
try {
InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
if(addr instanceof Inet4Address) {
byte raw[] = ((Inet4Address)addr).getAddress();
ip = raw[0] << 24 | raw[1] << 16 | raw[2] << 8 | raw[3];
}
} catch (UnknownHostException ex) {
/* ip blijft 1 */
}
seed = seed * ip;
if(request.getRemotePort() != 0) {
seed = seed * request.getRemotePort();
}
Random random = new Random(seed);
StringBuilder salt = new StringBuilder(SALT_SIZE*2);
for(int i = 0; i < SALT_SIZE; i++) {
int b = random.nextInt(16);
salt.append(Integer.toHexString(b));
b = random.nextInt(16);
salt.append(Integer.toHexString(b));
}
return salt.toString();
}
/**
* Methode om hash te maken van wachtwoord met salt
*
* @param saltHex de salt als String
* @param phrase het wachtwoord
* @return de hash
* @throws NoSuchAlgorithmException SHA1 niet beschikbaar
* @throws UnsupportedEncodingException UTF8 niet supported
*/
public static String getHexSha1(String saltHex, String phrase) throws NoSuchAlgorithmException, UnsupportedEncodingException {
saltHex = saltHex.trim();
if(saltHex.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid salt hex length (must be divisible by 2): " + saltHex.length());
}
byte[] salt = new byte[saltHex.length() / 2];
try {
for(int i = 0; i < saltHex.length() / 2; i++) {
int hexIdx = i*2;
int highNibble = Integer.parseInt(saltHex.substring(hexIdx,hexIdx+1), 16);
int lowNibble = Integer.parseInt(saltHex.substring(hexIdx+1,hexIdx+2), 16);
salt[i] = (byte)(highNibble << 4 | lowNibble);
}
} catch(NumberFormatException nfe) {
throw new IllegalArgumentException("Invalid hex characters in salt parameter: " + saltHex);
}
return getHexSha1(salt, phrase);
}
/**
* Methode om hash te maken van wachtwoord met gebruik van salt
*
* @param salt de salt als byte array
* @param phrase het wachtwoord
* @return de hash
* @throws NoSuchAlgorithmException SHA1 niet beschikbaar
* @throws UnsupportedEncodingException UTF8 niet supported
*/
public static String getHexSha1(byte[] salt, String phrase) throws NoSuchAlgorithmException, UnsupportedEncodingException {
byte[] phraseUTF8 = phrase.getBytes("UTF8");
byte[] saltedPhrase = new byte[salt.length + phraseUTF8.length];
System.arraycopy(salt, 0, saltedPhrase, 0, salt.length);
System.arraycopy(phraseUTF8, 0, saltedPhrase, salt.length, phraseUTF8.length);
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(saltedPhrase);
/* Converteer byte array naar hex-weergave */
StringBuilder sb = new StringBuilder(digest.length*2);
for(int i = 0; i < digest.length; i++) {
sb.append(Integer.toHexString(digest[i] >> 4 & 0xf)); /* and mask met 0xf nodig door sign-extenden van bytes... */
sb.append(Integer.toHexString(digest[i] & 0xf));
}
return sb.toString();
}
/**
* Authenticate a user.
*
* @param username a username
* @param password a plain text password, as entered by the user
*
* @return a Principal object representing the user if successful, false otherwise
*/
public Principal authenticate(String username, String password) {
/* TODO: "LOGIN", "username" en "ALLOW" MDC vars maken, gebruik wel filter dat bij
* elk request MDC.clear() doet en filter dat username instelt
*/
String auditAllow = "LOGIN ALLOW: username=\"" + username + "\": ";
String auditDeny = "LOGIN DENY: username=\"" + username + "\": ";
try {
Stripersist.requestInit();
EntityManager em = Stripersist.getEntityManager();
try {
Gebruiker g = (Gebruiker)em.createQuery(
"from Gebruiker g where " +
"g.username = :username ")
.setParameter("username", username)
.getSingleResult();
/* Check of het gegeven password overeenkomt: hash de salt met
* het gegeven password, indien dit overeenkomt met de opgeslagen
* hash is het password correct
*/
String hash = getHexSha1(g.getPasswordsalt(), password);
if(hash.equals(g.getPasswordhash())) {
String info = "authenticatie check ok; ";
Set roles=g.getRoles();
if (roles!=null){
Iterator it= roles.iterator();
while (it.hasNext()){
info+= " "+((Role)it.next()).getRole();
}
}
auditLog.info(auditAllow + info);
return g;
} else {
auditLog.info(auditDeny + "password hash komt niet overeen (ongeldig wachtwoord)");
return null;
}
} catch(NoResultException nre) {
auditLog.info(auditDeny + "geen gebruiker gevonden voor gebruikersnaam");
return null;
}
} catch(Exception e) {
auditLog.error("LOGIN ERROR: username=\"" + username + "\": exception", e);
throw new RuntimeException("Exception checking authentication database", e);
} finally {
Stripersist.requestComplete();
}
}
/**
* Er zijn drie rollen, bepaald door het feit of bij een Gebruiker entity
* de gemeente, regio of provincie relatie not-null is.
*
* @param principal de principal, de rollen van de gebruiker
* @param role de gevraagde rol
* @return boolean of rol geldig is
*/
public boolean isUserInRole(Principal principal, String role) {
if(principal == null) {
return false;
}
Gebruiker g = (Gebruiker)principal;
Set roles= g.getRoles();
Iterator it=roles.iterator();
while (it.hasNext()){
Role r = (Role)it.next();
if (role.equalsIgnoreCase(r.getRole())){
return true;
}
}
return false;
}
}
| wscherphof/kargeotool | src/main/java/nl/b3p/kar/SecurityRealm.java | 2,610 | /* Check of het gegeven password overeenkomt: hash de salt met
* het gegeven password, indien dit overeenkomt met de opgeslagen
* hash is het password correct
*/ | block_comment | nl | /**
* KAR Geo Tool - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kar;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import nl.b3p.kar.hibernate.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.securityfilter.realm.SecurityRealmInterface;
import org.stripesstuff.stripersist.Stripersist;
/**
* SecurityRealm implementatie voor SecurityFilter 2.0.
*
* Deze realm gebruikt "Gebruiker" objecten als Principal.
*
* Wachtwoorden worden gehashed opgeslagen in de database en er wordt gebruik
* gemaakt van een salt. De salt en het wachtwoord geconcateneerd worden
* gehashed met SHA-1. De salt en hash worden als hex in de database opgeslagen
* in een varchar kolom omdat dit wat handzamer is dan een blob/bytea kolom.
*
* Wachtwoorden worden gehashed in UTF8 encoding, dus
* salt = 00 11 22 33, wachtwoord = "test", hash phrase = 00 11 22 33 74 65 73 74
* sha-1 hash = af30b67b3c0e3fcd1d80ba679770f3947f6edd8d
* salt = 00 11 22 33, wachtwoord = "tëst", hash phrase = 00 11 22 33 74 c3 ab 73 74
* sha-1 hash = d49a8431ec274a1433b7fdda34e4de0b2784b812
*/
public class SecurityRealm implements SecurityRealmInterface {
private static final Log auditLog = LogFactory.getLog("audit");
private static final int SALT_SIZE = 4;
/**
* Methode om random salt tbv hash te genereren
*
* @param request gebruikt voor initialisatie PRNG met IP en poort van client
* @return salt in hex string
*/
public static String generateHexSalt(HttpServletRequest request) {
long seed = System.currentTimeMillis();
long ip = 1;
try {
InetAddress addr = InetAddress.getByName(request.getRemoteAddr());
if(addr instanceof Inet4Address) {
byte raw[] = ((Inet4Address)addr).getAddress();
ip = raw[0] << 24 | raw[1] << 16 | raw[2] << 8 | raw[3];
}
} catch (UnknownHostException ex) {
/* ip blijft 1 */
}
seed = seed * ip;
if(request.getRemotePort() != 0) {
seed = seed * request.getRemotePort();
}
Random random = new Random(seed);
StringBuilder salt = new StringBuilder(SALT_SIZE*2);
for(int i = 0; i < SALT_SIZE; i++) {
int b = random.nextInt(16);
salt.append(Integer.toHexString(b));
b = random.nextInt(16);
salt.append(Integer.toHexString(b));
}
return salt.toString();
}
/**
* Methode om hash te maken van wachtwoord met salt
*
* @param saltHex de salt als String
* @param phrase het wachtwoord
* @return de hash
* @throws NoSuchAlgorithmException SHA1 niet beschikbaar
* @throws UnsupportedEncodingException UTF8 niet supported
*/
public static String getHexSha1(String saltHex, String phrase) throws NoSuchAlgorithmException, UnsupportedEncodingException {
saltHex = saltHex.trim();
if(saltHex.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid salt hex length (must be divisible by 2): " + saltHex.length());
}
byte[] salt = new byte[saltHex.length() / 2];
try {
for(int i = 0; i < saltHex.length() / 2; i++) {
int hexIdx = i*2;
int highNibble = Integer.parseInt(saltHex.substring(hexIdx,hexIdx+1), 16);
int lowNibble = Integer.parseInt(saltHex.substring(hexIdx+1,hexIdx+2), 16);
salt[i] = (byte)(highNibble << 4 | lowNibble);
}
} catch(NumberFormatException nfe) {
throw new IllegalArgumentException("Invalid hex characters in salt parameter: " + saltHex);
}
return getHexSha1(salt, phrase);
}
/**
* Methode om hash te maken van wachtwoord met gebruik van salt
*
* @param salt de salt als byte array
* @param phrase het wachtwoord
* @return de hash
* @throws NoSuchAlgorithmException SHA1 niet beschikbaar
* @throws UnsupportedEncodingException UTF8 niet supported
*/
public static String getHexSha1(byte[] salt, String phrase) throws NoSuchAlgorithmException, UnsupportedEncodingException {
byte[] phraseUTF8 = phrase.getBytes("UTF8");
byte[] saltedPhrase = new byte[salt.length + phraseUTF8.length];
System.arraycopy(salt, 0, saltedPhrase, 0, salt.length);
System.arraycopy(phraseUTF8, 0, saltedPhrase, salt.length, phraseUTF8.length);
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(saltedPhrase);
/* Converteer byte array naar hex-weergave */
StringBuilder sb = new StringBuilder(digest.length*2);
for(int i = 0; i < digest.length; i++) {
sb.append(Integer.toHexString(digest[i] >> 4 & 0xf)); /* and mask met 0xf nodig door sign-extenden van bytes... */
sb.append(Integer.toHexString(digest[i] & 0xf));
}
return sb.toString();
}
/**
* Authenticate a user.
*
* @param username a username
* @param password a plain text password, as entered by the user
*
* @return a Principal object representing the user if successful, false otherwise
*/
public Principal authenticate(String username, String password) {
/* TODO: "LOGIN", "username" en "ALLOW" MDC vars maken, gebruik wel filter dat bij
* elk request MDC.clear() doet en filter dat username instelt
*/
String auditAllow = "LOGIN ALLOW: username=\"" + username + "\": ";
String auditDeny = "LOGIN DENY: username=\"" + username + "\": ";
try {
Stripersist.requestInit();
EntityManager em = Stripersist.getEntityManager();
try {
Gebruiker g = (Gebruiker)em.createQuery(
"from Gebruiker g where " +
"g.username = :username ")
.setParameter("username", username)
.getSingleResult();
/* Check of het<SUF>*/
String hash = getHexSha1(g.getPasswordsalt(), password);
if(hash.equals(g.getPasswordhash())) {
String info = "authenticatie check ok; ";
Set roles=g.getRoles();
if (roles!=null){
Iterator it= roles.iterator();
while (it.hasNext()){
info+= " "+((Role)it.next()).getRole();
}
}
auditLog.info(auditAllow + info);
return g;
} else {
auditLog.info(auditDeny + "password hash komt niet overeen (ongeldig wachtwoord)");
return null;
}
} catch(NoResultException nre) {
auditLog.info(auditDeny + "geen gebruiker gevonden voor gebruikersnaam");
return null;
}
} catch(Exception e) {
auditLog.error("LOGIN ERROR: username=\"" + username + "\": exception", e);
throw new RuntimeException("Exception checking authentication database", e);
} finally {
Stripersist.requestComplete();
}
}
/**
* Er zijn drie rollen, bepaald door het feit of bij een Gebruiker entity
* de gemeente, regio of provincie relatie not-null is.
*
* @param principal de principal, de rollen van de gebruiker
* @param role de gevraagde rol
* @return boolean of rol geldig is
*/
public boolean isUserInRole(Principal principal, String role) {
if(principal == null) {
return false;
}
Gebruiker g = (Gebruiker)principal;
Set roles= g.getRoles();
Iterator it=roles.iterator();
while (it.hasNext()){
Role r = (Role)it.next();
if (role.equalsIgnoreCase(r.getRole())){
return true;
}
}
return false;
}
}
|
69591_0 | package com.nhlstenden.amazonsimulatie.controllers;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import com.nhlstenden.amazonsimulatie.base.Command;
import com.nhlstenden.amazonsimulatie.models.Model;
import com.nhlstenden.amazonsimulatie.models.Object3D;
import com.nhlstenden.amazonsimulatie.models.World;
import com.nhlstenden.amazonsimulatie.views.View;
/*
* Dit is de controller class die de simulatie beheerd. Deze class erft van
* een generieke class Controller. Hierdoor krijgt SimulationController gratis
* functionaliteit mee voor het managen van views en een model.
*/
public class SimulationController extends Controller
{
public SimulationController(Model model) {
super(model); //Met dit onderdeel roep je de constructor aan van de superclass (Controller)
}
/*
* Deze methode wordt aangeroepen wanneer de controller wordt gestart. De methode start een infinite
* while-loop op in de thread van de controller. Normaal loopt een applicatie vast in een infinite
* loop, maar omdat de controller een eigen thread heeft loopt deze loop eigenlijk naast de rest
* van het programma. Elke keer wordt een Thread.sleep() gedaan met 100 als parameter. Dat betekent
* 100 miliseconden rust, en daarna gaat de loop verder. Dit betekent dat ongeveer 10 keer per seconden
* de wereld wordt geupdate. Dit is dus in feite 10 frames per seconde.
*/
@Override
public void run() {
while (true) {
if (this.getModel() != null)
this.getModel().update();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
protected void onViewAdded(final View view) {
final Controller t = this;
/*
* Hier wordt een interface (Command) gebruikt om een nieuw object
* te maken. Dit kan binnen Java en heet een anonymous inner class.
* Op deze manier hoef je niet steeds een nieuwe class aan te maken
* voor verschillende commando's. Zeker omdat je deze code maar één
* keer nodig hebt.
*/
view.onViewClose(new Command(){
@Override
public void execute() {
t.removeView(view);
}
});
/*
* Dit stukje code zorgt ervoor dat wanneer een nieuwe view verbinding maakt, deze view één
* keer alle objecten krijgt toegestuurd, ook als deze objecten niet updaten. Zo voorkom je
* dat de view alleen objecten ziet die worden geupdate (bijvoorbeeld bewegen).
*/
for (Object3D object : this.getModel().getWorldObjectsAsList()) {
view.update(Model.UPDATE_COMMAND, object);
}
}
/*
* Deze methode wordt aangeroepen wanneer er een update van het model binnenkomt. Zo'n "event"
* heeft een naam en een waarde. Die worden hieronder gebruikt om een updatesignaal te sturen
* naar de view.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
for(int i = 0; i < this.getViews().size(); i++) {
View currentView = this.getViews().get(i);
if(currentView != null) {
currentView.update(evt.getPropertyName(), (Object3D)evt.getNewValue());
}
}
}
} | Damiaen/AmazonSimulatie | src/main/java/com/nhlstenden/amazonsimulatie/controllers/SimulationController.java | 868 | /*
* Dit is de controller class die de simulatie beheerd. Deze class erft van
* een generieke class Controller. Hierdoor krijgt SimulationController gratis
* functionaliteit mee voor het managen van views en een model.
*/ | block_comment | nl | package com.nhlstenden.amazonsimulatie.controllers;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import com.nhlstenden.amazonsimulatie.base.Command;
import com.nhlstenden.amazonsimulatie.models.Model;
import com.nhlstenden.amazonsimulatie.models.Object3D;
import com.nhlstenden.amazonsimulatie.models.World;
import com.nhlstenden.amazonsimulatie.views.View;
/*
* Dit is de<SUF>*/
public class SimulationController extends Controller
{
public SimulationController(Model model) {
super(model); //Met dit onderdeel roep je de constructor aan van de superclass (Controller)
}
/*
* Deze methode wordt aangeroepen wanneer de controller wordt gestart. De methode start een infinite
* while-loop op in de thread van de controller. Normaal loopt een applicatie vast in een infinite
* loop, maar omdat de controller een eigen thread heeft loopt deze loop eigenlijk naast de rest
* van het programma. Elke keer wordt een Thread.sleep() gedaan met 100 als parameter. Dat betekent
* 100 miliseconden rust, en daarna gaat de loop verder. Dit betekent dat ongeveer 10 keer per seconden
* de wereld wordt geupdate. Dit is dus in feite 10 frames per seconde.
*/
@Override
public void run() {
while (true) {
if (this.getModel() != null)
this.getModel().update();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
protected void onViewAdded(final View view) {
final Controller t = this;
/*
* Hier wordt een interface (Command) gebruikt om een nieuw object
* te maken. Dit kan binnen Java en heet een anonymous inner class.
* Op deze manier hoef je niet steeds een nieuwe class aan te maken
* voor verschillende commando's. Zeker omdat je deze code maar één
* keer nodig hebt.
*/
view.onViewClose(new Command(){
@Override
public void execute() {
t.removeView(view);
}
});
/*
* Dit stukje code zorgt ervoor dat wanneer een nieuwe view verbinding maakt, deze view één
* keer alle objecten krijgt toegestuurd, ook als deze objecten niet updaten. Zo voorkom je
* dat de view alleen objecten ziet die worden geupdate (bijvoorbeeld bewegen).
*/
for (Object3D object : this.getModel().getWorldObjectsAsList()) {
view.update(Model.UPDATE_COMMAND, object);
}
}
/*
* Deze methode wordt aangeroepen wanneer er een update van het model binnenkomt. Zo'n "event"
* heeft een naam en een waarde. Die worden hieronder gebruikt om een updatesignaal te sturen
* naar de view.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
for(int i = 0; i < this.getViews().size(); i++) {
View currentView = this.getViews().get(i);
if(currentView != null) {
currentView.update(evt.getPropertyName(), (Object3D)evt.getNewValue());
}
}
}
} |
34102_23 | package simulator;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import agenda.Artist;
import agenda.Performance;
/*
* Alle waarden betreffende verloop zijn per seconde
*
* -- Thijs
*/
public class Visitor extends Agent {
static int i = 0;
static int i2 = 0;
private int mod = 0;
private int aantalDrankjes, aantalSnacks;
private String genreVoorkeur;
private double blaasInhoud = randomWaardeDouble(70, 100);
private double drankHandling = randomWaardeDouble(0.5, 1.5);
private double blaasToleratie = randomWaardeDouble(20, 50);
private double maagInhoud = randomWaardeDouble(700, 1000);
private double snackHandling = randomWaardeDouble(0.5, 1.5);
private double maagToleratie = randomWaardeDouble(200, 500);
private double dorst = randomWaardeDouble(700, 1000);
private double verloopDorst = randomWaardeDouble(0.5, 1.5);
private double dorstToleratie = randomWaardeDouble(200, 400);
private double honger = randomWaardeDouble(7000, 10000);
private double verloopHonger = randomWaardeDouble(0.5, 1.5);
private double hongerToleratie = randomWaardeDouble(200, 400);
private boolean toiletBezoek = false;
private boolean grootToiletBezoek = false;
private boolean drankBezoek = false;
private boolean eetBezoek = false;
private boolean goingtoexit = false;
private int destination;
private int teller = 0;
private Point2D nextDancePosition;
private Point2D currentDancePosition;
private float remainingDanceDistance;
private boolean toDance = false;
private int voorkeur = 0;
private boolean reached = false;
private boolean voorkeurchecked = false;
private int podiumsize = 0;
private static ArrayList<Image> images = new ArrayList<>();
public Visitor(Tile tile, float speed) {
super(getImage(), tile, new Point2D.Double(tile.X, -tile.Y), speed);
mod = World.instance.getSizeBuildingID();
int dest = i++ % mod;
setDestination(dest);
destination = dest;
// System.out.println(World.instance.getBuildings().get(dest).toString());
setGenreVoorkeur();
}
@Override
public void update() {
if (World.instance.getWorldTime() >= (24 * 60 * 60) && !goingtoexit) {
goingtoexit = true;
setDestination(World.instance.getPathID("exit"));
World.instance.p.stopTimer();
}
if (!goingtoexit) {
bezoekPerformance();
bezoekFaciliteit();
danceMethod();
toiletBehoefte();
groteBehoefte();
drankBehoefte();
setDorstPercentage();
snackBehoefte();
setHongerPercentage();
if (toDance) {
teller++;
}
}
move();
}
public Tile[] dance(String destenation) {
if (destenation.toLowerCase().endsWith("stage")) {
Stage stage = null;
for (Building b : World.instance.getBuildings()) {
if (b.name.equals(destenation)) {
stage = (Stage) b;
}
}
ArrayList<Tile> dancefloor = new ArrayList<>();
dancefloor.addAll(stage.getDanceFloor());
Tile punt1 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile punt2 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile punt3 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile[] tileArray = { punt1, punt2, punt3 };
return tileArray;
} else {
return null;
}
}
boolean closed = false;
@Override
void destenationReached() {
if(goingtoexit)
{
if(closed == false)
{
World.instance.remove(this);
closed = true;
}
}
// setDestination(i2++ % MOD);
if (World.instance.getBuildings().get(this.getDestinationOld()).toString().toLowerCase().endsWith("stage")) {
toDance = true;
} else {
// System.out.println(World.instance.getBuildings().get(this.getDestinationOld()).toString());
toDance = false;
int dest = i2++ % mod;
destination = dest;
setDestination(dest);
if (!reached)
reached = true;
}
// System.out.println("Destination reached! destination : " +
// destination + " stage ja nee? "
// +
// World.instance.getBuildings().get(this.getDestinationOld()).toString().toLowerCase().endsWith("stage")
// + " --- building : " +
// World.instance.getBuildings().get(this.getDestinationOld()).toString()
// + " --- dancing : " + toDance);
}
public void danceMethod() {
if (toDance) {
if (teller < 100) {
// STAAT STIL ATM.
// int tellertje = 0;
// Tile[] tiles =
// dance(World.instance.getBuildings().get(this.getDestinationOld()).toString());
// remainingDanceDistance = 0;
// if (nextDancePosition.distance(getCurrentPosition()) <=
// remainingDanceDistance) {
// remainingDanceDistance -=
// nextDancePosition.distance(getCurrentPosition());
// setCurrentPosition(nextDancePosition);
// nextDancePosition = new Point2D.Double(tiles[tellertje].X,
// -tiles[tellertje].Y);
// tellertje++;
// } else {
//
// float tempX = (float) (nextDancePosition.getX() -
// getCurrentPosition().getX()),
// tempY = (float) (nextDancePosition.getY() -
// getCurrentPosition().getY());
//
// float magnitude = (float) Math.sqrt(tempX * tempX + tempY *
// tempY);
// tempX /= magnitude;
// tempY /= magnitude;
//
// // now we have a unit vector
//
// tempX *= remainingDanceDistance;
// tempY *= remainingDanceDistance;
//
// remainingDanceDistance = 0;
//
// setCurrentPosition(new
// Point2D.Double(getCurrentPosition().getX() + tempX ,
// getCurrentPosition().getY() + tempY));
// }
} else {
toDance = false;
if (!toDance) {// System.out.println("dance voorbij");
teller = 0;
int dest = i++ % mod;
setDestination(dest);
// System.out.println("dest set " + dest);
destination = dest;
}
}
}
}
public static Image getImage() {
if (images.isEmpty()) {
File[] lijst = new File("static_data/sprites/").listFiles();
for (File f : lijst) {
try {
BufferedImage temp = (BufferedImage) ImageIO.read(f);
images.add(temp.getScaledInstance(32, 32, BufferedImage.SCALE_FAST));
} catch (IOException e) {
e.printStackTrace();
}
}
}
int getal = (int) (1 + Math.random() * 16);
return images.get(getal);
}
public void bezoekPerformance() {
ArrayList<String> podias = new ArrayList<>();
if (World.instance.getActualPerformances(World.instance.getTime()) != null) {
podias.addAll(World.instance.getActualPerformances(World.instance.getTime()));
if (!podias.isEmpty()) {
if (podiumsize != podias.size()) {
voorkeurchecked = false;
}
if (podias.size() > 0 && !voorkeurchecked) {
voorkeur = (int) (Math.random() * podias.size());
voorkeurchecked = true;
podiumsize = podias.size();
}
setDestination(World.instance.getPathID(podias.get(voorkeur)));
} else {
// TODO exit location
}
}
}
public void bezoekFaciliteit() {
if (toiletBezoek == true || grootToiletBezoek == true) {
if (toiletBezoek == true) {
setDestination(World.instance.getPathID("Toilet"));
if (reached) {
aantalDrankjes = 0;
blaasInhoud = 10000;
toiletBezoek = false;
}
}
if (grootToiletBezoek == true) {
setDestination(World.instance.getPathID("Toilet"));
if (reached) {
aantalSnacks = 0;
aantalDrankjes = 0;
maagInhoud = 10000;
blaasInhoud = 10000;
grootToiletBezoek = false;
}
}
} else {
if (drankBezoek == true) {
setDestination(World.instance.getPathID("Cafetaria"));
if (reached) {
aantalDrankjes++;
dorst = 10000;
setBlaasCapaciteit();
drankBezoek = false;
}
}
if (eetBezoek == true) {
setDestination(World.instance.getPathID("Cafetaria"));
if (reached) {
aantalSnacks++;
honger = 10000;
setMaagCapaciteit();
eetBezoek = false;
}
}
}
reached = false;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker pissen
*/
public boolean toiletBehoefte() {
if (blaasInhoud <= blaasToleratie)
toiletBezoek = true;
else
toiletBezoek = false;
return toiletBezoek;
}
public double getBlaasCapaciteit() {
return blaasInhoud;
}
public void setBlaasCapaciteit() {
blaasInhoud = blaasInhoud - drankHandling * aantalDrankjes;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker een grote
* boodschap doen
*/
public boolean groteBehoefte() {
if (maagInhoud <= maagToleratie)
grootToiletBezoek = true;
else
grootToiletBezoek = false;
return grootToiletBezoek;
}
public double getMaagCapaciteit() {
return maagInhoud;
}
public void setMaagCapaciteit() {
maagInhoud = maagInhoud - snackHandling * aantalSnacks;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker het op een
* zuipen zetten
*/
public boolean drankBehoefte() {
if (dorst <= dorstToleratie)
drankBezoek = true;
else
drankBezoek = false;
return drankBezoek;
}
public double getDorstPercentage() {
return dorst;
}
public void setDorstPercentage() {
dorst = dorst - verloopDorst;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker iets gaan eten
*/
public boolean snackBehoefte() {
if (honger <= hongerToleratie)
eetBezoek = true;
else
eetBezoek = false;
return eetBezoek;
}
public double getHongerPercentage() {
return honger;
}
public void setHongerPercentage() {
honger = honger - verloopHonger;
}
public String getGenreVoorkeur() {
return genreVoorkeur;
}
public void setGenreVoorkeur() {
ArrayList<String> genres = new ArrayList<String>() {
{
add("Rock");
add("Schlager");
add("Pop");
add("Funk");
add("Metal");
add("Techno");
add("Hiphop");
add("R&B");
add("Klassiek");
add("Volksmuziek");
add("Jazz");
add("Soul");
add("Religieus");
add("Disco");
add("Blues");
}
};
genreVoorkeur = genres.get(randomWaardeInt(0, 14));
}
/*
* Genereer hiermee een random waarden tbv attributen
*/
public int randomWaardeInt(int min, int max) {
int randomInt = min + (int) (Math.random() * ((max - min) + 1));
return randomInt;
}
public double randomWaardeDouble(double min, double max) {
double randomDouble = min + (double) (Math.random() * ((max - min) + 1));
return randomDouble;
}
}
| Kevintjeb/ProjectA5 | code/simulator/Visitor.java | 3,387 | // getCurrentPosition().getY() + tempY)); | line_comment | nl | package simulator;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import agenda.Artist;
import agenda.Performance;
/*
* Alle waarden betreffende verloop zijn per seconde
*
* -- Thijs
*/
public class Visitor extends Agent {
static int i = 0;
static int i2 = 0;
private int mod = 0;
private int aantalDrankjes, aantalSnacks;
private String genreVoorkeur;
private double blaasInhoud = randomWaardeDouble(70, 100);
private double drankHandling = randomWaardeDouble(0.5, 1.5);
private double blaasToleratie = randomWaardeDouble(20, 50);
private double maagInhoud = randomWaardeDouble(700, 1000);
private double snackHandling = randomWaardeDouble(0.5, 1.5);
private double maagToleratie = randomWaardeDouble(200, 500);
private double dorst = randomWaardeDouble(700, 1000);
private double verloopDorst = randomWaardeDouble(0.5, 1.5);
private double dorstToleratie = randomWaardeDouble(200, 400);
private double honger = randomWaardeDouble(7000, 10000);
private double verloopHonger = randomWaardeDouble(0.5, 1.5);
private double hongerToleratie = randomWaardeDouble(200, 400);
private boolean toiletBezoek = false;
private boolean grootToiletBezoek = false;
private boolean drankBezoek = false;
private boolean eetBezoek = false;
private boolean goingtoexit = false;
private int destination;
private int teller = 0;
private Point2D nextDancePosition;
private Point2D currentDancePosition;
private float remainingDanceDistance;
private boolean toDance = false;
private int voorkeur = 0;
private boolean reached = false;
private boolean voorkeurchecked = false;
private int podiumsize = 0;
private static ArrayList<Image> images = new ArrayList<>();
public Visitor(Tile tile, float speed) {
super(getImage(), tile, new Point2D.Double(tile.X, -tile.Y), speed);
mod = World.instance.getSizeBuildingID();
int dest = i++ % mod;
setDestination(dest);
destination = dest;
// System.out.println(World.instance.getBuildings().get(dest).toString());
setGenreVoorkeur();
}
@Override
public void update() {
if (World.instance.getWorldTime() >= (24 * 60 * 60) && !goingtoexit) {
goingtoexit = true;
setDestination(World.instance.getPathID("exit"));
World.instance.p.stopTimer();
}
if (!goingtoexit) {
bezoekPerformance();
bezoekFaciliteit();
danceMethod();
toiletBehoefte();
groteBehoefte();
drankBehoefte();
setDorstPercentage();
snackBehoefte();
setHongerPercentage();
if (toDance) {
teller++;
}
}
move();
}
public Tile[] dance(String destenation) {
if (destenation.toLowerCase().endsWith("stage")) {
Stage stage = null;
for (Building b : World.instance.getBuildings()) {
if (b.name.equals(destenation)) {
stage = (Stage) b;
}
}
ArrayList<Tile> dancefloor = new ArrayList<>();
dancefloor.addAll(stage.getDanceFloor());
Tile punt1 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile punt2 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile punt3 = dancefloor.get((int) (Math.random() * dancefloor.size() - 1));
Tile[] tileArray = { punt1, punt2, punt3 };
return tileArray;
} else {
return null;
}
}
boolean closed = false;
@Override
void destenationReached() {
if(goingtoexit)
{
if(closed == false)
{
World.instance.remove(this);
closed = true;
}
}
// setDestination(i2++ % MOD);
if (World.instance.getBuildings().get(this.getDestinationOld()).toString().toLowerCase().endsWith("stage")) {
toDance = true;
} else {
// System.out.println(World.instance.getBuildings().get(this.getDestinationOld()).toString());
toDance = false;
int dest = i2++ % mod;
destination = dest;
setDestination(dest);
if (!reached)
reached = true;
}
// System.out.println("Destination reached! destination : " +
// destination + " stage ja nee? "
// +
// World.instance.getBuildings().get(this.getDestinationOld()).toString().toLowerCase().endsWith("stage")
// + " --- building : " +
// World.instance.getBuildings().get(this.getDestinationOld()).toString()
// + " --- dancing : " + toDance);
}
public void danceMethod() {
if (toDance) {
if (teller < 100) {
// STAAT STIL ATM.
// int tellertje = 0;
// Tile[] tiles =
// dance(World.instance.getBuildings().get(this.getDestinationOld()).toString());
// remainingDanceDistance = 0;
// if (nextDancePosition.distance(getCurrentPosition()) <=
// remainingDanceDistance) {
// remainingDanceDistance -=
// nextDancePosition.distance(getCurrentPosition());
// setCurrentPosition(nextDancePosition);
// nextDancePosition = new Point2D.Double(tiles[tellertje].X,
// -tiles[tellertje].Y);
// tellertje++;
// } else {
//
// float tempX = (float) (nextDancePosition.getX() -
// getCurrentPosition().getX()),
// tempY = (float) (nextDancePosition.getY() -
// getCurrentPosition().getY());
//
// float magnitude = (float) Math.sqrt(tempX * tempX + tempY *
// tempY);
// tempX /= magnitude;
// tempY /= magnitude;
//
// // now we have a unit vector
//
// tempX *= remainingDanceDistance;
// tempY *= remainingDanceDistance;
//
// remainingDanceDistance = 0;
//
// setCurrentPosition(new
// Point2D.Double(getCurrentPosition().getX() + tempX ,
// getCurrentPosition().getY() +<SUF>
// }
} else {
toDance = false;
if (!toDance) {// System.out.println("dance voorbij");
teller = 0;
int dest = i++ % mod;
setDestination(dest);
// System.out.println("dest set " + dest);
destination = dest;
}
}
}
}
public static Image getImage() {
if (images.isEmpty()) {
File[] lijst = new File("static_data/sprites/").listFiles();
for (File f : lijst) {
try {
BufferedImage temp = (BufferedImage) ImageIO.read(f);
images.add(temp.getScaledInstance(32, 32, BufferedImage.SCALE_FAST));
} catch (IOException e) {
e.printStackTrace();
}
}
}
int getal = (int) (1 + Math.random() * 16);
return images.get(getal);
}
public void bezoekPerformance() {
ArrayList<String> podias = new ArrayList<>();
if (World.instance.getActualPerformances(World.instance.getTime()) != null) {
podias.addAll(World.instance.getActualPerformances(World.instance.getTime()));
if (!podias.isEmpty()) {
if (podiumsize != podias.size()) {
voorkeurchecked = false;
}
if (podias.size() > 0 && !voorkeurchecked) {
voorkeur = (int) (Math.random() * podias.size());
voorkeurchecked = true;
podiumsize = podias.size();
}
setDestination(World.instance.getPathID(podias.get(voorkeur)));
} else {
// TODO exit location
}
}
}
public void bezoekFaciliteit() {
if (toiletBezoek == true || grootToiletBezoek == true) {
if (toiletBezoek == true) {
setDestination(World.instance.getPathID("Toilet"));
if (reached) {
aantalDrankjes = 0;
blaasInhoud = 10000;
toiletBezoek = false;
}
}
if (grootToiletBezoek == true) {
setDestination(World.instance.getPathID("Toilet"));
if (reached) {
aantalSnacks = 0;
aantalDrankjes = 0;
maagInhoud = 10000;
blaasInhoud = 10000;
grootToiletBezoek = false;
}
}
} else {
if (drankBezoek == true) {
setDestination(World.instance.getPathID("Cafetaria"));
if (reached) {
aantalDrankjes++;
dorst = 10000;
setBlaasCapaciteit();
drankBezoek = false;
}
}
if (eetBezoek == true) {
setDestination(World.instance.getPathID("Cafetaria"));
if (reached) {
aantalSnacks++;
honger = 10000;
setMaagCapaciteit();
eetBezoek = false;
}
}
}
reached = false;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker pissen
*/
public boolean toiletBehoefte() {
if (blaasInhoud <= blaasToleratie)
toiletBezoek = true;
else
toiletBezoek = false;
return toiletBezoek;
}
public double getBlaasCapaciteit() {
return blaasInhoud;
}
public void setBlaasCapaciteit() {
blaasInhoud = blaasInhoud - drankHandling * aantalDrankjes;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker een grote
* boodschap doen
*/
public boolean groteBehoefte() {
if (maagInhoud <= maagToleratie)
grootToiletBezoek = true;
else
grootToiletBezoek = false;
return grootToiletBezoek;
}
public double getMaagCapaciteit() {
return maagInhoud;
}
public void setMaagCapaciteit() {
maagInhoud = maagInhoud - snackHandling * aantalSnacks;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker het op een
* zuipen zetten
*/
public boolean drankBehoefte() {
if (dorst <= dorstToleratie)
drankBezoek = true;
else
drankBezoek = false;
return drankBezoek;
}
public double getDorstPercentage() {
return dorst;
}
public void setDorstPercentage() {
dorst = dorst - verloopDorst;
}
/*
* Zodra deze methode true teruggeeft, dan moet de bezoeker iets gaan eten
*/
public boolean snackBehoefte() {
if (honger <= hongerToleratie)
eetBezoek = true;
else
eetBezoek = false;
return eetBezoek;
}
public double getHongerPercentage() {
return honger;
}
public void setHongerPercentage() {
honger = honger - verloopHonger;
}
public String getGenreVoorkeur() {
return genreVoorkeur;
}
public void setGenreVoorkeur() {
ArrayList<String> genres = new ArrayList<String>() {
{
add("Rock");
add("Schlager");
add("Pop");
add("Funk");
add("Metal");
add("Techno");
add("Hiphop");
add("R&B");
add("Klassiek");
add("Volksmuziek");
add("Jazz");
add("Soul");
add("Religieus");
add("Disco");
add("Blues");
}
};
genreVoorkeur = genres.get(randomWaardeInt(0, 14));
}
/*
* Genereer hiermee een random waarden tbv attributen
*/
public int randomWaardeInt(int min, int max) {
int randomInt = min + (int) (Math.random() * ((max - min) + 1));
return randomInt;
}
public double randomWaardeDouble(double min, double max) {
double randomDouble = min + (double) (Math.random() * ((max - min) + 1));
return randomDouble;
}
}
|
140317_0 | package ui;
import app.SportfeestPlannerService;
import ch.qos.logback.classic.Logger;
import com.google.inject.Guice;
import com.google.inject.Injector;
import domain.Afdeling;
import domain.Inschrijving;
import domain.Ring;
import domain.Sportfeest;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.util.Duration;
import javafx.util.Pair;
import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.slf4j.LoggerFactory;
import persistence.Marshalling;
import ui.importer.WizardImportController;
import ui.importer.WizardModule;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
public class SportfeestPlannerGUI extends Application {
private static Window primaryStage;
@FXML
private TableView<Inschrijving> tblInschrijvingen;
@FXML
private TableColumn tblColAfdeling, tblColDiscipline, tblColKorps, tblColRingnaam, tblColRingnummer;
@FXML
private Label txtStatusLabel;
@FXML
private ProgressBar prgStatusProgress;
@FXML
private MenuItem mnuStart, mnuStop, mnuExport, mnuSFSave, mnuScore;
@FXML
private AfdelingenController afdelingenController;
@FXML
private RingenController ringenController;
@FXML
private Tab tbInschrijvingen, tbLog, tbAfdelingen;
private final ObservableList<Inschrijving> ringverdeling = FXCollections.observableArrayList();
private SportfeestPlannerService sportfeestPlannerService;
private final static Logger logger = (Logger) LoggerFactory.getLogger(SportfeestPlannerGUI.class);
private final AtomicLong limiter = new AtomicLong(-1);
private final Timeline progressUpdater = new Timeline(new KeyFrame(Duration.millis(500), e -> progressUpdate()));
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
SportfeestPlannerGUI.primaryStage = primaryStage;
Parent root = FXMLLoader.load( getClass().getResource("/ui/Main.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
this.setTitle("");
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
Platform.exit();
System.exit(0);
}
});
}
private void setTitle(String subtitle) {
if(subtitle.equals("")) ((Stage)primaryStage).setTitle("KLJ Sportfeest Planner");
else ((Stage)primaryStage).setTitle("KLJ Sportfeest Planner - " + subtitle);
}
@FXML
public void SFOpen(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML-bestanden", "*.xml")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showOpenDialog(parentWindow);
if(selectedFile != null) {
try {
Sportfeest sf = Marshalling.unmarshallXml(selectedFile.getCanonicalPath());
setNewSportfeest(sf);
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
}
}
private void setNewSportfeest(Sportfeest sf) {
ringverdeling.clear();
for(Afdeling afdeling : sf.getAfdelingen()){
ringverdeling.addAll(afdeling.getInschrijvingen());
}
afdelingenController.setSportfeest(sf);
ringenController.setSportfeest(sf);
sportfeestPlannerService.setSportfeest(sf);
setTitle(sf.getLocatie() + " " + (new SimpleDateFormat("d/MM/yyyy")).format(sf.getDatum()));
}
@FXML
public void SFSave(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML-bestanden", "*.xml")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showSaveDialog(parentWindow);
if(selectedFile != null) {
try {
Marshalling.marshallXml(sportfeestPlannerService.getSportfeest(), selectedFile.getCanonicalPath());
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
}
}
@FXML
public void OpenImportExcelWizard(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Excel-bestanden", "*.xlsx;*.xlsb;*.xlsm")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showOpenDialog(parentWindow);
if(selectedFile != null) {
try {
final Injector injector = Guice.createInjector( new WizardModule() );
FXMLLoader loader = new FXMLLoader(getClass().getResource("/ui/WizardImport.fxml"),
null,
new JavaFXBuilderFactory(),
injector::getInstance);
Parent root = loader.load();
WizardImportController wizardImportController = loader.getController();
wizardImportController.setDataCallback(this::setNewSportfeest);
wizardImportController.setFilename(selectedFile.getCanonicalPath());
Stage stage = new Stage();
stage.setTitle("Importeer uit Excel");
stage.setScene(new Scene(root));
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(primaryStage);
stage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
@FXML
public void StartOplossen(ActionEvent actionEvent) {
//TODO: controleer of alle nodige ringen ingevuld zijn
sportfeestPlannerService.start();
tbLog.getTabPane().getSelectionModel().select(tbLog);
}
@FXML
public void StopOplossen(ActionEvent actionEvent) {
sportfeestPlannerService.cancel();
}
@FXML
public void ExportExcel(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Excel-bestanden", "*.xlsx")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
fileChooser.setInitialFileName("uurschema");
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showSaveDialog(parentWindow);
if(selectedFile != null) {
try {
Marshalling.marshall(sportfeestPlannerService.getSportfeest(), selectedFile.getPath());
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Exporteren naar Excel");
alert.setHeaderText("Fout bij Exporteren");
alert.setContentText(e.getMessage());
alert.showAndWait();
logger.error("Exporteren naar Excel", e);
}
}
}
@FXML
public void RingenInvullen(ActionEvent actionEvent) {
logger.info("Ringen aanvullen...");
ringverdeling.stream()
.filter(inschrijving -> inschrijving.getMogelijkeRingen().size() > 1)
.filter(inschrijving -> inschrijving.getRing() == null)
.collect(groupingBy(inschrijving -> new Pair<>(inschrijving.getDiscipline(), inschrijving.getAfdeling()), LinkedHashMap::new, toList()))
.values().stream()
.sorted(Comparator.comparing((Function<List<Inschrijving>, Integer>) List::size).reversed())
.forEach(inschrijvingen -> {
Ring leastUsedRing = inschrijvingen.get(0).getMogelijkeRingen().stream()
.map(ring -> new AbstractMap.SimpleEntry<Ring, Long>(ring, ringverdeling.stream()
.filter(inschr -> inschr.getDiscipline().getRingNaam().equals(inschrijvingen.get(0).getDiscipline().getRingNaam()))
.filter(inschr -> inschr.getRing() != null)
.collect(groupingBy(Inschrijving::getRing, Collectors.counting()))
.getOrDefault(ring, 0L)))
.min(Map.Entry.comparingByValue())
.orElse(new AbstractMap.SimpleEntry<Ring, Long>(null, 0L))
.getKey();
inschrijvingen.forEach(inschrijving -> {
logger.debug("Ring " + leastUsedRing + " toewijzen aan inschrijving " + inschrijving);
inschrijving.setRing(leastUsedRing);
});
});
logger.info("Einde ringen aanvullen...");
tblInschrijvingen.refresh();
}
@FXML
public void AnalyseResultaat(ActionEvent actionEvent) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/ui/AnalyseResultaat.fxml"));
Parent root = loader.load();
AnalyseResultaatController analyseResultaatController = loader.getController();
analyseResultaatController.setSportfeest(sportfeestPlannerService.getSportfeest(), sportfeestPlannerService.getScoreDirector());
Stage stage = new Stage();
stage.setTitle("Score en analyse resultaat");
stage.setScene(new Scene(root));
stage.initModality(Modality.NONE);
stage.initOwner(primaryStage);
stage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void initialize() {
tblColAfdeling.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getAfdeling().getNaam()));
tblColDiscipline.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getDiscipline().getNaam()));
tblColKorps.setCellValueFactory(inschr -> new SimpleIntegerProperty(((TableColumn.CellDataFeatures<Inschrijving, Integer>) inschr).getValue().getKorps()));
tblColKorps.setCellFactory(col -> new TableCell<Inschrijving, Integer>() {
@Override
protected void updateItem(Integer korps, boolean empty) {
super.updateItem(korps, empty);
if (empty) {
setText(null);
} else {
setText(korps > 0 ? korps.toString() : "");
}
}
});
tblColRingnaam.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getDiscipline().getRingNaam()));
tblColRingnummer.setCellFactory(col -> new EditingCell<Inschrijving, String>(){
@Override
public void updateItemHandler(String str) {
Inschrijving inschrijving = (Inschrijving) getTableRow().getItem();
if (inschrijving != null) {
if (inschrijving.getRing() == null) {
this.setStyle("-fx-background-color: yellow;");
} else {
this.setStyle("-fx-background-color: lightgreen;");
}
}
}
@Override
public void commitEditHandler(String newValue){
Inschrijving inschr = (Inschrijving) getTableRow().getItem();
inschr.setRing(inschr.getMogelijkeRingen().stream()
.filter(ring -> ring.getLetter().equals(newValue.trim()))
.findAny().orElse(null)
);
}
});
tblColRingnummer.setCellValueFactory(inschr -> new SimpleStringProperty(
Optional.ofNullable(
((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getRing())
.map(Ring::getLetter)
.orElse("")
));
tblInschrijvingen.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
int row = tblInschrijvingen.getSelectionModel().getSelectedIndex();
Platform.runLater(() -> tblInschrijvingen.edit(row, tblColRingnummer));
}
});
tblInschrijvingen.setItems(ringverdeling);
sportfeestPlannerService = new SportfeestPlannerService();
sportfeestPlannerService.addSolverEventListener(bestSolutionChangedEvent -> {
if (limiter.get() == -1) {
limiter.set(0);
bestSolutionChanged(bestSolutionChangedEvent);
}
});
sportfeestPlannerService.setOnSucceeded(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
setNewSportfeest(sportfeestPlannerService.getSportfeest());
AnalyseResultaat(new ActionEvent());
txtStatusLabel.setText("Einde van de berekening");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnCancelled(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
txtStatusLabel.setText("Berekening gestopt");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnFailed(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
txtStatusLabel.setText("Berekening gestopt (fout)");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnRunning(event -> {
progressUpdater.play();
prgStatusProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
txtStatusLabel.setText("Berekening starten...");
});
mnuStart.disableProperty().bind(sportfeestPlannerService.runningProperty());
mnuStop.disableProperty().bind(sportfeestPlannerService.runningProperty().not());
mnuExport.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
mnuSFSave.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
mnuScore.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
progressUpdater.setCycleCount(Animation.INDEFINITE);
}
private void bestSolutionChanged(BestSolutionChangedEvent<Sportfeest> bestSolutionChangedEvent) {
if(bestSolutionChangedEvent.isEveryProblemFactChangeProcessed()) {
//TODO: optie om te updaten
//final Sportfeest nSportfeest = (Sportfeest) bestSolutionChangedEvent.getNewBestSolution();
Platform.runLater(() -> {
txtStatusLabel.setText("Score " + bestSolutionChangedEvent.getNewBestScore().toString());
progressUpdate();
limiter.set(-1);
});
}
}
private void progressUpdate() {
if(sportfeestPlannerService.isRunning()) {
if(sportfeestPlannerService.getTimeScheduled() == Long.MAX_VALUE) {
prgStatusProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
} else {
prgStatusProgress.setProgress(sportfeestPlannerService.getTimeScheduled());
}
}
}
}
| samverstraete/klj-sf-planner | src/main/java/ui/SportfeestPlannerGUI.java | 3,956 | //TODO: controleer of alle nodige ringen ingevuld zijn | line_comment | nl | package ui;
import app.SportfeestPlannerService;
import ch.qos.logback.classic.Logger;
import com.google.inject.Guice;
import com.google.inject.Injector;
import domain.Afdeling;
import domain.Inschrijving;
import domain.Ring;
import domain.Sportfeest;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.util.Duration;
import javafx.util.Pair;
import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.slf4j.LoggerFactory;
import persistence.Marshalling;
import ui.importer.WizardImportController;
import ui.importer.WizardModule;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
public class SportfeestPlannerGUI extends Application {
private static Window primaryStage;
@FXML
private TableView<Inschrijving> tblInschrijvingen;
@FXML
private TableColumn tblColAfdeling, tblColDiscipline, tblColKorps, tblColRingnaam, tblColRingnummer;
@FXML
private Label txtStatusLabel;
@FXML
private ProgressBar prgStatusProgress;
@FXML
private MenuItem mnuStart, mnuStop, mnuExport, mnuSFSave, mnuScore;
@FXML
private AfdelingenController afdelingenController;
@FXML
private RingenController ringenController;
@FXML
private Tab tbInschrijvingen, tbLog, tbAfdelingen;
private final ObservableList<Inschrijving> ringverdeling = FXCollections.observableArrayList();
private SportfeestPlannerService sportfeestPlannerService;
private final static Logger logger = (Logger) LoggerFactory.getLogger(SportfeestPlannerGUI.class);
private final AtomicLong limiter = new AtomicLong(-1);
private final Timeline progressUpdater = new Timeline(new KeyFrame(Duration.millis(500), e -> progressUpdate()));
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
SportfeestPlannerGUI.primaryStage = primaryStage;
Parent root = FXMLLoader.load( getClass().getResource("/ui/Main.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
this.setTitle("");
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
Platform.exit();
System.exit(0);
}
});
}
private void setTitle(String subtitle) {
if(subtitle.equals("")) ((Stage)primaryStage).setTitle("KLJ Sportfeest Planner");
else ((Stage)primaryStage).setTitle("KLJ Sportfeest Planner - " + subtitle);
}
@FXML
public void SFOpen(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML-bestanden", "*.xml")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showOpenDialog(parentWindow);
if(selectedFile != null) {
try {
Sportfeest sf = Marshalling.unmarshallXml(selectedFile.getCanonicalPath());
setNewSportfeest(sf);
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
}
}
private void setNewSportfeest(Sportfeest sf) {
ringverdeling.clear();
for(Afdeling afdeling : sf.getAfdelingen()){
ringverdeling.addAll(afdeling.getInschrijvingen());
}
afdelingenController.setSportfeest(sf);
ringenController.setSportfeest(sf);
sportfeestPlannerService.setSportfeest(sf);
setTitle(sf.getLocatie() + " " + (new SimpleDateFormat("d/MM/yyyy")).format(sf.getDatum()));
}
@FXML
public void SFSave(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML-bestanden", "*.xml")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showSaveDialog(parentWindow);
if(selectedFile != null) {
try {
Marshalling.marshallXml(sportfeestPlannerService.getSportfeest(), selectedFile.getCanonicalPath());
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
}
}
@FXML
public void OpenImportExcelWizard(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Excel-bestanden", "*.xlsx;*.xlsb;*.xlsm")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showOpenDialog(parentWindow);
if(selectedFile != null) {
try {
final Injector injector = Guice.createInjector( new WizardModule() );
FXMLLoader loader = new FXMLLoader(getClass().getResource("/ui/WizardImport.fxml"),
null,
new JavaFXBuilderFactory(),
injector::getInstance);
Parent root = loader.load();
WizardImportController wizardImportController = loader.getController();
wizardImportController.setDataCallback(this::setNewSportfeest);
wizardImportController.setFilename(selectedFile.getCanonicalPath());
Stage stage = new Stage();
stage.setTitle("Importeer uit Excel");
stage.setScene(new Scene(root));
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(primaryStage);
stage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
@FXML
public void StartOplossen(ActionEvent actionEvent) {
//TODO: controleer<SUF>
sportfeestPlannerService.start();
tbLog.getTabPane().getSelectionModel().select(tbLog);
}
@FXML
public void StopOplossen(ActionEvent actionEvent) {
sportfeestPlannerService.cancel();
}
@FXML
public void ExportExcel(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Excel-bestanden", "*.xlsx")
,new FileChooser.ExtensionFilter("Alle bestanden", "*.*")
);
fileChooser.setInitialDirectory(new File("data/"));
fileChooser.setInitialFileName("uurschema");
Window parentWindow = ((MenuItem)(actionEvent.getTarget())).getParentPopup().getOwnerWindow();
File selectedFile = fileChooser.showSaveDialog(parentWindow);
if(selectedFile != null) {
try {
Marshalling.marshall(sportfeestPlannerService.getSportfeest(), selectedFile.getPath());
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Exporteren naar Excel");
alert.setHeaderText("Fout bij Exporteren");
alert.setContentText(e.getMessage());
alert.showAndWait();
logger.error("Exporteren naar Excel", e);
}
}
}
@FXML
public void RingenInvullen(ActionEvent actionEvent) {
logger.info("Ringen aanvullen...");
ringverdeling.stream()
.filter(inschrijving -> inschrijving.getMogelijkeRingen().size() > 1)
.filter(inschrijving -> inschrijving.getRing() == null)
.collect(groupingBy(inschrijving -> new Pair<>(inschrijving.getDiscipline(), inschrijving.getAfdeling()), LinkedHashMap::new, toList()))
.values().stream()
.sorted(Comparator.comparing((Function<List<Inschrijving>, Integer>) List::size).reversed())
.forEach(inschrijvingen -> {
Ring leastUsedRing = inschrijvingen.get(0).getMogelijkeRingen().stream()
.map(ring -> new AbstractMap.SimpleEntry<Ring, Long>(ring, ringverdeling.stream()
.filter(inschr -> inschr.getDiscipline().getRingNaam().equals(inschrijvingen.get(0).getDiscipline().getRingNaam()))
.filter(inschr -> inschr.getRing() != null)
.collect(groupingBy(Inschrijving::getRing, Collectors.counting()))
.getOrDefault(ring, 0L)))
.min(Map.Entry.comparingByValue())
.orElse(new AbstractMap.SimpleEntry<Ring, Long>(null, 0L))
.getKey();
inschrijvingen.forEach(inschrijving -> {
logger.debug("Ring " + leastUsedRing + " toewijzen aan inschrijving " + inschrijving);
inschrijving.setRing(leastUsedRing);
});
});
logger.info("Einde ringen aanvullen...");
tblInschrijvingen.refresh();
}
@FXML
public void AnalyseResultaat(ActionEvent actionEvent) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/ui/AnalyseResultaat.fxml"));
Parent root = loader.load();
AnalyseResultaatController analyseResultaatController = loader.getController();
analyseResultaatController.setSportfeest(sportfeestPlannerService.getSportfeest(), sportfeestPlannerService.getScoreDirector());
Stage stage = new Stage();
stage.setTitle("Score en analyse resultaat");
stage.setScene(new Scene(root));
stage.initModality(Modality.NONE);
stage.initOwner(primaryStage);
stage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void initialize() {
tblColAfdeling.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getAfdeling().getNaam()));
tblColDiscipline.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getDiscipline().getNaam()));
tblColKorps.setCellValueFactory(inschr -> new SimpleIntegerProperty(((TableColumn.CellDataFeatures<Inschrijving, Integer>) inschr).getValue().getKorps()));
tblColKorps.setCellFactory(col -> new TableCell<Inschrijving, Integer>() {
@Override
protected void updateItem(Integer korps, boolean empty) {
super.updateItem(korps, empty);
if (empty) {
setText(null);
} else {
setText(korps > 0 ? korps.toString() : "");
}
}
});
tblColRingnaam.setCellValueFactory(inschr -> new SimpleStringProperty(((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getDiscipline().getRingNaam()));
tblColRingnummer.setCellFactory(col -> new EditingCell<Inschrijving, String>(){
@Override
public void updateItemHandler(String str) {
Inschrijving inschrijving = (Inschrijving) getTableRow().getItem();
if (inschrijving != null) {
if (inschrijving.getRing() == null) {
this.setStyle("-fx-background-color: yellow;");
} else {
this.setStyle("-fx-background-color: lightgreen;");
}
}
}
@Override
public void commitEditHandler(String newValue){
Inschrijving inschr = (Inschrijving) getTableRow().getItem();
inschr.setRing(inschr.getMogelijkeRingen().stream()
.filter(ring -> ring.getLetter().equals(newValue.trim()))
.findAny().orElse(null)
);
}
});
tblColRingnummer.setCellValueFactory(inschr -> new SimpleStringProperty(
Optional.ofNullable(
((TableColumn.CellDataFeatures<Inschrijving, String>) inschr).getValue().getRing())
.map(Ring::getLetter)
.orElse("")
));
tblInschrijvingen.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
int row = tblInschrijvingen.getSelectionModel().getSelectedIndex();
Platform.runLater(() -> tblInschrijvingen.edit(row, tblColRingnummer));
}
});
tblInschrijvingen.setItems(ringverdeling);
sportfeestPlannerService = new SportfeestPlannerService();
sportfeestPlannerService.addSolverEventListener(bestSolutionChangedEvent -> {
if (limiter.get() == -1) {
limiter.set(0);
bestSolutionChanged(bestSolutionChangedEvent);
}
});
sportfeestPlannerService.setOnSucceeded(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
setNewSportfeest(sportfeestPlannerService.getSportfeest());
AnalyseResultaat(new ActionEvent());
txtStatusLabel.setText("Einde van de berekening");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnCancelled(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
txtStatusLabel.setText("Berekening gestopt");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnFailed(event -> {
progressUpdater.stop();
prgStatusProgress.setProgress(0);
txtStatusLabel.setText("Berekening gestopt (fout)");
sportfeestPlannerService.reset();
});
sportfeestPlannerService.setOnRunning(event -> {
progressUpdater.play();
prgStatusProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
txtStatusLabel.setText("Berekening starten...");
});
mnuStart.disableProperty().bind(sportfeestPlannerService.runningProperty());
mnuStop.disableProperty().bind(sportfeestPlannerService.runningProperty().not());
mnuExport.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
mnuSFSave.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
mnuScore.disableProperty().bind(sportfeestPlannerService.getSportfeestProperty().isNull());
progressUpdater.setCycleCount(Animation.INDEFINITE);
}
private void bestSolutionChanged(BestSolutionChangedEvent<Sportfeest> bestSolutionChangedEvent) {
if(bestSolutionChangedEvent.isEveryProblemFactChangeProcessed()) {
//TODO: optie om te updaten
//final Sportfeest nSportfeest = (Sportfeest) bestSolutionChangedEvent.getNewBestSolution();
Platform.runLater(() -> {
txtStatusLabel.setText("Score " + bestSolutionChangedEvent.getNewBestScore().toString());
progressUpdate();
limiter.set(-1);
});
}
}
private void progressUpdate() {
if(sportfeestPlannerService.isRunning()) {
if(sportfeestPlannerService.getTimeScheduled() == Long.MAX_VALUE) {
prgStatusProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
} else {
prgStatusProgress.setProgress(sportfeestPlannerService.getTimeScheduled());
}
}
}
}
|
187639_41 | /*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.file.impl;
import io.netty.util.internal.PlatformDependent;
import io.vertx.core.VertxException;
import io.vertx.core.file.FileSystemOptions;
import io.vertx.core.impl.Utils;
import io.vertx.core.spi.file.FileResolver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static io.vertx.core.net.impl.URIDecoder.decodeURIComponent;
/**
* Sometimes the file resources of an application are bundled into jars, or are somewhere on the classpath but not
* available on the file system, e.g. in the case of a Vert.x webapp bundled as a fat jar.
* <p>
* In this case we want the application to access the resource from the classpath as if it was on the file system.
* <p>
* We can do this by looking for the file on the classpath, and if found, copying it to a temporary cache directory
* on disk and serving it from there.
* <p>
* There is one cache dir per Vert.x instance and they are deleted on Vert.x shutdown.
*
* @author <a href="http://tfox.org">Tim Fox</a>
* @author <a href="https://github.com/rworsnop/">Rob Worsnop</a>
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class FileResolverImpl implements FileResolver {
private static final boolean NON_UNIX_FILE_SEP = File.separatorChar != '/';
private static final String JAR_URL_SEP = "!/";
private final boolean enableCaching;
private final boolean enableCPResolving;
private final FileCache cache;
public FileResolverImpl() {
this(new FileSystemOptions());
}
public FileResolverImpl(FileSystemOptions fileSystemOptions) {
enableCaching = fileSystemOptions.isFileCachingEnabled();
enableCPResolving = fileSystemOptions.isClassPathResolvingEnabled();
if (enableCPResolving) {
cache = FileCache.setupCache(fileSystemOptions.getFileCacheDir());
} else {
cache = null;
}
}
public String cacheDir() {
if (cache != null) {
return cache.cacheDir();
}
return null;
}
FileCache getFileCache() {
return this.cache;
}
/**
* Close this file resolver, this is a blocking operation.
*/
public void close() throws IOException {
if (enableCPResolving) {
synchronized (cache) {
cache.close();
}
}
}
public File resolveFile(String fileName) {
// First look for file with that name on disk
File file = new File(fileName);
boolean absolute = file.isAbsolute();
if (this.cache == null) {
return file;
}
// We need to synchronized here to avoid 2 different threads to copy the file to the cache directory and so
// corrupting the content.
if (!file.exists()) {
synchronized (cache) {
// When an absolute file is here, if it falls under the cache directory, then it should be made relative as it
// could mean that a previous resolution has been used to resolve a non local file system resource
File cacheFile = cache.getCanonicalFile(file);
// the file may or may not be in the cache dir after canonicalization
if (cacheFile == null) {
// the given file cannot be resolved to the real FS
return file;
}
// compute the difference of the path
String relativize = cache.relativize(cacheFile.getPath());
if (relativize != null) {
// file is inside the cache dir, we can continue with the search
if (this.enableCaching && cacheFile.exists()) {
return cacheFile;
}
// as it wasn't found, maybe it hasn't been extracted yet
// adjust the name and absolute references if needed
if (absolute) {
fileName = relativize;
file = new File(relativize);
absolute = false;
}
}
// https://vertx.io/docs/vertx-core/java/#classpath
// if a resource is still absolute, it means it's outside the cache, we don't need to handle it.
// otherwise, we need to go over the classpath resources
if (!absolute) {
// Look for file on classpath
ClassLoader cl = getClassLoader();
//https://github.com/eclipse/vert.x/issues/2126
//Cache all elements in the parent directory if it exists
//this is so that listing the directory after an individual file has
//been read works.
File parentFile = file.getParentFile();
while (parentFile != null) {
String parentFileName = parentFile.getPath();
if (NON_UNIX_FILE_SEP) {
parentFileName = parentFileName.replace(File.separatorChar, '/');
}
URL directoryContents = getValidClassLoaderResource(cl, parentFileName);
if (directoryContents != null) {
unpackUrlResource(directoryContents, parentFileName, cl, true);
}
// https://github.com/eclipse-vertx/vert.x/issues/3654
// go up one level until we reach the top, this way we ensure we extract the whole tree
// not just a branch so directory listing will be correct
parentFile = parentFile.getParentFile();
}
if (NON_UNIX_FILE_SEP) {
fileName = fileName.replace(File.separatorChar, '/');
}
URL url = getValidClassLoaderResource(cl, fileName);
if (url != null) {
return unpackUrlResource(url, fileName, cl, false);
}
}
}
}
return file;
}
private static boolean isValidWindowsCachePath(char c) {
if (c < 32) {
return false;
}
switch (c) {
case '"':
case '*':
case ':':
case '<':
case '>':
case '?':
case '|':
return false;
default:
return true;
}
}
private static boolean isValidCachePath(String fileName) {
if (PlatformDependent.isWindows()) {
int len = fileName.length();
for (int i = 0; i < len; i++) {
char c = fileName.charAt(i);
if (!isValidWindowsCachePath(c)) {
return false;
}
// Space only valid when it's not ending a name
if (c == ' ' && (i + 1 == len || fileName.charAt(i + 1) == '/')) {
return false;
}
}
return true;
} else {
return fileName.indexOf('\u0000') == -1;
}
}
/**
* Get a class loader resource that can unpack to a valid cache path.
* <p>
* Some valid entries are avoided purposely when we cannot create the corresponding file in the file cache.
*/
private static URL getValidClassLoaderResource(ClassLoader cl, String fileName) {
URL resource = cl.getResource(fileName);
if (resource != null && !isValidCachePath(fileName)) {
return null;
}
return resource;
}
private File unpackUrlResource(URL url, String fileName, ClassLoader cl, boolean isDir) {
String prot = url.getProtocol();
switch (prot) {
case "file":
return unpackFromFileURL(url, fileName, cl);
case "jar":
return unpackFromJarURL(url, fileName, cl);
case "bundle": // Apache Felix, Knopflerfish
case "bundleentry": // Equinox
case "bundleresource": // Equinox
case "jrt": // java run-time (JEP 220)
case "resource": // substratevm (graal native image)
case "vfs": // jboss-vfs
return unpackFromBundleURL(url, fileName, isDir);
default:
throw new IllegalStateException("Invalid url protocol: " + prot);
}
}
private File unpackFromFileURL(URL url, String fileName, ClassLoader cl) {
final File resource = new File(decodeURIComponent(url.getPath(), false));
boolean isDirectory = resource.isDirectory();
File cacheFile;
try {
cacheFile = cache.cacheFile(fileName, resource, !enableCaching);
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
if (isDirectory) {
String[] listing = resource.list();
if (listing != null) {
for (String file : listing) {
String subResource = fileName + "/" + file;
URL url2 = getValidClassLoaderResource(cl, subResource);
if (url2 == null) {
throw new VertxException("Invalid resource: " + subResource);
}
unpackFromFileURL(url2, subResource, cl);
}
}
}
return cacheFile;
}
/**
* Parse the list of entries of a URL assuming the URL is a jar URL.
*
* <ul>
* <li>when the URL is a nested file within the archive, the list is the jar entry</li>
* <li>when the URL is a nested file within a nested file within the archive, the list is jar entry followed by the jar entry of the nested archive</li>
* <li>and so on.</li>
* </ul>
*
* @param url the URL
* @return the list of entries
*/
private List<String> listOfEntries(URL url) {
String path = url.getPath();
List<String> list = new ArrayList<>();
int last = path.length();
for (int i = path.length() - 2; i >= 0;) {
if (path.charAt(i) == '!' && path.charAt(i + 1) == '/') {
list.add(path.substring(2 + i, last));
last = i;
i -= 2;
} else {
i--;
}
}
return list;
}
private File unpackFromJarURL(URL url, String fileName, ClassLoader cl) {
try {
List<String> listOfEntries = listOfEntries(url);
switch (listOfEntries.size()) {
case 1: {
JarURLConnection conn = (JarURLConnection) url.openConnection();
if (conn.getContentLength() == -1) {
// the entry is a directory, so, it does not really exist.
// which means we cannot get the JarFile from the connection.
// In general, we should not be here, as the URL should be a directory, and we should not have a JarURLConnection.
// However, classloader implementation may provide an URL. In this case, we should not try to get the JarFile
// as it does not exist (or is not valid), and it will throw an exception.
// We still retrieve it from the cache if it exists (got unzipped before or concurrently)
return cache.getFile(fileName);
}
ZipFile zip = conn.getJarFile();
try {
extractFilesFromJarFile(zip, fileName);
} finally {
if (!conn.getUseCaches()) {
zip.close();
}
}
break;
}
case 2:
URL nestedURL = cl.getResource(listOfEntries.get(1));
if (nestedURL != null && nestedURL.getProtocol().equals("jar")) {
File root = unpackFromJarURL(nestedURL, listOfEntries.get(1), cl);
if (root.isDirectory()) {
// jar:file:/path/to/nesting.jar!/xxx-inf/classes
// we need to unpack xxx-inf/classes and then copy the content as is in the cache
Path path = root.toPath();
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path relative = path.relativize(dir);
cache.cacheDir(relative.toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relative = path.relativize(file);
cache.cacheFile(relative.toString(), file.toFile(), false);
return FileVisitResult.CONTINUE;
}
});
} else {
// jar:file:/path/to/nesting.jar!/path/to/nested.jar
try (ZipFile zip = new ZipFile(root)) {
extractFilesFromJarFile(zip, fileName);
}
}
} else {
throw new VertxException("Unexpected nested url : " + nestedURL);
}
break;
default:
throw new VertxException("Nesting more than two levels is not supported");
}
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
return cache.getFile(fileName);
}
/**
* Extract a subset of the entries to the cache.
*/
private void extractFilesFromJarFile(ZipFile zip, String entryFilter) throws IOException {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
int len = name.length();
if (len == 0) {
return;
}
if (name.charAt(len - 1) != ' ' || !Utils.isWindows()) {
if (name.startsWith(entryFilter)) {
if (name.charAt(len - 1) == '/') {
cache.cacheDir(name);
} else {
try (InputStream is = zip.getInputStream(entry)) {
cache.cacheFile(name, is, !enableCaching);
}
}
}
}
}
}
/**
* It is possible to determine if a resource from a bundle is a directory based on whether or not the ClassLoader
* returns null for a path (which does not already contain a trailing '/') *and* that path with an added trailing '/'
*
* @param url the url
* @return if the bundle resource represented by the bundle URL is a directory
*/
private boolean isBundleUrlDirectory(URL url) {
return url.toExternalForm().endsWith("/") ||
getValidClassLoaderResource(getClassLoader(), url.getPath().substring(1) + "/") != null;
}
/**
* bundle:// urls are used by OSGi implementations to refer to a file contained in a bundle, or in a fragment. There
* is not much we can do to get the file from it, except reading it from the url. This method copies the files by
* reading it from the url.
*
* @param url the url
* @param fileName the file name used to cache the content
* @return the extracted file
*/
private File unpackFromBundleURL(URL url, String fileName, boolean isDir) {
try {
if ((getClassLoader() != null && isBundleUrlDirectory(url)) || isDir) {
// Directory
cache.cacheDir(fileName);
} else {
try (InputStream is = url.openStream()) {
cache.cacheFile(fileName, is, !enableCaching);
}
}
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
return cache.getFile(fileName);
}
private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
// when running on substratevm (graal) the access to class loaders
// is very limited and might be only available from compile time
// known classes. (Object is always known, so we do a final attempt
// to get it here).
if (cl == null) {
cl = Object.class.getClassLoader();
}
return cl;
}
}
| eclipse-vertx/vert.x | src/main/java/io/vertx/core/file/impl/FileResolverImpl.java | 4,222 | // to get it here). | line_comment | nl | /*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.file.impl;
import io.netty.util.internal.PlatformDependent;
import io.vertx.core.VertxException;
import io.vertx.core.file.FileSystemOptions;
import io.vertx.core.impl.Utils;
import io.vertx.core.spi.file.FileResolver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static io.vertx.core.net.impl.URIDecoder.decodeURIComponent;
/**
* Sometimes the file resources of an application are bundled into jars, or are somewhere on the classpath but not
* available on the file system, e.g. in the case of a Vert.x webapp bundled as a fat jar.
* <p>
* In this case we want the application to access the resource from the classpath as if it was on the file system.
* <p>
* We can do this by looking for the file on the classpath, and if found, copying it to a temporary cache directory
* on disk and serving it from there.
* <p>
* There is one cache dir per Vert.x instance and they are deleted on Vert.x shutdown.
*
* @author <a href="http://tfox.org">Tim Fox</a>
* @author <a href="https://github.com/rworsnop/">Rob Worsnop</a>
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class FileResolverImpl implements FileResolver {
private static final boolean NON_UNIX_FILE_SEP = File.separatorChar != '/';
private static final String JAR_URL_SEP = "!/";
private final boolean enableCaching;
private final boolean enableCPResolving;
private final FileCache cache;
public FileResolverImpl() {
this(new FileSystemOptions());
}
public FileResolverImpl(FileSystemOptions fileSystemOptions) {
enableCaching = fileSystemOptions.isFileCachingEnabled();
enableCPResolving = fileSystemOptions.isClassPathResolvingEnabled();
if (enableCPResolving) {
cache = FileCache.setupCache(fileSystemOptions.getFileCacheDir());
} else {
cache = null;
}
}
public String cacheDir() {
if (cache != null) {
return cache.cacheDir();
}
return null;
}
FileCache getFileCache() {
return this.cache;
}
/**
* Close this file resolver, this is a blocking operation.
*/
public void close() throws IOException {
if (enableCPResolving) {
synchronized (cache) {
cache.close();
}
}
}
public File resolveFile(String fileName) {
// First look for file with that name on disk
File file = new File(fileName);
boolean absolute = file.isAbsolute();
if (this.cache == null) {
return file;
}
// We need to synchronized here to avoid 2 different threads to copy the file to the cache directory and so
// corrupting the content.
if (!file.exists()) {
synchronized (cache) {
// When an absolute file is here, if it falls under the cache directory, then it should be made relative as it
// could mean that a previous resolution has been used to resolve a non local file system resource
File cacheFile = cache.getCanonicalFile(file);
// the file may or may not be in the cache dir after canonicalization
if (cacheFile == null) {
// the given file cannot be resolved to the real FS
return file;
}
// compute the difference of the path
String relativize = cache.relativize(cacheFile.getPath());
if (relativize != null) {
// file is inside the cache dir, we can continue with the search
if (this.enableCaching && cacheFile.exists()) {
return cacheFile;
}
// as it wasn't found, maybe it hasn't been extracted yet
// adjust the name and absolute references if needed
if (absolute) {
fileName = relativize;
file = new File(relativize);
absolute = false;
}
}
// https://vertx.io/docs/vertx-core/java/#classpath
// if a resource is still absolute, it means it's outside the cache, we don't need to handle it.
// otherwise, we need to go over the classpath resources
if (!absolute) {
// Look for file on classpath
ClassLoader cl = getClassLoader();
//https://github.com/eclipse/vert.x/issues/2126
//Cache all elements in the parent directory if it exists
//this is so that listing the directory after an individual file has
//been read works.
File parentFile = file.getParentFile();
while (parentFile != null) {
String parentFileName = parentFile.getPath();
if (NON_UNIX_FILE_SEP) {
parentFileName = parentFileName.replace(File.separatorChar, '/');
}
URL directoryContents = getValidClassLoaderResource(cl, parentFileName);
if (directoryContents != null) {
unpackUrlResource(directoryContents, parentFileName, cl, true);
}
// https://github.com/eclipse-vertx/vert.x/issues/3654
// go up one level until we reach the top, this way we ensure we extract the whole tree
// not just a branch so directory listing will be correct
parentFile = parentFile.getParentFile();
}
if (NON_UNIX_FILE_SEP) {
fileName = fileName.replace(File.separatorChar, '/');
}
URL url = getValidClassLoaderResource(cl, fileName);
if (url != null) {
return unpackUrlResource(url, fileName, cl, false);
}
}
}
}
return file;
}
private static boolean isValidWindowsCachePath(char c) {
if (c < 32) {
return false;
}
switch (c) {
case '"':
case '*':
case ':':
case '<':
case '>':
case '?':
case '|':
return false;
default:
return true;
}
}
private static boolean isValidCachePath(String fileName) {
if (PlatformDependent.isWindows()) {
int len = fileName.length();
for (int i = 0; i < len; i++) {
char c = fileName.charAt(i);
if (!isValidWindowsCachePath(c)) {
return false;
}
// Space only valid when it's not ending a name
if (c == ' ' && (i + 1 == len || fileName.charAt(i + 1) == '/')) {
return false;
}
}
return true;
} else {
return fileName.indexOf('\u0000') == -1;
}
}
/**
* Get a class loader resource that can unpack to a valid cache path.
* <p>
* Some valid entries are avoided purposely when we cannot create the corresponding file in the file cache.
*/
private static URL getValidClassLoaderResource(ClassLoader cl, String fileName) {
URL resource = cl.getResource(fileName);
if (resource != null && !isValidCachePath(fileName)) {
return null;
}
return resource;
}
private File unpackUrlResource(URL url, String fileName, ClassLoader cl, boolean isDir) {
String prot = url.getProtocol();
switch (prot) {
case "file":
return unpackFromFileURL(url, fileName, cl);
case "jar":
return unpackFromJarURL(url, fileName, cl);
case "bundle": // Apache Felix, Knopflerfish
case "bundleentry": // Equinox
case "bundleresource": // Equinox
case "jrt": // java run-time (JEP 220)
case "resource": // substratevm (graal native image)
case "vfs": // jboss-vfs
return unpackFromBundleURL(url, fileName, isDir);
default:
throw new IllegalStateException("Invalid url protocol: " + prot);
}
}
private File unpackFromFileURL(URL url, String fileName, ClassLoader cl) {
final File resource = new File(decodeURIComponent(url.getPath(), false));
boolean isDirectory = resource.isDirectory();
File cacheFile;
try {
cacheFile = cache.cacheFile(fileName, resource, !enableCaching);
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
if (isDirectory) {
String[] listing = resource.list();
if (listing != null) {
for (String file : listing) {
String subResource = fileName + "/" + file;
URL url2 = getValidClassLoaderResource(cl, subResource);
if (url2 == null) {
throw new VertxException("Invalid resource: " + subResource);
}
unpackFromFileURL(url2, subResource, cl);
}
}
}
return cacheFile;
}
/**
* Parse the list of entries of a URL assuming the URL is a jar URL.
*
* <ul>
* <li>when the URL is a nested file within the archive, the list is the jar entry</li>
* <li>when the URL is a nested file within a nested file within the archive, the list is jar entry followed by the jar entry of the nested archive</li>
* <li>and so on.</li>
* </ul>
*
* @param url the URL
* @return the list of entries
*/
private List<String> listOfEntries(URL url) {
String path = url.getPath();
List<String> list = new ArrayList<>();
int last = path.length();
for (int i = path.length() - 2; i >= 0;) {
if (path.charAt(i) == '!' && path.charAt(i + 1) == '/') {
list.add(path.substring(2 + i, last));
last = i;
i -= 2;
} else {
i--;
}
}
return list;
}
private File unpackFromJarURL(URL url, String fileName, ClassLoader cl) {
try {
List<String> listOfEntries = listOfEntries(url);
switch (listOfEntries.size()) {
case 1: {
JarURLConnection conn = (JarURLConnection) url.openConnection();
if (conn.getContentLength() == -1) {
// the entry is a directory, so, it does not really exist.
// which means we cannot get the JarFile from the connection.
// In general, we should not be here, as the URL should be a directory, and we should not have a JarURLConnection.
// However, classloader implementation may provide an URL. In this case, we should not try to get the JarFile
// as it does not exist (or is not valid), and it will throw an exception.
// We still retrieve it from the cache if it exists (got unzipped before or concurrently)
return cache.getFile(fileName);
}
ZipFile zip = conn.getJarFile();
try {
extractFilesFromJarFile(zip, fileName);
} finally {
if (!conn.getUseCaches()) {
zip.close();
}
}
break;
}
case 2:
URL nestedURL = cl.getResource(listOfEntries.get(1));
if (nestedURL != null && nestedURL.getProtocol().equals("jar")) {
File root = unpackFromJarURL(nestedURL, listOfEntries.get(1), cl);
if (root.isDirectory()) {
// jar:file:/path/to/nesting.jar!/xxx-inf/classes
// we need to unpack xxx-inf/classes and then copy the content as is in the cache
Path path = root.toPath();
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path relative = path.relativize(dir);
cache.cacheDir(relative.toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relative = path.relativize(file);
cache.cacheFile(relative.toString(), file.toFile(), false);
return FileVisitResult.CONTINUE;
}
});
} else {
// jar:file:/path/to/nesting.jar!/path/to/nested.jar
try (ZipFile zip = new ZipFile(root)) {
extractFilesFromJarFile(zip, fileName);
}
}
} else {
throw new VertxException("Unexpected nested url : " + nestedURL);
}
break;
default:
throw new VertxException("Nesting more than two levels is not supported");
}
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
return cache.getFile(fileName);
}
/**
* Extract a subset of the entries to the cache.
*/
private void extractFilesFromJarFile(ZipFile zip, String entryFilter) throws IOException {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
int len = name.length();
if (len == 0) {
return;
}
if (name.charAt(len - 1) != ' ' || !Utils.isWindows()) {
if (name.startsWith(entryFilter)) {
if (name.charAt(len - 1) == '/') {
cache.cacheDir(name);
} else {
try (InputStream is = zip.getInputStream(entry)) {
cache.cacheFile(name, is, !enableCaching);
}
}
}
}
}
}
/**
* It is possible to determine if a resource from a bundle is a directory based on whether or not the ClassLoader
* returns null for a path (which does not already contain a trailing '/') *and* that path with an added trailing '/'
*
* @param url the url
* @return if the bundle resource represented by the bundle URL is a directory
*/
private boolean isBundleUrlDirectory(URL url) {
return url.toExternalForm().endsWith("/") ||
getValidClassLoaderResource(getClassLoader(), url.getPath().substring(1) + "/") != null;
}
/**
* bundle:// urls are used by OSGi implementations to refer to a file contained in a bundle, or in a fragment. There
* is not much we can do to get the file from it, except reading it from the url. This method copies the files by
* reading it from the url.
*
* @param url the url
* @param fileName the file name used to cache the content
* @return the extracted file
*/
private File unpackFromBundleURL(URL url, String fileName, boolean isDir) {
try {
if ((getClassLoader() != null && isBundleUrlDirectory(url)) || isDir) {
// Directory
cache.cacheDir(fileName);
} else {
try (InputStream is = url.openStream()) {
cache.cacheFile(fileName, is, !enableCaching);
}
}
} catch (IOException e) {
throw new VertxException(FileSystemImpl.getFileAccessErrorMessage("unpack", url.toString()), e);
}
return cache.getFile(fileName);
}
private ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
// when running on substratevm (graal) the access to class loaders
// is very limited and might be only available from compile time
// known classes. (Object is always known, so we do a final attempt
// to get<SUF>
if (cl == null) {
cl = Object.class.getClassLoader();
}
return cl;
}
}
|
126659_9 | public class A_IfStatements {
public static void main(String[] args) {
//
// IF Statements 1
//
int number = 2;
// implementeer de conditie van het if statement.
if (number % 2 != 0) {
System.out.println("Odd");
} else {
System.out.println("Even");
}
//
// IF Statements 2
//
float totalAmount = 100.5f;
float discount = 0f;
// voeg een if statement toe voor het kortingsysteem.
// als de klant voor meer dan 50 besteld, wordt er 5% korting gegeven.
// als de klant voor meer dan 100 besteld, wordt er 10% korting gegeven.
// anders krijgt de klant 1% korting
// maak je geen zorgen over afronding.
if (totalAmount > 50f) {
discount = 0.05f;
} else if (totalAmount > 100f) {
discount = 0.1f;
} else {
discount = 1f;
}
float totalAmountIncludingVAT = (totalAmount - (totalAmount * discount)) * 1.22f;
System.out.println("Te betalen: " + totalAmountIncludingVAT);
//
// IF Statements 3
//
int x = 8;
int y = 10;
// Voeg een if statement toe zodat alleen het juiste statement hieronder wordt uitgevoerd. Het if statement moet controleren of x groter is dan y, of y groter is dan x.
if (x > y) {
System.out.println(x + " > " + y);
} else if (y > x) {
System.out.println(y + " > " + x);
} else {
System.out.println("I can't choose... I think they are equal...");
}
}
} | Aphelion-im/EdHub-Programmeren-met-Java-opdrachten | H3.5 - Controlflow-constructies/backend-java-controlflow/src/main/java/A_IfStatements.java | 480 | // Voeg een if statement toe zodat alleen het juiste statement hieronder wordt uitgevoerd. Het if statement moet controleren of x groter is dan y, of y groter is dan x. | line_comment | nl | public class A_IfStatements {
public static void main(String[] args) {
//
// IF Statements 1
//
int number = 2;
// implementeer de conditie van het if statement.
if (number % 2 != 0) {
System.out.println("Odd");
} else {
System.out.println("Even");
}
//
// IF Statements 2
//
float totalAmount = 100.5f;
float discount = 0f;
// voeg een if statement toe voor het kortingsysteem.
// als de klant voor meer dan 50 besteld, wordt er 5% korting gegeven.
// als de klant voor meer dan 100 besteld, wordt er 10% korting gegeven.
// anders krijgt de klant 1% korting
// maak je geen zorgen over afronding.
if (totalAmount > 50f) {
discount = 0.05f;
} else if (totalAmount > 100f) {
discount = 0.1f;
} else {
discount = 1f;
}
float totalAmountIncludingVAT = (totalAmount - (totalAmount * discount)) * 1.22f;
System.out.println("Te betalen: " + totalAmountIncludingVAT);
//
// IF Statements 3
//
int x = 8;
int y = 10;
// Voeg een<SUF>
if (x > y) {
System.out.println(x + " > " + y);
} else if (y > x) {
System.out.println(y + " > " + x);
} else {
System.out.println("I can't choose... I think they are equal...");
}
}
} |
120641_48 | /* LanguageTool, a natural language style checker
* Copyright (C) 2015 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.languagetool.*;
import org.languagetool.chunking.GermanChunker;
import org.languagetool.language.German;
import org.languagetool.rules.RuleMatch;
public class SubjectVerbAgreementRuleTest {
private static SubjectVerbAgreementRule rule;
private static JLanguageTool langTool;
@BeforeClass
public static void setUp() {
Language german = Languages.getLanguageForShortCode("de-DE");
rule = new SubjectVerbAgreementRule(TestTools.getMessages("de"), (German) german);
langTool = new JLanguageTool(german);
}
@Test
public void testTemp() throws IOException {
// For debugging, comment in the next three lines:
//GermanChunker.setDebug(true);
//assertGood("...");
//assertBad("...");
// Hier ist (auch: sind) sowohl Anhalten wie Parken verboten.
// TODO - false alarms from Tatoeba and Wikipedia:
// "Die restlichen sechsundachtzig oder siebenundachtzig Prozent sind in der Flasche.",
// "Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.", // OpenNLP doesn't find 'Unternehmensnamen' as a noun
// "Die ältere der beiden Töchter ist hier.",
// "Liebe und Hochzeit sind nicht das Gleiche."
// "Die Typologie oder besser Typographie ist die Klassifikation von Objekten"
// "Im Falle qualitativer, quantitativer und örtlicher Veränderung ist dies ein konkretes Einzelding,"
// "...zu finden, in denen die Päpste selbst Partei waren."
// "Hauptfigur der beiden Bücher ist Golan Trevize."
// "Das größte und bekannteste Unternehmen dieses Genres ist der Cirque du Soleil."
// "In Schweden, Finnland, Dänemark und Österreich ist die Haltung von Wildtieren erlaubt."
// "Die einzige Waffe, die keine Waffe der Gewalt ist: die Wahrheit."
// "Du weißt ja wie töricht Verliebte sind."
// "Freies Assoziieren und Phantasieren ist erlaubt."
// "In den beiden Städten Bremen und Bremerhaven ist jeweils eine Müllverbrennungsanlage in Betrieb."
// "Hauptstadt und größte Stadt des Landes ist Sarajevo."
// "Durch Rutschen, Fallrohre oder Schläuche ist der Beton bis in die Schalung zu leiten."
// "Wegen ihres ganzen Erfolgs war sie unglücklich."
// "Eines der bedeutendsten Museen ist das Museo Nacional de Bellas Artes."
// "Die Nominierung der Filme sowie die Auswahl der Jurymitglieder ist Aufgabe der Festivaldirektion."
// "Ehemalige Fraktionsvorsitzende waren Schmidt, Kohl und Merkel."
// "Die Hälfte der Äpfel sind verfault."
// "... in der Geschichte des Museums, die Sammlung ist seit März 2011 dauerhaft der Öffentlichkeit zugänglich."
// "Ein gutes Aufwärmen und Dehnen ist zwingend notwendig."
// "Eine Stammfunktion oder ein unbestimmtes Integral ist eine mathematische Funktion ..."
// "Wenn die Begeisterung für eine Person, Gruppe oder Sache religiöser Art ist ..."
// "Ein Staat, dessen Oberhaupt nicht ein König oder eine Königin ist."
// "Des Menschen größter Feind und bester Freund ist ein anderer Mensch."
// "Die Nauheimer Musiktage, die zu einer Tradition geworden sind und immer wieder ein kultureller Höhepunkt sind."
// "Ein erheblicher Teil der anderen Transportmaschinen waren schwerbeschädigt." // ??
// "Die herrschende Klasse und die Klassengesellschaft war geboren." // ??
// "Russland ist der größte Staat der Welt und der Vatikan ist der kleinste Staat der Welt.",
// "Eine Rose ist eine Blume und eine Taube ist ein Vogel.",
// "Der beste Beobachter und der tiefste Denker ist immer der mildeste Richter.",
//assertGood("Dumas ist der Familienname folgender Personen."); // Dumas wird als Plural von Duma erkannt
//assertGood("Berlin war Hauptstadt des Vergnügens und der Wintergarten war angesagt."); // wg. 'und'
//assertGood("Elemente eines axiomatischen Systems sind:"); // 'Elemente' ist ambig (SIN, PLU)
//assertGood("Auch wenn Dortmund größte Stadt und ein Zentrum dieses Raums ist."); // unsere 'und'-Regel darf hier nicht matchen
//assertGood("Die Zielgruppe waren Glaubensangehörige im Ausland sowie Reisende."); // Glaubensangehörige hat kein Plural-Reading in Morphy
}
@Test
public void testPrevChunkIsNominative() throws IOException {
assertTrue(rule.prevChunkIsNominative(getTokens("Die Katze ist süß"), 2));
assertTrue(rule.prevChunkIsNominative(getTokens("Das Fell der Katzen ist süß"), 4));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem alten Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Beiden Filmen war kein Erfolg beschieden."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Aber beiden Filmen war kein Erfolg beschieden."), 3));
//assertFalse(rule.prevChunkIsNominative(getTokens("Der Katzen Fell ist süß"), 3));
}
@Test
public void testArrayOutOfBoundsBug() throws IOException {
rule.match(langTool.getAnalyzedSentence("Die nicht Teil des Näherungsmodells sind"));
}
private AnalyzedTokenReadings[] getTokens(String s) throws IOException {
return langTool.getAnalyzedSentence(s).getTokensWithoutWhitespace();
}
@Test
public void testRuleWithIncorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Autos ist schnell.",
"Der Hund und die Katze ist draußen.",
"Ein Hund und eine Katze ist schön.",
"Der Hund und die Katze ist schön.",
"Der große Hund und die Katze ist schön.",
"Der Hund und die graue Katze ist schön.",
"Der große Hund und die graue Katze ist schön.",
"Die Kenntnisse ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der neuen europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der aktuellen deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Drei Katzen ist im Haus.",
"Drei kleine Katzen ist im Haus.",
"Viele Katzen ist schön.",
"Drei Viertel der Erdoberfläche ist Wasser.", // http://canoonet.eu/blog/2012/04/02/ein-drittel-der-schueler-istsind/
"Die ältesten und bekanntesten Maßnahmen ist die Einrichtung von Schutzgebieten.",
"Ein Gramm Pfeffer waren früher wertvoll.",
"Isolation und ihre Überwindung ist ein häufiges Thema in der Literatur."
//"Katzen ist schön."
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"All diesen Bereichen ist gemeinsam, dass sie unterfinanziert sind.",
"Nicht entmutigen lassen, nur weil Sie kein Genie sind.",
"Denken Sie daran, dass Sie hier zu Gast sind und sich entsprechend verhalten sollten.",
"Ist es wahr, dass Sie ein guter Mensch sind?",
"Die Katze ist schön.",
"Die eine Katze ist schön.",
"Eine Katze ist schön.",
"Beiden Filmen war kein Erfolg beschieden.",
"In einigen Fällen ist der vermeintliche Beschützer schwach.",
"Was Wasser für die Fische ist.",
"In den letzten Jahrzehnten ist die Zusammenarbeit der Astronomie verbessert worden.",
"Für Oberleitungen bei elektrischen Bahnen ist es dagegen anders.",
"... deren Thema die Liebe zwischen männlichen Charakteren ist.",
"Mehr als das in westlichen Produktionen der Fall ist.",
"Da das ein fast aussichtsloses Unterfangen ist.",
"Was sehr verbreitet bei der Synthese organischer Verbindungen ist.",
"In chemischen Komplexverbindungen ist das Kation wichtig.",
"In chemischen Komplexverbindungen ist das As5+-Kation wichtig.",
"Die selbstständige Behandlung psychischer Störungen ist jedoch ineffektiv.",
"Die selbstständige Behandlung eigener psychischer Störungen ist jedoch ineffektiv.",
"Im Gegensatz zu anderen akademischen Berufen ist es in der Medizin durchaus üblich ...",
"Im Unterschied zu anderen Branchen ist Ärzten anpreisende Werbung verboten.",
"Aus den verfügbaren Quellen ist es ersichtlich.",
"Das Mädchen mit den langen Haaren ist Judy.",
"Der Durchschnitt offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt vieler offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt unendlich vieler offener Mengen ist nicht notwendig offen.",
"Der Ausgangspunkt für die heute gebräuchlichen Alphabete ist ...",
"Nach sieben männlichen Amtsvorgängern ist Merkel ...",
"Für einen japanischen Hamburger ist er günstig.",
"Derzeitiger Bürgermeister ist seit 2008 der ehemalige Minister Müller.",
"Derzeitiger Bürgermeister der Stadt ist seit 2008 der ehemalige Minister Müller.",
"Die Eingabe mehrerer assoziativer Verknüpfungen ist beliebig.",
"Die inhalative Anwendung anderer Adrenalinpräparate zur Akutbehandlung asthmatischer Beschwerden ist somit außerhalb der arzneimittelrechtlichen Zulassung.",
"Die Kategorisierung anhand morphologischer Merkmale ist nicht objektivierbar.",
"Die Kategorisierung mit morphologischen Merkmalen ist nicht objektivierbar.",
"Ute, deren Hauptproblem ihr Mangel an Problemen ist, geht baden.",
"Ute, deren Hauptproblem ihr Mangel an realen Problemen ist, geht baden.",
"In zwei Wochen ist Weihnachten.",
"In nur zwei Wochen ist Weihnachten.",
"Mit chemischen Methoden ist es möglich, das zu erreichen.",
"Für die Stadtteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Für die Stadtteile und selbständigen Ortsteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Die Qualität der Straßen ist unterschiedlich.",
"In deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.",
"Die Führung des Wortes in Unternehmensnamen und Institutionen ist nur mit Genehmigung zulässig.",
"Die Hintereinanderreihung mehrerer Einheitenvorsatznamen oder Einheitenvorsatzzeichen ist nicht zulässig.",
"Eines ihrer drei Autos ist blau und die anderen sind weiß.",
"Eines von ihren drei Autos ist blau und die anderen sind weiß.",
"Bei fünf Filmen war Robert F. Boyle für das Production Design verantwortlich.",
"Insbesondere das Wasserstoffatom als das einfachste aller Atome war dabei wichtig.",
"In den darauf folgenden Wochen war die Partei führungslos",
"Gegen die wegen ihrer Schönheit bewunderte Phryne ist ein Asebie-Prozess überliefert.",
"Dieses für Ärzte und Ärztinnen festgestellte Risikoprofil ist berufsunabhängig.",
"Das ist problematisch, da kDa eine Masseeinheit und keine Gewichtseinheit ist.",
"Nach sachlichen oder militärischen Kriterien war das nicht nötig.",
"Die Pyramide des Friedens und der Eintracht ist ein Bauwerk.",
"Ohne Architektur der Griechen ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur und Kunst der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"In denen jeweils für eine bestimmte Anzahl Elektronen Platz ist.",
"Mit über 1000 Handschriften ist Aristoteles ein Vielschreiber.",
"Mit über neun Handschriften ist Aristoteles ein Vielschreiber.",
"Die Klammerung assoziativer Verknüpfungen ist beliebig.",
"Die Klammerung mehrerer assoziativer Verknüpfungen ist beliebig.",
"Einen Sonderfall bildete jedoch Ägypten, dessen neue Hauptstadt Alexandria eine Gründung Alexanders und der Ort seines Grabes war.",
"Jeder Junge und jedes Mädchen war erfreut.",
"Jedes Mädchen und jeder Junge war erfreut.",
"Jede Frau und jeder Junge war erfreut.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und neurowissenschaftlichen Grundlagen ist die Psychologie interdisziplinär.", // 'neurowissenschaftlichen' not known
"Als Wissenschaft vom Erleben und Verhalten des Menschen einschließlich der biologischen bzw. sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Alle vier Jahre ist dem Volksfest das Landwirtschaftliche Hauptfest angeschlossen.",
"Aller Anfang ist schwer.",
"Alle Dichtung ist zudem Darstellung von Handlungen.",
"Allen drei Varianten ist gemeinsam, dass meistens nicht unter bürgerlichem...",
"Er sagte, dass es neun Uhr war.",
"Auch den Mädchen war es untersagt, eine Schule zu besuchen.",
"Das dazugehörende Modell der Zeichen-Wahrscheinlichkeiten ist unter Entropiekodierung beschrieben.",
"Ein über längere Zeit entladener Akku ist zerstört.",
"Der Fluss mit seinen Oberläufen Río Paraná und Río Uruguay ist der wichtigste Wasserweg.",
"In den alten Mythen und Sagen war die Eiche ein heiliger Baum.",
"In den alten Religionen, Mythen und Sagen war die Eiche ein heiliger Baum.",
"Zehn Jahre ist es her, seit ich mit achtzehn nach Tokio kam.",
"Bei den niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Bei den sehr niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Die älteste und bekannteste Maßnahme ist die Einrichtung von Schutzgebieten.",
"Die größte Dortmunder Grünanlage ist der Friedhof.",
"Die größte Berliner Grünanlage ist der Friedhof.",
"Die größte Bielefelder Grünanlage ist der Friedhof.",
"Die Pariser Linie ist hier mit 2,2558 mm gerechnet.",
"Die Frankfurter Innenstadt ist 7 km entfernt.",
"Die Dortmunder Konzernzentrale ist ein markantes Gebäude an der Bundesstraße 1.",
"Die Düsseldorfer Brückenfamilie war ursprünglich ein Sammelbegriff.",
"Die Düssel ist ein rund 40 Kilometer langer Fluss.",
"Die Berliner Mauer war während der Teilung Deutschlands die Grenze.",
"Für amtliche Dokumente und Formulare ist das anders.",
"Wie viele Kilometer ist ihre Stadt von unserer entfernt?",
"Über laufende Sanierungsmaßnahmen ist bislang nichts bekannt.",
"In den letzten zwei Monate war ich fleißig wie eine Biene.",
"Durch Einsatz größerer Maschinen und bessere Kapazitätsplanung ist die Zahl der Flüge gestiegen.",
"Die hohe Zahl dieser relativ kleinen Verwaltungseinheiten ist immer wieder Gegenstand von Diskussionen.",
"Teil der ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der umfangreichen dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Der zweite Teil dieses Buches ist in England angesiedelt.",
"Eine der am meisten verbreiteten Krankheiten ist die Diagnose",
"Eine der verbreitetsten Krankheiten ist hier.",
"Die Krankheit unserer heutigen Städte und Siedlungen ist folgendes.",
"Die darauffolgenden Jahre war er ...",
"Die letzten zwei Monate war ich fleißig wie eine Biene.",
"Bei sehr guten Beobachtungsbedingungen ist zu erkennen, dass ...",
"Die beste Rache für Undank und schlechte Manieren ist Höflichkeit.",
"Ein Gramm Pfeffer war früher wertvoll.",
"Die größte Stuttgarter Grünanlage ist der Friedhof.",
"Mancher will Meister sein und ist kein Lehrjunge gewesen.",
"Ellen war vom Schock ganz bleich.", // Ellen: auch Plural von Elle
"Nun gut, die Nacht ist sehr lang, oder?",
"Der Morgen ist angebrochen, die lange Nacht ist vorüber.",
"Die stabilste und häufigste Oxidationsstufe ist dabei −1.",
"Man kann nicht eindeutig zuordnen, wer Täter und wer Opfer war.",
"Ich schätze, die Batterie ist leer.",
"Der größte und schönste Tempel eines Menschen ist in ihm selbst.",
"Begehe keine Dummheit zweimal, die Auswahl ist doch groß genug!",
"Seine größte und erfolgreichste Erfindung war die Säule.",
"Egal was du sagst, die Antwort ist Nein.",
"... in der Geschichte des Museums, die Sammlung ist seit 2011 zugänglich.",
"Deren Bestimmung und Funktion ist allerdings nicht so klar.",
"Sie hat eine Tochter, die Pianistin ist.",
"Ja, die Milch ist sehr gut.",
"Der als Befestigung gedachte östliche Teil der Burg ist weitgehend verfallen.",
"Das Kopieren und Einfügen ist sehr nützlich.",
"Der letzte der vier großen Flüsse ist die Kolyma.",
"In christlichen, islamischen und jüdischen Traditionen ist das höchste Ziel der meditativen Praxis.",
"Der Autor der beiden Spielbücher war Markus Heitz selbst.",
"Der Autor der ersten beiden Spielbücher war Markus Heitz selbst.",
"Das Ziel der elf neuen Vorstandmitglieder ist klar definiert.",
"Laut den meisten Quellen ist das Seitenverhältnis der Nationalflagge...",
"Seine Novelle, die eigentlich eine Glosse ist, war toll.",
"Für in Österreich lebende Afrikaner und Afrikanerinnen ist dies nicht üblich.",
"Von ursprünglich drei Almhütten ist noch eine erhalten.",
"Einer seiner bedeutendsten Kämpfe war gegen den späteren Weltmeister.",
"Aufgrund stark schwankender Absatzmärkte war die GEFA-Flug Mitte der 90er Jahre gezwungen, ...",
"Der Abzug der Besatzungssoldaten und deren mittlerweile ansässigen Angehörigen der Besatzungsmächte war vereinbart.",
"Das Bündnis zwischen der Sowjetunion und Kuba war für beide vorteilhaft.",
"Knapp acht Monate ist die Niederlage nun her.",
"Vier Monate ist die Niederlage nun her.",
"Sie liebt Kunst und Kunst war auch kein Problem, denn er würde das Geld zurückkriegen.",
"Bei komplexen und andauernden Störungen ist der Stress-Stoffwechsel des Hundes entgleist."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithIncorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze sind schön.",
"Die Katze waren schön.",
"Der Text sind gut.",
"Das Auto sind schnell.",
//"Herr Müller sind alt." -- Müller has a plural reading
"Herr Schröder sind alt.",
"Julia und Karsten ist alt.",
"Julia, Heike und Karsten ist alt.",
"Herr Karsten Schröder sind alt."
//"Die heute bekannten Bonsai sind häufig im japanischen Stil gestaltet." // plural: Bonsais (laut Duden) - sollte von AgreementRule gefunden werden
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Eine Persönlichkeit sind Sie selbst.",
"Die Katzen sind schön.",
"Frau Meier und Herr Müller sind alt.",
"Frau Julia Meier und Herr Karsten Müller sind alt.",
"Julia und Karsten sind alt.",
"Julia, Heike und Karsten sind alt.",
"Frau und Herr Müller sind alt.",
"Herr und Frau Schröder sind alt.",
"Herr Meier und Frau Schröder sind alt.",
"Die restlichen 86 Prozent sind in der Flasche.",
"Die restlichen sechsundachtzig Prozent sind in der Flasche.",
"Die restlichen 86 oder 87 Prozent sind in der Flasche.",
"Die restlichen 86 % sind in der Flasche.",
"Durch den schnellen Zerfall des Actiniums waren stets nur geringe Mengen verfügbar.",
"Soda und Anilin waren die ersten Produkte des Unternehmens.",
"Bob und Tom sind Brüder.",
"Letztes Jahr sind wir nach London gegangen.",
"Trotz des Regens sind die Kinder in die Schule gegangen.",
"Die Zielgruppe sind Männer.",
"Männer sind die Zielgruppe.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die USA sind ein repräsentativer demokratischer Staat.",
"Wesentliche Eigenschaften der Hülle sind oben beschrieben.",
"Wesentliche Eigenschaften der Hülle sind oben unter Quantenmechanische Atommodelle und Erklärung grundlegender Atomeigenschaften dargestellt.",
"Er und seine Schwester sind eingeladen.",
"Er und seine Schwester sind zur Party eingeladen.",
"Sowohl er als auch seine Schwester sind zur Party eingeladen.",
"Rekonstruktionen oder der Wiederaufbau sind wissenschaftlich sehr umstritten.",
"Form und Materie eines Einzeldings sind aber nicht zwei verschiedene Objekte.",
"Dieses Jahr sind die Birnen groß.",
"Es so umzugestalten, dass sie wie ein Spiel sind.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die Ursache eines Hauses sind so Ziegel und Holz.",
"Vertreter dieses Ansatzes sind unter anderem Roth und Meyer.",
"Sowohl sein Vater als auch seine Mutter sind tot.",
"Einige der Inhaltsstoffe sind schädlich.",
"Diese Woche sind wir schon einen großen Schritt weiter.",
"Diese Woche sind sie hier.",
"Vorsitzende des Vereins waren:",
"Weder Gerechtigkeit noch Freiheit sind möglich, wenn nur das Geld regiert.",
"Ein typisches Beispiel sind Birkenpollenallergene.",
"Eine weitere Variante sind die Miniatur-Wohnlandschaften.",
"Eine Menge englischer Wörter sind aus dem Lateinischen abgeleitet.",
"Völkerrechtlich umstrittenes Territorium sind die Falklandinseln.",
"Einige dieser älteren Synthesen sind wegen geringer Ausbeuten ...",
"Einzelne Atome sind klein.",
"Die Haare dieses Jungens sind schwarz.",
"Die wichtigsten Mechanismen des Aminosäurenabbaus sind:",
"Wasserlösliche Bariumverbindungen sind giftig.",
"Die Schweizer Trinkweise ist dabei die am wenigsten etablierte.",
"Die Anordnung der vier Achsen ist damit identisch.",
"Die Nauheimer Musiktage, die immer wieder ein kultureller Höhepunkt sind.",
"Räumliche und zeitliche Abstände sowie die Trägheit sind vom Bewegungszustand abhängig.",
"Solche Gewerbe sowie der Karosseriebau sind traditionell stark vertreten.",
"Hundert Dollar sind doch gar nichts!",
"Sowohl Tom als auch Maria waren überrascht.",
"Robben, die die hauptsächliche Beute der Eisbären sind.",
"Die Albatrosse sind eine Gruppe von Seevögeln",
"Die Albatrosse sind eine Gruppe von großen Seevögeln",
"Die Albatrosse sind eine Gruppe von großen bis sehr großen Seevögeln",
"Vier Elemente, welche der Urstoff aller Körper sind.",
"Die Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die diplomatischen Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die letzten zehn Jahre seines Lebens war er erblindet.",
"Die letzten zehn Jahre war er erblindet.",
"... so dass Knochenbrüche und Platzwunden die Regel sind.",
"Die Eigentumsverhältnisse an der Gesellschaft sind unverändert geblieben.",
"Gegenstand der Definition sind für ihn die Urbilder.",
"Mindestens zwanzig Häuser sind abgebrannt.",
"Sie hielten geheim, dass sie Geliebte waren.",
"Einige waren verspätet.",
"Kommentare, Korrekturen und Kritik sind verboten.",
"Kommentare, Korrekturen, Kritik sind verboten.",
"Letztere sind wichtig, um die Datensicherheit zu garantieren.",
"Jüngere sind oft davon überzeugt, im Recht zu sein.",
"Verwandte sind selten mehr als Bekannte.",
"Ursache waren die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Ursache waren unter anderem die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Er ahnt nicht, dass sie und sein Sohn ein Paar sind.",
"Die Ursachen der vorliegenden Durchblutungsstörung sind noch unbekannt.",
"Der See und das Marschland sind ein Naturschutzgebiet",
"Details, Dialoge, wie auch die Typologie der Charaktere sind frei erfunden.",
"Die internen Ermittler und auch die Staatsanwaltschaft sind nun am Zug.",
"Sie sind so erfolgreich, weil sie eine Einheit sind.",
"Auch Polizisten zu Fuß sind unterwegs.",
"Julia sagte, dass Vater und Mutter zu Hause sind."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithCorrectSingularAndPluralVerb() throws IOException {
// Manchmal sind beide Varianten korrekt:
// siehe http://www.canoonet.eu/services/OnlineGrammar/Wort/Verb/Numerus-Person/ProblemNum.html
List<String> sentences = Arrays.asList(
"So mancher Mitarbeiter und manche Führungskraft ist im Urlaub.",
"So mancher Mitarbeiter und manche Führungskraft sind im Urlaub.",
"Jeder Schüler und jede Schülerin ist mal schlecht gelaunt.",
"Jeder Schüler und jede Schülerin sind mal schlecht gelaunt.",
"Kaum mehr als vier Prozent der Fläche ist für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Prozent der Fläche sind für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Millionen Euro des Haushalts ist verplant.",
"Kaum mehr als vier Millionen Euro des Haushalts sind verplant.",
"80 Cent ist nicht genug.", // ugs.
"80 Cent sind nicht genug.",
"1,5 Pfund ist nicht genug.", // ugs.
"1,5 Pfund sind nicht genug.",
"Hier ist sowohl Anhalten wie Parken verboten.",
"Hier sind sowohl Anhalten wie Parken verboten."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
private void assertGood(String input) throws IOException {
RuleMatch[] matches = getMatches(input);
if (matches.length != 0) {
fail("Got unexpected match(es) for '" + input + "': " + Arrays.toString(matches), input);
}
}
private void assertBad(String input) throws IOException {
int matchCount = getMatches(input).length;
if (matchCount == 0) {
fail("Did not get the expected match for '" + input + "'", input);
}
}
private void fail(String message, String input) throws IOException {
if (!GermanChunker.isDebug()) {
GermanChunker.setDebug(true);
getMatches(input); // run again with debug mode
}
Assert.fail(message);
}
private RuleMatch[] getMatches(String input) throws IOException {
return rule.match(langTool.getAnalyzedSentence(input));
}
}
| TheDoctorRAB/languagetool | languagetool-language-modules/de/src/test/java/org/languagetool/rules/de/SubjectVerbAgreementRuleTest.java | 6,664 | // Manchmal sind beide Varianten korrekt: | line_comment | nl | /* LanguageTool, a natural language style checker
* Copyright (C) 2015 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.languagetool.*;
import org.languagetool.chunking.GermanChunker;
import org.languagetool.language.German;
import org.languagetool.rules.RuleMatch;
public class SubjectVerbAgreementRuleTest {
private static SubjectVerbAgreementRule rule;
private static JLanguageTool langTool;
@BeforeClass
public static void setUp() {
Language german = Languages.getLanguageForShortCode("de-DE");
rule = new SubjectVerbAgreementRule(TestTools.getMessages("de"), (German) german);
langTool = new JLanguageTool(german);
}
@Test
public void testTemp() throws IOException {
// For debugging, comment in the next three lines:
//GermanChunker.setDebug(true);
//assertGood("...");
//assertBad("...");
// Hier ist (auch: sind) sowohl Anhalten wie Parken verboten.
// TODO - false alarms from Tatoeba and Wikipedia:
// "Die restlichen sechsundachtzig oder siebenundachtzig Prozent sind in der Flasche.",
// "Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.", // OpenNLP doesn't find 'Unternehmensnamen' as a noun
// "Die ältere der beiden Töchter ist hier.",
// "Liebe und Hochzeit sind nicht das Gleiche."
// "Die Typologie oder besser Typographie ist die Klassifikation von Objekten"
// "Im Falle qualitativer, quantitativer und örtlicher Veränderung ist dies ein konkretes Einzelding,"
// "...zu finden, in denen die Päpste selbst Partei waren."
// "Hauptfigur der beiden Bücher ist Golan Trevize."
// "Das größte und bekannteste Unternehmen dieses Genres ist der Cirque du Soleil."
// "In Schweden, Finnland, Dänemark und Österreich ist die Haltung von Wildtieren erlaubt."
// "Die einzige Waffe, die keine Waffe der Gewalt ist: die Wahrheit."
// "Du weißt ja wie töricht Verliebte sind."
// "Freies Assoziieren und Phantasieren ist erlaubt."
// "In den beiden Städten Bremen und Bremerhaven ist jeweils eine Müllverbrennungsanlage in Betrieb."
// "Hauptstadt und größte Stadt des Landes ist Sarajevo."
// "Durch Rutschen, Fallrohre oder Schläuche ist der Beton bis in die Schalung zu leiten."
// "Wegen ihres ganzen Erfolgs war sie unglücklich."
// "Eines der bedeutendsten Museen ist das Museo Nacional de Bellas Artes."
// "Die Nominierung der Filme sowie die Auswahl der Jurymitglieder ist Aufgabe der Festivaldirektion."
// "Ehemalige Fraktionsvorsitzende waren Schmidt, Kohl und Merkel."
// "Die Hälfte der Äpfel sind verfault."
// "... in der Geschichte des Museums, die Sammlung ist seit März 2011 dauerhaft der Öffentlichkeit zugänglich."
// "Ein gutes Aufwärmen und Dehnen ist zwingend notwendig."
// "Eine Stammfunktion oder ein unbestimmtes Integral ist eine mathematische Funktion ..."
// "Wenn die Begeisterung für eine Person, Gruppe oder Sache religiöser Art ist ..."
// "Ein Staat, dessen Oberhaupt nicht ein König oder eine Königin ist."
// "Des Menschen größter Feind und bester Freund ist ein anderer Mensch."
// "Die Nauheimer Musiktage, die zu einer Tradition geworden sind und immer wieder ein kultureller Höhepunkt sind."
// "Ein erheblicher Teil der anderen Transportmaschinen waren schwerbeschädigt." // ??
// "Die herrschende Klasse und die Klassengesellschaft war geboren." // ??
// "Russland ist der größte Staat der Welt und der Vatikan ist der kleinste Staat der Welt.",
// "Eine Rose ist eine Blume und eine Taube ist ein Vogel.",
// "Der beste Beobachter und der tiefste Denker ist immer der mildeste Richter.",
//assertGood("Dumas ist der Familienname folgender Personen."); // Dumas wird als Plural von Duma erkannt
//assertGood("Berlin war Hauptstadt des Vergnügens und der Wintergarten war angesagt."); // wg. 'und'
//assertGood("Elemente eines axiomatischen Systems sind:"); // 'Elemente' ist ambig (SIN, PLU)
//assertGood("Auch wenn Dortmund größte Stadt und ein Zentrum dieses Raums ist."); // unsere 'und'-Regel darf hier nicht matchen
//assertGood("Die Zielgruppe waren Glaubensangehörige im Ausland sowie Reisende."); // Glaubensangehörige hat kein Plural-Reading in Morphy
}
@Test
public void testPrevChunkIsNominative() throws IOException {
assertTrue(rule.prevChunkIsNominative(getTokens("Die Katze ist süß"), 2));
assertTrue(rule.prevChunkIsNominative(getTokens("Das Fell der Katzen ist süß"), 4));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem alten Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Beiden Filmen war kein Erfolg beschieden."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Aber beiden Filmen war kein Erfolg beschieden."), 3));
//assertFalse(rule.prevChunkIsNominative(getTokens("Der Katzen Fell ist süß"), 3));
}
@Test
public void testArrayOutOfBoundsBug() throws IOException {
rule.match(langTool.getAnalyzedSentence("Die nicht Teil des Näherungsmodells sind"));
}
private AnalyzedTokenReadings[] getTokens(String s) throws IOException {
return langTool.getAnalyzedSentence(s).getTokensWithoutWhitespace();
}
@Test
public void testRuleWithIncorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Autos ist schnell.",
"Der Hund und die Katze ist draußen.",
"Ein Hund und eine Katze ist schön.",
"Der Hund und die Katze ist schön.",
"Der große Hund und die Katze ist schön.",
"Der Hund und die graue Katze ist schön.",
"Der große Hund und die graue Katze ist schön.",
"Die Kenntnisse ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der neuen europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der aktuellen deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Drei Katzen ist im Haus.",
"Drei kleine Katzen ist im Haus.",
"Viele Katzen ist schön.",
"Drei Viertel der Erdoberfläche ist Wasser.", // http://canoonet.eu/blog/2012/04/02/ein-drittel-der-schueler-istsind/
"Die ältesten und bekanntesten Maßnahmen ist die Einrichtung von Schutzgebieten.",
"Ein Gramm Pfeffer waren früher wertvoll.",
"Isolation und ihre Überwindung ist ein häufiges Thema in der Literatur."
//"Katzen ist schön."
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"All diesen Bereichen ist gemeinsam, dass sie unterfinanziert sind.",
"Nicht entmutigen lassen, nur weil Sie kein Genie sind.",
"Denken Sie daran, dass Sie hier zu Gast sind und sich entsprechend verhalten sollten.",
"Ist es wahr, dass Sie ein guter Mensch sind?",
"Die Katze ist schön.",
"Die eine Katze ist schön.",
"Eine Katze ist schön.",
"Beiden Filmen war kein Erfolg beschieden.",
"In einigen Fällen ist der vermeintliche Beschützer schwach.",
"Was Wasser für die Fische ist.",
"In den letzten Jahrzehnten ist die Zusammenarbeit der Astronomie verbessert worden.",
"Für Oberleitungen bei elektrischen Bahnen ist es dagegen anders.",
"... deren Thema die Liebe zwischen männlichen Charakteren ist.",
"Mehr als das in westlichen Produktionen der Fall ist.",
"Da das ein fast aussichtsloses Unterfangen ist.",
"Was sehr verbreitet bei der Synthese organischer Verbindungen ist.",
"In chemischen Komplexverbindungen ist das Kation wichtig.",
"In chemischen Komplexverbindungen ist das As5+-Kation wichtig.",
"Die selbstständige Behandlung psychischer Störungen ist jedoch ineffektiv.",
"Die selbstständige Behandlung eigener psychischer Störungen ist jedoch ineffektiv.",
"Im Gegensatz zu anderen akademischen Berufen ist es in der Medizin durchaus üblich ...",
"Im Unterschied zu anderen Branchen ist Ärzten anpreisende Werbung verboten.",
"Aus den verfügbaren Quellen ist es ersichtlich.",
"Das Mädchen mit den langen Haaren ist Judy.",
"Der Durchschnitt offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt vieler offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt unendlich vieler offener Mengen ist nicht notwendig offen.",
"Der Ausgangspunkt für die heute gebräuchlichen Alphabete ist ...",
"Nach sieben männlichen Amtsvorgängern ist Merkel ...",
"Für einen japanischen Hamburger ist er günstig.",
"Derzeitiger Bürgermeister ist seit 2008 der ehemalige Minister Müller.",
"Derzeitiger Bürgermeister der Stadt ist seit 2008 der ehemalige Minister Müller.",
"Die Eingabe mehrerer assoziativer Verknüpfungen ist beliebig.",
"Die inhalative Anwendung anderer Adrenalinpräparate zur Akutbehandlung asthmatischer Beschwerden ist somit außerhalb der arzneimittelrechtlichen Zulassung.",
"Die Kategorisierung anhand morphologischer Merkmale ist nicht objektivierbar.",
"Die Kategorisierung mit morphologischen Merkmalen ist nicht objektivierbar.",
"Ute, deren Hauptproblem ihr Mangel an Problemen ist, geht baden.",
"Ute, deren Hauptproblem ihr Mangel an realen Problemen ist, geht baden.",
"In zwei Wochen ist Weihnachten.",
"In nur zwei Wochen ist Weihnachten.",
"Mit chemischen Methoden ist es möglich, das zu erreichen.",
"Für die Stadtteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Für die Stadtteile und selbständigen Ortsteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Die Qualität der Straßen ist unterschiedlich.",
"In deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.",
"Die Führung des Wortes in Unternehmensnamen und Institutionen ist nur mit Genehmigung zulässig.",
"Die Hintereinanderreihung mehrerer Einheitenvorsatznamen oder Einheitenvorsatzzeichen ist nicht zulässig.",
"Eines ihrer drei Autos ist blau und die anderen sind weiß.",
"Eines von ihren drei Autos ist blau und die anderen sind weiß.",
"Bei fünf Filmen war Robert F. Boyle für das Production Design verantwortlich.",
"Insbesondere das Wasserstoffatom als das einfachste aller Atome war dabei wichtig.",
"In den darauf folgenden Wochen war die Partei führungslos",
"Gegen die wegen ihrer Schönheit bewunderte Phryne ist ein Asebie-Prozess überliefert.",
"Dieses für Ärzte und Ärztinnen festgestellte Risikoprofil ist berufsunabhängig.",
"Das ist problematisch, da kDa eine Masseeinheit und keine Gewichtseinheit ist.",
"Nach sachlichen oder militärischen Kriterien war das nicht nötig.",
"Die Pyramide des Friedens und der Eintracht ist ein Bauwerk.",
"Ohne Architektur der Griechen ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur und Kunst der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"In denen jeweils für eine bestimmte Anzahl Elektronen Platz ist.",
"Mit über 1000 Handschriften ist Aristoteles ein Vielschreiber.",
"Mit über neun Handschriften ist Aristoteles ein Vielschreiber.",
"Die Klammerung assoziativer Verknüpfungen ist beliebig.",
"Die Klammerung mehrerer assoziativer Verknüpfungen ist beliebig.",
"Einen Sonderfall bildete jedoch Ägypten, dessen neue Hauptstadt Alexandria eine Gründung Alexanders und der Ort seines Grabes war.",
"Jeder Junge und jedes Mädchen war erfreut.",
"Jedes Mädchen und jeder Junge war erfreut.",
"Jede Frau und jeder Junge war erfreut.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und neurowissenschaftlichen Grundlagen ist die Psychologie interdisziplinär.", // 'neurowissenschaftlichen' not known
"Als Wissenschaft vom Erleben und Verhalten des Menschen einschließlich der biologischen bzw. sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Alle vier Jahre ist dem Volksfest das Landwirtschaftliche Hauptfest angeschlossen.",
"Aller Anfang ist schwer.",
"Alle Dichtung ist zudem Darstellung von Handlungen.",
"Allen drei Varianten ist gemeinsam, dass meistens nicht unter bürgerlichem...",
"Er sagte, dass es neun Uhr war.",
"Auch den Mädchen war es untersagt, eine Schule zu besuchen.",
"Das dazugehörende Modell der Zeichen-Wahrscheinlichkeiten ist unter Entropiekodierung beschrieben.",
"Ein über längere Zeit entladener Akku ist zerstört.",
"Der Fluss mit seinen Oberläufen Río Paraná und Río Uruguay ist der wichtigste Wasserweg.",
"In den alten Mythen und Sagen war die Eiche ein heiliger Baum.",
"In den alten Religionen, Mythen und Sagen war die Eiche ein heiliger Baum.",
"Zehn Jahre ist es her, seit ich mit achtzehn nach Tokio kam.",
"Bei den niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Bei den sehr niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Die älteste und bekannteste Maßnahme ist die Einrichtung von Schutzgebieten.",
"Die größte Dortmunder Grünanlage ist der Friedhof.",
"Die größte Berliner Grünanlage ist der Friedhof.",
"Die größte Bielefelder Grünanlage ist der Friedhof.",
"Die Pariser Linie ist hier mit 2,2558 mm gerechnet.",
"Die Frankfurter Innenstadt ist 7 km entfernt.",
"Die Dortmunder Konzernzentrale ist ein markantes Gebäude an der Bundesstraße 1.",
"Die Düsseldorfer Brückenfamilie war ursprünglich ein Sammelbegriff.",
"Die Düssel ist ein rund 40 Kilometer langer Fluss.",
"Die Berliner Mauer war während der Teilung Deutschlands die Grenze.",
"Für amtliche Dokumente und Formulare ist das anders.",
"Wie viele Kilometer ist ihre Stadt von unserer entfernt?",
"Über laufende Sanierungsmaßnahmen ist bislang nichts bekannt.",
"In den letzten zwei Monate war ich fleißig wie eine Biene.",
"Durch Einsatz größerer Maschinen und bessere Kapazitätsplanung ist die Zahl der Flüge gestiegen.",
"Die hohe Zahl dieser relativ kleinen Verwaltungseinheiten ist immer wieder Gegenstand von Diskussionen.",
"Teil der ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der umfangreichen dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Der zweite Teil dieses Buches ist in England angesiedelt.",
"Eine der am meisten verbreiteten Krankheiten ist die Diagnose",
"Eine der verbreitetsten Krankheiten ist hier.",
"Die Krankheit unserer heutigen Städte und Siedlungen ist folgendes.",
"Die darauffolgenden Jahre war er ...",
"Die letzten zwei Monate war ich fleißig wie eine Biene.",
"Bei sehr guten Beobachtungsbedingungen ist zu erkennen, dass ...",
"Die beste Rache für Undank und schlechte Manieren ist Höflichkeit.",
"Ein Gramm Pfeffer war früher wertvoll.",
"Die größte Stuttgarter Grünanlage ist der Friedhof.",
"Mancher will Meister sein und ist kein Lehrjunge gewesen.",
"Ellen war vom Schock ganz bleich.", // Ellen: auch Plural von Elle
"Nun gut, die Nacht ist sehr lang, oder?",
"Der Morgen ist angebrochen, die lange Nacht ist vorüber.",
"Die stabilste und häufigste Oxidationsstufe ist dabei −1.",
"Man kann nicht eindeutig zuordnen, wer Täter und wer Opfer war.",
"Ich schätze, die Batterie ist leer.",
"Der größte und schönste Tempel eines Menschen ist in ihm selbst.",
"Begehe keine Dummheit zweimal, die Auswahl ist doch groß genug!",
"Seine größte und erfolgreichste Erfindung war die Säule.",
"Egal was du sagst, die Antwort ist Nein.",
"... in der Geschichte des Museums, die Sammlung ist seit 2011 zugänglich.",
"Deren Bestimmung und Funktion ist allerdings nicht so klar.",
"Sie hat eine Tochter, die Pianistin ist.",
"Ja, die Milch ist sehr gut.",
"Der als Befestigung gedachte östliche Teil der Burg ist weitgehend verfallen.",
"Das Kopieren und Einfügen ist sehr nützlich.",
"Der letzte der vier großen Flüsse ist die Kolyma.",
"In christlichen, islamischen und jüdischen Traditionen ist das höchste Ziel der meditativen Praxis.",
"Der Autor der beiden Spielbücher war Markus Heitz selbst.",
"Der Autor der ersten beiden Spielbücher war Markus Heitz selbst.",
"Das Ziel der elf neuen Vorstandmitglieder ist klar definiert.",
"Laut den meisten Quellen ist das Seitenverhältnis der Nationalflagge...",
"Seine Novelle, die eigentlich eine Glosse ist, war toll.",
"Für in Österreich lebende Afrikaner und Afrikanerinnen ist dies nicht üblich.",
"Von ursprünglich drei Almhütten ist noch eine erhalten.",
"Einer seiner bedeutendsten Kämpfe war gegen den späteren Weltmeister.",
"Aufgrund stark schwankender Absatzmärkte war die GEFA-Flug Mitte der 90er Jahre gezwungen, ...",
"Der Abzug der Besatzungssoldaten und deren mittlerweile ansässigen Angehörigen der Besatzungsmächte war vereinbart.",
"Das Bündnis zwischen der Sowjetunion und Kuba war für beide vorteilhaft.",
"Knapp acht Monate ist die Niederlage nun her.",
"Vier Monate ist die Niederlage nun her.",
"Sie liebt Kunst und Kunst war auch kein Problem, denn er würde das Geld zurückkriegen.",
"Bei komplexen und andauernden Störungen ist der Stress-Stoffwechsel des Hundes entgleist."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithIncorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze sind schön.",
"Die Katze waren schön.",
"Der Text sind gut.",
"Das Auto sind schnell.",
//"Herr Müller sind alt." -- Müller has a plural reading
"Herr Schröder sind alt.",
"Julia und Karsten ist alt.",
"Julia, Heike und Karsten ist alt.",
"Herr Karsten Schröder sind alt."
//"Die heute bekannten Bonsai sind häufig im japanischen Stil gestaltet." // plural: Bonsais (laut Duden) - sollte von AgreementRule gefunden werden
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Eine Persönlichkeit sind Sie selbst.",
"Die Katzen sind schön.",
"Frau Meier und Herr Müller sind alt.",
"Frau Julia Meier und Herr Karsten Müller sind alt.",
"Julia und Karsten sind alt.",
"Julia, Heike und Karsten sind alt.",
"Frau und Herr Müller sind alt.",
"Herr und Frau Schröder sind alt.",
"Herr Meier und Frau Schröder sind alt.",
"Die restlichen 86 Prozent sind in der Flasche.",
"Die restlichen sechsundachtzig Prozent sind in der Flasche.",
"Die restlichen 86 oder 87 Prozent sind in der Flasche.",
"Die restlichen 86 % sind in der Flasche.",
"Durch den schnellen Zerfall des Actiniums waren stets nur geringe Mengen verfügbar.",
"Soda und Anilin waren die ersten Produkte des Unternehmens.",
"Bob und Tom sind Brüder.",
"Letztes Jahr sind wir nach London gegangen.",
"Trotz des Regens sind die Kinder in die Schule gegangen.",
"Die Zielgruppe sind Männer.",
"Männer sind die Zielgruppe.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die USA sind ein repräsentativer demokratischer Staat.",
"Wesentliche Eigenschaften der Hülle sind oben beschrieben.",
"Wesentliche Eigenschaften der Hülle sind oben unter Quantenmechanische Atommodelle und Erklärung grundlegender Atomeigenschaften dargestellt.",
"Er und seine Schwester sind eingeladen.",
"Er und seine Schwester sind zur Party eingeladen.",
"Sowohl er als auch seine Schwester sind zur Party eingeladen.",
"Rekonstruktionen oder der Wiederaufbau sind wissenschaftlich sehr umstritten.",
"Form und Materie eines Einzeldings sind aber nicht zwei verschiedene Objekte.",
"Dieses Jahr sind die Birnen groß.",
"Es so umzugestalten, dass sie wie ein Spiel sind.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die Ursache eines Hauses sind so Ziegel und Holz.",
"Vertreter dieses Ansatzes sind unter anderem Roth und Meyer.",
"Sowohl sein Vater als auch seine Mutter sind tot.",
"Einige der Inhaltsstoffe sind schädlich.",
"Diese Woche sind wir schon einen großen Schritt weiter.",
"Diese Woche sind sie hier.",
"Vorsitzende des Vereins waren:",
"Weder Gerechtigkeit noch Freiheit sind möglich, wenn nur das Geld regiert.",
"Ein typisches Beispiel sind Birkenpollenallergene.",
"Eine weitere Variante sind die Miniatur-Wohnlandschaften.",
"Eine Menge englischer Wörter sind aus dem Lateinischen abgeleitet.",
"Völkerrechtlich umstrittenes Territorium sind die Falklandinseln.",
"Einige dieser älteren Synthesen sind wegen geringer Ausbeuten ...",
"Einzelne Atome sind klein.",
"Die Haare dieses Jungens sind schwarz.",
"Die wichtigsten Mechanismen des Aminosäurenabbaus sind:",
"Wasserlösliche Bariumverbindungen sind giftig.",
"Die Schweizer Trinkweise ist dabei die am wenigsten etablierte.",
"Die Anordnung der vier Achsen ist damit identisch.",
"Die Nauheimer Musiktage, die immer wieder ein kultureller Höhepunkt sind.",
"Räumliche und zeitliche Abstände sowie die Trägheit sind vom Bewegungszustand abhängig.",
"Solche Gewerbe sowie der Karosseriebau sind traditionell stark vertreten.",
"Hundert Dollar sind doch gar nichts!",
"Sowohl Tom als auch Maria waren überrascht.",
"Robben, die die hauptsächliche Beute der Eisbären sind.",
"Die Albatrosse sind eine Gruppe von Seevögeln",
"Die Albatrosse sind eine Gruppe von großen Seevögeln",
"Die Albatrosse sind eine Gruppe von großen bis sehr großen Seevögeln",
"Vier Elemente, welche der Urstoff aller Körper sind.",
"Die Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die diplomatischen Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die letzten zehn Jahre seines Lebens war er erblindet.",
"Die letzten zehn Jahre war er erblindet.",
"... so dass Knochenbrüche und Platzwunden die Regel sind.",
"Die Eigentumsverhältnisse an der Gesellschaft sind unverändert geblieben.",
"Gegenstand der Definition sind für ihn die Urbilder.",
"Mindestens zwanzig Häuser sind abgebrannt.",
"Sie hielten geheim, dass sie Geliebte waren.",
"Einige waren verspätet.",
"Kommentare, Korrekturen und Kritik sind verboten.",
"Kommentare, Korrekturen, Kritik sind verboten.",
"Letztere sind wichtig, um die Datensicherheit zu garantieren.",
"Jüngere sind oft davon überzeugt, im Recht zu sein.",
"Verwandte sind selten mehr als Bekannte.",
"Ursache waren die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Ursache waren unter anderem die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Er ahnt nicht, dass sie und sein Sohn ein Paar sind.",
"Die Ursachen der vorliegenden Durchblutungsstörung sind noch unbekannt.",
"Der See und das Marschland sind ein Naturschutzgebiet",
"Details, Dialoge, wie auch die Typologie der Charaktere sind frei erfunden.",
"Die internen Ermittler und auch die Staatsanwaltschaft sind nun am Zug.",
"Sie sind so erfolgreich, weil sie eine Einheit sind.",
"Auch Polizisten zu Fuß sind unterwegs.",
"Julia sagte, dass Vater und Mutter zu Hause sind."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithCorrectSingularAndPluralVerb() throws IOException {
// Manchmal sind<SUF>
// siehe http://www.canoonet.eu/services/OnlineGrammar/Wort/Verb/Numerus-Person/ProblemNum.html
List<String> sentences = Arrays.asList(
"So mancher Mitarbeiter und manche Führungskraft ist im Urlaub.",
"So mancher Mitarbeiter und manche Führungskraft sind im Urlaub.",
"Jeder Schüler und jede Schülerin ist mal schlecht gelaunt.",
"Jeder Schüler und jede Schülerin sind mal schlecht gelaunt.",
"Kaum mehr als vier Prozent der Fläche ist für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Prozent der Fläche sind für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Millionen Euro des Haushalts ist verplant.",
"Kaum mehr als vier Millionen Euro des Haushalts sind verplant.",
"80 Cent ist nicht genug.", // ugs.
"80 Cent sind nicht genug.",
"1,5 Pfund ist nicht genug.", // ugs.
"1,5 Pfund sind nicht genug.",
"Hier ist sowohl Anhalten wie Parken verboten.",
"Hier sind sowohl Anhalten wie Parken verboten."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
private void assertGood(String input) throws IOException {
RuleMatch[] matches = getMatches(input);
if (matches.length != 0) {
fail("Got unexpected match(es) for '" + input + "': " + Arrays.toString(matches), input);
}
}
private void assertBad(String input) throws IOException {
int matchCount = getMatches(input).length;
if (matchCount == 0) {
fail("Did not get the expected match for '" + input + "'", input);
}
}
private void fail(String message, String input) throws IOException {
if (!GermanChunker.isDebug()) {
GermanChunker.setDebug(true);
getMatches(input); // run again with debug mode
}
Assert.fail(message);
}
private RuleMatch[] getMatches(String input) throws IOException {
return rule.match(langTool.getAnalyzedSentence(input));
}
}
|
132766_1 | /*
* 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 controllers;
import domein.Catalogus;
import domein.Doelgroep;
import domein.Firma;
import domein.Leergebied;
import domein.Product;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
/**
*
* @author Maarten
*/
public class ProductBeherenControllerTest
{
@Mock
private Catalogus catalogus;
private Doelgroep doelgroep1;
private Doelgroep doelgroep2;
private Doelgroep doelgroep3;
private Doelgroep doelgroep4;
private Leergebied leergebied1;
private Leergebied leergebied2;
private Firma firma1;
private Product product;
private List<Doelgroep> doelgroepenTest;
private List<Leergebied> leergebiedenTest;
private List<Firma> firmasTest;
private ProductBeherenController controller;
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
doelgroep1 = new Doelgroep("Kleuter onderwijs");
doelgroep2 = new Doelgroep("Lager onderwijs");
doelgroep3 = new Doelgroep("Secundair onderwijs");
doelgroep4 = new Doelgroep("Afstands Onderwijs");
leergebied1 = new Leergebied("mens");
leergebied2 = new Leergebied("biologie");
firma1 = new Firma("firma1", "website", "contactPersoon", "emailContactPersoon");
controller = new ProductToevoegenController(catalogus);
doelgroepenTest = new ArrayList<>();
leergebiedenTest = new ArrayList<>();
firmasTest = new ArrayList<>();
doelgroepenTest.add(doelgroep1);
doelgroepenTest.add(doelgroep2);
doelgroepenTest.add(doelgroep3);
leergebiedenTest.add(leergebied1);
firmasTest.add(firma1);
}
@Test
public void getKandidaatDoelgroepenGeeftDeKandidaatDoelgroepenTerug()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> lijst = controller.getKandidaatDoelgroepen();
Assert.assertEquals(3, lijst.size());
Assert.assertNotNull(lijst);
}
@Test
public void getGekozenDoelgroepenGeeftDeGekozenDoelgroepenTerug()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstGekozenDoelgroepen.size());
Assert.assertEquals(doelgroep1, lijstGekozenDoelgroepen.get(0));
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void getAlleFirmasGeeftAlleFirmasTerug()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
ObservableList<Firma> lijstFirmas = controller.getAlleFirmas();
Assert.assertEquals(1, lijstFirmas.size());
Assert.assertEquals(firma1, lijstFirmas.get(0));
Assert.assertNotNull(lijstFirmas);
}
@Test
public void addKandidaatLeergebiedVoegtLeergebiedToeAanKandidaatLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addKandidaatLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getKandidaatLeergebieden();
Assert.assertEquals(2, lijstLeergebieden.size());
Assert.assertNotNull(lijstLeergebieden);
}
@Test
public void removeGekozenLeergebiedenVerwijdertDeMeegegevenLeergebiedenUitGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> hulp = FXCollections.observableArrayList();
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
hulp.add(leergebied1);
controller.removeGekozenLeergebieden(hulp);
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstGekozenLeergebieden.size());
Assert.assertNotNull(lijstGekozenLeergebieden);
Assert.assertEquals(leergebied2, lijstGekozenLeergebieden.get(0));
}
@Test
public void addGekozenDoelgroepVoegtDoelgroepToeAanGekozenDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstDoelgroepen.size());
}
@Test
public void removeKandidaatDoelgroepVerwijdertDoelgroepUitKandidaatDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
System.out.println(lijstDoelgroepen);
Assert.assertEquals(2, lijstDoelgroepen.size());
}
@Test
public void addKandidaatDoelgroepVoegtDoelgroepToeAanKandidaatDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addKandidaatDoelgroep(doelgroep4);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
Assert.assertEquals(4, lijstDoelgroepen.size());
}
@Test
public void setGekozenFirmaVultDeGekozenFirmaIn()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
controller.setGekozenFirma(firma1);
Assert.assertEquals(firma1, controller.getGekozenFirma());
}
@Test
public void getGekozenFirmaGeeftDeGekozenFirmaTerug()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
controller.setGekozenFirma(firma1);
Firma f = controller.getGekozenFirma();
Assert.assertEquals(firma1, f);
}
@Test
public void removeGekozenDoelgroepenMaaktDeGekozenDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> hulp = FXCollections.observableArrayList();
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep4);
controller.removeGekozenDoelgroepen();
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(0, lijstGekozenDoelgroepen.size());
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void geenDoelgroepKandidatenGeeftTrueTerugIndienDoelgroepKandidatenLeegIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleKandidaatDoelgroepen();
Assert.assertTrue(controller.geenDoelgroepKandidaten());
}
@Test
public void geenDoelgroepKandidatenGeeftFalseTerugIndienDoelgroepKandidatenGevuldIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Assert.assertFalse(controller.geenDoelgroepKandidaten());
}
@Test
public void geenGekozenDoelgroepGeeftFalseTerugIndienGekozenDoelgroepenGevuldIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
Assert.assertFalse(controller.geenGekozenDoelgroep());
}
@Test
public void geenGekozenDoelgroepGeeftTrueTerugIndienGekozenDoelgroepenLeegIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleGekozenDoelgroepen();
Assert.assertTrue(controller.geenGekozenDoelgroep());
}
@Test
public void getKandidaatLeergebiedenGeeftDeKandidaatLeergebiedenTerug()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> lijst = controller.getKandidaatLeergebieden();
System.out.println(lijst);
Assert.assertEquals(1, lijst.size());
Assert.assertNotNull(lijst);
}
@Test
public void getGekozenLeergebiedenGeeftDeGekozenLeergebiedenTerug()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstGekozenLeergebieden.size());
Assert.assertEquals(leergebied2, lijstGekozenLeergebieden.get(0));
Assert.assertNotNull(lijstGekozenLeergebieden);
}
@Test
public void addGekozenLeergebiedVoegtLeergebiedToeAanGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstLeergebieden.size());
}
@Test
public void removeKandidaatLeergebiedVerwijdertLeergebiedUitKandidaatLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatLeergebied(leergebied1);
ObservableList<Leergebied> lijstLeergebieden = controller.getKandidaatLeergebieden();
Assert.assertEquals(0, lijstLeergebieden.size());
}
@Test
public void geenLeergebiedKandidatenGeeftTrueTerugIndienLeergebiedKandidatenLeegIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatLeergebied(leergebied1);
Assert.assertTrue(controller.geenLeergebiedKandidaten());
}
@Test
public void geenLeergebiedKandidatenGeeftFalseTerugIndienLeergebiedKandidatenGevuldIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Assert.assertFalse(controller.geenLeergebiedKandidaten());
}
@Test
public void geenGekozenLeergebiedGeeftFalseTerugIndienGekozenLeergebiedenGevuldIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
Assert.assertFalse(controller.geenGekozenLeergebied());
}
@Test
public void geenGekozenLeergebiedGeeftTrueTerugIndienGekozenLeergebiedenLeegIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleGekozenLeergebieden();
Assert.assertTrue(controller.geenGekozenLeergebied());
}
@Test
public void removeGekozenLeergebiedVerwijdertLeergebiedUitGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
controller.removeGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstLeergebieden.size());
Assert.assertEquals(leergebied1, lijstLeergebieden.get(0));
}
@Test
public void removeAlleGekozenLeergebiedenMaaktDeGekozenLeergebiedenLeeg()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> hulp = FXCollections.observableArrayList();
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
controller.removeAlleGekozenLeergebieden();
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(0, lijstGekozenLeergebieden.size());
Assert.assertNotNull(lijstGekozenLeergebieden);
}
@Test
public void removeAlleGekozenDoelgroepenMaaktDeGekozenDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> hulp = FXCollections.observableArrayList();
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep2);
controller.removeAlleGekozenDoelgroepen();
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(0, lijstGekozenDoelgroepen.size());
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void removeAlleKandidaatDoelgroepenMaaktDeKandidaatDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleKandidaatDoelgroepen();
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
Assert.assertEquals(0, lijstDoelgroepen.size());
Assert.assertNotNull(lijstDoelgroepen);
}
@Test
public void removeGekozenDoelgroepVerwijdertDoelgroepUitGekozenDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep4);
controller.removeGekozenDoelgroep(doelgroep4);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstDoelgroepen.size());
Assert.assertEquals(doelgroep1, lijstDoelgroepen.get(0));
}
@Test
public void addFirmaVoegtFirmaToeAanLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
Firma firma2 = new Firma("firma2", "website", "contactPersoon", "emailContactPersoon");
controller.addFirma(firma2);
ObservableList<Firma> lijstFirmas = controller.getAlleFirmas();
Assert.assertEquals(2, lijstFirmas.size());
Assert.assertEquals(firma2, lijstFirmas.get(1));
}
@Test
public void bevatFirmaGeeftTrueTerugIndienDeFirmaAanwezigIsInDeLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
System.out.println(controller.getAlleFirmas());
Firma f = new Firma("firma1", null, null, null);
Assert.assertTrue(controller.bevatFirma(f));
}
@Test
public void bevatFirmaGeeftFalseTerugIndienDeFirmaNietAanwezigIsInDeLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
Firma f = new Firma("firma2", null, null, null);
Assert.assertFalse(controller.bevatFirma(f));
}
@Test
public void bevatLeergebiedGeeftTrueTerugIndienLeergebiedAanwezigIsInDeLijstMetLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Leergebied l = new Leergebied("mens");
Assert.assertTrue(controller.bevatLeergebied(l));
}
@Test
public void bevatLeergebiedGeeftFalseTerugIndienLeergebiedNietAanwezigIsInDeLijstMetLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Leergebied l = new Leergebied("leergebiedNaam");
Assert.assertFalse(controller.bevatLeergebied(l));
}
@Test
public void bevatDoelgroepGeeftTrueTerugIndienDoelgroepAanwezigIsInDeLijstMetDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Doelgroep d = new Doelgroep("Lager onderwijs");
Assert.assertTrue(controller.bevatDoelgroep(d));
}
@Test
public void bevatDoelgroepGeeftFalseTerugIndienDoelgroepNietAanwezigIsInDeLijstMetDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Doelgroep d = new Doelgroep("Volwassenen onderwijs");
Assert.assertFalse(controller.bevatDoelgroep(d));
}
//MOCKITO
public void mockitoInOrdeZettenDoelGroepen()
{
Mockito.when(catalogus.getDoelgroepenLijst()).thenReturn(doelgroepenTest);
}
public void mockitoInOrdeZettenLeergebieden()
{
Mockito.when(catalogus.getLeergebiedenLijst()).thenReturn(leergebiedenTest);
}
public void mockitoInOrdeZettenFirmas()
{
Mockito.when(catalogus.getFirmaLijst()).thenReturn(firmasTest);
}
}
| poldepuysseleyr/catalogus-java | test/controllers/ProductBeherenControllerTest.java | 4,848 | /**
*
* @author Maarten
*/ | 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 controllers;
import domein.Catalogus;
import domein.Doelgroep;
import domein.Firma;
import domein.Leergebied;
import domein.Product;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
/**
*
* @author Maarten
<SUF>*/
public class ProductBeherenControllerTest
{
@Mock
private Catalogus catalogus;
private Doelgroep doelgroep1;
private Doelgroep doelgroep2;
private Doelgroep doelgroep3;
private Doelgroep doelgroep4;
private Leergebied leergebied1;
private Leergebied leergebied2;
private Firma firma1;
private Product product;
private List<Doelgroep> doelgroepenTest;
private List<Leergebied> leergebiedenTest;
private List<Firma> firmasTest;
private ProductBeherenController controller;
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
doelgroep1 = new Doelgroep("Kleuter onderwijs");
doelgroep2 = new Doelgroep("Lager onderwijs");
doelgroep3 = new Doelgroep("Secundair onderwijs");
doelgroep4 = new Doelgroep("Afstands Onderwijs");
leergebied1 = new Leergebied("mens");
leergebied2 = new Leergebied("biologie");
firma1 = new Firma("firma1", "website", "contactPersoon", "emailContactPersoon");
controller = new ProductToevoegenController(catalogus);
doelgroepenTest = new ArrayList<>();
leergebiedenTest = new ArrayList<>();
firmasTest = new ArrayList<>();
doelgroepenTest.add(doelgroep1);
doelgroepenTest.add(doelgroep2);
doelgroepenTest.add(doelgroep3);
leergebiedenTest.add(leergebied1);
firmasTest.add(firma1);
}
@Test
public void getKandidaatDoelgroepenGeeftDeKandidaatDoelgroepenTerug()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> lijst = controller.getKandidaatDoelgroepen();
Assert.assertEquals(3, lijst.size());
Assert.assertNotNull(lijst);
}
@Test
public void getGekozenDoelgroepenGeeftDeGekozenDoelgroepenTerug()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstGekozenDoelgroepen.size());
Assert.assertEquals(doelgroep1, lijstGekozenDoelgroepen.get(0));
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void getAlleFirmasGeeftAlleFirmasTerug()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
ObservableList<Firma> lijstFirmas = controller.getAlleFirmas();
Assert.assertEquals(1, lijstFirmas.size());
Assert.assertEquals(firma1, lijstFirmas.get(0));
Assert.assertNotNull(lijstFirmas);
}
@Test
public void addKandidaatLeergebiedVoegtLeergebiedToeAanKandidaatLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addKandidaatLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getKandidaatLeergebieden();
Assert.assertEquals(2, lijstLeergebieden.size());
Assert.assertNotNull(lijstLeergebieden);
}
@Test
public void removeGekozenLeergebiedenVerwijdertDeMeegegevenLeergebiedenUitGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> hulp = FXCollections.observableArrayList();
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
hulp.add(leergebied1);
controller.removeGekozenLeergebieden(hulp);
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstGekozenLeergebieden.size());
Assert.assertNotNull(lijstGekozenLeergebieden);
Assert.assertEquals(leergebied2, lijstGekozenLeergebieden.get(0));
}
@Test
public void addGekozenDoelgroepVoegtDoelgroepToeAanGekozenDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstDoelgroepen.size());
}
@Test
public void removeKandidaatDoelgroepVerwijdertDoelgroepUitKandidaatDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatDoelgroep(doelgroep1);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
System.out.println(lijstDoelgroepen);
Assert.assertEquals(2, lijstDoelgroepen.size());
}
@Test
public void addKandidaatDoelgroepVoegtDoelgroepToeAanKandidaatDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addKandidaatDoelgroep(doelgroep4);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
Assert.assertEquals(4, lijstDoelgroepen.size());
}
@Test
public void setGekozenFirmaVultDeGekozenFirmaIn()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
controller.setGekozenFirma(firma1);
Assert.assertEquals(firma1, controller.getGekozenFirma());
}
@Test
public void getGekozenFirmaGeeftDeGekozenFirmaTerug()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
controller.setGekozenFirma(firma1);
Firma f = controller.getGekozenFirma();
Assert.assertEquals(firma1, f);
}
@Test
public void removeGekozenDoelgroepenMaaktDeGekozenDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> hulp = FXCollections.observableArrayList();
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep4);
controller.removeGekozenDoelgroepen();
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(0, lijstGekozenDoelgroepen.size());
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void geenDoelgroepKandidatenGeeftTrueTerugIndienDoelgroepKandidatenLeegIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleKandidaatDoelgroepen();
Assert.assertTrue(controller.geenDoelgroepKandidaten());
}
@Test
public void geenDoelgroepKandidatenGeeftFalseTerugIndienDoelgroepKandidatenGevuldIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Assert.assertFalse(controller.geenDoelgroepKandidaten());
}
@Test
public void geenGekozenDoelgroepGeeftFalseTerugIndienGekozenDoelgroepenGevuldIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
Assert.assertFalse(controller.geenGekozenDoelgroep());
}
@Test
public void geenGekozenDoelgroepGeeftTrueTerugIndienGekozenDoelgroepenLeegIs()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleGekozenDoelgroepen();
Assert.assertTrue(controller.geenGekozenDoelgroep());
}
@Test
public void getKandidaatLeergebiedenGeeftDeKandidaatLeergebiedenTerug()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> lijst = controller.getKandidaatLeergebieden();
System.out.println(lijst);
Assert.assertEquals(1, lijst.size());
Assert.assertNotNull(lijst);
}
@Test
public void getGekozenLeergebiedenGeeftDeGekozenLeergebiedenTerug()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstGekozenLeergebieden.size());
Assert.assertEquals(leergebied2, lijstGekozenLeergebieden.get(0));
Assert.assertNotNull(lijstGekozenLeergebieden);
}
@Test
public void addGekozenLeergebiedVoegtLeergebiedToeAanGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstLeergebieden.size());
}
@Test
public void removeKandidaatLeergebiedVerwijdertLeergebiedUitKandidaatLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatLeergebied(leergebied1);
ObservableList<Leergebied> lijstLeergebieden = controller.getKandidaatLeergebieden();
Assert.assertEquals(0, lijstLeergebieden.size());
}
@Test
public void geenLeergebiedKandidatenGeeftTrueTerugIndienLeergebiedKandidatenLeegIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeKandidaatLeergebied(leergebied1);
Assert.assertTrue(controller.geenLeergebiedKandidaten());
}
@Test
public void geenLeergebiedKandidatenGeeftFalseTerugIndienLeergebiedKandidatenGevuldIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Assert.assertFalse(controller.geenLeergebiedKandidaten());
}
@Test
public void geenGekozenLeergebiedGeeftFalseTerugIndienGekozenLeergebiedenGevuldIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied2);
Assert.assertFalse(controller.geenGekozenLeergebied());
}
@Test
public void geenGekozenLeergebiedGeeftTrueTerugIndienGekozenLeergebiedenLeegIs()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleGekozenLeergebieden();
Assert.assertTrue(controller.geenGekozenLeergebied());
}
@Test
public void removeGekozenLeergebiedVerwijdertLeergebiedUitGekozenLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
controller.removeGekozenLeergebied(leergebied2);
ObservableList<Leergebied> lijstLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(1, lijstLeergebieden.size());
Assert.assertEquals(leergebied1, lijstLeergebieden.get(0));
}
@Test
public void removeAlleGekozenLeergebiedenMaaktDeGekozenLeergebiedenLeeg()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
ObservableList<Leergebied> hulp = FXCollections.observableArrayList();
controller.addGekozenLeergebied(leergebied1);
controller.addGekozenLeergebied(leergebied2);
controller.removeAlleGekozenLeergebieden();
ObservableList<Leergebied> lijstGekozenLeergebieden = controller.getGekozenLeergebieden();
Assert.assertEquals(0, lijstGekozenLeergebieden.size());
Assert.assertNotNull(lijstGekozenLeergebieden);
}
@Test
public void removeAlleGekozenDoelgroepenMaaktDeGekozenDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
ObservableList<Doelgroep> hulp = FXCollections.observableArrayList();
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep2);
controller.removeAlleGekozenDoelgroepen();
ObservableList<Doelgroep> lijstGekozenDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(0, lijstGekozenDoelgroepen.size());
Assert.assertNotNull(lijstGekozenDoelgroepen);
}
@Test
public void removeAlleKandidaatDoelgroepenMaaktDeKandidaatDoelgroepenLeeg()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.removeAlleKandidaatDoelgroepen();
ObservableList<Doelgroep> lijstDoelgroepen = controller.getKandidaatDoelgroepen();
Assert.assertEquals(0, lijstDoelgroepen.size());
Assert.assertNotNull(lijstDoelgroepen);
}
@Test
public void removeGekozenDoelgroepVerwijdertDoelgroepUitGekozenDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
controller.addGekozenDoelgroep(doelgroep1);
controller.addGekozenDoelgroep(doelgroep4);
controller.removeGekozenDoelgroep(doelgroep4);
ObservableList<Doelgroep> lijstDoelgroepen = controller.getGekozenDoelgroepen();
Assert.assertEquals(1, lijstDoelgroepen.size());
Assert.assertEquals(doelgroep1, lijstDoelgroepen.get(0));
}
@Test
public void addFirmaVoegtFirmaToeAanLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
Firma firma2 = new Firma("firma2", "website", "contactPersoon", "emailContactPersoon");
controller.addFirma(firma2);
ObservableList<Firma> lijstFirmas = controller.getAlleFirmas();
Assert.assertEquals(2, lijstFirmas.size());
Assert.assertEquals(firma2, lijstFirmas.get(1));
}
@Test
public void bevatFirmaGeeftTrueTerugIndienDeFirmaAanwezigIsInDeLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
System.out.println(controller.getAlleFirmas());
Firma f = new Firma("firma1", null, null, null);
Assert.assertTrue(controller.bevatFirma(f));
}
@Test
public void bevatFirmaGeeftFalseTerugIndienDeFirmaNietAanwezigIsInDeLijstMetFirmas()
{
mockitoInOrdeZettenFirmas();
controller = new ProductToevoegenController(catalogus);
Firma f = new Firma("firma2", null, null, null);
Assert.assertFalse(controller.bevatFirma(f));
}
@Test
public void bevatLeergebiedGeeftTrueTerugIndienLeergebiedAanwezigIsInDeLijstMetLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Leergebied l = new Leergebied("mens");
Assert.assertTrue(controller.bevatLeergebied(l));
}
@Test
public void bevatLeergebiedGeeftFalseTerugIndienLeergebiedNietAanwezigIsInDeLijstMetLeergebieden()
{
mockitoInOrdeZettenLeergebieden();
controller = new ProductToevoegenController(catalogus);
Leergebied l = new Leergebied("leergebiedNaam");
Assert.assertFalse(controller.bevatLeergebied(l));
}
@Test
public void bevatDoelgroepGeeftTrueTerugIndienDoelgroepAanwezigIsInDeLijstMetDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Doelgroep d = new Doelgroep("Lager onderwijs");
Assert.assertTrue(controller.bevatDoelgroep(d));
}
@Test
public void bevatDoelgroepGeeftFalseTerugIndienDoelgroepNietAanwezigIsInDeLijstMetDoelgroepen()
{
mockitoInOrdeZettenDoelGroepen();
controller = new ProductToevoegenController(catalogus);
Doelgroep d = new Doelgroep("Volwassenen onderwijs");
Assert.assertFalse(controller.bevatDoelgroep(d));
}
//MOCKITO
public void mockitoInOrdeZettenDoelGroepen()
{
Mockito.when(catalogus.getDoelgroepenLijst()).thenReturn(doelgroepenTest);
}
public void mockitoInOrdeZettenLeergebieden()
{
Mockito.when(catalogus.getLeergebiedenLijst()).thenReturn(leergebiedenTest);
}
public void mockitoInOrdeZettenFirmas()
{
Mockito.when(catalogus.getFirmaLijst()).thenReturn(firmasTest);
}
}
|
18424_8 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 1,963 | //haalt breedte scherm op | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte<SUF>
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
|
182335_52 | /*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
/* J2ObjC removed
import jdk.internal.vm.annotation.IntrinsicCandidate;
import libcore.util.HexEncoding;
*/
// Android-removed: CDS is not used on Android.
// import jdk.internal.misc.CDS;
// BEGIN Android-removed: dynamic constants not supported on Android.
/*
import java.lang.constant.Constable;
import java.lang.constant.DynamicConstantDesc;
import java.util.Optional;
import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
import static java.lang.constant.ConstantDescs.CD_byte;
import static java.lang.constant.ConstantDescs.CD_int;
import static java.lang.constant.ConstantDescs.DEFAULT_NAME;
*/
// END Android-removed: dynamic constants not supported on Android.
/**
*
* The {@code Byte} class wraps a value of primitive type {@code byte}
* in an object. An object of type {@code Byte} contains a single
* field whose type is {@code byte}.
*
* <p>In addition, this class provides several methods for converting
* a {@code byte} to a {@code String} and a {@code String} to a {@code
* byte}, as well as other constants and methods useful when dealing
* with a {@code byte}.
*
* <!-- Android-removed: paragraph on ValueBased
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; programmers should treat instances that are
* {@linkplain #equals(Object) equal} as interchangeable and should not
* use instances for synchronization, or unpredictable behavior may
* occur. For example, in a future release, synchronization may fail.
* -->
*
* @author Nakul Saraiya
* @author Joseph D. Darcy
* @see java.lang.Number
* @since 1.1
*/
// Android-removed: ValueBased
// @jdk.internal.ValueBased
public final class Byte extends Number implements Comparable<Byte>
// Android-removed: no Constable support.
// , Constable
{
/**
* A constant holding the minimum value a {@code byte} can
* have, -2<sup>7</sup>.
*/
public static final byte MIN_VALUE = -128;
/**
* A constant holding the maximum value a {@code byte} can
* have, 2<sup>7</sup>-1.
*/
public static final byte MAX_VALUE = 127;
/**
* The {@code Class} instance representing the primitive type
* {@code byte}.
*/
@SuppressWarnings("unchecked")
public static final Class<Byte> TYPE = (Class<Byte>) byte[].class.getComponentType();
/**
* Returns a new {@code String} object representing the
* specified {@code byte}. The radix is assumed to be 10.
*
* @param b the {@code byte} to be converted
* @return the string representation of the specified {@code byte}
* @see java.lang.Integer#toString(int)
*/
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
// BEGIN Android-removed: dynamic constants not supported on Android.
/**
* Returns an {@link Optional} containing the nominal descriptor for this
* instance.
*
* @return an {@link Optional} describing the {@linkplain Byte} instance
* @since 15
*
@Override
public Optional<DynamicConstantDesc<Byte>> describeConstable() {
return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_byte, intValue()));
}
*/
// END Android-removed: dynamic constants not supported on Android.
private static class ByteCache {
private ByteCache() {}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
fillValues(cache);
}
private static native void fillValues(Byte[] values) /*-[
Class self = [JavaLangByte class];
size_t objSize = class_getInstanceSize(self);
uintptr_t ptr = (uintptr_t)calloc(objSize, 256);
id *buf = values->buffer_;
for (jint i = -128; i < 128; i++) {
id obj = objc_constructInstance(self, (void *)ptr);
JavaLangByte_initWithByte_(obj, (jbyte)i);
*(buf++) = obj;
ptr += objSize;
}
]-*/;
}
/**
* Returns a {@code Byte} instance representing the specified
* {@code byte} value.
* If a new {@code Byte} instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Byte(byte)}, as this method is likely to yield
* significantly better space and time performance since
* all byte values are cached.
*
* @param b a byte value.
* @return a {@code Byte} instance representing {@code b}.
* @since 1.5
*/
/* J2Objc removed
@IntrinsicCandidate
*/
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
/**
* Parses the string argument as a signed {@code byte} in the
* radix specified by the second argument. The characters in the
* string must all be digits, of the specified radix (as
* determined by whether {@link java.lang.Character#digit(char,
* int)} returns a nonnegative value) except that the first
* character may be an ASCII minus sign {@code '-'}
* ({@code '\u005Cu002D'}) to indicate a negative value or an
* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
* indicate a positive value. The resulting {@code byte} value is
* returned.
*
* <p>An exception of type {@code NumberFormatException} is
* thrown if any of the following situations occurs:
* <ul>
* <li> The first argument is {@code null} or is a string of
* length zero.
*
* <li> The radix is either smaller than {@link
* java.lang.Character#MIN_RADIX} or larger than {@link
* java.lang.Character#MAX_RADIX}.
*
* <li> Any character of the string is not a digit of the
* specified radix, except that the first character may be a minus
* sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
* {@code '+'} ({@code '\u005Cu002B'}) provided that the
* string is longer than length 1.
*
* <li> The value represented by the string is not a value of type
* {@code byte}.
* </ul>
*
* @param s the {@code String} containing the
* {@code byte}
* representation to be parsed
* @param radix the radix to be used while parsing {@code s}
* @return the {@code byte} value represented by the string
* argument in the specified radix
* @throws NumberFormatException If the string does
* not contain a parsable {@code byte}.
*/
public static byte parseByte(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (byte)i;
}
/**
* Parses the string argument as a signed decimal {@code
* byte}. The characters in the string must all be decimal digits,
* except that the first character may be an ASCII minus sign
* {@code '-'} ({@code '\u005Cu002D'}) to indicate a negative
* value or an ASCII plus sign {@code '+'}
* ({@code '\u005Cu002B'}) to indicate a positive value. The
* resulting {@code byte} value is returned, exactly as if the
* argument and the radix 10 were given as arguments to the {@link
* #parseByte(java.lang.String, int)} method.
*
* @param s a {@code String} containing the
* {@code byte} representation to be parsed
* @return the {@code byte} value represented by the
* argument in decimal
* @throws NumberFormatException if the string does not
* contain a parsable {@code byte}.
*/
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
/**
* Returns a {@code Byte} object holding the value
* extracted from the specified {@code String} when parsed
* with the radix given by the second argument. The first argument
* is interpreted as representing a signed {@code byte} in
* the radix specified by the second argument, exactly as if the
* argument were given to the {@link #parseByte(java.lang.String,
* int)} method. The result is a {@code Byte} object that
* represents the {@code byte} value specified by the string.
*
* <p> In other words, this method returns a {@code Byte} object
* equal to the value of:
*
* <blockquote>
* {@code new Byte(Byte.parseByte(s, radix))}
* </blockquote>
*
* @param s the string to be parsed
* @param radix the radix to be used in interpreting {@code s}
* @return a {@code Byte} object holding the value
* represented by the string argument in the
* specified radix.
* @throws NumberFormatException If the {@code String} does
* not contain a parsable {@code byte}.
*/
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
/**
* Returns a {@code Byte} object holding the value
* given by the specified {@code String}. The argument is
* interpreted as representing a signed decimal {@code byte},
* exactly as if the argument were given to the {@link
* #parseByte(java.lang.String)} method. The result is a
* {@code Byte} object that represents the {@code byte}
* value specified by the string.
*
* <p> In other words, this method returns a {@code Byte} object
* equal to the value of:
*
* <blockquote>
* {@code new Byte(Byte.parseByte(s))}
* </blockquote>
*
* @param s the string to be parsed
* @return a {@code Byte} object holding the value
* represented by the string argument
* @throws NumberFormatException If the {@code String} does
* not contain a parsable {@code byte}.
*/
public static Byte valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
/**
* Decodes a {@code String} into a {@code Byte}.
* Accepts decimal, hexadecimal, and octal numbers given by
* the following grammar:
*
* <blockquote>
* <dl>
* <dt><i>DecodableString:</i>
* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
*
* <dt><i>Sign:</i>
* <dd>{@code -}
* <dd>{@code +}
* </dl>
* </blockquote>
*
* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
* are as defined in section {@jls 3.10.1} of
* <cite>The Java Language Specification</cite>,
* except that underscores are not accepted between digits.
*
* <p>The sequence of characters following an optional
* sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
* "{@code #}", or leading zero) is parsed as by the {@code
* Byte.parseByte} method with the indicated radix (10, 16, or 8).
* This sequence of characters must represent a positive value or
* a {@link NumberFormatException} will be thrown. The result is
* negated if first character of the specified {@code String} is
* the minus sign. No whitespace characters are permitted in the
* {@code String}.
*
* @param nm the {@code String} to decode.
* @return a {@code Byte} object holding the {@code byte}
* value represented by {@code nm}
* @throws NumberFormatException if the {@code String} does not
* contain a parsable {@code byte}.
* @see java.lang.Byte#parseByte(java.lang.String, int)
*/
public static Byte decode(String nm) throws NumberFormatException {
int i = Integer.decode(nm);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return valueOf((byte)i);
}
/**
* The value of the {@code Byte}.
*
* @serial
*/
private final byte value;
/**
* Constructs a newly allocated {@code Byte} object that
* represents the specified {@code byte} value.
*
* @param value the value to be represented by the
* {@code Byte}.
*
* @deprecated
* It is rarely appropriate to use this constructor. The static factory
* {@link #valueOf(byte)} is generally a better choice, as it is
* likely to yield significantly better space and time performance.
*/
// Android-changed: not yet forRemoval on Android.
@Deprecated(/*, forRemoval = true*/) // J2ObjC modified: removed since="9"
public Byte(byte value) {
this.value = value;
}
/**
* Constructs a newly allocated {@code Byte} object that
* represents the {@code byte} value indicated by the
* {@code String} parameter. The string is converted to a
* {@code byte} value in exactly the manner used by the
* {@code parseByte} method for radix 10.
*
* @param s the {@code String} to be converted to a
* {@code Byte}
* @throws NumberFormatException if the {@code String}
* does not contain a parsable {@code byte}.
*
* @deprecated
* It is rarely appropriate to use this constructor.
* Use {@link #parseByte(String)} to convert a string to a
* {@code byte} primitive, or use {@link #valueOf(String)}
* to convert a string to a {@code Byte} object.
*/
// Android-changed: not yet forRemoval on Android.
@Deprecated(/*, forRemoval = true*/) // J2ObjC modified: removed since="9"
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}
/**
* Returns the value of this {@code Byte} as a
* {@code byte}.
*/
/* J2Objc removed
@IntrinsicCandidate
*/
public byte byteValue() {
return value;
}
/**
* Returns the value of this {@code Byte} as a {@code short} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public short shortValue() {
return (short)value;
}
/**
* Returns the value of this {@code Byte} as an {@code int} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public int intValue() {
return (int)value;
}
/**
* Returns the value of this {@code Byte} as a {@code long} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public long longValue() {
return (long)value;
}
/**
* Returns the value of this {@code Byte} as a {@code float} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public float floatValue() {
return (float)value;
}
/**
* Returns the value of this {@code Byte} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public double doubleValue() {
return (double)value;
}
/**
* Returns a {@code String} object representing this
* {@code Byte}'s value. The value is converted to signed
* decimal representation and returned as a string, exactly as if
* the {@code byte} value were given as an argument to the
* {@link java.lang.Byte#toString(byte)} method.
*
* @return a string representation of the value of this object in
* base 10.
*/
public String toString() {
return Integer.toString((int)value);
}
/**
* Returns a hash code for this {@code Byte}; equal to the result
* of invoking {@code intValue()}.
*
* @return a hash code value for this {@code Byte}
*/
@Override
public int hashCode() {
return Byte.hashCode(value);
}
/**
* Returns a hash code for a {@code byte} value; compatible with
* {@code Byte.hashCode()}.
*
* @param value the value to hash
* @return a hash code value for a {@code byte} value.
* @since 1.8
*/
public static int hashCode(byte value) {
return (int)value;
}
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is a {@code Byte} object that
* contains the same {@code byte} value as this object.
*
* @param obj the object to compare with
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
/**
* Compares two {@code Byte} objects numerically.
*
* @param anotherByte the {@code Byte} to be compared.
* @return the value {@code 0} if this {@code Byte} is
* equal to the argument {@code Byte}; a value less than
* {@code 0} if this {@code Byte} is numerically less
* than the argument {@code Byte}; and a value greater than
* {@code 0} if this {@code Byte} is numerically
* greater than the argument {@code Byte} (signed
* comparison).
* @since 1.2
*/
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
/**
* Compares two {@code byte} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Byte.valueOf(x).compareTo(Byte.valueOf(y))
* </pre>
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(byte x, byte y) {
return x - y;
}
/**
* Compares two {@code byte} values numerically treating the values
* as unsigned.
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y}; a value less
* than {@code 0} if {@code x < y} as unsigned values; and
* a value greater than {@code 0} if {@code x > y} as
* unsigned values
* @since 9
*/
public static int compareUnsigned(byte x, byte y) {
return Byte.toUnsignedInt(x) - Byte.toUnsignedInt(y);
}
/**
* Converts the argument to an {@code int} by an unsigned
* conversion. In an unsigned conversion to an {@code int}, the
* high-order 24 bits of the {@code int} are zero and the
* low-order 8 bits are equal to the bits of the {@code byte} argument.
*
* Consequently, zero and positive {@code byte} values are mapped
* to a numerically equal {@code int} value and negative {@code
* byte} values are mapped to an {@code int} value equal to the
* input plus 2<sup>8</sup>.
*
* @param x the value to convert to an unsigned {@code int}
* @return the argument converted to {@code int} by an unsigned
* conversion
* @since 1.8
*/
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
/**
* Converts the argument to a {@code long} by an unsigned
* conversion. In an unsigned conversion to a {@code long}, the
* high-order 56 bits of the {@code long} are zero and the
* low-order 8 bits are equal to the bits of the {@code byte} argument.
*
* Consequently, zero and positive {@code byte} values are mapped
* to a numerically equal {@code long} value and negative {@code
* byte} values are mapped to a {@code long} value equal to the
* input plus 2<sup>8</sup>.
*
* @param x the value to convert to an unsigned {@code long}
* @return the argument converted to {@code long} by an unsigned
* conversion
* @since 1.8
*/
public static long toUnsignedLong(byte x) {
return ((long) x) & 0xffL;
}
/**
* The number of bits used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.5
*/
public static final int SIZE = 8;
/**
* The number of bytes used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.8
*/
public static final int BYTES = SIZE / Byte.SIZE;
/** use serialVersionUID from JDK 1.1. for interoperability */
@java.io.Serial
private static final long serialVersionUID = -7183698231559129828L;
// BEGIN Android-added: toHexString() for internal use.
/**
* @hide
*/
public static String toHexString(byte b, boolean upperCase) {
char[] digits = upperCase ? UPPER_CASE_DIGITS : DIGITS;
char[] buf = new char[2]; // We always want two digits.
buf[0] = digits[(b >> 4) & 0xf];
buf[1] = digits[b & 0xf];
return new String(buf, 0, 2);
}
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
private static final char[] UPPER_CASE_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
// ----- END android -----
/*
* These ObjC methods are needed to support subclassing of NSNumber.
* objCType and charValue are used by descriptionWithLocale:.
* getValue: is used by copyWithZone:.
*/
/*-[
- (const char *)objCType {
return "c";
}
- (void)getValue:(void *)buffer {
*((char *) buffer) = value_;
}
]-*/
}
| google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Byte.java | 6,679 | /**
* @hide
*/ | block_comment | nl | /*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
/* J2ObjC removed
import jdk.internal.vm.annotation.IntrinsicCandidate;
import libcore.util.HexEncoding;
*/
// Android-removed: CDS is not used on Android.
// import jdk.internal.misc.CDS;
// BEGIN Android-removed: dynamic constants not supported on Android.
/*
import java.lang.constant.Constable;
import java.lang.constant.DynamicConstantDesc;
import java.util.Optional;
import static java.lang.constant.ConstantDescs.BSM_EXPLICIT_CAST;
import static java.lang.constant.ConstantDescs.CD_byte;
import static java.lang.constant.ConstantDescs.CD_int;
import static java.lang.constant.ConstantDescs.DEFAULT_NAME;
*/
// END Android-removed: dynamic constants not supported on Android.
/**
*
* The {@code Byte} class wraps a value of primitive type {@code byte}
* in an object. An object of type {@code Byte} contains a single
* field whose type is {@code byte}.
*
* <p>In addition, this class provides several methods for converting
* a {@code byte} to a {@code String} and a {@code String} to a {@code
* byte}, as well as other constants and methods useful when dealing
* with a {@code byte}.
*
* <!-- Android-removed: paragraph on ValueBased
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; programmers should treat instances that are
* {@linkplain #equals(Object) equal} as interchangeable and should not
* use instances for synchronization, or unpredictable behavior may
* occur. For example, in a future release, synchronization may fail.
* -->
*
* @author Nakul Saraiya
* @author Joseph D. Darcy
* @see java.lang.Number
* @since 1.1
*/
// Android-removed: ValueBased
// @jdk.internal.ValueBased
public final class Byte extends Number implements Comparable<Byte>
// Android-removed: no Constable support.
// , Constable
{
/**
* A constant holding the minimum value a {@code byte} can
* have, -2<sup>7</sup>.
*/
public static final byte MIN_VALUE = -128;
/**
* A constant holding the maximum value a {@code byte} can
* have, 2<sup>7</sup>-1.
*/
public static final byte MAX_VALUE = 127;
/**
* The {@code Class} instance representing the primitive type
* {@code byte}.
*/
@SuppressWarnings("unchecked")
public static final Class<Byte> TYPE = (Class<Byte>) byte[].class.getComponentType();
/**
* Returns a new {@code String} object representing the
* specified {@code byte}. The radix is assumed to be 10.
*
* @param b the {@code byte} to be converted
* @return the string representation of the specified {@code byte}
* @see java.lang.Integer#toString(int)
*/
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
// BEGIN Android-removed: dynamic constants not supported on Android.
/**
* Returns an {@link Optional} containing the nominal descriptor for this
* instance.
*
* @return an {@link Optional} describing the {@linkplain Byte} instance
* @since 15
*
@Override
public Optional<DynamicConstantDesc<Byte>> describeConstable() {
return Optional.of(DynamicConstantDesc.ofNamed(BSM_EXPLICIT_CAST, DEFAULT_NAME, CD_byte, intValue()));
}
*/
// END Android-removed: dynamic constants not supported on Android.
private static class ByteCache {
private ByteCache() {}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
fillValues(cache);
}
private static native void fillValues(Byte[] values) /*-[
Class self = [JavaLangByte class];
size_t objSize = class_getInstanceSize(self);
uintptr_t ptr = (uintptr_t)calloc(objSize, 256);
id *buf = values->buffer_;
for (jint i = -128; i < 128; i++) {
id obj = objc_constructInstance(self, (void *)ptr);
JavaLangByte_initWithByte_(obj, (jbyte)i);
*(buf++) = obj;
ptr += objSize;
}
]-*/;
}
/**
* Returns a {@code Byte} instance representing the specified
* {@code byte} value.
* If a new {@code Byte} instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Byte(byte)}, as this method is likely to yield
* significantly better space and time performance since
* all byte values are cached.
*
* @param b a byte value.
* @return a {@code Byte} instance representing {@code b}.
* @since 1.5
*/
/* J2Objc removed
@IntrinsicCandidate
*/
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
/**
* Parses the string argument as a signed {@code byte} in the
* radix specified by the second argument. The characters in the
* string must all be digits, of the specified radix (as
* determined by whether {@link java.lang.Character#digit(char,
* int)} returns a nonnegative value) except that the first
* character may be an ASCII minus sign {@code '-'}
* ({@code '\u005Cu002D'}) to indicate a negative value or an
* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
* indicate a positive value. The resulting {@code byte} value is
* returned.
*
* <p>An exception of type {@code NumberFormatException} is
* thrown if any of the following situations occurs:
* <ul>
* <li> The first argument is {@code null} or is a string of
* length zero.
*
* <li> The radix is either smaller than {@link
* java.lang.Character#MIN_RADIX} or larger than {@link
* java.lang.Character#MAX_RADIX}.
*
* <li> Any character of the string is not a digit of the
* specified radix, except that the first character may be a minus
* sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
* {@code '+'} ({@code '\u005Cu002B'}) provided that the
* string is longer than length 1.
*
* <li> The value represented by the string is not a value of type
* {@code byte}.
* </ul>
*
* @param s the {@code String} containing the
* {@code byte}
* representation to be parsed
* @param radix the radix to be used while parsing {@code s}
* @return the {@code byte} value represented by the string
* argument in the specified radix
* @throws NumberFormatException If the string does
* not contain a parsable {@code byte}.
*/
public static byte parseByte(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (byte)i;
}
/**
* Parses the string argument as a signed decimal {@code
* byte}. The characters in the string must all be decimal digits,
* except that the first character may be an ASCII minus sign
* {@code '-'} ({@code '\u005Cu002D'}) to indicate a negative
* value or an ASCII plus sign {@code '+'}
* ({@code '\u005Cu002B'}) to indicate a positive value. The
* resulting {@code byte} value is returned, exactly as if the
* argument and the radix 10 were given as arguments to the {@link
* #parseByte(java.lang.String, int)} method.
*
* @param s a {@code String} containing the
* {@code byte} representation to be parsed
* @return the {@code byte} value represented by the
* argument in decimal
* @throws NumberFormatException if the string does not
* contain a parsable {@code byte}.
*/
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
/**
* Returns a {@code Byte} object holding the value
* extracted from the specified {@code String} when parsed
* with the radix given by the second argument. The first argument
* is interpreted as representing a signed {@code byte} in
* the radix specified by the second argument, exactly as if the
* argument were given to the {@link #parseByte(java.lang.String,
* int)} method. The result is a {@code Byte} object that
* represents the {@code byte} value specified by the string.
*
* <p> In other words, this method returns a {@code Byte} object
* equal to the value of:
*
* <blockquote>
* {@code new Byte(Byte.parseByte(s, radix))}
* </blockquote>
*
* @param s the string to be parsed
* @param radix the radix to be used in interpreting {@code s}
* @return a {@code Byte} object holding the value
* represented by the string argument in the
* specified radix.
* @throws NumberFormatException If the {@code String} does
* not contain a parsable {@code byte}.
*/
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
/**
* Returns a {@code Byte} object holding the value
* given by the specified {@code String}. The argument is
* interpreted as representing a signed decimal {@code byte},
* exactly as if the argument were given to the {@link
* #parseByte(java.lang.String)} method. The result is a
* {@code Byte} object that represents the {@code byte}
* value specified by the string.
*
* <p> In other words, this method returns a {@code Byte} object
* equal to the value of:
*
* <blockquote>
* {@code new Byte(Byte.parseByte(s))}
* </blockquote>
*
* @param s the string to be parsed
* @return a {@code Byte} object holding the value
* represented by the string argument
* @throws NumberFormatException If the {@code String} does
* not contain a parsable {@code byte}.
*/
public static Byte valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
/**
* Decodes a {@code String} into a {@code Byte}.
* Accepts decimal, hexadecimal, and octal numbers given by
* the following grammar:
*
* <blockquote>
* <dl>
* <dt><i>DecodableString:</i>
* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
* <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
*
* <dt><i>Sign:</i>
* <dd>{@code -}
* <dd>{@code +}
* </dl>
* </blockquote>
*
* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
* are as defined in section {@jls 3.10.1} of
* <cite>The Java Language Specification</cite>,
* except that underscores are not accepted between digits.
*
* <p>The sequence of characters following an optional
* sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
* "{@code #}", or leading zero) is parsed as by the {@code
* Byte.parseByte} method with the indicated radix (10, 16, or 8).
* This sequence of characters must represent a positive value or
* a {@link NumberFormatException} will be thrown. The result is
* negated if first character of the specified {@code String} is
* the minus sign. No whitespace characters are permitted in the
* {@code String}.
*
* @param nm the {@code String} to decode.
* @return a {@code Byte} object holding the {@code byte}
* value represented by {@code nm}
* @throws NumberFormatException if the {@code String} does not
* contain a parsable {@code byte}.
* @see java.lang.Byte#parseByte(java.lang.String, int)
*/
public static Byte decode(String nm) throws NumberFormatException {
int i = Integer.decode(nm);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return valueOf((byte)i);
}
/**
* The value of the {@code Byte}.
*
* @serial
*/
private final byte value;
/**
* Constructs a newly allocated {@code Byte} object that
* represents the specified {@code byte} value.
*
* @param value the value to be represented by the
* {@code Byte}.
*
* @deprecated
* It is rarely appropriate to use this constructor. The static factory
* {@link #valueOf(byte)} is generally a better choice, as it is
* likely to yield significantly better space and time performance.
*/
// Android-changed: not yet forRemoval on Android.
@Deprecated(/*, forRemoval = true*/) // J2ObjC modified: removed since="9"
public Byte(byte value) {
this.value = value;
}
/**
* Constructs a newly allocated {@code Byte} object that
* represents the {@code byte} value indicated by the
* {@code String} parameter. The string is converted to a
* {@code byte} value in exactly the manner used by the
* {@code parseByte} method for radix 10.
*
* @param s the {@code String} to be converted to a
* {@code Byte}
* @throws NumberFormatException if the {@code String}
* does not contain a parsable {@code byte}.
*
* @deprecated
* It is rarely appropriate to use this constructor.
* Use {@link #parseByte(String)} to convert a string to a
* {@code byte} primitive, or use {@link #valueOf(String)}
* to convert a string to a {@code Byte} object.
*/
// Android-changed: not yet forRemoval on Android.
@Deprecated(/*, forRemoval = true*/) // J2ObjC modified: removed since="9"
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}
/**
* Returns the value of this {@code Byte} as a
* {@code byte}.
*/
/* J2Objc removed
@IntrinsicCandidate
*/
public byte byteValue() {
return value;
}
/**
* Returns the value of this {@code Byte} as a {@code short} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public short shortValue() {
return (short)value;
}
/**
* Returns the value of this {@code Byte} as an {@code int} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public int intValue() {
return (int)value;
}
/**
* Returns the value of this {@code Byte} as a {@code long} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public long longValue() {
return (long)value;
}
/**
* Returns the value of this {@code Byte} as a {@code float} after
* a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public float floatValue() {
return (float)value;
}
/**
* Returns the value of this {@code Byte} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversion
*/
public double doubleValue() {
return (double)value;
}
/**
* Returns a {@code String} object representing this
* {@code Byte}'s value. The value is converted to signed
* decimal representation and returned as a string, exactly as if
* the {@code byte} value were given as an argument to the
* {@link java.lang.Byte#toString(byte)} method.
*
* @return a string representation of the value of this object in
* base 10.
*/
public String toString() {
return Integer.toString((int)value);
}
/**
* Returns a hash code for this {@code Byte}; equal to the result
* of invoking {@code intValue()}.
*
* @return a hash code value for this {@code Byte}
*/
@Override
public int hashCode() {
return Byte.hashCode(value);
}
/**
* Returns a hash code for a {@code byte} value; compatible with
* {@code Byte.hashCode()}.
*
* @param value the value to hash
* @return a hash code value for a {@code byte} value.
* @since 1.8
*/
public static int hashCode(byte value) {
return (int)value;
}
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is a {@code Byte} object that
* contains the same {@code byte} value as this object.
*
* @param obj the object to compare with
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
/**
* Compares two {@code Byte} objects numerically.
*
* @param anotherByte the {@code Byte} to be compared.
* @return the value {@code 0} if this {@code Byte} is
* equal to the argument {@code Byte}; a value less than
* {@code 0} if this {@code Byte} is numerically less
* than the argument {@code Byte}; and a value greater than
* {@code 0} if this {@code Byte} is numerically
* greater than the argument {@code Byte} (signed
* comparison).
* @since 1.2
*/
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
/**
* Compares two {@code byte} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Byte.valueOf(x).compareTo(Byte.valueOf(y))
* </pre>
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(byte x, byte y) {
return x - y;
}
/**
* Compares two {@code byte} values numerically treating the values
* as unsigned.
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y}; a value less
* than {@code 0} if {@code x < y} as unsigned values; and
* a value greater than {@code 0} if {@code x > y} as
* unsigned values
* @since 9
*/
public static int compareUnsigned(byte x, byte y) {
return Byte.toUnsignedInt(x) - Byte.toUnsignedInt(y);
}
/**
* Converts the argument to an {@code int} by an unsigned
* conversion. In an unsigned conversion to an {@code int}, the
* high-order 24 bits of the {@code int} are zero and the
* low-order 8 bits are equal to the bits of the {@code byte} argument.
*
* Consequently, zero and positive {@code byte} values are mapped
* to a numerically equal {@code int} value and negative {@code
* byte} values are mapped to an {@code int} value equal to the
* input plus 2<sup>8</sup>.
*
* @param x the value to convert to an unsigned {@code int}
* @return the argument converted to {@code int} by an unsigned
* conversion
* @since 1.8
*/
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
/**
* Converts the argument to a {@code long} by an unsigned
* conversion. In an unsigned conversion to a {@code long}, the
* high-order 56 bits of the {@code long} are zero and the
* low-order 8 bits are equal to the bits of the {@code byte} argument.
*
* Consequently, zero and positive {@code byte} values are mapped
* to a numerically equal {@code long} value and negative {@code
* byte} values are mapped to a {@code long} value equal to the
* input plus 2<sup>8</sup>.
*
* @param x the value to convert to an unsigned {@code long}
* @return the argument converted to {@code long} by an unsigned
* conversion
* @since 1.8
*/
public static long toUnsignedLong(byte x) {
return ((long) x) & 0xffL;
}
/**
* The number of bits used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.5
*/
public static final int SIZE = 8;
/**
* The number of bytes used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.8
*/
public static final int BYTES = SIZE / Byte.SIZE;
/** use serialVersionUID from JDK 1.1. for interoperability */
@java.io.Serial
private static final long serialVersionUID = -7183698231559129828L;
// BEGIN Android-added: toHexString() for internal use.
/**
* @hide
<SUF>*/
public static String toHexString(byte b, boolean upperCase) {
char[] digits = upperCase ? UPPER_CASE_DIGITS : DIGITS;
char[] buf = new char[2]; // We always want two digits.
buf[0] = digits[(b >> 4) & 0xf];
buf[1] = digits[b & 0xf];
return new String(buf, 0, 2);
}
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
private static final char[] UPPER_CASE_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
// ----- END android -----
/*
* These ObjC methods are needed to support subclassing of NSNumber.
* objCType and charValue are used by descriptionWithLocale:.
* getValue: is used by copyWithZone:.
*/
/*-[
- (const char *)objCType {
return "c";
}
- (void)getValue:(void *)buffer {
*((char *) buffer) = value_;
}
]-*/
}
|
83211_8 | import java.io.*;
import java.util.Scanner;
public class BinaireFileIODemo {
public void opslaanGetallen(String bestandsnaam){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
//Getallen inlezen
Scanner keyboard = new Scanner(System.in);
System.out.println ("Geef een positief getal .");
System.out.println ("Om te stoppen geef een negatief getal.");
int getal;
do
{
getal = keyboard.nextInt ();
output.writeInt(getal);
}
while (getal >= 0);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void lezenGetallen(String bestandsnaam) {
//aanmaken ObjectInputStream object
//ObjectOutputStream object aanmaken`
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
int getal = input.readInt();
while (true) {
System.out.println(getal);
getal = input.readInt();
}
}
catch (EOFException e){
System.out.println("einde bestand");
}
catch (IOException e) {
e.printStackTrace();
}
//input.close();
}
public void bewarenStudenten(String bestandsnaam){
Student student1 = new Student("Boels","Karel","45678");
Student student2 = new Student("De Smet","Dirk","67567");
//aanmaken ObjectOutputStream
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
output.writeObject(student1);
output.writeObject(student2);
}
catch(Exception e){
System.out.println(e.getMessage());
}
//wegschrijven van studenten + stoppen bij fout
// sluiten stream
}
public void lezenStudenten(String bestandsnaam){
//aanmaken ObjectInpuStream
//lezen van objecten en stoppen bij EOFException
ObjectInputStream input = null;
try {
try{
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
while (true) {
Student student = (Student) input.readObject();
System.out.println(student.toString());
}
} catch (EOFException e) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void schrijvenStudenten(String bestandsnaam, Student[] studenten){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
output.writeObject(studenten);
}
catch(Exception e){
System.out.println(e.getMessage());
}
//wegschrijven van studenten + stoppen bij fout
// sluiten stream
}
public Student[] lezenStudent(String bestandsnaam){
//aanmaken ObjectInpuStream
//lezen van objecten en stoppen bij EOFException
ObjectInputStream input = null;
Student[] students = null;
try {
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
students = (Student[]) input.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return students;
}
public static void main(String[] args) {
//DEMO 1
//String bestandsnaam1 = "numbers.dat";
//BinaireFileIODemo demo1 = new BinaireFileIODemo();
//demo1.opslaanGetallen(bestandsnaam1);
//demo1.lezenGetallen(bestandsnaam1);
//Demo 2
String bestandsnaam2 = "student.dat";
BinaireFileIODemo demo2 = new BinaireFileIODemo();
demo2.bewarenStudenten(bestandsnaam2);
demo2.lezenStudenten(bestandsnaam2);
//Demo 3
Student student1 = new Student("Boels","Karel","45678");
Student student2 = new Student("De Smet","Dirk","67567");
Student[] studenten = new Student[2];
studenten[0] = student1;
studenten[1] = student2;
String bestandsnaam3 = "studentenArray.dat";
BinaireFileIODemo demo3 = new BinaireFileIODemo();
demo3.schrijvenStudenten(bestandsnaam2,studenten);
Student[] result = demo3.lezenStudent(bestandsnaam3);
}
}
| UGent-AD2324-BusinessEngineering/CodeVoorbeeldenHOC-2324 | Bestanden/BinaireFileIODemo.java | 1,203 | //lezen van objecten en stoppen bij EOFException | line_comment | nl | import java.io.*;
import java.util.Scanner;
public class BinaireFileIODemo {
public void opslaanGetallen(String bestandsnaam){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
//Getallen inlezen
Scanner keyboard = new Scanner(System.in);
System.out.println ("Geef een positief getal .");
System.out.println ("Om te stoppen geef een negatief getal.");
int getal;
do
{
getal = keyboard.nextInt ();
output.writeInt(getal);
}
while (getal >= 0);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void lezenGetallen(String bestandsnaam) {
//aanmaken ObjectInputStream object
//ObjectOutputStream object aanmaken`
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
int getal = input.readInt();
while (true) {
System.out.println(getal);
getal = input.readInt();
}
}
catch (EOFException e){
System.out.println("einde bestand");
}
catch (IOException e) {
e.printStackTrace();
}
//input.close();
}
public void bewarenStudenten(String bestandsnaam){
Student student1 = new Student("Boels","Karel","45678");
Student student2 = new Student("De Smet","Dirk","67567");
//aanmaken ObjectOutputStream
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
output.writeObject(student1);
output.writeObject(student2);
}
catch(Exception e){
System.out.println(e.getMessage());
}
//wegschrijven van studenten + stoppen bij fout
// sluiten stream
}
public void lezenStudenten(String bestandsnaam){
//aanmaken ObjectInpuStream
//lezen van objecten en stoppen bij EOFException
ObjectInputStream input = null;
try {
try{
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
while (true) {
Student student = (Student) input.readObject();
System.out.println(student.toString());
}
} catch (EOFException e) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void schrijvenStudenten(String bestandsnaam, Student[] studenten){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(bestandsnaam));
output.writeObject(studenten);
}
catch(Exception e){
System.out.println(e.getMessage());
}
//wegschrijven van studenten + stoppen bij fout
// sluiten stream
}
public Student[] lezenStudent(String bestandsnaam){
//aanmaken ObjectInpuStream
//lezen van<SUF>
ObjectInputStream input = null;
Student[] students = null;
try {
input = new ObjectInputStream(new FileInputStream(bestandsnaam));
students = (Student[]) input.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return students;
}
public static void main(String[] args) {
//DEMO 1
//String bestandsnaam1 = "numbers.dat";
//BinaireFileIODemo demo1 = new BinaireFileIODemo();
//demo1.opslaanGetallen(bestandsnaam1);
//demo1.lezenGetallen(bestandsnaam1);
//Demo 2
String bestandsnaam2 = "student.dat";
BinaireFileIODemo demo2 = new BinaireFileIODemo();
demo2.bewarenStudenten(bestandsnaam2);
demo2.lezenStudenten(bestandsnaam2);
//Demo 3
Student student1 = new Student("Boels","Karel","45678");
Student student2 = new Student("De Smet","Dirk","67567");
Student[] studenten = new Student[2];
studenten[0] = student1;
studenten[1] = student2;
String bestandsnaam3 = "studentenArray.dat";
BinaireFileIODemo demo3 = new BinaireFileIODemo();
demo3.schrijvenStudenten(bestandsnaam2,studenten);
Student[] result = demo3.lezenStudent(bestandsnaam3);
}
}
|
22602_10 | /*
Copyright 2020, 2022, 2024 WeAreFrank!, 2018, 2019 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.testtool.echo2.reports;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nextapp.echo2.app.filetransfer.UploadEvent;
import nextapp.echo2.app.filetransfer.UploadListener;
import nl.nn.testtool.echo2.test.TestComponent;
import nl.nn.testtool.echo2.util.Upload;
import nl.nn.testtool.storage.CrudStorage;
import nl.nn.testtool.storage.StorageException;
/**
* @author Jaco de Groot
*/
public class ReportUploadListener implements UploadListener {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
ReportsComponent reportsComponent;
TestComponent testComponent;
CrudStorage storage;
public ReportUploadListener() {
}
public void setReportsComponent(ReportsComponent reportsComponent) {
this.reportsComponent = reportsComponent;
}
public void setTestComponent(TestComponent testComponent) {
this.testComponent = testComponent;
}
public void setStorage(CrudStorage storage) {
this.storage = storage;
}
public void fileUpload(UploadEvent uploadEvent) {
List reports = new ArrayList();
// String errorMessage = DownUpLoad.getReports(uploadEvent.getFileName(), uploadEvent.getInputStream(), reports, log);
// // TODO checken of errorMessage != null?
// for (int i = 0; i < reports.size(); i++) {
// Report report = (Report)reports.get(i);
// if (reportsComponent != null) {
// reportsComponent.openReport(report, true);
// } else {
// try {
// storage.store(report);
// } catch (StorageException e) {
// // TODO iets doen, errorMessage vullen?
// e.printStackTrace();
// }
// }
// }
CrudStorage storage = null;
if (reportsComponent != null) {
// TODO in reportsComponent memory storage bijhouden en gebruiken
// voor download en upload (niet telkens nieuwe aanmaken maar
// synchroon houden met open reports)?
storage = new nl.nn.testtool.storage.memory.Storage();
}
if (testComponent != null) {
storage = this.storage;
}
String errorMessage = Upload.upload(uploadEvent.getFileName(), uploadEvent.getInputStream(), storage, log);
if (reportsComponent != null) {
try {
List storageIds = storage.getStorageIds();
for (int i = storageIds.size() - 1; i > -1; i--) {
reportsComponent.openReport(storage.getReport((Integer)storageIds.get(i)),
ReportsComponent.OPEN_REPORT_ALLOWED, false, true);
}
} catch (StorageException e) {
// TODO iets doen, errorMessage vullen?
e.printStackTrace();
}
}
if (errorMessage != null) {
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayAndLogError(errorMessage);
}
if (testComponent != null) {
testComponent.displayAndLogError(errorMessage);
}
}
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
if (testComponent != null) {
testComponent.getUploadOptionsWindow().setVisible(false);
testComponent.refresh();
}
}
public void invalidFileUpload(UploadEvent uploadEvent) {
String message = "Invalid file upload: " + uploadEvent.getFileName()
+ ", " + uploadEvent.getContentType() + ", " + uploadEvent.getSize();
log.error(message);
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayError(message);
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
}
}
| wearefrank/ladybug | src/main/java/nl/nn/testtool/echo2/reports/ReportUploadListener.java | 1,170 | // TODO in reportsComponent memory storage bijhouden en gebruiken | line_comment | nl | /*
Copyright 2020, 2022, 2024 WeAreFrank!, 2018, 2019 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.testtool.echo2.reports;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nextapp.echo2.app.filetransfer.UploadEvent;
import nextapp.echo2.app.filetransfer.UploadListener;
import nl.nn.testtool.echo2.test.TestComponent;
import nl.nn.testtool.echo2.util.Upload;
import nl.nn.testtool.storage.CrudStorage;
import nl.nn.testtool.storage.StorageException;
/**
* @author Jaco de Groot
*/
public class ReportUploadListener implements UploadListener {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
ReportsComponent reportsComponent;
TestComponent testComponent;
CrudStorage storage;
public ReportUploadListener() {
}
public void setReportsComponent(ReportsComponent reportsComponent) {
this.reportsComponent = reportsComponent;
}
public void setTestComponent(TestComponent testComponent) {
this.testComponent = testComponent;
}
public void setStorage(CrudStorage storage) {
this.storage = storage;
}
public void fileUpload(UploadEvent uploadEvent) {
List reports = new ArrayList();
// String errorMessage = DownUpLoad.getReports(uploadEvent.getFileName(), uploadEvent.getInputStream(), reports, log);
// // TODO checken of errorMessage != null?
// for (int i = 0; i < reports.size(); i++) {
// Report report = (Report)reports.get(i);
// if (reportsComponent != null) {
// reportsComponent.openReport(report, true);
// } else {
// try {
// storage.store(report);
// } catch (StorageException e) {
// // TODO iets doen, errorMessage vullen?
// e.printStackTrace();
// }
// }
// }
CrudStorage storage = null;
if (reportsComponent != null) {
// TODO in<SUF>
// voor download en upload (niet telkens nieuwe aanmaken maar
// synchroon houden met open reports)?
storage = new nl.nn.testtool.storage.memory.Storage();
}
if (testComponent != null) {
storage = this.storage;
}
String errorMessage = Upload.upload(uploadEvent.getFileName(), uploadEvent.getInputStream(), storage, log);
if (reportsComponent != null) {
try {
List storageIds = storage.getStorageIds();
for (int i = storageIds.size() - 1; i > -1; i--) {
reportsComponent.openReport(storage.getReport((Integer)storageIds.get(i)),
ReportsComponent.OPEN_REPORT_ALLOWED, false, true);
}
} catch (StorageException e) {
// TODO iets doen, errorMessage vullen?
e.printStackTrace();
}
}
if (errorMessage != null) {
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayAndLogError(errorMessage);
}
if (testComponent != null) {
testComponent.displayAndLogError(errorMessage);
}
}
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
if (testComponent != null) {
testComponent.getUploadOptionsWindow().setVisible(false);
testComponent.refresh();
}
}
public void invalidFileUpload(UploadEvent uploadEvent) {
String message = "Invalid file upload: " + uploadEvent.getFileName()
+ ", " + uploadEvent.getContentType() + ", " + uploadEvent.getSize();
log.error(message);
// TODO generieker maken zodat het ook voor TestComponent werkt
if (reportsComponent != null) {
reportsComponent.displayError(message);
reportsComponent.getUploadOptionsWindow().setVisible(false);
}
}
}
|
17691_6 | /*
* Copyright 2020, Verizon Media.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms.
*/
package com.yahoo.oak;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A concurrent map implementation which supports off-heap memory.
*/
public class OakMap<K, V> extends AbstractMap<K, V>
implements AutoCloseable, ConcurrentNavigableMap<K, V>, ConcurrentZCMap<K, V> {
private final InternalOakMap<K, V> internalOakMap;
// Used for iterators
private final Function<Map.Entry<OakScopedReadBuffer, OakScopedReadBuffer>,
Map.Entry<K, V>> entryDeserializeTransformer;
// SubOakMap fields
private final K fromKey;
private final boolean fromInclusive;
private final K toKey;
private final boolean toInclusive;
private final boolean isDescending;
// Main constructor: used by the constructors below.
private OakMap(InternalOakMap<K, V> internalOakMap,
K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive, boolean isDescending) {
final OakSharedConfig<K, V> config = internalOakMap.config;
this.internalOakMap = internalOakMap;
this.fromKey = fromKey;
this.fromInclusive = fromInclusive;
this.toKey = toKey;
this.toInclusive = toInclusive;
this.isDescending = isDescending;
this.entryDeserializeTransformer = entry -> new AbstractMap.SimpleEntry<>(
config.keySerializer.deserialize(entry.getKey()),
config.valueSerializer.deserialize(entry.getValue()));
}
// Builder constructor: used by OakMapBuilder (package private).
OakMap(OakSharedConfig<K, V> config, K minKey, int chunkMaxItems) {
this(
new InternalOakMap<>(config, minKey, chunkMaxItems),
null, false, null, false, false
);
}
// Sub map constructor: used for subMap, headMap, tailMap, descendingMap.
private OakMap(OakMap<K, V> oakMap, K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive, boolean isDescending) {
this(
oakMap.internalOakMap,
fromKey, fromInclusive, toKey, toInclusive, isDescending
);
}
/* ------ Map API methods ------ */
/**
* Returns the current number of key-value mappings in this map.
* Not supported for SubMaps.
*
* @return the number of key-value mappings in this map
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public int size() {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.entries();
}
/**
* Returns a deserialized copy of the value to which the specified key is
* mapped, or {@code null} if this map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the value associated with that key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V get(Object key) {
checkKey((K) key);
return internalOakMap.getValueTransformation((K) key, internalOakMap.config.valueSerializer::deserialize);
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
* Creates a copy of the value in the map.
*
* @param key the key whose associated value is to be returned
* @return the value associated with that key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V put(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return internalOakMap.put(key, value, internalOakMap.config.valueSerializer::deserialize);
}
/**
* Removes the mapping for a key from this map if it is present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with the provided key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V remove(Object key) {
checkKey((K) key);
return (V) internalOakMap.remove((K) key, null, internalOakMap.config.valueSerializer::deserialize).value;
}
/* ------ SortedMap API methods ------ */
@Override
public Comparator<? super K> comparator() {
return internalOakMap.config.comparator;
}
/**
* Returns the minimal key in the map,
* or {@code null} if this map contains no keys.
*
* @return the minimal key in the map, or {@code null} if this map contains
* no keys.
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K firstKey() {
// this interface shouldn't be used with subMap
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.getMinKeyTransformation(internalOakMap.config.keySerializer::deserialize);
}
/**
* Returns the maximal key in the map,
* or {@code null} if this map contains no keys.
*
* @return the maximal key in the map, or {@code null} if this map contains
* no keys.
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K lastKey() {
// this interface shouldn't be used with subMap
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.getMaxKeyTransformation(internalOakMap.config.keySerializer::deserialize);
}
/* ------ ConcurrentMap API methods ------ */
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object key, Object value) {
checkKey((K) key);
return (value != null) && (internalOakMap.remove((K) key, (V) value,
internalOakMap.config.valueSerializer::deserialize).operationResult == ValueUtils.ValueResult.TRUE);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the specified key or value is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V replace(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return internalOakMap.replace(key, value, internalOakMap.config.valueSerializer::deserialize);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if any of the arguments are null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public boolean replace(K key, V oldValue, V newValue) {
checkKey(key);
if (oldValue == null || newValue == null) {
throw new NullPointerException();
}
return internalOakMap.replace(key, oldValue, newValue, internalOakMap.config.valueSerializer::deserialize);
}
/**
* If the specified key is not already associated
* with a value, associate it with the given value.
* Creates a copy of the value in the map.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
public V putIfAbsent(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return (V) internalOakMap.putIfAbsent(key, value, internalOakMap.config.valueSerializer::deserialize).value;
}
/* ---------------- NavigableMap API methods -------------- */
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public Entry<K, V> lowerEntry(K key) {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
if (key == null) {
throw new NullPointerException();
}
return internalOakMap.lowerEntry(key);
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K lowerKey(K key) {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
if (key == null) {
throw new NullPointerException();
}
return internalOakMap.lowerEntry(key).getKey();
}
/* ---------------- ConcurrentNavigableMap API methods -------------- */
/*-------------- SubMap --------------*/
private boolean inBounds(K key) {
int res;
if (fromKey != null) {
res = internalOakMap.config.comparator.compareKeys(key, fromKey);
if (res < 0 || (res == 0 && !fromInclusive)) {
return false;
}
}
if (toKey != null) {
res = internalOakMap.config.comparator.compareKeys(key, toKey);
return res <= 0 && (res != 0 || toInclusive);
}
return true;
}
/**
* Returns a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}. If {@code fromKey} and
* {@code toKey} are equal, the returned map is empty unless
* {@code fromInclusive} and {@code toInclusive} are both true. The
* returned map is backed by this map, so changes in the returned map are
* reflected in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside of its range, or to construct a
* submap either of whose endpoints lie outside its range.
*
* @param fromKey low endpoint of the keys in the returned map
* @param fromInclusive {@code true} if the low endpoint
* is to be included in the returned view
* @param toKey high endpoint of the keys in the returned map
* @param toInclusive {@code true} if the high endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}
* @throws NullPointerException if {@code fromKey} or {@code toKey}
* is null and this map does not permit null keys
* @throws IllegalArgumentException if {@code fromKey} is greater than
* {@code toKey}; or if this map itself has a restricted
* range, and {@code fromKey} or {@code toKey} lies
* outside the bounds of the range
*/
public OakMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return subMap(fromKey, fromInclusive, toKey, toInclusive, this.isDescending);
}
@Override
public OakMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false, this.isDescending);
}
public OakMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, boolean descending) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, fromKey, fromInclusive, toKey, toInclusive, descending);
}
/**
* Returns a view of the portion of this map whose keys are less than (or
* equal to, if {@code inclusive} is true) {@code toKey}. The returned
* map is backed by this map, so changes in the returned map are reflected
* in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param toKey high endpoint of the keys in the returned map
* @param inclusive {@code true} if the high endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys are less than
* (or equal to, if {@code inclusive} is true) {@code toKey}
* @throws NullPointerException if {@code toKey} is null
* and this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
* restricted range, and {@code toKey} lies outside the
* bounds of the range
*/
public OakMap<K, V> headMap(K toKey, boolean inclusive) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, this.fromKey, this.fromInclusive, toKey, inclusive, this.isDescending);
}
@Override
public ConcurrentNavigableMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
/**
* Returns a view of the portion of this map whose keys are greater than (or
* equal to, if {@code inclusive} is true) {@code fromKey}. The returned
* map is backed by this map, so changes in the returned map are reflected
* in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param fromKey low endpoint of the keys in the returned map
* @param inclusive {@code true} if the low endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys are greater than
* (or equal to, if {@code inclusive} is true) {@code fromKey}
* @throws NullPointerException if {@code fromKey} is null
* and this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
* restricted range, and {@code fromKey} lies outside the
* bounds of the range
*/
public OakMap<K, V> tailMap(K fromKey, boolean inclusive) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, fromKey, inclusive, this.toKey, this.toInclusive, this.isDescending);
}
@Override
public ConcurrentNavigableMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
/**
* Returns a reverse order view of the mappings contained in this map.
* The descending map is backed by this map, so changes to the map are
* reflected in the descending map, and vice-versa.
* <p>The expression {@code m.descendingMap().descendingMap()} returns a
* view of {@code m} essentially equivalent to {@code m}.
*
* @return a reverse order view of this map
*/
public OakMap<K, V> descendingMap() {
internalOakMap.open();
return new OakMap<>(this, this.fromKey, this.fromInclusive, this.toKey, this.toInclusive, true);
}
@Override
public NavigableSet<K> navigableKeySet() {
return new KeySet<>(this);
}
@Override
public NavigableSet<K> keySet() {
return new KeySet<>(this);
}
@Override
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet<>(this);
}
@Override
public Collection<V> values() {
return new Values<>(this);
}
/* ------ Zero-Copy API methods ------ */
public ZeroCopyMap<K, V> zc() {
return new OakZeroCopyMap<>(this);
}
public MemoryManager getValuesMemoryManager() {
return this.internalOakMap.getValuesMemoryManager();
}
public static class OakZeroCopyMap<K, V> implements ZeroCopyMap<K, V> {
private OakMap<K, V> m;
OakZeroCopyMap(OakMap<K, V> kvOakMap) {
this.m = kvOakMap;
}
public void put(K key, V value) {
m.checkKey(key);
if (value == null) {
throw new NullPointerException();
}
m.internalOakMap.put(key, value, null);
}
public OakUnscopedBuffer get(K key) {
m.checkKey(key);
return m.internalOakMap.get(key);
}
public boolean remove(K key) {
m.checkKey(key);
return m.internalOakMap.remove(key, null, null).operationResult == ValueUtils.ValueResult.TRUE;
}
public boolean putIfAbsent(K key, V value) {
m.checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return m.internalOakMap.putIfAbsent(key, value, null).operationResult == ValueUtils.ValueResult.TRUE;
}
public boolean computeIfPresent(K key, Consumer<OakScopedWriteBuffer> computer) {
m.checkKey(key);
if (computer == null) {
throw new NullPointerException();
}
return m.internalOakMap.computeIfPresent(key, computer);
}
public boolean putIfAbsentComputeIfPresent(K key, V value, Consumer<OakScopedWriteBuffer> computer) {
m.checkKey(key);
if (value == null || computer == null) {
throw new IllegalArgumentException();
}
return m.internalOakMap.putIfAbsentComputeIfPresent(key, value, computer);
}
public Set<OakUnscopedBuffer> keySet() {
return new KeyBufferSet<>(m);
}
public Collection<OakUnscopedBuffer> values() {
return new ValueBuffers<>(m);
}
public Set<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entrySet() {
return new EntryBufferSet<>(m);
}
public Set<OakUnscopedBuffer> keyStreamSet() {
return new KeyStreamBufferSet<>(m);
}
public Collection<OakUnscopedBuffer> valuesStream() {
return new ValueStreamBuffers<>(m);
}
public Set<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entryStreamSet() {
return new EntryStreamBufferSet<>(m);
}
}
/* ----------- Oak misc methods ----------- */
/**
* @return current off heap memory usage in bytes
*/
@Override
public long memorySize() {
return internalOakMap.memorySize();
}
/**
* Close and release the map and all the memory that is used by it.
* The user should ensure that there are no concurrent operations
* that are undergoing at the time this method is called.
* Failing to do so will result in an undefined behaviour.
*/
@Override
public void close() {
internalOakMap.close();
}
/* ---------------- Private utility methods -------------- */
private void checkKey(K key) {
if (key == null) {
throw new NullPointerException();
}
if (!inBounds(key)) {
throw new IllegalArgumentException("The key is out of map bounds");
}
}
private boolean isSubmap() {
return (this.fromKey != null || this.toKey != null);
}
/**
* Returns a {@link Iterator} of the values contained in this map
* in ascending order of the corresponding keys.
*/
private Iterator<V> valuesIterator() {
return internalOakMap.valuesTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
internalOakMap.config.valueSerializer::deserialize);
}
/**
* Returns a {@link Iterator} of the mappings contained in this map in ascending key order.
*/
private Iterator<Map.Entry<K, V>> entriesIterator() {
return internalOakMap.entriesTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
entryDeserializeTransformer);
}
/**
* Returns a {@link Iterator} of the keys contained in this map in ascending order.
*/
private Iterator<K> keysIterator() {
return internalOakMap.keysTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
internalOakMap.config.keySerializer::deserialize);
}
private Iterator<OakUnscopedBuffer> keysBufferIterator() {
return internalOakMap.keysBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> valuesBufferIterator() {
return internalOakMap.valuesBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<Map.Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entriesBufferIterator() {
return internalOakMap.entriesBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> keysStreamIterator() {
return internalOakMap.keysStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> valuesStreamIterator() {
return internalOakMap.valuesStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<Map.Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entriesStreamIterator() {
return internalOakMap.entriesStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
/* ---------------- TODO: Move methods below to their proper place as they are implemented -------------- */
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
return null;
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public Entry<K, V> floorEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K floorKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> ceilingEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K ceilingKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> higherEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K higherKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> firstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> lastEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
/* ---------------- View Classes -------------- */
static class KeySet<K> extends AbstractSet<K> implements NavigableSet<K> {
private final OakMap<K, ?> m;
KeySet(OakMap<K, ?> m) {
this.m = m;
}
@Override
public K lower(K k) {
return m.lowerKey(k);
}
@Override
public K floor(K k) {
return m.floorKey(k);
}
@Override
public K ceiling(K k) {
return m.ceilingKey(k);
}
@Override
public K higher(K k) {
return m.higherKey(k);
}
@Override
public K pollFirst() {
Map.Entry<K, ?> e = m.pollFirstEntry();
return (e == null) ? null : e.getKey();
}
@Override
public K pollLast() {
Map.Entry<K, ?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
@Override
public Iterator<K> iterator() {
return m.keysIterator();
}
@Override
public NavigableSet<K> descendingSet() {
return new KeySet<>(m.descendingMap());
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new KeySet<>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return new KeySet<>(m.headMap(toElement, inclusive));
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return new KeySet<>(m.tailMap(fromElement, inclusive));
}
@Override
public Comparator<? super K> comparator() {
return m.comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public SortedSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
@Override
public K first() {
return m.firstKey();
}
@Override
public K last() {
return m.lastKey();
}
@Override
public int size() {
return m.size();
}
}
static class EntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> {
private final OakMap<K, V> m;
EntrySet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return m.entriesIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class Values<V> extends AbstractCollection<V> {
private final OakMap<?, V> m;
Values(OakMap<?, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<V> iterator() {
return m.valuesIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class KeyBufferSet<K, V> extends AbstractSet<OakUnscopedBuffer> {
private final OakMap<K, V> m;
KeyBufferSet(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.keysBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static class EntryBufferSet<K, V> extends AbstractSet<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> {
private final OakMap<K, V> m;
EntryBufferSet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> iterator() {
return m.entriesBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class ValueBuffers<K, V> extends AbstractCollection<OakUnscopedBuffer> {
private final OakMap<K, V> m;
ValueBuffers(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.valuesBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class KeyStreamBufferSet<K, V> extends AbstractSet<OakUnscopedBuffer> {
private final OakMap<K, V> m;
KeyStreamBufferSet(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.keysStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
static class EntryStreamBufferSet<K, V> extends AbstractSet<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> {
private final OakMap<K, V> m;
EntryStreamBufferSet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> iterator() {
return m.entriesStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class ValueStreamBuffers<K, V> extends AbstractCollection<OakUnscopedBuffer> {
private final OakMap<K, V> m;
ValueStreamBuffers(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.valuesStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
}
| yahoo/Oak | core/src/main/java/com/yahoo/oak/OakMap.java | 7,897 | /* ------ Map API methods ------ */ | block_comment | nl | /*
* Copyright 2020, Verizon Media.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms.
*/
package com.yahoo.oak;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A concurrent map implementation which supports off-heap memory.
*/
public class OakMap<K, V> extends AbstractMap<K, V>
implements AutoCloseable, ConcurrentNavigableMap<K, V>, ConcurrentZCMap<K, V> {
private final InternalOakMap<K, V> internalOakMap;
// Used for iterators
private final Function<Map.Entry<OakScopedReadBuffer, OakScopedReadBuffer>,
Map.Entry<K, V>> entryDeserializeTransformer;
// SubOakMap fields
private final K fromKey;
private final boolean fromInclusive;
private final K toKey;
private final boolean toInclusive;
private final boolean isDescending;
// Main constructor: used by the constructors below.
private OakMap(InternalOakMap<K, V> internalOakMap,
K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive, boolean isDescending) {
final OakSharedConfig<K, V> config = internalOakMap.config;
this.internalOakMap = internalOakMap;
this.fromKey = fromKey;
this.fromInclusive = fromInclusive;
this.toKey = toKey;
this.toInclusive = toInclusive;
this.isDescending = isDescending;
this.entryDeserializeTransformer = entry -> new AbstractMap.SimpleEntry<>(
config.keySerializer.deserialize(entry.getKey()),
config.valueSerializer.deserialize(entry.getValue()));
}
// Builder constructor: used by OakMapBuilder (package private).
OakMap(OakSharedConfig<K, V> config, K minKey, int chunkMaxItems) {
this(
new InternalOakMap<>(config, minKey, chunkMaxItems),
null, false, null, false, false
);
}
// Sub map constructor: used for subMap, headMap, tailMap, descendingMap.
private OakMap(OakMap<K, V> oakMap, K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive, boolean isDescending) {
this(
oakMap.internalOakMap,
fromKey, fromInclusive, toKey, toInclusive, isDescending
);
}
/* ------ Map API<SUF>*/
/**
* Returns the current number of key-value mappings in this map.
* Not supported for SubMaps.
*
* @return the number of key-value mappings in this map
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public int size() {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.entries();
}
/**
* Returns a deserialized copy of the value to which the specified key is
* mapped, or {@code null} if this map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the value associated with that key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V get(Object key) {
checkKey((K) key);
return internalOakMap.getValueTransformation((K) key, internalOakMap.config.valueSerializer::deserialize);
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
* Creates a copy of the value in the map.
*
* @param key the key whose associated value is to be returned
* @return the value associated with that key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V put(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return internalOakMap.put(key, value, internalOakMap.config.valueSerializer::deserialize);
}
/**
* Removes the mapping for a key from this map if it is present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with the provided key, or
* {@code null} if this map contains no mapping for the key
* @throws NullPointerException if the specified key is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V remove(Object key) {
checkKey((K) key);
return (V) internalOakMap.remove((K) key, null, internalOakMap.config.valueSerializer::deserialize).value;
}
/* ------ SortedMap API methods ------ */
@Override
public Comparator<? super K> comparator() {
return internalOakMap.config.comparator;
}
/**
* Returns the minimal key in the map,
* or {@code null} if this map contains no keys.
*
* @return the minimal key in the map, or {@code null} if this map contains
* no keys.
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K firstKey() {
// this interface shouldn't be used with subMap
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.getMinKeyTransformation(internalOakMap.config.keySerializer::deserialize);
}
/**
* Returns the maximal key in the map,
* or {@code null} if this map contains no keys.
*
* @return the maximal key in the map, or {@code null} if this map contains
* no keys.
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K lastKey() {
// this interface shouldn't be used with subMap
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
return internalOakMap.getMaxKeyTransformation(internalOakMap.config.keySerializer::deserialize);
}
/* ------ ConcurrentMap API methods ------ */
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object key, Object value) {
checkKey((K) key);
return (value != null) && (internalOakMap.remove((K) key, (V) value,
internalOakMap.config.valueSerializer::deserialize).operationResult == ValueUtils.ValueResult.TRUE);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the specified key or value is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public V replace(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return internalOakMap.replace(key, value, internalOakMap.config.valueSerializer::deserialize);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if any of the arguments are null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
@Override
public boolean replace(K key, V oldValue, V newValue) {
checkKey(key);
if (oldValue == null || newValue == null) {
throw new NullPointerException();
}
return internalOakMap.replace(key, oldValue, newValue, internalOakMap.config.valueSerializer::deserialize);
}
/**
* If the specified key is not already associated
* with a value, associate it with the given value.
* Creates a copy of the value in the map.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
* @throws IllegalArgumentException if the specified key is out of bounds
*/
public V putIfAbsent(K key, V value) {
checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return (V) internalOakMap.putIfAbsent(key, value, internalOakMap.config.valueSerializer::deserialize).value;
}
/* ---------------- NavigableMap API methods -------------- */
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public Entry<K, V> lowerEntry(K key) {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
if (key == null) {
throw new NullPointerException();
}
return internalOakMap.lowerEntry(key);
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException if used on a SubMap
*/
@Override
public K lowerKey(K key) {
if (this.isSubmap()) {
throw new UnsupportedOperationException();
}
if (key == null) {
throw new NullPointerException();
}
return internalOakMap.lowerEntry(key).getKey();
}
/* ---------------- ConcurrentNavigableMap API methods -------------- */
/*-------------- SubMap --------------*/
private boolean inBounds(K key) {
int res;
if (fromKey != null) {
res = internalOakMap.config.comparator.compareKeys(key, fromKey);
if (res < 0 || (res == 0 && !fromInclusive)) {
return false;
}
}
if (toKey != null) {
res = internalOakMap.config.comparator.compareKeys(key, toKey);
return res <= 0 && (res != 0 || toInclusive);
}
return true;
}
/**
* Returns a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}. If {@code fromKey} and
* {@code toKey} are equal, the returned map is empty unless
* {@code fromInclusive} and {@code toInclusive} are both true. The
* returned map is backed by this map, so changes in the returned map are
* reflected in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside of its range, or to construct a
* submap either of whose endpoints lie outside its range.
*
* @param fromKey low endpoint of the keys in the returned map
* @param fromInclusive {@code true} if the low endpoint
* is to be included in the returned view
* @param toKey high endpoint of the keys in the returned map
* @param toInclusive {@code true} if the high endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}
* @throws NullPointerException if {@code fromKey} or {@code toKey}
* is null and this map does not permit null keys
* @throws IllegalArgumentException if {@code fromKey} is greater than
* {@code toKey}; or if this map itself has a restricted
* range, and {@code fromKey} or {@code toKey} lies
* outside the bounds of the range
*/
public OakMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return subMap(fromKey, fromInclusive, toKey, toInclusive, this.isDescending);
}
@Override
public OakMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false, this.isDescending);
}
public OakMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, boolean descending) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, fromKey, fromInclusive, toKey, toInclusive, descending);
}
/**
* Returns a view of the portion of this map whose keys are less than (or
* equal to, if {@code inclusive} is true) {@code toKey}. The returned
* map is backed by this map, so changes in the returned map are reflected
* in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param toKey high endpoint of the keys in the returned map
* @param inclusive {@code true} if the high endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys are less than
* (or equal to, if {@code inclusive} is true) {@code toKey}
* @throws NullPointerException if {@code toKey} is null
* and this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
* restricted range, and {@code toKey} lies outside the
* bounds of the range
*/
public OakMap<K, V> headMap(K toKey, boolean inclusive) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, this.fromKey, this.fromInclusive, toKey, inclusive, this.isDescending);
}
@Override
public ConcurrentNavigableMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
/**
* Returns a view of the portion of this map whose keys are greater than (or
* equal to, if {@code inclusive} is true) {@code fromKey}. The returned
* map is backed by this map, so changes in the returned map are reflected
* in this map, and vice-versa. The returned map supports all
* map operations that this map supports.
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param fromKey low endpoint of the keys in the returned map
* @param inclusive {@code true} if the low endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys are greater than
* (or equal to, if {@code inclusive} is true) {@code fromKey}
* @throws NullPointerException if {@code fromKey} is null
* and this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
* restricted range, and {@code fromKey} lies outside the
* bounds of the range
*/
public OakMap<K, V> tailMap(K fromKey, boolean inclusive) {
internalOakMap.validateBoundariesOrder(fromKey, toKey);
internalOakMap.open();
return new OakMap<>(this, fromKey, inclusive, this.toKey, this.toInclusive, this.isDescending);
}
@Override
public ConcurrentNavigableMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
/**
* Returns a reverse order view of the mappings contained in this map.
* The descending map is backed by this map, so changes to the map are
* reflected in the descending map, and vice-versa.
* <p>The expression {@code m.descendingMap().descendingMap()} returns a
* view of {@code m} essentially equivalent to {@code m}.
*
* @return a reverse order view of this map
*/
public OakMap<K, V> descendingMap() {
internalOakMap.open();
return new OakMap<>(this, this.fromKey, this.fromInclusive, this.toKey, this.toInclusive, true);
}
@Override
public NavigableSet<K> navigableKeySet() {
return new KeySet<>(this);
}
@Override
public NavigableSet<K> keySet() {
return new KeySet<>(this);
}
@Override
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet<>(this);
}
@Override
public Collection<V> values() {
return new Values<>(this);
}
/* ------ Zero-Copy API methods ------ */
public ZeroCopyMap<K, V> zc() {
return new OakZeroCopyMap<>(this);
}
public MemoryManager getValuesMemoryManager() {
return this.internalOakMap.getValuesMemoryManager();
}
public static class OakZeroCopyMap<K, V> implements ZeroCopyMap<K, V> {
private OakMap<K, V> m;
OakZeroCopyMap(OakMap<K, V> kvOakMap) {
this.m = kvOakMap;
}
public void put(K key, V value) {
m.checkKey(key);
if (value == null) {
throw new NullPointerException();
}
m.internalOakMap.put(key, value, null);
}
public OakUnscopedBuffer get(K key) {
m.checkKey(key);
return m.internalOakMap.get(key);
}
public boolean remove(K key) {
m.checkKey(key);
return m.internalOakMap.remove(key, null, null).operationResult == ValueUtils.ValueResult.TRUE;
}
public boolean putIfAbsent(K key, V value) {
m.checkKey(key);
if (value == null) {
throw new NullPointerException();
}
return m.internalOakMap.putIfAbsent(key, value, null).operationResult == ValueUtils.ValueResult.TRUE;
}
public boolean computeIfPresent(K key, Consumer<OakScopedWriteBuffer> computer) {
m.checkKey(key);
if (computer == null) {
throw new NullPointerException();
}
return m.internalOakMap.computeIfPresent(key, computer);
}
public boolean putIfAbsentComputeIfPresent(K key, V value, Consumer<OakScopedWriteBuffer> computer) {
m.checkKey(key);
if (value == null || computer == null) {
throw new IllegalArgumentException();
}
return m.internalOakMap.putIfAbsentComputeIfPresent(key, value, computer);
}
public Set<OakUnscopedBuffer> keySet() {
return new KeyBufferSet<>(m);
}
public Collection<OakUnscopedBuffer> values() {
return new ValueBuffers<>(m);
}
public Set<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entrySet() {
return new EntryBufferSet<>(m);
}
public Set<OakUnscopedBuffer> keyStreamSet() {
return new KeyStreamBufferSet<>(m);
}
public Collection<OakUnscopedBuffer> valuesStream() {
return new ValueStreamBuffers<>(m);
}
public Set<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entryStreamSet() {
return new EntryStreamBufferSet<>(m);
}
}
/* ----------- Oak misc methods ----------- */
/**
* @return current off heap memory usage in bytes
*/
@Override
public long memorySize() {
return internalOakMap.memorySize();
}
/**
* Close and release the map and all the memory that is used by it.
* The user should ensure that there are no concurrent operations
* that are undergoing at the time this method is called.
* Failing to do so will result in an undefined behaviour.
*/
@Override
public void close() {
internalOakMap.close();
}
/* ---------------- Private utility methods -------------- */
private void checkKey(K key) {
if (key == null) {
throw new NullPointerException();
}
if (!inBounds(key)) {
throw new IllegalArgumentException("The key is out of map bounds");
}
}
private boolean isSubmap() {
return (this.fromKey != null || this.toKey != null);
}
/**
* Returns a {@link Iterator} of the values contained in this map
* in ascending order of the corresponding keys.
*/
private Iterator<V> valuesIterator() {
return internalOakMap.valuesTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
internalOakMap.config.valueSerializer::deserialize);
}
/**
* Returns a {@link Iterator} of the mappings contained in this map in ascending key order.
*/
private Iterator<Map.Entry<K, V>> entriesIterator() {
return internalOakMap.entriesTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
entryDeserializeTransformer);
}
/**
* Returns a {@link Iterator} of the keys contained in this map in ascending order.
*/
private Iterator<K> keysIterator() {
return internalOakMap.keysTransformIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending,
internalOakMap.config.keySerializer::deserialize);
}
private Iterator<OakUnscopedBuffer> keysBufferIterator() {
return internalOakMap.keysBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> valuesBufferIterator() {
return internalOakMap.valuesBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<Map.Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entriesBufferIterator() {
return internalOakMap.entriesBufferViewIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> keysStreamIterator() {
return internalOakMap.keysStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<OakUnscopedBuffer> valuesStreamIterator() {
return internalOakMap.valuesStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
private Iterator<Map.Entry<OakUnscopedBuffer, OakUnscopedBuffer>> entriesStreamIterator() {
return internalOakMap.entriesStreamIterator(fromKey, fromInclusive, toKey, toInclusive, isDescending);
}
/* ---------------- TODO: Move methods below to their proper place as they are implemented -------------- */
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
return null;
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
return null;
}
@Override
public Entry<K, V> floorEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K floorKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> ceilingEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K ceilingKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> higherEntry(K key) {
throw new UnsupportedOperationException();
}
@Override
public K higherKey(K key) {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> firstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> lastEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<K, V> pollLastEntry() {
throw new UnsupportedOperationException();
}
/* ---------------- View Classes -------------- */
static class KeySet<K> extends AbstractSet<K> implements NavigableSet<K> {
private final OakMap<K, ?> m;
KeySet(OakMap<K, ?> m) {
this.m = m;
}
@Override
public K lower(K k) {
return m.lowerKey(k);
}
@Override
public K floor(K k) {
return m.floorKey(k);
}
@Override
public K ceiling(K k) {
return m.ceilingKey(k);
}
@Override
public K higher(K k) {
return m.higherKey(k);
}
@Override
public K pollFirst() {
Map.Entry<K, ?> e = m.pollFirstEntry();
return (e == null) ? null : e.getKey();
}
@Override
public K pollLast() {
Map.Entry<K, ?> e = m.pollLastEntry();
return (e == null) ? null : e.getKey();
}
@Override
public Iterator<K> iterator() {
return m.keysIterator();
}
@Override
public NavigableSet<K> descendingSet() {
return new KeySet<>(m.descendingMap());
}
@Override
public Iterator<K> descendingIterator() {
return descendingSet().iterator();
}
@Override
public NavigableSet<K> subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new KeySet<>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return new KeySet<>(m.headMap(toElement, inclusive));
}
@Override
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return new KeySet<>(m.tailMap(fromElement, inclusive));
}
@Override
public Comparator<? super K> comparator() {
return m.comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public SortedSet<K> headSet(K toElement) {
return headSet(toElement, false);
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
@Override
public K first() {
return m.firstKey();
}
@Override
public K last() {
return m.lastKey();
}
@Override
public int size() {
return m.size();
}
}
static class EntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> {
private final OakMap<K, V> m;
EntrySet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return m.entriesIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class Values<V> extends AbstractCollection<V> {
private final OakMap<?, V> m;
Values(OakMap<?, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<V> iterator() {
return m.valuesIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class KeyBufferSet<K, V> extends AbstractSet<OakUnscopedBuffer> {
private final OakMap<K, V> m;
KeyBufferSet(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.keysBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static class EntryBufferSet<K, V> extends AbstractSet<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> {
private final OakMap<K, V> m;
EntryBufferSet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> iterator() {
return m.entriesBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class ValueBuffers<K, V> extends AbstractCollection<OakUnscopedBuffer> {
private final OakMap<K, V> m;
ValueBuffers(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.valuesBufferIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class KeyStreamBufferSet<K, V> extends AbstractSet<OakUnscopedBuffer> {
private final OakMap<K, V> m;
KeyStreamBufferSet(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.keysStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
static class EntryStreamBufferSet<K, V> extends AbstractSet<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> {
private final OakMap<K, V> m;
EntryStreamBufferSet(OakMap<K, V> m) {
this.m = m;
}
@Override
public Iterator<Entry<OakUnscopedBuffer, OakUnscopedBuffer>> iterator() {
return m.entriesStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
static final class ValueStreamBuffers<K, V> extends AbstractCollection<OakUnscopedBuffer> {
private final OakMap<K, V> m;
ValueStreamBuffers(OakMap<K, V> oakMap) {
this.m = oakMap;
}
@Override
public Iterator<OakUnscopedBuffer> iterator() {
return m.valuesStreamIterator();
}
@Override
public int size() {
return m.size();
}
}
}
|
100491_4 | /*
* Copyright (C) 2018 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.web.jsp;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
/**
*
* @author mprins
*/
public final class LogfileUtil {
private static final Log LOG = LogFactory.getLog(LogfileUtil.class);
/**
* opzoeken van log file, de logger heeft de naam 'file' in de log4j
* properties.
*
* @return volledig pad naar actuele logfile 'file', mogelijk null. Het pad
* is de string die geconfigureerd is in de log4j properties
*/
public static String getLogfile() {
String file = null;
Enumeration e = Logger.getRootLogger().getAllAppenders();
while (e.hasMoreElements()) {
Appender a = (Appender) e.nextElement();
if (a instanceof FileAppender && a.getName() != null && a.getName().equals("file")) {
LOG.debug("Gevonden logfile (naam): " + ((FileAppender) a).getFile());
file = ((FileAppender) a).getFile();
break;
}
}
File f = new File(file);
return f.getAbsolutePath();
}
/**
* zoek alle logfiles, ook geroteerde, op aan de hand van de basename van de
* actuele logfile.
*
* @return lijst met logfile namen incl. pad
* @see #getLogfile()
*/
public static List<String> getLogfileList() {
List<String> files = new ArrayList<>();
// opzoeken van brmo log files, de logger heeft de naam 'file' in de log4j properties
final File f = new File(getLogfile());
// filter op basename van actuele logfile zodat geroteerde files ook in de lijst komen
DirectoryStream.Filter<Path> filter = (Path p) -> (p.getFileName().toString().startsWith(FilenameUtils.getBaseName(f.getName())));
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(f.getParent()), filter)) {
for (Path path : directoryStream) {
files.add(path.toString());
}
} catch (IOException ioe) {
LOG.warn("Lijst van logfiles ophalen is mislukt.", ioe);
}
return files;
}
private LogfileUtil() {
}
}
| puckipedia/brmo | brmo-taglib/src/main/java/nl/b3p/web/jsp/LogfileUtil.java | 887 | // opzoeken van brmo log files, de logger heeft de naam 'file' in de log4j properties | line_comment | nl | /*
* Copyright (C) 2018 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.web.jsp;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
/**
*
* @author mprins
*/
public final class LogfileUtil {
private static final Log LOG = LogFactory.getLog(LogfileUtil.class);
/**
* opzoeken van log file, de logger heeft de naam 'file' in de log4j
* properties.
*
* @return volledig pad naar actuele logfile 'file', mogelijk null. Het pad
* is de string die geconfigureerd is in de log4j properties
*/
public static String getLogfile() {
String file = null;
Enumeration e = Logger.getRootLogger().getAllAppenders();
while (e.hasMoreElements()) {
Appender a = (Appender) e.nextElement();
if (a instanceof FileAppender && a.getName() != null && a.getName().equals("file")) {
LOG.debug("Gevonden logfile (naam): " + ((FileAppender) a).getFile());
file = ((FileAppender) a).getFile();
break;
}
}
File f = new File(file);
return f.getAbsolutePath();
}
/**
* zoek alle logfiles, ook geroteerde, op aan de hand van de basename van de
* actuele logfile.
*
* @return lijst met logfile namen incl. pad
* @see #getLogfile()
*/
public static List<String> getLogfileList() {
List<String> files = new ArrayList<>();
// opzoeken van<SUF>
final File f = new File(getLogfile());
// filter op basename van actuele logfile zodat geroteerde files ook in de lijst komen
DirectoryStream.Filter<Path> filter = (Path p) -> (p.getFileName().toString().startsWith(FilenameUtils.getBaseName(f.getName())));
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(f.getParent()), filter)) {
for (Path path : directoryStream) {
files.add(path.toString());
}
} catch (IOException ioe) {
LOG.warn("Lijst van logfiles ophalen is mislukt.", ioe);
}
return files;
}
private LogfileUtil() {
}
}
|
82017_4 | /**
* Created by Nav on 22-3-2015.
*/
// The Exceptions from Exceptions Package
import Exceptions.CrashException;
import Exceptions.EngineException;
import Exceptions.FlapException;
import Exceptions.PilotException;
public class Airplane {
// Create a Parts Array
static Part[] parts = new Part[9];
// Boolean to define failed or not
static boolean[] fails = new boolean[parts.length];
Airplane(){
// Een Boeing 747 heeft 4 motoren, genummerd van 1 t/m 4.
// Motor 1 en 4 zijn de buitenste motoren; Motor 2 en 3 de binnenste.
parts[0] = new Engine(); // Buitenste
parts[1] = new Engine(); // Buitenste
parts[2] = new Engine(); // Binnenste
parts[3] = new Engine(); // Binnenste
// Alleen als beide flaps uitvallen, zal het vliegtuig neerstorten.
parts[4] = new Flap();
parts[5] = new Flap();
// Alleen als alle piloten uitvallen, zal het vliegtuig neerstorten.
parts[6] = new Pilot();
parts[7] = new Pilot();
parts[8] = new Pilot();
}
static void flight(int n) throws CrashException
{
int engineNummer = 0;
int flapNummer = 0;
int pilotNummer = 0;
for (int i=0; i<parts.length; i++)
{
try
{
parts[i].calculate();
}
catch (EngineException e)
{
engineNummer++;
fails[i] = true;
}
catch (FlapException e)
{
flapNummer++;
fails[i] = true;
}
catch (PilotException e)
{
pilotNummer++;
fails[i] = true;
}
catch (Exception e){} // dummy
}
Recorder.engineFailure += engineNummer;
Recorder.flapFailure += flapNummer;
Recorder.pilotFailure += pilotNummer;
// chance for fEngine is really small (0.001^3)
// check if both inner engines failed
boolean fEngine = (engineNummer >= 3 && fails[1] && fails[2]);
if (fEngine || flapNummer == 2 || pilotNummer == 3)
{
String s = "\n\tFlight: "+n
+(engineNummer>0 ? "\n\tEngines: "+engineNummer : "")
+(flapNummer>0 ? "\n\tFlaps: "+flapNummer : "")
+(pilotNummer>0 ? "\n\tPilots: "+pilotNummer : "");
throw new CrashException(s);
}
}
}
| Nav-Appaiya/JavaAssignments | HetVliegtuig/src/Airplane.java | 679 | // Een Boeing 747 heeft 4 motoren, genummerd van 1 t/m 4. | line_comment | nl | /**
* Created by Nav on 22-3-2015.
*/
// The Exceptions from Exceptions Package
import Exceptions.CrashException;
import Exceptions.EngineException;
import Exceptions.FlapException;
import Exceptions.PilotException;
public class Airplane {
// Create a Parts Array
static Part[] parts = new Part[9];
// Boolean to define failed or not
static boolean[] fails = new boolean[parts.length];
Airplane(){
// Een Boeing<SUF>
// Motor 1 en 4 zijn de buitenste motoren; Motor 2 en 3 de binnenste.
parts[0] = new Engine(); // Buitenste
parts[1] = new Engine(); // Buitenste
parts[2] = new Engine(); // Binnenste
parts[3] = new Engine(); // Binnenste
// Alleen als beide flaps uitvallen, zal het vliegtuig neerstorten.
parts[4] = new Flap();
parts[5] = new Flap();
// Alleen als alle piloten uitvallen, zal het vliegtuig neerstorten.
parts[6] = new Pilot();
parts[7] = new Pilot();
parts[8] = new Pilot();
}
static void flight(int n) throws CrashException
{
int engineNummer = 0;
int flapNummer = 0;
int pilotNummer = 0;
for (int i=0; i<parts.length; i++)
{
try
{
parts[i].calculate();
}
catch (EngineException e)
{
engineNummer++;
fails[i] = true;
}
catch (FlapException e)
{
flapNummer++;
fails[i] = true;
}
catch (PilotException e)
{
pilotNummer++;
fails[i] = true;
}
catch (Exception e){} // dummy
}
Recorder.engineFailure += engineNummer;
Recorder.flapFailure += flapNummer;
Recorder.pilotFailure += pilotNummer;
// chance for fEngine is really small (0.001^3)
// check if both inner engines failed
boolean fEngine = (engineNummer >= 3 && fails[1] && fails[2]);
if (fEngine || flapNummer == 2 || pilotNummer == 3)
{
String s = "\n\tFlight: "+n
+(engineNummer>0 ? "\n\tEngines: "+engineNummer : "")
+(flapNummer>0 ? "\n\tFlaps: "+flapNummer : "")
+(pilotNummer>0 ? "\n\tPilots: "+pilotNummer : "");
throw new CrashException(s);
}
}
}
|
184977_44 | /**
*
*/
package net.varkhan.serv.p2p.message.transport;
import net.varkhan.base.management.report.JMXAverageMonitorReport;
import net.varkhan.serv.p2p.message.dispatch.MesgDispatcher;
import net.varkhan.serv.p2p.message.dispatch.MesgReceiver;
import net.varkhan.serv.p2p.message.dispatch.MesgSender;
import net.varkhan.serv.p2p.connect.PeerNode;
import net.varkhan.serv.p2p.message.PeerResolver;
import net.varkhan.serv.p2p.connect.PeerAddress;
import net.varkhan.serv.p2p.connect.transport.MTXAddress;
import net.varkhan.serv.p2p.message.*;
import net.varkhan.serv.p2p.message.protocol.BinaryEnvelope;
import net.varkhan.serv.p2p.message.protocol.BinaryPayload;
import net.varkhan.serv.p2p.connect.transport.UDPAddress;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.Enumeration;
/**
* <b>.</b>
* <p/>
* @author varkhan
* @date Nov 12, 2009
* @time 9:40:07 AM
*/
@SuppressWarnings( { "UnusedDeclaration" })
public class MTXTransport implements MesgTransport, MesgSender {
public static final Logger log=LogManager.getLogger(MTXTransport.class);
// Incoming packet queue size
public static final int QUEUE_SIZE =100;
// Default packet recv / send size
public static final int PACKET_SIZE =1024*16;
// Maximum data payload inside packets
public static final int MAX_DATA_SIZE=PACKET_SIZE-50;
// Maximum time spent waiting for message reception (5sec)
private static final int RECV_TIMEOUT =5000;
/** The MTX group address */
private InetAddress groupAddr;
/** The MTX group port */
private int groupPort;
private int timeout =RECV_TIMEOUT;
private int packetSize=PACKET_SIZE;
private int queueSize =QUEUE_SIZE;
private InetAddress localAddr;
protected MulticastSocket server=null;
protected PeerResolver resolver;
protected MesgDispatcher dispatcher;
protected PeerAddress local;
private JMXAverageMonitorReport stats;
private String name;
private volatile boolean run =false;
private volatile Thread thread=null;
/**
* Creates a Multicast PeerChannel, specifying incoming packet and queue size
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param queueSize the size of the packet queue
* @param packetSize the size of outgoing/incoming packets
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
int queueSize, int packetSize, JMXAverageMonitorReport stats) throws IOException {
this.resolver=resolver;
this.dispatcher=dispatcher;
this.local=localPoint;
this.stats=stats;
this.localAddr=localAddr;
this.groupAddr = groupAddr;
this.groupPort = groupPort;
if(log.isDebugEnabled()) log.debug("BIND MTX "+(localAddr==null?"0.0.0.0":localAddr.getHostAddress())+":"+groupPort);
server=new MulticastSocket(new InetSocketAddress(localAddr,groupPort));
server.setReuseAddress(true);
server.setSoTimeout(timeout);
// socket.joinGroup(groupAddr);
if(this.localAddr==null) {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
if(ifaces.hasMoreElements()) server.setNetworkInterface(ifaces.nextElement());
}
else {
// This fails because Java sucks at networking
// server.setInterface(this.localAddr);
NetworkInterface localIface = NetworkInterface.getByInetAddress(this.localAddr);
if(localIface!=null) {
server.setNetworkInterface(localIface);
}
}
setQueueSize(queueSize);
setPacketSize(packetSize);
this.name = ((server.getLocalAddress()==null)?"0.0.0.0": server.getLocalAddress().getHostAddress())+
":"+server.getLocalPort()+
"@"+localPoint.name();
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,localAddr,groupAddr,groupPort,QUEUE_SIZE,PACKET_SIZE,stats);
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,null,groupAddr,groupPort,QUEUE_SIZE, PACKET_SIZE,stats);
}
/**
* Get the size of datagram packets emitted from or received by this server
*
* @return the size of datagram packets emitted from or received by this server
*/
public int getPacketSize() {
return packetSize;
}
/**
* Set the size of datagram packets emitted from or received by this server
*
* @param size the size of datagram packets emitted from or received by this server
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setPacketSize(int size) throws SocketException {
packetSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the size of the message waiting queue
*
* @return the number of messages that can be queued in the reception buffer
*/
public int getQueueSize() {
return queueSize;
}
/**
* Set the size of the message waiting queue
*
* @param size the number of messages that can be queued in the reception buffer
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setQueueSize(int size) throws SocketException {
queueSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the message reception timeout
*
* @return the maximum number of milliseconds the exchange will wait for the reception of a single message
*/
public int getTimeout() {
return timeout;
}
/**
* Set the message reception timeout
*
* @param delay the maximum number of milliseconds the exchange will wait for the reception of a single message
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setTimeout(int delay) throws SocketException {
timeout = delay;
if(server!=null) server.setSoTimeout(timeout);
}
/**
* Gets the local listening address for this exchange
*
* @return the local address this exchange listens on
*/
public InetAddress getAddress() {
return server.getLocalAddress();
}
/**
* Gets the local listening port for this exchange
*
* @return the local port this exchange listens on
*/
public int getPort() {
return server.getLocalPort();
}
public InetAddress getGroupAddr() {
return groupAddr;
}
public int getGroupPort() {
return groupPort;
}
/**********************************************************************************
** Lifecycle management
**/
@Override
public PeerAddress endpoint() {
return new MTXAddress() {
@Override
public InetAddress addrMTXgroup() {
return groupAddr;
}
@Override
public int portMTXgroup() {
return groupPort;
}
@Override
public String name() {
return name;
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> c) {
if(c.isAssignableFrom(UDPAddress.class)) return (T) this;
return null;
}
};
}
/**
* Indicates whether the exchange is started and able to handle messages
*
* @return {@code true} if the exchange transport layer is ready to handle outgoing messages,
* and the listening thread is handling incoming messages
*/
public boolean isStarted() {
return run && thread!=null && thread.isAlive();
}
/**
* Start the exchange
*
* @throws java.io.IOException if the exchange could not bind to an address
*/
public synchronized void start() throws IOException {
if(run || (thread!=null && thread.isAlive())) return;
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": start "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
server.joinGroup(groupAddr);
thread = new Thread() {
public void run() { receive(); }
};
thread.setName(MTXTransport.class.getSimpleName()+"("+groupAddr.getHostAddress()+":"+ groupPort+")");
thread.setDaemon(true);
run = true;
thread.start();
}
/**
* Stop the exchange
*
* @throws java.io.IOException if the exchange could not free resources
*/
public synchronized void stop() throws IOException {
run = false;
Thread t=thread;
if(t==null) return;
server.leaveGroup(groupAddr);
thread = null;
t.interrupt();
try {
t.join(2*timeout);
}
catch(InterruptedException e) {
// ignore
}
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": stop "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
}
public void receive() {
DatagramPacket pakt = new DatagramPacket(new byte[packetSize], packetSize);
// Main message listening loop
while(run) {
// Waiting for reception of a message
try {
server.receive(pakt);
}
catch(SocketTimeoutException e) {
// Ignore this, as receive naturally times out because we set SO_TIMEOUT
continue;
}
catch(InterruptedIOException e) {
if(!run) return;
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" interrupted",e);
continue;
}
catch(SocketException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" protocol error",e);
continue;
}
catch(IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed", e);
continue;
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
continue;
}
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" receiving from "+pakt.getAddress().getHostAddress());
// Handle the message
try {
receive(pakt);
stats.inc(MTXTransport.class.getSimpleName()+".Recv.Success");
}
catch (IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed to read data", e);
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
}
}
}
private void receive(DatagramPacket pakt) throws IOException {// Building received message
BinaryEnvelope recv = new BinaryEnvelope(pakt.getData(), pakt.getOffset(), pakt.getLength());
String method=recv.method();
MesgPayload mesg = recv.message();
long sequence=recv.sequence();
// Passing message to the dispatcher
switch(recv.type()) {
case BinaryEnvelope.PING: {
PeerAddress remote = resolver.update(recv.srcId(),mesg);
if(sequence>=0){
// Reply immediately, with decremented ttl
ping(local, remote, method, resolver.info(), sequence-1);
}
}
break;
case BinaryEnvelope.CALL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
if(sequence<0) {
dispatcher.call(src, dst, method, mesg, null, -1, null);
}
else {
BinaryPayload repl = new BinaryPayload();
dispatcher.call(src, dst, method, mesg, repl, sequence, this);
}
}
break;
case BinaryEnvelope.REPL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
dispatcher.repl(src, dst, method, mesg, sequence);
}
break;
}
}
/**********************************************************************************
** Message transmission handling
**/
public boolean call(PeerAddress src, PeerAddress dst, String method, MesgPayload message, MesgReceiver handler) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Address.Unsupported");
return false;
}
long sequence = -1;
if(handler!=null) sequence = dispatcher.register(handler);
if(log.isDebugEnabled()) log.debug("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),"",dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Call.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Call.Success");
return true;
}
public boolean repl(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Address.Unsupported");
return false;
}
if(log.isDebugEnabled()) log.debug("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Repl.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Success");
return true;
}
public boolean ping(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotLocal");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not from local "+src.name());
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Oversize");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" oversize message "+message.getLength());
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Protocol.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to multicast "+dst.name());
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Address.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to group "+dst.name());
return false;
}
if(log.isDebugEnabled()) log.debug("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.PING, src.name(), method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Ping.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Success");
return true;
}
public void send(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
// Send reply
PeerNode node = (PeerNode)dst;
node.repl(method, message, sequence);
}
}
| varkhan/VCom4j | Serv/P2PConnect/src/net/varkhan/serv/p2p/message/transport/MTXTransport.java | 5,688 | //"+groupAddr+":"+groupPort+" oversize message "+message.getLength()); | line_comment | nl | /**
*
*/
package net.varkhan.serv.p2p.message.transport;
import net.varkhan.base.management.report.JMXAverageMonitorReport;
import net.varkhan.serv.p2p.message.dispatch.MesgDispatcher;
import net.varkhan.serv.p2p.message.dispatch.MesgReceiver;
import net.varkhan.serv.p2p.message.dispatch.MesgSender;
import net.varkhan.serv.p2p.connect.PeerNode;
import net.varkhan.serv.p2p.message.PeerResolver;
import net.varkhan.serv.p2p.connect.PeerAddress;
import net.varkhan.serv.p2p.connect.transport.MTXAddress;
import net.varkhan.serv.p2p.message.*;
import net.varkhan.serv.p2p.message.protocol.BinaryEnvelope;
import net.varkhan.serv.p2p.message.protocol.BinaryPayload;
import net.varkhan.serv.p2p.connect.transport.UDPAddress;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.Enumeration;
/**
* <b>.</b>
* <p/>
* @author varkhan
* @date Nov 12, 2009
* @time 9:40:07 AM
*/
@SuppressWarnings( { "UnusedDeclaration" })
public class MTXTransport implements MesgTransport, MesgSender {
public static final Logger log=LogManager.getLogger(MTXTransport.class);
// Incoming packet queue size
public static final int QUEUE_SIZE =100;
// Default packet recv / send size
public static final int PACKET_SIZE =1024*16;
// Maximum data payload inside packets
public static final int MAX_DATA_SIZE=PACKET_SIZE-50;
// Maximum time spent waiting for message reception (5sec)
private static final int RECV_TIMEOUT =5000;
/** The MTX group address */
private InetAddress groupAddr;
/** The MTX group port */
private int groupPort;
private int timeout =RECV_TIMEOUT;
private int packetSize=PACKET_SIZE;
private int queueSize =QUEUE_SIZE;
private InetAddress localAddr;
protected MulticastSocket server=null;
protected PeerResolver resolver;
protected MesgDispatcher dispatcher;
protected PeerAddress local;
private JMXAverageMonitorReport stats;
private String name;
private volatile boolean run =false;
private volatile Thread thread=null;
/**
* Creates a Multicast PeerChannel, specifying incoming packet and queue size
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param queueSize the size of the packet queue
* @param packetSize the size of outgoing/incoming packets
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
int queueSize, int packetSize, JMXAverageMonitorReport stats) throws IOException {
this.resolver=resolver;
this.dispatcher=dispatcher;
this.local=localPoint;
this.stats=stats;
this.localAddr=localAddr;
this.groupAddr = groupAddr;
this.groupPort = groupPort;
if(log.isDebugEnabled()) log.debug("BIND MTX "+(localAddr==null?"0.0.0.0":localAddr.getHostAddress())+":"+groupPort);
server=new MulticastSocket(new InetSocketAddress(localAddr,groupPort));
server.setReuseAddress(true);
server.setSoTimeout(timeout);
// socket.joinGroup(groupAddr);
if(this.localAddr==null) {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
if(ifaces.hasMoreElements()) server.setNetworkInterface(ifaces.nextElement());
}
else {
// This fails because Java sucks at networking
// server.setInterface(this.localAddr);
NetworkInterface localIface = NetworkInterface.getByInetAddress(this.localAddr);
if(localIface!=null) {
server.setNetworkInterface(localIface);
}
}
setQueueSize(queueSize);
setPacketSize(packetSize);
this.name = ((server.getLocalAddress()==null)?"0.0.0.0": server.getLocalAddress().getHostAddress())+
":"+server.getLocalPort()+
"@"+localPoint.name();
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param localAddr the local address to bind to (or {@code null} if any)
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress localAddr,
InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,localAddr,groupAddr,groupPort,QUEUE_SIZE,PACKET_SIZE,stats);
}
/**
* Creates a Multicast MesgChannel
*
* @param resolver the point name resolver
* @param dispatcher the message dispatcher
* @param localPoint the local point node
* @param groupAddr the multicast group address
* @param groupPort the multicast group port number
* @param stats activity statistics collector
* @throws java.net.SocketException if the UDP listening socket could not be created and bound
*/
public MTXTransport(
PeerResolver resolver, MesgDispatcher dispatcher,
PeerAddress localPoint, InetAddress groupAddr, int groupPort,
JMXAverageMonitorReport stats) throws IOException {
this(resolver,dispatcher,localPoint,null,groupAddr,groupPort,QUEUE_SIZE, PACKET_SIZE,stats);
}
/**
* Get the size of datagram packets emitted from or received by this server
*
* @return the size of datagram packets emitted from or received by this server
*/
public int getPacketSize() {
return packetSize;
}
/**
* Set the size of datagram packets emitted from or received by this server
*
* @param size the size of datagram packets emitted from or received by this server
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setPacketSize(int size) throws SocketException {
packetSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the size of the message waiting queue
*
* @return the number of messages that can be queued in the reception buffer
*/
public int getQueueSize() {
return queueSize;
}
/**
* Set the size of the message waiting queue
*
* @param size the number of messages that can be queued in the reception buffer
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setQueueSize(int size) throws SocketException {
queueSize = size;
if (server!= null) {
server.setReceiveBufferSize(packetSize * queueSize);
server.setSendBufferSize(packetSize * queueSize);
}
}
/**
* Get the message reception timeout
*
* @return the maximum number of milliseconds the exchange will wait for the reception of a single message
*/
public int getTimeout() {
return timeout;
}
/**
* Set the message reception timeout
*
* @param delay the maximum number of milliseconds the exchange will wait for the reception of a single message
* @throws java.net.SocketException if the underlying transport did not accept reconfiguration
*/
public void setTimeout(int delay) throws SocketException {
timeout = delay;
if(server!=null) server.setSoTimeout(timeout);
}
/**
* Gets the local listening address for this exchange
*
* @return the local address this exchange listens on
*/
public InetAddress getAddress() {
return server.getLocalAddress();
}
/**
* Gets the local listening port for this exchange
*
* @return the local port this exchange listens on
*/
public int getPort() {
return server.getLocalPort();
}
public InetAddress getGroupAddr() {
return groupAddr;
}
public int getGroupPort() {
return groupPort;
}
/**********************************************************************************
** Lifecycle management
**/
@Override
public PeerAddress endpoint() {
return new MTXAddress() {
@Override
public InetAddress addrMTXgroup() {
return groupAddr;
}
@Override
public int portMTXgroup() {
return groupPort;
}
@Override
public String name() {
return name;
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> c) {
if(c.isAssignableFrom(UDPAddress.class)) return (T) this;
return null;
}
};
}
/**
* Indicates whether the exchange is started and able to handle messages
*
* @return {@code true} if the exchange transport layer is ready to handle outgoing messages,
* and the listening thread is handling incoming messages
*/
public boolean isStarted() {
return run && thread!=null && thread.isAlive();
}
/**
* Start the exchange
*
* @throws java.io.IOException if the exchange could not bind to an address
*/
public synchronized void start() throws IOException {
if(run || (thread!=null && thread.isAlive())) return;
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": start "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
server.joinGroup(groupAddr);
thread = new Thread() {
public void run() { receive(); }
};
thread.setName(MTXTransport.class.getSimpleName()+"("+groupAddr.getHostAddress()+":"+ groupPort+")");
thread.setDaemon(true);
run = true;
thread.start();
}
/**
* Stop the exchange
*
* @throws java.io.IOException if the exchange could not free resources
*/
public synchronized void stop() throws IOException {
run = false;
Thread t=thread;
if(t==null) return;
server.leaveGroup(groupAddr);
thread = null;
t.interrupt();
try {
t.join(2*timeout);
}
catch(InterruptedException e) {
// ignore
}
if (log.isDebugEnabled()) {
log.debug(MTXTransport.class.getSimpleName()+": stop "+name +
"(" + getAddress().getHostAddress() + ":" + getPort() +
"@" + groupAddr.getHostAddress()+":"+ groupPort + ")");
}
}
public void receive() {
DatagramPacket pakt = new DatagramPacket(new byte[packetSize], packetSize);
// Main message listening loop
while(run) {
// Waiting for reception of a message
try {
server.receive(pakt);
}
catch(SocketTimeoutException e) {
// Ignore this, as receive naturally times out because we set SO_TIMEOUT
continue;
}
catch(InterruptedIOException e) {
if(!run) return;
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" interrupted",e);
continue;
}
catch(SocketException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" protocol error",e);
continue;
}
catch(IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if(log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed", e);
continue;
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
continue;
}
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" receiving from "+pakt.getAddress().getHostAddress());
// Handle the message
try {
receive(pakt);
stats.inc(MTXTransport.class.getSimpleName()+".Recv.Success");
}
catch (IOException e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
if (log.isDebugEnabled()) log.debug("RECV mtx://"+groupAddr+":"+groupPort+" failed to read data", e);
}
catch (Throwable e) {
stats.inc(MTXTransport.class.getSimpleName()+".Recv.error["+e.getClass().getSimpleName()+"]");
log.error("Unexpected exception", e);
}
}
}
private void receive(DatagramPacket pakt) throws IOException {// Building received message
BinaryEnvelope recv = new BinaryEnvelope(pakt.getData(), pakt.getOffset(), pakt.getLength());
String method=recv.method();
MesgPayload mesg = recv.message();
long sequence=recv.sequence();
// Passing message to the dispatcher
switch(recv.type()) {
case BinaryEnvelope.PING: {
PeerAddress remote = resolver.update(recv.srcId(),mesg);
if(sequence>=0){
// Reply immediately, with decremented ttl
ping(local, remote, method, resolver.info(), sequence-1);
}
}
break;
case BinaryEnvelope.CALL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
if(sequence<0) {
dispatcher.call(src, dst, method, mesg, null, -1, null);
}
else {
BinaryPayload repl = new BinaryPayload();
dispatcher.call(src, dst, method, mesg, repl, sequence, this);
}
}
break;
case BinaryEnvelope.REPL: {
PeerAddress src = resolver.resolve(recv.srcId());
PeerAddress dst = resolver.resolve(recv.dstId());
dispatcher.repl(src, dst, method, mesg, sequence);
}
break;
}
}
/**********************************************************************************
** Message transmission handling
**/
public boolean call(PeerAddress src, PeerAddress dst, String method, MesgPayload message, MesgReceiver handler) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Call.Address.Unsupported");
return false;
}
long sequence = -1;
if(handler!=null) sequence = dispatcher.register(handler);
if(log.isDebugEnabled()) log.debug("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),"",dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("CALL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Call.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Call.Success");
return true;
}
public boolean repl(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.NotLocal");
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Oversize");
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Protocol.Unsupported");
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Address.Unsupported");
return false;
}
if(log.isDebugEnabled()) log.debug("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.REPL, src.name(),method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("REPL mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Repl.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Repl.Success");
return true;
}
public boolean ping(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
if(!run) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotRunning");
return false;
}
// We only know how to send messages from the local addr
if(!local.equals(src)) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.NotLocal");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not from local "+src.name());
return false;
}
// We do not handle messages bigger than the packet size
if(message.getLength()>MAX_DATA_SIZE) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Oversize");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" oversize<SUF>
return false;
}
MTXAddress node = dst.as(MTXAddress.class);
if(node==null) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Protocol.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to multicast "+dst.name());
return false;
}
InetAddress addr=node.addrMTXgroup();
int port=node.portMTXgroup();
if(!groupAddr.equals(addr) || groupPort!=port) {
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Address.Unsupported");
if (log.isDebugEnabled()) log.debug("PING mtx://"+groupAddr+":"+groupPort+" not to group "+dst.name());
return false;
}
if(log.isDebugEnabled()) log.debug("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence);
BinaryEnvelope send = new BinaryEnvelope(BinaryEnvelope.PING, src.name(), method,dst.name(),sequence,message);
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
send.send(data);
byte[] buf = data.toByteArray();
server.send(new DatagramPacket(buf,0,buf.length, addr, port));
}
catch(IOException e) {
if(log.isInfoEnabled()) log.info("PING mtx://"+addr.getHostAddress()+":"+port+"/"+method+"#"+sequence+" failed", e);
stats.inc(MTXTransport.class.getSimpleName()+".Ping.error["+e.getClass().getSimpleName()+"]");
throw e;
}
stats.inc(MTXTransport.class.getSimpleName()+".Ping.Success");
return true;
}
public void send(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException {
// Send reply
PeerNode node = (PeerNode)dst;
node.repl(method, message, sequence);
}
}
|
8446_11 | import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.ImageObserver;
import java.util.Vector;
/** Ean slide
* <P>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: Slide.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: Slide.java,v 1.2 2003/11/19 Sylvia Stuurman
* @version $Id: Slide.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: Slide.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
public class Slide {
public final static int referenceWidth = 800;
public final static int referenceHeight = 600;
protected String title; // de titel wordt apart bewaard
protected Vector<SlideItem> items; // de slide-items wordne in een Vector bewaard
public Slide() {
items = new Vector<SlideItem>();
}
// Voeg een SlideItem toe
public void append(SlideItem anItem) {
items.addElement(anItem);
}
// geef de titel van de slide
public String getTitle() {
return title;
}
// verander de titel van de slide
public void setTitle(String newTitle) {
title = newTitle;
}
// Maak een TextItem van String, en voeg het TextItem toe
public void append(int level, String message) {
append(new TextItem(level, message));
}
// geef het betreffende SlideItem
public SlideItem getSlideItem(int number) {
return (SlideItem)items.elementAt(number);
}
// geef alle SlideItems in een Vector
public Vector getSlideItems() {
return items;
}
// geef de afmeting van de Slide
public int getSize() {
return items.size();
}
// teken de slide
public void draw(Graphics g, Rectangle area, ImageObserver view) {
float scale = getScale(area);
int y = area.y;
// De titel wordt apart behandeld
SlideItem slideItem = new TextItem(0, getTitle());
Style style = Style.getStyle(slideItem.getLevel());
slideItem.draw(area.x, y, scale, g, style, view);
y += slideItem.getBoundingBox(g, view, scale, style).height;
for (int number=0; number<getSize(); number++) {
slideItem = (SlideItem)getSlideItems().elementAt(number);
style = Style.getStyle(slideItem.getLevel());
slideItem.draw(area.x, y, scale, g, style, view);
y += slideItem.getBoundingBox(g, view, scale, style).height;
}
}
// geef de schaal om de slide te kunnen tekenen
private float getScale(Rectangle area) {
return Math.min(((float)area.width) / ((float)referenceWidth), ((float)area.height) / ((float)referenceHeight));
}
}
| MichielMertens/OU_JP_MM_EVB | src/Slide.java | 861 | // De titel wordt apart behandeld
| line_comment | nl | import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.ImageObserver;
import java.util.Vector;
/** Ean slide
* <P>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: Slide.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: Slide.java,v 1.2 2003/11/19 Sylvia Stuurman
* @version $Id: Slide.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: Slide.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
public class Slide {
public final static int referenceWidth = 800;
public final static int referenceHeight = 600;
protected String title; // de titel wordt apart bewaard
protected Vector<SlideItem> items; // de slide-items wordne in een Vector bewaard
public Slide() {
items = new Vector<SlideItem>();
}
// Voeg een SlideItem toe
public void append(SlideItem anItem) {
items.addElement(anItem);
}
// geef de titel van de slide
public String getTitle() {
return title;
}
// verander de titel van de slide
public void setTitle(String newTitle) {
title = newTitle;
}
// Maak een TextItem van String, en voeg het TextItem toe
public void append(int level, String message) {
append(new TextItem(level, message));
}
// geef het betreffende SlideItem
public SlideItem getSlideItem(int number) {
return (SlideItem)items.elementAt(number);
}
// geef alle SlideItems in een Vector
public Vector getSlideItems() {
return items;
}
// geef de afmeting van de Slide
public int getSize() {
return items.size();
}
// teken de slide
public void draw(Graphics g, Rectangle area, ImageObserver view) {
float scale = getScale(area);
int y = area.y;
// De titel<SUF>
SlideItem slideItem = new TextItem(0, getTitle());
Style style = Style.getStyle(slideItem.getLevel());
slideItem.draw(area.x, y, scale, g, style, view);
y += slideItem.getBoundingBox(g, view, scale, style).height;
for (int number=0; number<getSize(); number++) {
slideItem = (SlideItem)getSlideItems().elementAt(number);
style = Style.getStyle(slideItem.getLevel());
slideItem.draw(area.x, y, scale, g, style, view);
y += slideItem.getBoundingBox(g, view, scale, style).height;
}
}
// geef de schaal om de slide te kunnen tekenen
private float getScale(Rectangle area) {
return Math.min(((float)area.width) / ((float)referenceWidth), ((float)area.height) / ((float)referenceHeight));
}
}
|
97555_54 | package idlab.examples.generators;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket(maxTextMessageSize = 64 * 1024)
public class SimpleEventSocket {
private final CountDownLatch closeLatch;
@SuppressWarnings("unused")
private Session session;
public SimpleEventSocket() {
this.closeLatch = new CountDownLatch(1);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
}
@OnWebSocketConnect
public void onConnect(Session session) {
try {
System.out.println("trying to send:");
for (int i = 0; i < 10; i++) {
session.getRemote().sendString(EVENT);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String msg) {
System.out.println("received");
}
@OnWebSocketError
public void onError(Throwable cause) {
System.out.print("WebSocket Error: ");
cause.printStackTrace(System.out);
}
private static String ONT_EVENT = "<?xml version=\"1.0\"?>\n"
+ "<rdf:RDF xmlns=\"http://IBCNServices.github.io/homelabPlus.owl#\"\n"
+ " xml:base=\"http://IBCNServices.github.io/homelabPlus.owl\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:ssn=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#\"\n"
+ " xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n"
+ " <owl:Ontology rdf:about=\"http://IBCNServices.github.io/homelabPlus2.owl\">\n"
+ " <owl:imports rdf:resource=\"http://IBCNServices.github.io/homelabPlus.owl\"/>\n"
+ " </owl:Ontology>\n" + " \n" + "\n" + "\n" + " <!-- \n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " //\n" + " // Individuals\n" + " //\n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " -->\n" + "\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#lightIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#LightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#motionIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#motionIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Motion\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#soundIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#soundIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Sound\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelabPlus.owl#obs -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelabPlus.owl#obs\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#Observation\"/>\n"
+ " <ssn:observedProperty rdf:resource=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + "</rdf:RDF>";
private static String EVENT = "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
+ "@prefix td: <http://purl.org/td/transportdisruption#> .\n"
+ "@prefix dct: <http://purl.org/dc/terms/> .\n" + "@prefix gtfs: <http://vocab.gtfs.org/terms#> .\n"
+ "@prefix ex: <http://example.com/> .\n" + "\n" + "_:b12_0 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door wegenwerken rijdt lijn 6, de rit van 10.50 u. uit Oostende Station & de rit van 11.08 uur uit Raversijde Middenlaan niet\"@nl ;\n"
+ " td:factor td:RoadWorks ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> ;\n"
+ " ex:hasBusLine <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN>, <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> .\n"
+ "\n" + "_:b12_1 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle streeklijnen ernstig verstoord * Vermoedelijk hinder 14:00u tot 19.00u\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "_:b12_2 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle stadslijnen ernstig verstoord. vermoedelijke hinder tussen 12 en 20 uur\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501331\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501331\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510003\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510003\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506330\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506330\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510004\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510004\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501373\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501373\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506374\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506374\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"109744\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/109744\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN> rdf:type gtfs:Route ;\n"
+ " dct:description \"Oostende Station-Luchthaven Raversijde\"@nl .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> rdf:type gtfs:Route ;\n"
+ " dct:description \"Luchthaven via Raversijde-Oostende Station\"@nl .\n" + "\n" + "";
} | IBCNServices/StreamingMASSIF | src/main/java/idlab/examples/generators/SimpleEventSocket.java | 6,646 | //www.delijn.be/nl/haltes/halte/506330\" .\n" + "\n" | line_comment | nl | package idlab.examples.generators;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
@WebSocket(maxTextMessageSize = 64 * 1024)
public class SimpleEventSocket {
private final CountDownLatch closeLatch;
@SuppressWarnings("unused")
private Session session;
public SimpleEventSocket() {
this.closeLatch = new CountDownLatch(1);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
}
@OnWebSocketConnect
public void onConnect(Session session) {
try {
System.out.println("trying to send:");
for (int i = 0; i < 10; i++) {
session.getRemote().sendString(EVENT);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String msg) {
System.out.println("received");
}
@OnWebSocketError
public void onError(Throwable cause) {
System.out.print("WebSocket Error: ");
cause.printStackTrace(System.out);
}
private static String ONT_EVENT = "<?xml version=\"1.0\"?>\n"
+ "<rdf:RDF xmlns=\"http://IBCNServices.github.io/homelabPlus.owl#\"\n"
+ " xml:base=\"http://IBCNServices.github.io/homelabPlus.owl\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:ssn=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#\"\n"
+ " xmlns:xml=\"http://www.w3.org/XML/1998/namespace\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n"
+ " <owl:Ontology rdf:about=\"http://IBCNServices.github.io/homelabPlus2.owl\">\n"
+ " <owl:imports rdf:resource=\"http://IBCNServices.github.io/homelabPlus.owl\"/>\n"
+ " </owl:Ontology>\n" + " \n" + "\n" + "\n" + " <!-- \n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " //\n" + " // Individuals\n" + " //\n"
+ " ///////////////////////////////////////////////////////////////////////////////////////\n"
+ " -->\n" + "\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#lightIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#LightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#motionIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#motionIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Motion\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelab.owl#soundIntensity -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelab.owl#soundIntensity\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/SSNiot#Sound\"/>\n"
+ " </owl:NamedIndividual>\n" + " \n" + "\n" + "\n"
+ " <!-- http://IBCNServices.github.io/homelabPlus.owl#obs -->\n" + "\n"
+ " <owl:NamedIndividual rdf:about=\"http://IBCNServices.github.io/homelabPlus.owl#obs\">\n"
+ " <rdf:type rdf:resource=\"http://IBCNServices.github.io/Accio-Ontology/ontologies/ssn#Observation\"/>\n"
+ " <ssn:observedProperty rdf:resource=\"http://IBCNServices.github.io/homelab.owl#lightIntensity\"/>\n"
+ " </owl:NamedIndividual>\n" + "</rdf:RDF>";
private static String EVENT = "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
+ "@prefix td: <http://purl.org/td/transportdisruption#> .\n"
+ "@prefix dct: <http://purl.org/dc/terms/> .\n" + "@prefix gtfs: <http://vocab.gtfs.org/terms#> .\n"
+ "@prefix ex: <http://example.com/> .\n" + "\n" + "_:b12_0 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door wegenwerken rijdt lijn 6, de rit van 10.50 u. uit Oostende Station & de rit van 11.08 uur uit Raversijde Middenlaan niet\"@nl ;\n"
+ " td:factor td:RoadWorks ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291>, <https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> ;\n"
+ " ex:hasBusLine <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN>, <https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> .\n"
+ "\n" + "_:b12_1 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle streeklijnen ernstig verstoord * Vermoedelijk hinder 14:00u tot 19.00u\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "_:b12_2 rdf:type td:PublicTransportDiversion ;\n"
+ " dct:description \"Door weersomstandigheden is de dienstregeling van alle stadslijnen ernstig verstoord. vermoedelijke hinder tussen 12 en 20 uur\"@nl ;\n"
+ " td:factor td:BadWeather ;\n"
+ " ex:hasHalte <https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501331> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501331\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501331\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510003> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510003\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510003\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506290> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506290\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506290\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506307> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506307\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506307\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506262> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506262\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506262\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506372> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506372\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506372\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501286> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501286\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501286\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506330> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506330\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506330\" .\n"<SUF>
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506375> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506375\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506375\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/510004> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"510004\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/510004\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506326> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506326\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506326\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501373> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501373\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501373\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506300> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506300\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506300\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501289> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501289\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501289\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506345> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506345\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506345\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506374> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506374\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506374\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/506348> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"506348\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/506348\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501291> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501291\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501291\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/501337> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"501337\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/501337\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/haltes/5/109744> rdf:type gtfs:Stop ;\n"
+ " gtfs:code \"109744\" ;\n" + " foaf:page \"https://www.delijn.be/nl/haltes/halte/109744\" .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/HEEN> rdf:type gtfs:Route ;\n"
+ " dct:description \"Oostende Station-Luchthaven Raversijde\"@nl .\n" + "\n"
+ "<https://api.delijn.be/DLKernOpenData/v1/lijnen/5/906/lijnrichtingen/TERUG> rdf:type gtfs:Route ;\n"
+ " dct:description \"Luchthaven via Raversijde-Oostende Station\"@nl .\n" + "\n" + "";
} |
1699_0 | /**
* Bescherming --> look zal een beschermings voorwerp worden met sterkte nul
* maar door zijn naam toch effectief
*/
public class Bescherming extends Item
{
public Bescherming(String description, int gewicht, int sterkte)
{super(description, gewicht, sterkte);}
public String gebruik() {return "";}
public int getKrachtVerdedigingsWapen() {return getGetal();}
public int getKrachtAanvalsWapen() {return 0;}
} | bartgerard/Village_of_Zuul | Bescherming.java | 131 | /**
* Bescherming --> look zal een beschermings voorwerp worden met sterkte nul
* maar door zijn naam toch effectief
*/ | block_comment | nl | /**
* Bescherming --> look<SUF>*/
public class Bescherming extends Item
{
public Bescherming(String description, int gewicht, int sterkte)
{super(description, gewicht, sterkte);}
public String gebruik() {return "";}
public int getKrachtVerdedigingsWapen() {return getGetal();}
public int getKrachtAanvalsWapen() {return 0;}
} |
41751_4 | /*
* SpeechTendancyToken.java
* Copyright 2003 (C) Devon Jones <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package plugin.exporttokens.deprecated;
import pcgen.core.display.CharacterDisplay;
import pcgen.io.ExportHandler;
import pcgen.io.exporttoken.AbstractExportToken;
/**
* SPEECHTENDANCY token for export
*/
public class SpeechTendancyToken extends AbstractExportToken
{
/**
* @see pcgen.io.exporttoken.Token#getTokenName()
*/
@Override
public String getTokenName()
{
return "SPEECHTENDENCY";
}
//TODO: Move this to a token that has all of the descriptive stuff about a cahracter
/**
* @see pcgen.io.exporttoken.AbstractExportToken#getToken(java.lang.String, pcgen.core.display.CharacterDisplay, pcgen.io.ExportHandler)
*/
@Override
public String getToken(String tokenSource, CharacterDisplay display,
ExportHandler eh)
{
return display.getSpeechTendency();
}
}
| acidburn0zzz/pcgen | code/src/java/plugin/exporttokens/deprecated/SpeechTendancyToken.java | 455 | /**
* @see pcgen.io.exporttoken.AbstractExportToken#getToken(java.lang.String, pcgen.core.display.CharacterDisplay, pcgen.io.ExportHandler)
*/ | block_comment | nl | /*
* SpeechTendancyToken.java
* Copyright 2003 (C) Devon Jones <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package plugin.exporttokens.deprecated;
import pcgen.core.display.CharacterDisplay;
import pcgen.io.ExportHandler;
import pcgen.io.exporttoken.AbstractExportToken;
/**
* SPEECHTENDANCY token for export
*/
public class SpeechTendancyToken extends AbstractExportToken
{
/**
* @see pcgen.io.exporttoken.Token#getTokenName()
*/
@Override
public String getTokenName()
{
return "SPEECHTENDENCY";
}
//TODO: Move this to a token that has all of the descriptive stuff about a cahracter
/**
* @see pcgen.io.exporttoken.AbstractExportToken#getToken(java.lang.String, pcgen.core.display.CharacterDisplay,<SUF>*/
@Override
public String getToken(String tokenSource, CharacterDisplay display,
ExportHandler eh)
{
return display.getSpeechTendency();
}
}
|
33127_16 | package nl.mrensen.aoc.days;
import nl.mrensen.aoc.common.Day;
import org.checkerframework.checker.units.qual.A;
import java.util.*;
public class Day07 implements Day<Integer> {
int line = 0;
HashMap<String, Integer> goodDirs = new HashMap<>();
HashMap<String, Integer> allDirs = new HashMap<>();
Dir home;
Dir current;
private void parseCom(String input){
String command = input.substring(2,4).trim();
String rest = input.substring(4).trim();
// "CD /" -> Zet de "home" dir als de huidige dir.
if(command.equals("cd") && rest.equals("/")){
if(home == null){
// Set home
home = new Dir("null", null, new ArrayList<>(), new ArrayList<>());
}
current = home;
}
// "CD .." -> De parent van de huidige dir wordt de huidige dir
else if(command.equals("cd") && rest.equals("..")) {
if(current!= home) {
current = current.parent;
} else {
System.out.println("current is home: " + current);
}
}
// "CD [naam van dir]" -> De child dir met de jusite naam, wordt de huidige dir.
else if(command.equals("cd")){
Dir moveTo = null;
// Door zoek de namen van de childrenDirs en ga naar de childDir die overeen komt met de naam in het CD command
for(Dir d : current.children){
if(d.name.equals(rest)){
moveTo = d;
}
}
if(moveTo == null){
// Hier zou je niet moeten kunnen komen
throw new RuntimeException("Dir does not exist as co-sibling of parent: " + input);
}
current = moveTo;
} else if(command.equals("ls")){
}
}
private void parseDir(String input){
String[] split = input.split(" ");
String name = split[1];
createDir(name);
}
private void createDir(String name) {
// check of de parent als een dir heeft met deze naam
if(current.children.stream().noneMatch((e)->name.equals(e.getName()))){
//zo niet, maak dan deze dir aan en voeg het toe aan de children lijst van de parent.
Dir d = new Dir(name, current, new ArrayList<>(), new ArrayList<>());
current.children.add(d);
} else {
// Als het goed is kun je hier niet komen, want een LS laat alle dirs van een parent zien, geen dubbele
System.out.println("Dir already crated (should not be possible) -> line:" + lineCounter);
}
}
private void parseFile(String input){
// maak een file en voeg toe aan de parent
String[] split = input.split(" ");
Integer size = Integer.valueOf(split[0]);
String name = split[1];
File f = new File(current, size, name);
current.files.add(f);
}
private Integer getDirSize(Dir dir){
// Deze methode gebruikt recursie om de size van een dir te bepalen.
Integer size = 0;
// loop door alle child-dirs heen
for(Dir d: dir.children){
// voor elke child-dir, roep deze methode opnieuw aan.
// Returned pas tot het bij een childmap zonder eigen children komt.
size += getDirSize(d);
}
// voeg de filesizes toe aan de totale size van deze dir
size += dir.files.stream().mapToInt(e->e.size).sum();
// Als het totaal onder de 100000, voldoet het aan de eis van de opdracht.
if(size <= 100000){
if(goodDirs.containsKey(dir)){throw new RuntimeException("DOUBLE KEY IN MAP IS IMPOSSIBLE");}
// Omdat "goodDirs" een Map is, moet de key uniek zijn. Daarom voegen we een unieke identifier toe aan de dirNaam.
goodDirs.put(dir.name +"("+totalDirs+")", size);
}
allDirs.put(dir.name +"("+totalDirs+")", size); //handig voor debuggen
totalDirs ++; //handig voor debuggen
// return de size (dit is ook belangrijk voor de recursie.)
return size;
}
int lineCounter = 0;
int totalDirs = 0;
@Override
public Integer part1(List<String> input) {
// Loop door alle regels van de input heen
for(String s : input){
lineCounter ++; // handig voor debuggen
// Er zijn drie mogelijke inputs: COMMAND, DIR en FILE
if(s.startsWith("$")){
parseCom(s);
} else if(s.startsWith("dir")){
parseDir(s);
} else {
parseFile(s);
}
line++;
}
// Berekend de size van alle dirs.
getDirSize(home);
return goodDirs.values().stream().mapToInt(Integer::intValue).sum();
}
@Override
public Integer part2(List<String> input) {
// Loop nogmaals door alle regels van de input heen om de file structuur weer op te zetten
for(String s : input){
lineCounter ++; // handig voor debuggen
// Er zijn drie mogelijke inputs: COMMAND, DIR en FILE
if(s.startsWith("$")){
parseCom(s);
} else if(s.startsWith("dir")){
parseDir(s);
} else {
parseFile(s);
}
line++;
}
// Hoeveel ruimte hebben we nu gebruikt?
// Dit vult ook meteen de "allDirs" hashMap.
int currentUsedDiscSize = getDirSize(home);
// Dit zijn de waardes vanuit de opdracht
int TOTALDISCSPACE = 70000000;
int NEEDEDDISCSPACE = 30000000;
// Een lijst met alle sizes van alle dirs (we hebben de namen van dedirs niet nodig)
ArrayList<Integer> allDirSizes = new ArrayList<>(allDirs.values());
// sorteer de sizes van laag naar hoog
Collections.sort(allDirSizes);
for(int i : allDirSizes){
int freeSpace = TOTALDISCSPACE - currentUsedDiscSize + i;
if (freeSpace >= NEEDEDDISCSPACE){
// Return de eerste size die voldoende ruimte maakt
return i;
}
}
// Als er geen resultaat gevonden wordt, return je null. De test faalt dan.
return null;
}
private class File{
Dir container;
int size;
String name;
public File(Dir container, int size, String name) {
this.container = container;
this.size = size;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
File file = (File) o;
return size == file.size && Objects.equals(container, file.container) && Objects.equals(name, file.name);
}
@Override
public int hashCode() {
return Objects.hash(container.name, size, name);
}
@Override
public String toString() {
return "File{" +
"container=" + container.name +
", size=" + size +
", name='" + name +
'}';
}
}
private class Dir{
String name;
Dir parent;
List<Dir> children;
List<File> files;
public Dir(String name, Dir parent, List<Dir> children, List<File> files) {
this.name = name;
this.parent = parent;
this.children = children;
this.files = files;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dir dir = (Dir) o;
return Objects.equals(name, dir.name) && Objects.equals(parent, dir.parent) && Objects.equals(children, dir.children) && Objects.equals(files, dir.files);
}
@Override
public int hashCode() {
return Objects.hash(name, parent.name, children.size(), files.size());
}
@Override
public String toString() {
return "Dir{" +
"name='" + name + '\'' +
", parent=" + parent.name +
", children=" + children.size() +
", files=" + files.size() +
'}';
}
}
}
| MRensen/AoC22 | src/main/java/nl/mrensen/aoc/days/Day07.java | 2,177 | //handig voor debuggen | line_comment | nl | package nl.mrensen.aoc.days;
import nl.mrensen.aoc.common.Day;
import org.checkerframework.checker.units.qual.A;
import java.util.*;
public class Day07 implements Day<Integer> {
int line = 0;
HashMap<String, Integer> goodDirs = new HashMap<>();
HashMap<String, Integer> allDirs = new HashMap<>();
Dir home;
Dir current;
private void parseCom(String input){
String command = input.substring(2,4).trim();
String rest = input.substring(4).trim();
// "CD /" -> Zet de "home" dir als de huidige dir.
if(command.equals("cd") && rest.equals("/")){
if(home == null){
// Set home
home = new Dir("null", null, new ArrayList<>(), new ArrayList<>());
}
current = home;
}
// "CD .." -> De parent van de huidige dir wordt de huidige dir
else if(command.equals("cd") && rest.equals("..")) {
if(current!= home) {
current = current.parent;
} else {
System.out.println("current is home: " + current);
}
}
// "CD [naam van dir]" -> De child dir met de jusite naam, wordt de huidige dir.
else if(command.equals("cd")){
Dir moveTo = null;
// Door zoek de namen van de childrenDirs en ga naar de childDir die overeen komt met de naam in het CD command
for(Dir d : current.children){
if(d.name.equals(rest)){
moveTo = d;
}
}
if(moveTo == null){
// Hier zou je niet moeten kunnen komen
throw new RuntimeException("Dir does not exist as co-sibling of parent: " + input);
}
current = moveTo;
} else if(command.equals("ls")){
}
}
private void parseDir(String input){
String[] split = input.split(" ");
String name = split[1];
createDir(name);
}
private void createDir(String name) {
// check of de parent als een dir heeft met deze naam
if(current.children.stream().noneMatch((e)->name.equals(e.getName()))){
//zo niet, maak dan deze dir aan en voeg het toe aan de children lijst van de parent.
Dir d = new Dir(name, current, new ArrayList<>(), new ArrayList<>());
current.children.add(d);
} else {
// Als het goed is kun je hier niet komen, want een LS laat alle dirs van een parent zien, geen dubbele
System.out.println("Dir already crated (should not be possible) -> line:" + lineCounter);
}
}
private void parseFile(String input){
// maak een file en voeg toe aan de parent
String[] split = input.split(" ");
Integer size = Integer.valueOf(split[0]);
String name = split[1];
File f = new File(current, size, name);
current.files.add(f);
}
private Integer getDirSize(Dir dir){
// Deze methode gebruikt recursie om de size van een dir te bepalen.
Integer size = 0;
// loop door alle child-dirs heen
for(Dir d: dir.children){
// voor elke child-dir, roep deze methode opnieuw aan.
// Returned pas tot het bij een childmap zonder eigen children komt.
size += getDirSize(d);
}
// voeg de filesizes toe aan de totale size van deze dir
size += dir.files.stream().mapToInt(e->e.size).sum();
// Als het totaal onder de 100000, voldoet het aan de eis van de opdracht.
if(size <= 100000){
if(goodDirs.containsKey(dir)){throw new RuntimeException("DOUBLE KEY IN MAP IS IMPOSSIBLE");}
// Omdat "goodDirs" een Map is, moet de key uniek zijn. Daarom voegen we een unieke identifier toe aan de dirNaam.
goodDirs.put(dir.name +"("+totalDirs+")", size);
}
allDirs.put(dir.name +"("+totalDirs+")", size); //handig voor<SUF>
totalDirs ++; //handig voor debuggen
// return de size (dit is ook belangrijk voor de recursie.)
return size;
}
int lineCounter = 0;
int totalDirs = 0;
@Override
public Integer part1(List<String> input) {
// Loop door alle regels van de input heen
for(String s : input){
lineCounter ++; // handig voor debuggen
// Er zijn drie mogelijke inputs: COMMAND, DIR en FILE
if(s.startsWith("$")){
parseCom(s);
} else if(s.startsWith("dir")){
parseDir(s);
} else {
parseFile(s);
}
line++;
}
// Berekend de size van alle dirs.
getDirSize(home);
return goodDirs.values().stream().mapToInt(Integer::intValue).sum();
}
@Override
public Integer part2(List<String> input) {
// Loop nogmaals door alle regels van de input heen om de file structuur weer op te zetten
for(String s : input){
lineCounter ++; // handig voor debuggen
// Er zijn drie mogelijke inputs: COMMAND, DIR en FILE
if(s.startsWith("$")){
parseCom(s);
} else if(s.startsWith("dir")){
parseDir(s);
} else {
parseFile(s);
}
line++;
}
// Hoeveel ruimte hebben we nu gebruikt?
// Dit vult ook meteen de "allDirs" hashMap.
int currentUsedDiscSize = getDirSize(home);
// Dit zijn de waardes vanuit de opdracht
int TOTALDISCSPACE = 70000000;
int NEEDEDDISCSPACE = 30000000;
// Een lijst met alle sizes van alle dirs (we hebben de namen van dedirs niet nodig)
ArrayList<Integer> allDirSizes = new ArrayList<>(allDirs.values());
// sorteer de sizes van laag naar hoog
Collections.sort(allDirSizes);
for(int i : allDirSizes){
int freeSpace = TOTALDISCSPACE - currentUsedDiscSize + i;
if (freeSpace >= NEEDEDDISCSPACE){
// Return de eerste size die voldoende ruimte maakt
return i;
}
}
// Als er geen resultaat gevonden wordt, return je null. De test faalt dan.
return null;
}
private class File{
Dir container;
int size;
String name;
public File(Dir container, int size, String name) {
this.container = container;
this.size = size;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
File file = (File) o;
return size == file.size && Objects.equals(container, file.container) && Objects.equals(name, file.name);
}
@Override
public int hashCode() {
return Objects.hash(container.name, size, name);
}
@Override
public String toString() {
return "File{" +
"container=" + container.name +
", size=" + size +
", name='" + name +
'}';
}
}
private class Dir{
String name;
Dir parent;
List<Dir> children;
List<File> files;
public Dir(String name, Dir parent, List<Dir> children, List<File> files) {
this.name = name;
this.parent = parent;
this.children = children;
this.files = files;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dir dir = (Dir) o;
return Objects.equals(name, dir.name) && Objects.equals(parent, dir.parent) && Objects.equals(children, dir.children) && Objects.equals(files, dir.files);
}
@Override
public int hashCode() {
return Objects.hash(name, parent.name, children.size(), files.size());
}
@Override
public String toString() {
return "Dir{" +
"name='" + name + '\'' +
", parent=" + parent.name +
", children=" + children.size() +
", files=" + files.size() +
'}';
}
}
}
|
15319_13 | /*
* Gemaakt door: Twan
* Aangepast door: Jasper
* Functie: DatabaseManager zorgt voor de communicatie met de server. Dit zorgt ervoor dat er buiten de databasemanger niet met queries gewerkt hoeft te worden.
* De databasemanger zet data om naar java objecten en kan ook een rij in de database updaten aan de hand van bepaalde objecten.
*/
package TZTBackOffice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseManager {
private HashMap<Integer, Locatie> locaties;
private String url;
private String username, password;
private HashMap<Integer, Contact> contactHashmap;
private HashMap<Integer, Probleem> problemen;
private ArrayList<UitbetalingsVerzoek> uitbetalingsVerzoeken;
private ArrayList<TrajectProbleem> bezorgProblemen;
private ArrayList<Klacht> klachten;
private ArrayList<Pakket> pakketten;
private ArrayList<Contact> contactArray;
private HashMap<String, Integer> types;
private Traject vorigTraject;
// Aangemeld, verzonden, gearriveerd
public DatabaseManager() {
//Zet de url, username en password voor de server
url = "jdbc:mysql://localhost:3307/mydb";
username = "root";
password = "usbw";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
haalDataOp();
}
public ArrayList<Contact> getContacten() {
return contactArray;
}
public ArrayList<UitbetalingsVerzoek> getUitbetalingsVerzoeken() {
return uitbetalingsVerzoeken;
}
public ArrayList<TrajectProbleem> getBezorgProblemen() {
return bezorgProblemen;
}
public ArrayList<Klacht> getKlachten() {
return klachten;
}
public HashMap<Integer, Contact> getContactMap(){
return contactHashmap;
}
public Pakket getPakket(int pakketID) {
for (Pakket pakket : pakketten) {
if (pakket.getPakketID() == pakketID) {
return pakket;
}
}
return null;
}
//Geeft een array van alle pakketten.
public ArrayList<Pakket> getPakketten() {
return pakketten;
}
public void voegKoeriersdienstToe(Contact contact1) {
//Voeg een koeriersdienst toe in de database
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
contactArray.add(0, contact1);
contactHashmap.put(contact1.getContactID(), contact1);
//Insert statement maken
String query = " INSERT INTO stakeholder (stakeholderID, type, naam, achternaam, emailadres, telefoonnr, idkaart, ovkaart, krediet, wachtwoord, locatie, snelheid, rekeningnr)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setNull(1, java.sql.Types.INTEGER);
preparedStmt.setInt(2, 4);
preparedStmt.setString(3, contact1.getNaam());
preparedStmt.setNull(4, java.sql.Types.VARCHAR);
preparedStmt.setString(5, contact1.getEmail());
preparedStmt.setString(6, contact1.getTelefoonnr());
preparedStmt.setNull(7, java.sql.Types.VARCHAR);
preparedStmt.setNull(8, java.sql.Types.VARCHAR);
preparedStmt.setNull(9, java.sql.Types.DOUBLE);
preparedStmt.setNull(10, java.sql.Types.VARCHAR);
preparedStmt.setNull(11, java.sql.Types.INTEGER);
preparedStmt.setNull(12, java.sql.Types.DOUBLE);
preparedStmt.setNull(13, java.sql.Types.VARCHAR);
//Voer preparedstatement uit
preparedStmt.execute();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie voegKoeriersdienstToe");
System.out.println(e);
}
}
//Maakt een traject object aan met behulp van gegevens uit de resultset.
private void maakTraject(Pakket p, ResultSet r) throws SQLException {
//Maak traject
//t.trajectID, afhaaltijd, aflevertijd, r.beginlocatie, r.eindlocatie, r.koerierID, pr1.probleemID, pr2.probleemID
int trajectID = r.getInt("t.trajectID");
int geclaimd = r.getInt("geclaimd");
if (trajectID != 0 && geclaimd > 0) {
int koerierID = r.getInt("r.koerierID");
if(koerierID == 0){
System.out.println("KoerierID " + geclaimd);
koerierID = geclaimd;
}
if (vorigTraject == null || vorigTraject.getTrajectID() != trajectID) {
Timestamp afhaaltijd = r.getTimestamp("afhaaltijd");
Timestamp aflevertijd = r.getTimestamp("aflevertijd");
Locatie beginLocatie = locaties.get(r.getInt("r.beginlocatie"));
Locatie eindLocatie = locaties.get(r.getInt("r.eindlocatie"));
Contact koerier = contactHashmap.get(koerierID);
vorigTraject = new Traject(trajectID, afhaaltijd, aflevertijd, koerier, beginLocatie, eindLocatie);
p.voegTrajectToe(vorigTraject);
}
int probleemID = r.getInt("pr1.probleemID");
if (probleemID != 0) {
TrajectProbleem trajectProbleem = (TrajectProbleem) problemen.get(probleemID);
trajectProbleem.setBezorging(vorigTraject);
}
}
}
public void voegTariefToe(Tarief tarief1) {
//Voeg tarief toe in de database
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
//Insert statement maken
String query = " INSERT INTO tarief (koeriersID, km, prijs, extraprijs)" + " values (?, ?, ?, ?)";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(1, tarief1.getKoeriersDienst().getContactID());
preparedStmt.setInt(2, tarief1.getKm());
preparedStmt.setDouble(3, tarief1.getPrijs());
preparedStmt.setDouble(4, tarief1.getExtraPrijs());
//Voer preparedstatement uit
preparedStmt.execute();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie voegTariefToe");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateContact(Contact contact) {
//Update de gegevens van een contact
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String typenaam = contact.getType();
int typeID = types.get(typenaam);
int contactID = contact.getContactID();
String naam = contact.getNaam();
String telefoon = contact.getTelefoonnr();
if (contact instanceof KoeriersDienst) {
//Update statement maken
String query = " UPDATE stakeholder SET naam = ?, telefoonnr = ?, type = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, telefoon);
preparedStmt.setInt(3, typeID);
preparedStmt.setInt(4, contact.getContactID());
//Voer preparedstatement uit
preparedStmt.executeUpdate();
} else if (contact instanceof AccountHouder) {
AccountHouder account = (AccountHouder) contact;
String achternaam = account.getAchternaam();
if (contact instanceof TreinKoerier) {
TreinKoerier koerier = (TreinKoerier) contact;
double krediet = koerier.getKrediet();
String rekeningnr = koerier.getRekeningnr();
String query = "UPDATE stakeholder SET naam = ?, achternaam = ?, telefoonnr = ?, type = ?, rekeningnr = ?, krediet = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, achternaam);
preparedStmt.setString(3, telefoon);
preparedStmt.setInt(4, typeID);
preparedStmt.setString(5, rekeningnr);
preparedStmt.setDouble(6, krediet);
preparedStmt.setInt(7, contact.getContactID());
preparedStmt.executeUpdate();
} else {
String query = "UPDATE stakeholder SET naam = ?, achternaam = ?, telefoonnr = ?, type = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, achternaam);
preparedStmt.setString(3, telefoon);
preparedStmt.setInt(4, typeID);
preparedStmt.setInt(5, contact.getContactID());
preparedStmt.executeUpdate();
}
}
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateContact");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateUitbetalingsVerzoek(UitbetalingsVerzoek verzoek) {
//Update de gegevens van uitbetalingsverzoek
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
boolean afgehandeld = verzoek.isAfgehandeld();
boolean goedgekeurd = verzoek.isGoedgekeurd();
int treinkoeriersID = verzoek.getKoerier().getContactID();
Timestamp datum = verzoek.getDatum();
//Update statement maken
String query = " UPDATE kredietomzetting SET isafgehandeld = ?, goedgekeurd = ? WHERE treinkoerier = ? AND datum = ? ";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setBoolean(1, afgehandeld);
preparedStmt.setBoolean(2, goedgekeurd);
preparedStmt.setInt(3, treinkoeriersID);
preparedStmt.setTimestamp(4, datum);
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateUitbetalingsVerzoek");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
//verwijdert een stakeholder uit de database die dezelfde ID heeft als contact
public void verwijderContact(Contact contact) {
//Update de gegevens van uitbetalingsverzoek
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
int contactID = contact.getContactID();
//Update statement maken
String query = " DELETE FROM stakeholder WHERE stakeholderID = ? ";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(1, contactID);
contactHashmap.remove(contactID);
contactArray.remove(contact);
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan bij het verwijderen van contact");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateLocatie(AccountHouder a) {
//Update de locatie gegevens
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
//Dit moet allemaal geupdate worden
// a.setNaam(strNaam);
// a.setAchternaam(strAchternaam);
// a.setTelefoonnr(strTelefoonnummer);
// a.getLocatie().setPlaats(strWoonplaats);
// a.getLocatie().setPostcode(strPostcode);
// a.getLocatie().setStraat(strStraat);
// a.getLocatie().setHuisnummer(strHuisnummer);
// type
//Update statement maken
String query = " UPDATE locatie SET straat = ?, huisnummer = ?, plaats = ?, postcode = ? WHERE locatienr = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, a.getLocatie().getStraat());
preparedStmt.setString(2, a.getLocatie().getHuisnummer());
preparedStmt.setString(3, a.getLocatie().getPlaats());
preparedStmt.setString(4, a.getLocatie().getPostcode());
preparedStmt.setInt(5, a.getLocatie().getLocatieID());
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateLocatie");
System.out.println(e);
}
}
//Maakt nieuwe pakketten aan met behulp van gegevens uit de order en resultset.
//Bijbehorende trajecten worden ook aangemaakt.
private void maakPakket(VerzendOrder order, ResultSet r) throws SQLException {
//Maak pakket
int pakketID = r.getInt("p.pakketID");
if (pakketID == 0) {
return;
}
Pakket pakket;
if (pakketten.isEmpty() || pakketten.get(pakketten.size() - 1).getPakketID() != pakketID) {
Double gewicht = r.getDouble("gewicht");
String formaat = r.getString("formaat");
String opmerking = r.getString("opmerking");
String status = r.getString("status");
pakket = new Pakket(pakketID, gewicht, formaat, order, opmerking, status);
pakketten.add(pakket);
maakTraject(pakket, r);
} else {
pakket = pakketten.get(pakketten.size() - 1);
maakTraject(pakket, r);
}
int probleemID = r.getInt("pr2.probleemID");
if (probleemID != 0) {
Klacht klacht = (Klacht) problemen.get(probleemID);
klacht.setPakket(pakket);
}
}
public void maakTarief(KoeriersDienst koeriersDienst, ResultSet rs) throws SQLException {
//Maak tarief
int km = rs.getInt("km");
Double prijs = rs.getDouble("prijs");
if (prijs == 0) {
return;
}
Double extraPrijs = rs.getDouble("extraPrijs");
Tarief tarief = new Tarief(koeriersDienst, km, prijs, extraPrijs);
koeriersDienst.voegTariefToe(tarief);
}
//Haalt pakketten op uit de database en vult de array pakket objecten;
public void haalDataOp() {
//Haal de data op uit de database
Connection connection = null;
Statement statement;
vorigTraject = null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
if (username.equals("root")) {
url = "jdbc:mysql://karsbarendrecht.nl:3306/karsbaj97_tzt";
username = "karsbaj97_tzt";
password = "wtj01";
System.out.println("Kan geen verbinding maken met USBwebserver. In plaats daarvan wordt er nu geprobeerd om verbinding te maken met de live database op karsbarendrecht.nl");
haalDataOp();
} else {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
return;
}
pakketten = new ArrayList();
bezorgProblemen = new ArrayList();
uitbetalingsVerzoeken = new ArrayList();
contactArray = new ArrayList();
klachten = new ArrayList();
contactHashmap = new HashMap();
locaties = new HashMap();
problemen = new HashMap();
types = new HashMap();
//Indien er een werkende connectie is worden de queries uitgevoerd en worden er objecten aangemaakt.
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT locatienr, straat, huisnummer, plaats, postcode FROM locatie");
while (rs.next()) {
int id = rs.getInt(1);
String straat = rs.getString(2);
String huisnummer = rs.getString(3);
String plaats = rs.getString(4);
String postcode = rs.getString(5);
Locatie locatie = new Locatie(id, straat, huisnummer, plaats, postcode);
locaties.put(id, locatie);
}
rs = statement.executeQuery("SELECT probleemID, beschrijving, datum, titel, afgehandeld, pakketID, trajectID FROM probleem");
while (rs.next()) {
int probleemID = rs.getInt("probleemID");
String beschrijving = rs.getString("beschrijving");
Timestamp datum = rs.getTimestamp("datum");
String titel = rs.getString("titel");
boolean afgehandeld = rs.getBoolean("afgehandeld");
int trajectID = rs.getInt("trajectID");
Probleem probleem;
if (trajectID == 0) {
Klacht klacht = new Klacht(probleemID, titel, beschrijving, datum, afgehandeld);
klachten.add(klacht);
probleem = klacht;
} else {
TrajectProbleem bezorgprobleem = new TrajectProbleem(probleemID, titel, beschrijving, datum, afgehandeld);
bezorgProblemen.add(bezorgprobleem);
probleem = bezorgprobleem;
}
problemen.put(probleemID, probleem);
}
rs = statement.executeQuery("SELECT stakeholderID, s.type, (SELECT typenaam FROM stakeholdertype ty WHERE ty.typeID = s.type) typenaam ,naam, achternaam, emailadres, telefoonnr, idkaart, ovkaart, krediet\n"
+ ", locatie, rekeningnr, km, prijs, extraprijs FROM stakeholder s\n"
+ "LEFT OUTER JOIN tarief t ON stakeholderID = koeriersID\n"
+ "ORDER BY stakeholderID DESC;");
int contactID = 0;
while (rs.next()) {
int newContactID = rs.getInt(1);
String typenaam = rs.getString("typenaam");
int typeID = rs.getInt("s.type");
if (!types.containsKey(typeID)) {
types.put(typenaam, typeID);
}
if (newContactID != contactID) {
Contact contact;
contactID = newContactID;
String naam = rs.getString("naam");
String email = rs.getString("emailadres");
String telefoonnr = rs.getString("telefoonnr");
if ("gebruiker".equals(typenaam) || "geverifieerd".equals(typenaam)) {
String achternaam = rs.getString("achternaam");
Locatie locatie = locaties.get(rs.getInt("locatie"));
String rekeningnr = rs.getString("rekeningnr");
AccountHouder klant;
if ("geverifieerd".equals(typenaam)) {
Double krediet = rs.getDouble("krediet");
TreinKoerier koerier = new TreinKoerier(krediet, rekeningnr, naam, typenaam, email, telefoonnr, contactID, achternaam, locatie);
klant = koerier;
} else {
String ovkaart = rs.getString("ovkaart");
String idkaart = rs.getString("idkaart");
klant = new AccountHouder(naam, typenaam, email, telefoonnr, contactID, achternaam, locatie, ovkaart, idkaart, rekeningnr);
}
contact = klant;
} else {
KoeriersDienst koeriersDienst = new KoeriersDienst(naam, typenaam, email, telefoonnr, contactID);
maakTarief(koeriersDienst, rs);
contact = koeriersDienst;
}
contactHashmap.put(contact.getContactID(), contact);
contactArray.add(contact);
} else if (!"gebruiker".equals(typenaam) || "geverifieerd".equals(typenaam)) {
try {
KoeriersDienst koeriersDienst = (KoeriersDienst) contactArray.get(contactArray.size() - 1);
maakTarief(koeriersDienst, rs);
} catch (ClassCastException ex) {
}
}
}
rs = statement.executeQuery("SELECT v.orderID, v.klantID, definitief, aanmeldtijd, v.beginlocatie, v.eindlocatie, p.pakketID, gewicht, formaat, opmerking, status\n"
+ ", t.trajectID, afhaaltijd, aflevertijd, geclaimd, r.beginlocatie, r.eindlocatie, r.koerierID, pr1.probleemID, pr2.probleemID FROM verzendorder v\n"
+ "LEFT OUTER JOIN pakket p ON v.orderID = p.orderID\n"
+ "LEFT OUTER JOIN traject t ON p.pakketID = t.pakketID\n"
+ "LEFT OUTER JOIN reis r ON t.reisID = r.reisID\n"
+ "LEFT OUTER JOIN probleem pr1 ON pr1.trajectID = t.trajectID\n"
+ "LEFT OUTER JOIN probleem pr2 ON pr2.pakketID = p.pakketID ORDER BY v.orderID DESC, pakketID DESC, trajectID ASC;");
while (rs.next()) {
int orderID = rs.getInt("v.orderID");
boolean definitief = rs.getBoolean("definitief");
//Check of er een definitieve order is die nog niet is toegevoegd.
if (definitief) {
if (pakketten.isEmpty() || (orderID != pakketten.get(pakketten.size() - 1).getOrder().getOrderID())) {
int klantID = rs.getInt("v.klantID");
AccountHouder klant = (AccountHouder) contactHashmap.get(klantID);
Timestamp aanmeldTijd = rs.getTimestamp("aanmeldtijd");
Locatie beginLocatie = locaties.get(rs.getInt("v.beginlocatie"));
Locatie eindLocatie = locaties.get(rs.getInt("v.eindlocatie"));
VerzendOrder order = new VerzendOrder(klant, aanmeldTijd, orderID, beginLocatie, eindLocatie);
maakPakket(order, rs);
} else {
VerzendOrder order = pakketten.get(pakketten.size() - 1).getOrder();
maakPakket(order, rs);
}
}
}
rs = statement.executeQuery("SELECT treinkoerier, datum, bedrag, isafgehandeld, goedgekeurd FROM kredietomzetting ORDER BY datum DESC");
while (rs.next()) {
TreinKoerier treinKoerier = (TreinKoerier) contactHashmap.get(rs.getInt("treinkoerier"));
Timestamp datum = rs.getTimestamp("datum");
Double bedrag = rs.getDouble("bedrag");
Boolean isafgehandeld = rs.getBoolean("isafgehandeld");
Boolean goedgekeurd = rs.getBoolean("goedgekeurd");
UitbetalingsVerzoek verzoek = new UitbetalingsVerzoek(datum, bedrag, isafgehandeld, treinKoerier, goedgekeurd);
uitbetalingsVerzoeken.add(verzoek);
}
statement.close();
connection.close();
} catch (SQLException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
}
}
}
}
| TNvGelder/ProjectTZTperiode4 | JAVA/src/TZTBackOffice/DatabaseManager.java | 6,469 | //Probeer de statement uit te voeren | line_comment | nl | /*
* Gemaakt door: Twan
* Aangepast door: Jasper
* Functie: DatabaseManager zorgt voor de communicatie met de server. Dit zorgt ervoor dat er buiten de databasemanger niet met queries gewerkt hoeft te worden.
* De databasemanger zet data om naar java objecten en kan ook een rij in de database updaten aan de hand van bepaalde objecten.
*/
package TZTBackOffice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseManager {
private HashMap<Integer, Locatie> locaties;
private String url;
private String username, password;
private HashMap<Integer, Contact> contactHashmap;
private HashMap<Integer, Probleem> problemen;
private ArrayList<UitbetalingsVerzoek> uitbetalingsVerzoeken;
private ArrayList<TrajectProbleem> bezorgProblemen;
private ArrayList<Klacht> klachten;
private ArrayList<Pakket> pakketten;
private ArrayList<Contact> contactArray;
private HashMap<String, Integer> types;
private Traject vorigTraject;
// Aangemeld, verzonden, gearriveerd
public DatabaseManager() {
//Zet de url, username en password voor de server
url = "jdbc:mysql://localhost:3307/mydb";
username = "root";
password = "usbw";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
haalDataOp();
}
public ArrayList<Contact> getContacten() {
return contactArray;
}
public ArrayList<UitbetalingsVerzoek> getUitbetalingsVerzoeken() {
return uitbetalingsVerzoeken;
}
public ArrayList<TrajectProbleem> getBezorgProblemen() {
return bezorgProblemen;
}
public ArrayList<Klacht> getKlachten() {
return klachten;
}
public HashMap<Integer, Contact> getContactMap(){
return contactHashmap;
}
public Pakket getPakket(int pakketID) {
for (Pakket pakket : pakketten) {
if (pakket.getPakketID() == pakketID) {
return pakket;
}
}
return null;
}
//Geeft een array van alle pakketten.
public ArrayList<Pakket> getPakketten() {
return pakketten;
}
public void voegKoeriersdienstToe(Contact contact1) {
//Voeg een koeriersdienst toe in de database
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
contactArray.add(0, contact1);
contactHashmap.put(contact1.getContactID(), contact1);
//Insert statement maken
String query = " INSERT INTO stakeholder (stakeholderID, type, naam, achternaam, emailadres, telefoonnr, idkaart, ovkaart, krediet, wachtwoord, locatie, snelheid, rekeningnr)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setNull(1, java.sql.Types.INTEGER);
preparedStmt.setInt(2, 4);
preparedStmt.setString(3, contact1.getNaam());
preparedStmt.setNull(4, java.sql.Types.VARCHAR);
preparedStmt.setString(5, contact1.getEmail());
preparedStmt.setString(6, contact1.getTelefoonnr());
preparedStmt.setNull(7, java.sql.Types.VARCHAR);
preparedStmt.setNull(8, java.sql.Types.VARCHAR);
preparedStmt.setNull(9, java.sql.Types.DOUBLE);
preparedStmt.setNull(10, java.sql.Types.VARCHAR);
preparedStmt.setNull(11, java.sql.Types.INTEGER);
preparedStmt.setNull(12, java.sql.Types.DOUBLE);
preparedStmt.setNull(13, java.sql.Types.VARCHAR);
//Voer preparedstatement uit
preparedStmt.execute();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie voegKoeriersdienstToe");
System.out.println(e);
}
}
//Maakt een traject object aan met behulp van gegevens uit de resultset.
private void maakTraject(Pakket p, ResultSet r) throws SQLException {
//Maak traject
//t.trajectID, afhaaltijd, aflevertijd, r.beginlocatie, r.eindlocatie, r.koerierID, pr1.probleemID, pr2.probleemID
int trajectID = r.getInt("t.trajectID");
int geclaimd = r.getInt("geclaimd");
if (trajectID != 0 && geclaimd > 0) {
int koerierID = r.getInt("r.koerierID");
if(koerierID == 0){
System.out.println("KoerierID " + geclaimd);
koerierID = geclaimd;
}
if (vorigTraject == null || vorigTraject.getTrajectID() != trajectID) {
Timestamp afhaaltijd = r.getTimestamp("afhaaltijd");
Timestamp aflevertijd = r.getTimestamp("aflevertijd");
Locatie beginLocatie = locaties.get(r.getInt("r.beginlocatie"));
Locatie eindLocatie = locaties.get(r.getInt("r.eindlocatie"));
Contact koerier = contactHashmap.get(koerierID);
vorigTraject = new Traject(trajectID, afhaaltijd, aflevertijd, koerier, beginLocatie, eindLocatie);
p.voegTrajectToe(vorigTraject);
}
int probleemID = r.getInt("pr1.probleemID");
if (probleemID != 0) {
TrajectProbleem trajectProbleem = (TrajectProbleem) problemen.get(probleemID);
trajectProbleem.setBezorging(vorigTraject);
}
}
}
public void voegTariefToe(Tarief tarief1) {
//Voeg tarief toe in de database
Connection connection = null;
Statement statement;
//Probeer de<SUF>
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
//Insert statement maken
String query = " INSERT INTO tarief (koeriersID, km, prijs, extraprijs)" + " values (?, ?, ?, ?)";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(1, tarief1.getKoeriersDienst().getContactID());
preparedStmt.setInt(2, tarief1.getKm());
preparedStmt.setDouble(3, tarief1.getPrijs());
preparedStmt.setDouble(4, tarief1.getExtraPrijs());
//Voer preparedstatement uit
preparedStmt.execute();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie voegTariefToe");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateContact(Contact contact) {
//Update de gegevens van een contact
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String typenaam = contact.getType();
int typeID = types.get(typenaam);
int contactID = contact.getContactID();
String naam = contact.getNaam();
String telefoon = contact.getTelefoonnr();
if (contact instanceof KoeriersDienst) {
//Update statement maken
String query = " UPDATE stakeholder SET naam = ?, telefoonnr = ?, type = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, telefoon);
preparedStmt.setInt(3, typeID);
preparedStmt.setInt(4, contact.getContactID());
//Voer preparedstatement uit
preparedStmt.executeUpdate();
} else if (contact instanceof AccountHouder) {
AccountHouder account = (AccountHouder) contact;
String achternaam = account.getAchternaam();
if (contact instanceof TreinKoerier) {
TreinKoerier koerier = (TreinKoerier) contact;
double krediet = koerier.getKrediet();
String rekeningnr = koerier.getRekeningnr();
String query = "UPDATE stakeholder SET naam = ?, achternaam = ?, telefoonnr = ?, type = ?, rekeningnr = ?, krediet = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, achternaam);
preparedStmt.setString(3, telefoon);
preparedStmt.setInt(4, typeID);
preparedStmt.setString(5, rekeningnr);
preparedStmt.setDouble(6, krediet);
preparedStmt.setInt(7, contact.getContactID());
preparedStmt.executeUpdate();
} else {
String query = "UPDATE stakeholder SET naam = ?, achternaam = ?, telefoonnr = ?, type = ? WHERE stakeholderID = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, naam);
preparedStmt.setString(2, achternaam);
preparedStmt.setString(3, telefoon);
preparedStmt.setInt(4, typeID);
preparedStmt.setInt(5, contact.getContactID());
preparedStmt.executeUpdate();
}
}
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateContact");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateUitbetalingsVerzoek(UitbetalingsVerzoek verzoek) {
//Update de gegevens van uitbetalingsverzoek
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
boolean afgehandeld = verzoek.isAfgehandeld();
boolean goedgekeurd = verzoek.isGoedgekeurd();
int treinkoeriersID = verzoek.getKoerier().getContactID();
Timestamp datum = verzoek.getDatum();
//Update statement maken
String query = " UPDATE kredietomzetting SET isafgehandeld = ?, goedgekeurd = ? WHERE treinkoerier = ? AND datum = ? ";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setBoolean(1, afgehandeld);
preparedStmt.setBoolean(2, goedgekeurd);
preparedStmt.setInt(3, treinkoeriersID);
preparedStmt.setTimestamp(4, datum);
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateUitbetalingsVerzoek");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
//verwijdert een stakeholder uit de database die dezelfde ID heeft als contact
public void verwijderContact(Contact contact) {
//Update de gegevens van uitbetalingsverzoek
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
int contactID = contact.getContactID();
//Update statement maken
String query = " DELETE FROM stakeholder WHERE stakeholderID = ? ";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(1, contactID);
contactHashmap.remove(contactID);
contactArray.remove(contact);
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan bij het verwijderen van contact");
Logger.getLogger("").log(Level.SEVERE, null, e);
}
}
public void updateLocatie(AccountHouder a) {
//Update de locatie gegevens
Connection connection = null;
Statement statement;
//Probeer de statement uit te voeren
try {
//Maak connectie met DB
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
//Dit moet allemaal geupdate worden
// a.setNaam(strNaam);
// a.setAchternaam(strAchternaam);
// a.setTelefoonnr(strTelefoonnummer);
// a.getLocatie().setPlaats(strWoonplaats);
// a.getLocatie().setPostcode(strPostcode);
// a.getLocatie().setStraat(strStraat);
// a.getLocatie().setHuisnummer(strHuisnummer);
// type
//Update statement maken
String query = " UPDATE locatie SET straat = ?, huisnummer = ?, plaats = ?, postcode = ? WHERE locatienr = ?";
//Preparedstatement maken
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, a.getLocatie().getStraat());
preparedStmt.setString(2, a.getLocatie().getHuisnummer());
preparedStmt.setString(3, a.getLocatie().getPlaats());
preparedStmt.setString(4, a.getLocatie().getPostcode());
preparedStmt.setInt(5, a.getLocatie().getLocatieID());
//Voer preparedstatement uit
preparedStmt.executeUpdate();
//Sluit connectie
connection.close();
} catch (Exception e) {
//Als de connectie of statement een error opleverd
System.out.println("Er is iets misgegaan met de functie updateLocatie");
System.out.println(e);
}
}
//Maakt nieuwe pakketten aan met behulp van gegevens uit de order en resultset.
//Bijbehorende trajecten worden ook aangemaakt.
private void maakPakket(VerzendOrder order, ResultSet r) throws SQLException {
//Maak pakket
int pakketID = r.getInt("p.pakketID");
if (pakketID == 0) {
return;
}
Pakket pakket;
if (pakketten.isEmpty() || pakketten.get(pakketten.size() - 1).getPakketID() != pakketID) {
Double gewicht = r.getDouble("gewicht");
String formaat = r.getString("formaat");
String opmerking = r.getString("opmerking");
String status = r.getString("status");
pakket = new Pakket(pakketID, gewicht, formaat, order, opmerking, status);
pakketten.add(pakket);
maakTraject(pakket, r);
} else {
pakket = pakketten.get(pakketten.size() - 1);
maakTraject(pakket, r);
}
int probleemID = r.getInt("pr2.probleemID");
if (probleemID != 0) {
Klacht klacht = (Klacht) problemen.get(probleemID);
klacht.setPakket(pakket);
}
}
public void maakTarief(KoeriersDienst koeriersDienst, ResultSet rs) throws SQLException {
//Maak tarief
int km = rs.getInt("km");
Double prijs = rs.getDouble("prijs");
if (prijs == 0) {
return;
}
Double extraPrijs = rs.getDouble("extraPrijs");
Tarief tarief = new Tarief(koeriersDienst, km, prijs, extraPrijs);
koeriersDienst.voegTariefToe(tarief);
}
//Haalt pakketten op uit de database en vult de array pakket objecten;
public void haalDataOp() {
//Haal de data op uit de database
Connection connection = null;
Statement statement;
vorigTraject = null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
if (username.equals("root")) {
url = "jdbc:mysql://karsbarendrecht.nl:3306/karsbaj97_tzt";
username = "karsbaj97_tzt";
password = "wtj01";
System.out.println("Kan geen verbinding maken met USBwebserver. In plaats daarvan wordt er nu geprobeerd om verbinding te maken met de live database op karsbarendrecht.nl");
haalDataOp();
} else {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
return;
}
pakketten = new ArrayList();
bezorgProblemen = new ArrayList();
uitbetalingsVerzoeken = new ArrayList();
contactArray = new ArrayList();
klachten = new ArrayList();
contactHashmap = new HashMap();
locaties = new HashMap();
problemen = new HashMap();
types = new HashMap();
//Indien er een werkende connectie is worden de queries uitgevoerd en worden er objecten aangemaakt.
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT locatienr, straat, huisnummer, plaats, postcode FROM locatie");
while (rs.next()) {
int id = rs.getInt(1);
String straat = rs.getString(2);
String huisnummer = rs.getString(3);
String plaats = rs.getString(4);
String postcode = rs.getString(5);
Locatie locatie = new Locatie(id, straat, huisnummer, plaats, postcode);
locaties.put(id, locatie);
}
rs = statement.executeQuery("SELECT probleemID, beschrijving, datum, titel, afgehandeld, pakketID, trajectID FROM probleem");
while (rs.next()) {
int probleemID = rs.getInt("probleemID");
String beschrijving = rs.getString("beschrijving");
Timestamp datum = rs.getTimestamp("datum");
String titel = rs.getString("titel");
boolean afgehandeld = rs.getBoolean("afgehandeld");
int trajectID = rs.getInt("trajectID");
Probleem probleem;
if (trajectID == 0) {
Klacht klacht = new Klacht(probleemID, titel, beschrijving, datum, afgehandeld);
klachten.add(klacht);
probleem = klacht;
} else {
TrajectProbleem bezorgprobleem = new TrajectProbleem(probleemID, titel, beschrijving, datum, afgehandeld);
bezorgProblemen.add(bezorgprobleem);
probleem = bezorgprobleem;
}
problemen.put(probleemID, probleem);
}
rs = statement.executeQuery("SELECT stakeholderID, s.type, (SELECT typenaam FROM stakeholdertype ty WHERE ty.typeID = s.type) typenaam ,naam, achternaam, emailadres, telefoonnr, idkaart, ovkaart, krediet\n"
+ ", locatie, rekeningnr, km, prijs, extraprijs FROM stakeholder s\n"
+ "LEFT OUTER JOIN tarief t ON stakeholderID = koeriersID\n"
+ "ORDER BY stakeholderID DESC;");
int contactID = 0;
while (rs.next()) {
int newContactID = rs.getInt(1);
String typenaam = rs.getString("typenaam");
int typeID = rs.getInt("s.type");
if (!types.containsKey(typeID)) {
types.put(typenaam, typeID);
}
if (newContactID != contactID) {
Contact contact;
contactID = newContactID;
String naam = rs.getString("naam");
String email = rs.getString("emailadres");
String telefoonnr = rs.getString("telefoonnr");
if ("gebruiker".equals(typenaam) || "geverifieerd".equals(typenaam)) {
String achternaam = rs.getString("achternaam");
Locatie locatie = locaties.get(rs.getInt("locatie"));
String rekeningnr = rs.getString("rekeningnr");
AccountHouder klant;
if ("geverifieerd".equals(typenaam)) {
Double krediet = rs.getDouble("krediet");
TreinKoerier koerier = new TreinKoerier(krediet, rekeningnr, naam, typenaam, email, telefoonnr, contactID, achternaam, locatie);
klant = koerier;
} else {
String ovkaart = rs.getString("ovkaart");
String idkaart = rs.getString("idkaart");
klant = new AccountHouder(naam, typenaam, email, telefoonnr, contactID, achternaam, locatie, ovkaart, idkaart, rekeningnr);
}
contact = klant;
} else {
KoeriersDienst koeriersDienst = new KoeriersDienst(naam, typenaam, email, telefoonnr, contactID);
maakTarief(koeriersDienst, rs);
contact = koeriersDienst;
}
contactHashmap.put(contact.getContactID(), contact);
contactArray.add(contact);
} else if (!"gebruiker".equals(typenaam) || "geverifieerd".equals(typenaam)) {
try {
KoeriersDienst koeriersDienst = (KoeriersDienst) contactArray.get(contactArray.size() - 1);
maakTarief(koeriersDienst, rs);
} catch (ClassCastException ex) {
}
}
}
rs = statement.executeQuery("SELECT v.orderID, v.klantID, definitief, aanmeldtijd, v.beginlocatie, v.eindlocatie, p.pakketID, gewicht, formaat, opmerking, status\n"
+ ", t.trajectID, afhaaltijd, aflevertijd, geclaimd, r.beginlocatie, r.eindlocatie, r.koerierID, pr1.probleemID, pr2.probleemID FROM verzendorder v\n"
+ "LEFT OUTER JOIN pakket p ON v.orderID = p.orderID\n"
+ "LEFT OUTER JOIN traject t ON p.pakketID = t.pakketID\n"
+ "LEFT OUTER JOIN reis r ON t.reisID = r.reisID\n"
+ "LEFT OUTER JOIN probleem pr1 ON pr1.trajectID = t.trajectID\n"
+ "LEFT OUTER JOIN probleem pr2 ON pr2.pakketID = p.pakketID ORDER BY v.orderID DESC, pakketID DESC, trajectID ASC;");
while (rs.next()) {
int orderID = rs.getInt("v.orderID");
boolean definitief = rs.getBoolean("definitief");
//Check of er een definitieve order is die nog niet is toegevoegd.
if (definitief) {
if (pakketten.isEmpty() || (orderID != pakketten.get(pakketten.size() - 1).getOrder().getOrderID())) {
int klantID = rs.getInt("v.klantID");
AccountHouder klant = (AccountHouder) contactHashmap.get(klantID);
Timestamp aanmeldTijd = rs.getTimestamp("aanmeldtijd");
Locatie beginLocatie = locaties.get(rs.getInt("v.beginlocatie"));
Locatie eindLocatie = locaties.get(rs.getInt("v.eindlocatie"));
VerzendOrder order = new VerzendOrder(klant, aanmeldTijd, orderID, beginLocatie, eindLocatie);
maakPakket(order, rs);
} else {
VerzendOrder order = pakketten.get(pakketten.size() - 1).getOrder();
maakPakket(order, rs);
}
}
}
rs = statement.executeQuery("SELECT treinkoerier, datum, bedrag, isafgehandeld, goedgekeurd FROM kredietomzetting ORDER BY datum DESC");
while (rs.next()) {
TreinKoerier treinKoerier = (TreinKoerier) contactHashmap.get(rs.getInt("treinkoerier"));
Timestamp datum = rs.getTimestamp("datum");
Double bedrag = rs.getDouble("bedrag");
Boolean isafgehandeld = rs.getBoolean("isafgehandeld");
Boolean goedgekeurd = rs.getBoolean("goedgekeurd");
UitbetalingsVerzoek verzoek = new UitbetalingsVerzoek(datum, bedrag, isafgehandeld, treinKoerier, goedgekeurd);
uitbetalingsVerzoeken.add(verzoek);
}
statement.close();
connection.close();
} catch (SQLException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger("").log(Level.SEVERE, null, ex);
}
}
}
}
}
|
123394_0 | package kermis;
public class Mueslikraam extends Voedselkraam {
//Constructor waarbij naam, ervaring en prijs gelijk hiervoor worden ingevuld
Mueslikraam(){
setNaam("Mueslikraam ");
setErvaring("Bijzonder om een keer muesli op een kermis te hebben gegeten.");
setPrijs(9.00);
}
}//einde class
| jaseterhaar/Kermis | src/kermis/Mueslikraam.java | 98 | //Constructor waarbij naam, ervaring en prijs gelijk hiervoor worden ingevuld | line_comment | nl | package kermis;
public class Mueslikraam extends Voedselkraam {
//Constructor waarbij<SUF>
Mueslikraam(){
setNaam("Mueslikraam ");
setErvaring("Bijzonder om een keer muesli op een kermis te hebben gegeten.");
setPrijs(9.00);
}
}//einde class
|
63256_14 | /*
* Created on Dec 24, 2004
*
*/
package nl.fountain.xelem.expat;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import junit.framework.TestCase;
import nl.fountain.xelem.XSerializer;
import nl.fountain.xelem.XelemException;
import nl.fountain.xelem.excel.Cell;
import nl.fountain.xelem.excel.Row;
import nl.fountain.xelem.excel.XLElement;
import nl.fountain.xelem.excel.ss.SSCell;
import nl.fountain.xelem.excel.ss.SSRow;
/**
*
*/
public class XLDocumentTest extends TestCase {
// the path to the directory for test files.
private String testOutputDir = "testoutput/XLDocumentTest/";
// when set to true, test files will be created.
// the path mentioned after 'testOutputDir' should exist.
private boolean toFile = true;
private String templateFile;
public static void main(String[] args) {
junit.textui.TestRunner.run(XLDocumentTest.class);
}
@Override
public void setUp() {
templateFile = "testsuitefiles/XLDocumentTest/aviso.xml";
}
public void testAdvise() {
if (toFile) {
System.out.println();
System.out.println(this.getClass() + " is writing files to: " + testOutputDir);
}
}
public void testConstructor() {
try {
new XLDocument("this/file/does/not/exist");
fail("geen exceptie gegooid.");
}
catch (XelemException e) {
assertEquals("java.io.FileNotFoundException", e.getCause().getClass().getName());
}
try {
XLDocument xldoc = new XLDocument(templateFile);
assertNotNull(xldoc.getDocument());
}
catch (XelemException e1) {
fail(e1.getMessage());
}
}
public void testGetTable() throws Exception {
XLDocument xldoc = new XLDocument(templateFile);
Node table = xldoc.getTableElement("Sheet1");
assertNotNull(table);
try {
table.getAttributes().removeNamedItemNS(XLElement.XMLNS_SS, "ExpandedColumnCount");
fail("should have thrown exception.");
}
catch (DOMException e) {
//
}
try {
table.getAttributes().removeNamedItemNS(XLElement.XMLNS_SS, "ExpandedRowCount");
fail("should have thrown exception.");
}
catch (DOMException e) {
//
}
try {
xldoc.getTableElement("nosheetwiththisname");
fail("should have thrown exception.");
}
catch (RuntimeException e1) {
assertEquals("The worksheet 'nosheetwiththisname' does not exist.", e1.getMessage());
}
}
public void testAppendRow() throws Exception {
Row row = new SSRow();
row.addCell("419900");
row.addCell("wk 43, piet 45,8 u.");
row.addCell("002020");
row.addCell(-12345.67);
XLDocument xldoc = new XLDocument(templateFile);
// XLDocument xldoc = new XLDocument("D:/test/book2.xml");
xldoc.appendRow("Sheet1", row);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
// System.out.println(xml);
String expected = "<Data ss:Type=\"Number\">-12345.67</Data>";
assertTrue(xml.indexOf(expected) > 0);
if (toFile) serialize(doc, testOutputDir + "aviso01.xls");
}
public void testAppendRows() throws Exception {
Collection<Row> rows = new ArrayList<Row>();
Row row = new SSRow();
row.addCell("501000");
row.addCell("wk 02, Claude 5,8 u.");
row.addCell("123456");
row.addCell(45.67);
rows.add(row);
row = new SSRow();
row.addCell("551000");
row.addCell("wk 02, Claude voor 123456 5,8 u.");
row.addCell("002020");
row.addCell(-45.67);
rows.add(row);
XLDocument xldoc = new XLDocument(templateFile);
xldoc.appendRows("Sheet1", rows);
Cell cell = new SSCell();
cell.setData(new Date());
xldoc.setCellData(cell, "Sheet1", 7, 2);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
// System.out.println(xml);
String expected = "<Data ss:Type=\"Number\">-45.67</Data>";
assertTrue(xml.indexOf(expected) > 0);
expected = "<Data ss:Type=\"String\">wk 02, Claude voor 123456 5,8 u.</Data>";
assertTrue(xml.indexOf(expected) > 0);
if (toFile) serialize(doc, testOutputDir + "aviso02.xls");
}
public void testSetCellData() throws Exception {
XLDocument xldoc = new XLDocument(templateFile);
Cell cell = new SSCell();
cell.setData("nieuw gegeven");
xldoc.setCellData(cell, "Sheet1", 1, 2);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
String expected = "<Data ss:Type=\"String\">nieuw gegeven</Data>";
assertTrue(xml.indexOf(expected) > 0);
// System.out.println(xml);
}
// public void testSetCellDataSpeed() throws Exception {
// XLDocument xldoc = new XLDocument(templateFile);
// Cell cell = new SSCell();
// int itters = 1000;
// long start = System.currentTimeMillis();
// for (int i = 1; i <= itters; i++) {
// cell.setData(i);
// xldoc.setCellData(cell, "Sheet2", i, 1);
// }
// long timeXLDoc = System.currentTimeMillis() - start;
// Workbook wb = new XLWorkbook("timetest");
// Worksheet sheet = wb.addSheet();
// start = System.currentTimeMillis();
// for (int i = 1; i <= itters; i++) {
// sheet.addCell(i);
// sheet.getCellPointer().moveCRLF();
// }
// long timeXelem = System.currentTimeMillis() - start;
// System.out.println();
// System.out.println("setCellData: " + timeXLDoc + " ms.");
// System.out.println("addCell : " + timeXelem + " ms.");
// }
public void testPivotWithNamedRange() throws Exception {
if (toFile) {
Collection<Row> rows = getData();
String template = "testsuitefiles/XLDocumentTest/prices0.xml";
XLDocument xlDoc = new XLDocument(template);
Cell cel = new SSCell();
cel.setData("created on " + new Date());
xlDoc.setCellData(cel, "average prices", 1, 5);
xlDoc.appendRows("data", rows);
String fileName = "prices_nr.xls";
xlDoc.setPTSourceFileName(fileName);
serialize(xlDoc.getDocument(), testOutputDir + fileName);
}
}
public void testPivotWithRange() throws Exception {
String template = "testsuitefiles/XLDocumentTest/prices1.1.xml";
XLDocument xlDoc = new XLDocument(template);
Collection<Row> rows = getData();
Cell cel = new SSCell();
cel.setData("created on " + new Date());
xlDoc.setCellData(cel, "prices", 1, 1);
xlDoc.appendRows("Sheet1", rows);
String fileName = "prices r.xls";
assertEquals(1, xlDoc.setPTSourceFileName(fileName, "Sheet1"));
xlDoc.setPTSourceReference(1, 1, rows.size() + 1, 5);
if (toFile) {
serialize(xlDoc.getDocument(), testOutputDir + fileName);
}
}
public void testPivot() {
Object[][] data = { { "blue", "A", "Star", new Double(2.95), new Double(55.6) },
{ "red", "A", "Planet", new Double(3.10), new Double(123.5) },
{ "green", "C", "Star", new Double(3.21), new Double(20.356) },
{ "green", "B", "Star", new Double(4.23), new Double(456) },
{ "red", "B", "Planet", new Double(4.21), new Double(789) },
{ "blue", "D", "Planet", new Double(4.51), new Double(9.6) },
{ "yellow", "A", "Commet", new Double(4.15), new Double(19.8) } };
// set up a collection of rows and populate them with data.
// your data will probably be collected in a more sophisticated way.
Collection<Row> rows = new ArrayList<Row>();
for (int r = 0; r < data.length; r++) {
Row row = new SSRow();
for (int c = 0; c < data[r].length; c++) {
row.addCell(data[r][c]);
}
rows.add(row);
}
OutputStream out;
try {
// create the XLDocument
XLDocument xlDoc = new XLDocument("testsuitefiles/XLDocumentTest/prices0.xml");
// append the rows to the sheet 'data'
xlDoc.appendRows("data", rows);
// this will be the new filename
String fileName = "prices.xls";
// we'll change the FileName-element to reflect our new filename
xlDoc.setPTSourceFileName(fileName, "data");
// we'll change the Reference-element to reflect
// the size of the new source table
xlDoc.setPTSourceReference(1, 1, rows.size() + 1, 5);
// output the new file
out = new BufferedOutputStream(new FileOutputStream(testOutputDir + fileName));
new XSerializer().serialize(xlDoc.getDocument(), out);
out.close();
}
catch (XelemException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private Collection<Row> getData() {
// Object[][] data = {
// {"koffie", "java", "Sun", new Double(2.95), new Double(55.6)},
// {"koffie", "arabica", "Sun", new Double(3.10), new Double(123.5)},
// {"thee", "ceylon", "Sun", new Double(3.21), new Double(20.356)},
// {"soep", "tomaten", "Moon", new Double(4.23), new Double(456)},
// {"soep", "groente", "Moon", new Double(4.21), new Double(789)},
// {"soep", "ossestaart", "Moon", new Double(4.51), new Double(9.6)}
// };
Object[][] data = { { "blue", "A", "Star", new Double(2.95), new Double(55.6) },
{ "red", "A", "Planet", new Double(3.10), new Double(123.5) },
{ "green", "C", "Star", new Double(3.21), new Double(20.356) },
{ "green", "B", "Star", new Double(4.23), new Double(456) },
{ "red", "B", "Planet", new Double(4.21), new Double(789) },
{ "blue", "D", "Planet", new Double(4.51), new Double(9.6) },
{ "yellow", "A", "Commet", new Double(4.15), new Double(19.8) } };
Collection<Row> rows = new ArrayList<Row>();
for (int r = 0; r < data.length; r++) {
Row row = new SSRow();
for (int c = 0; c < data[r].length; c++) {
row.addCell(data[r][c]);
}
rows.add(row);
}
return rows;
}
private void serialize(Document doc, String fileName) throws Exception {
OutputStream out = new FileOutputStream(fileName);
serialize(doc, out);
out.close();
}
private String serialize(Document doc) throws Exception {
XSerializer xs = new XSerializer(XSerializer.US_ASCII);
StringWriter sw = new StringWriter();
xs.serialize(doc, sw);
return sw.toString();
}
private void serialize(Document doc, OutputStream out) throws Exception {
XSerializer xs = new XSerializer(XSerializer.US_ASCII);
xs.serialize(doc, out);
}
}
| bellmit/framework-10 | src/main/java/nl/fountain/xelem/expat/XLDocumentTest.java | 3,521 | // Worksheet sheet = wb.addSheet();
| line_comment | nl | /*
* Created on Dec 24, 2004
*
*/
package nl.fountain.xelem.expat;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import junit.framework.TestCase;
import nl.fountain.xelem.XSerializer;
import nl.fountain.xelem.XelemException;
import nl.fountain.xelem.excel.Cell;
import nl.fountain.xelem.excel.Row;
import nl.fountain.xelem.excel.XLElement;
import nl.fountain.xelem.excel.ss.SSCell;
import nl.fountain.xelem.excel.ss.SSRow;
/**
*
*/
public class XLDocumentTest extends TestCase {
// the path to the directory for test files.
private String testOutputDir = "testoutput/XLDocumentTest/";
// when set to true, test files will be created.
// the path mentioned after 'testOutputDir' should exist.
private boolean toFile = true;
private String templateFile;
public static void main(String[] args) {
junit.textui.TestRunner.run(XLDocumentTest.class);
}
@Override
public void setUp() {
templateFile = "testsuitefiles/XLDocumentTest/aviso.xml";
}
public void testAdvise() {
if (toFile) {
System.out.println();
System.out.println(this.getClass() + " is writing files to: " + testOutputDir);
}
}
public void testConstructor() {
try {
new XLDocument("this/file/does/not/exist");
fail("geen exceptie gegooid.");
}
catch (XelemException e) {
assertEquals("java.io.FileNotFoundException", e.getCause().getClass().getName());
}
try {
XLDocument xldoc = new XLDocument(templateFile);
assertNotNull(xldoc.getDocument());
}
catch (XelemException e1) {
fail(e1.getMessage());
}
}
public void testGetTable() throws Exception {
XLDocument xldoc = new XLDocument(templateFile);
Node table = xldoc.getTableElement("Sheet1");
assertNotNull(table);
try {
table.getAttributes().removeNamedItemNS(XLElement.XMLNS_SS, "ExpandedColumnCount");
fail("should have thrown exception.");
}
catch (DOMException e) {
//
}
try {
table.getAttributes().removeNamedItemNS(XLElement.XMLNS_SS, "ExpandedRowCount");
fail("should have thrown exception.");
}
catch (DOMException e) {
//
}
try {
xldoc.getTableElement("nosheetwiththisname");
fail("should have thrown exception.");
}
catch (RuntimeException e1) {
assertEquals("The worksheet 'nosheetwiththisname' does not exist.", e1.getMessage());
}
}
public void testAppendRow() throws Exception {
Row row = new SSRow();
row.addCell("419900");
row.addCell("wk 43, piet 45,8 u.");
row.addCell("002020");
row.addCell(-12345.67);
XLDocument xldoc = new XLDocument(templateFile);
// XLDocument xldoc = new XLDocument("D:/test/book2.xml");
xldoc.appendRow("Sheet1", row);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
// System.out.println(xml);
String expected = "<Data ss:Type=\"Number\">-12345.67</Data>";
assertTrue(xml.indexOf(expected) > 0);
if (toFile) serialize(doc, testOutputDir + "aviso01.xls");
}
public void testAppendRows() throws Exception {
Collection<Row> rows = new ArrayList<Row>();
Row row = new SSRow();
row.addCell("501000");
row.addCell("wk 02, Claude 5,8 u.");
row.addCell("123456");
row.addCell(45.67);
rows.add(row);
row = new SSRow();
row.addCell("551000");
row.addCell("wk 02, Claude voor 123456 5,8 u.");
row.addCell("002020");
row.addCell(-45.67);
rows.add(row);
XLDocument xldoc = new XLDocument(templateFile);
xldoc.appendRows("Sheet1", rows);
Cell cell = new SSCell();
cell.setData(new Date());
xldoc.setCellData(cell, "Sheet1", 7, 2);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
// System.out.println(xml);
String expected = "<Data ss:Type=\"Number\">-45.67</Data>";
assertTrue(xml.indexOf(expected) > 0);
expected = "<Data ss:Type=\"String\">wk 02, Claude voor 123456 5,8 u.</Data>";
assertTrue(xml.indexOf(expected) > 0);
if (toFile) serialize(doc, testOutputDir + "aviso02.xls");
}
public void testSetCellData() throws Exception {
XLDocument xldoc = new XLDocument(templateFile);
Cell cell = new SSCell();
cell.setData("nieuw gegeven");
xldoc.setCellData(cell, "Sheet1", 1, 2);
Document doc = xldoc.getDocument();
String xml = serialize(doc);
String expected = "<Data ss:Type=\"String\">nieuw gegeven</Data>";
assertTrue(xml.indexOf(expected) > 0);
// System.out.println(xml);
}
// public void testSetCellDataSpeed() throws Exception {
// XLDocument xldoc = new XLDocument(templateFile);
// Cell cell = new SSCell();
// int itters = 1000;
// long start = System.currentTimeMillis();
// for (int i = 1; i <= itters; i++) {
// cell.setData(i);
// xldoc.setCellData(cell, "Sheet2", i, 1);
// }
// long timeXLDoc = System.currentTimeMillis() - start;
// Workbook wb = new XLWorkbook("timetest");
// Worksheet sheet<SUF>
// start = System.currentTimeMillis();
// for (int i = 1; i <= itters; i++) {
// sheet.addCell(i);
// sheet.getCellPointer().moveCRLF();
// }
// long timeXelem = System.currentTimeMillis() - start;
// System.out.println();
// System.out.println("setCellData: " + timeXLDoc + " ms.");
// System.out.println("addCell : " + timeXelem + " ms.");
// }
public void testPivotWithNamedRange() throws Exception {
if (toFile) {
Collection<Row> rows = getData();
String template = "testsuitefiles/XLDocumentTest/prices0.xml";
XLDocument xlDoc = new XLDocument(template);
Cell cel = new SSCell();
cel.setData("created on " + new Date());
xlDoc.setCellData(cel, "average prices", 1, 5);
xlDoc.appendRows("data", rows);
String fileName = "prices_nr.xls";
xlDoc.setPTSourceFileName(fileName);
serialize(xlDoc.getDocument(), testOutputDir + fileName);
}
}
public void testPivotWithRange() throws Exception {
String template = "testsuitefiles/XLDocumentTest/prices1.1.xml";
XLDocument xlDoc = new XLDocument(template);
Collection<Row> rows = getData();
Cell cel = new SSCell();
cel.setData("created on " + new Date());
xlDoc.setCellData(cel, "prices", 1, 1);
xlDoc.appendRows("Sheet1", rows);
String fileName = "prices r.xls";
assertEquals(1, xlDoc.setPTSourceFileName(fileName, "Sheet1"));
xlDoc.setPTSourceReference(1, 1, rows.size() + 1, 5);
if (toFile) {
serialize(xlDoc.getDocument(), testOutputDir + fileName);
}
}
public void testPivot() {
Object[][] data = { { "blue", "A", "Star", new Double(2.95), new Double(55.6) },
{ "red", "A", "Planet", new Double(3.10), new Double(123.5) },
{ "green", "C", "Star", new Double(3.21), new Double(20.356) },
{ "green", "B", "Star", new Double(4.23), new Double(456) },
{ "red", "B", "Planet", new Double(4.21), new Double(789) },
{ "blue", "D", "Planet", new Double(4.51), new Double(9.6) },
{ "yellow", "A", "Commet", new Double(4.15), new Double(19.8) } };
// set up a collection of rows and populate them with data.
// your data will probably be collected in a more sophisticated way.
Collection<Row> rows = new ArrayList<Row>();
for (int r = 0; r < data.length; r++) {
Row row = new SSRow();
for (int c = 0; c < data[r].length; c++) {
row.addCell(data[r][c]);
}
rows.add(row);
}
OutputStream out;
try {
// create the XLDocument
XLDocument xlDoc = new XLDocument("testsuitefiles/XLDocumentTest/prices0.xml");
// append the rows to the sheet 'data'
xlDoc.appendRows("data", rows);
// this will be the new filename
String fileName = "prices.xls";
// we'll change the FileName-element to reflect our new filename
xlDoc.setPTSourceFileName(fileName, "data");
// we'll change the Reference-element to reflect
// the size of the new source table
xlDoc.setPTSourceReference(1, 1, rows.size() + 1, 5);
// output the new file
out = new BufferedOutputStream(new FileOutputStream(testOutputDir + fileName));
new XSerializer().serialize(xlDoc.getDocument(), out);
out.close();
}
catch (XelemException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private Collection<Row> getData() {
// Object[][] data = {
// {"koffie", "java", "Sun", new Double(2.95), new Double(55.6)},
// {"koffie", "arabica", "Sun", new Double(3.10), new Double(123.5)},
// {"thee", "ceylon", "Sun", new Double(3.21), new Double(20.356)},
// {"soep", "tomaten", "Moon", new Double(4.23), new Double(456)},
// {"soep", "groente", "Moon", new Double(4.21), new Double(789)},
// {"soep", "ossestaart", "Moon", new Double(4.51), new Double(9.6)}
// };
Object[][] data = { { "blue", "A", "Star", new Double(2.95), new Double(55.6) },
{ "red", "A", "Planet", new Double(3.10), new Double(123.5) },
{ "green", "C", "Star", new Double(3.21), new Double(20.356) },
{ "green", "B", "Star", new Double(4.23), new Double(456) },
{ "red", "B", "Planet", new Double(4.21), new Double(789) },
{ "blue", "D", "Planet", new Double(4.51), new Double(9.6) },
{ "yellow", "A", "Commet", new Double(4.15), new Double(19.8) } };
Collection<Row> rows = new ArrayList<Row>();
for (int r = 0; r < data.length; r++) {
Row row = new SSRow();
for (int c = 0; c < data[r].length; c++) {
row.addCell(data[r][c]);
}
rows.add(row);
}
return rows;
}
private void serialize(Document doc, String fileName) throws Exception {
OutputStream out = new FileOutputStream(fileName);
serialize(doc, out);
out.close();
}
private String serialize(Document doc) throws Exception {
XSerializer xs = new XSerializer(XSerializer.US_ASCII);
StringWriter sw = new StringWriter();
xs.serialize(doc, sw);
return sw.toString();
}
private void serialize(Document doc, OutputStream out) throws Exception {
XSerializer xs = new XSerializer(XSerializer.US_ASCII);
xs.serialize(doc, out);
}
}
|
47470_13 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api;
import java.util.Objects;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.transform.IdentityTransform;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG;
import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties;
/**
* Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not
* changed.
*/
public final class JsonNewReportEncoder {
private static MathTransform transform;
private JsonNewReportEncoder() {
// Private constructor to avoid instantiation
}
public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) {
LatLon reportLatLon = reportLatLon(report.getLatLon());
JsonObjectBuilder result = Json.createObjectBuilder();
Objects.requireNonNull(report);
result.add("type", "FeatureCollection");
result.add("name", "TerugmeldingGeneriek");
result
.add("crs", Json.createObjectBuilder()
.add("type", "name")
.add("properties", Json.createObjectBuilder()
.add("name", "urn:ogc:def:crs:EPSG::28992")));
result.add(
"features", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "Feature")
.addAll(getReport(report))
.add("geometry", Json.createObjectBuilder()
.add("type", "Point")
.add("coordinates", Json.createArrayBuilder()
.add(reportLatLon.getX())
.add(reportLatLon.getY())
)
)
)
);
return result;
}
private static JsonObjectBuilder getReport(ReportNewBAG report) {
JsonObjectBuilder result = Json.createObjectBuilder();
JsonObjectBuilder properties = Json.createObjectBuilder();
properties.add("registratie", report.getBaseRegistration());
// Verplicht. Keuze uit BGT,BAG,BRT of KLIC
// properties.add("product", ...);
// Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of
// TOP1000, anders veld weglaten.
properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString());
// Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt.
properties.add("omschrijving", report.getDescription());
// Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt
// openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters.
// properties.add("objectId", "");
// Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("objectType", "");
// Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment
// alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("klicmeldnummer", )
// Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC,
// anders veld weglaten.
// properties.add("EigenVeld2", "");
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC.
if (ReportProperties.USER_EMAIL.isSet()) {
properties.add("email", ReportProperties.USER_EMAIL.get());
// Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen.
// NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd."
}
if (!ReportProperties.USER_ORGANISATION.get().isEmpty())
{
properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get());
// Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra
// informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen.
}
// final JsonArrayBuilder bagChanges = Json.createArrayBuilder();
// for (File file : report.getFile) {
// bagChanges.add(encodeBAGChanges(img));
// }
result.add("properties", properties);
return result;
}
/**
* Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992.
*
* @param osmLatLon
* the {@link LatLon} containing coordinate in EPSG:4326
* @return the encoded {@link LatLon} coordinate in EPSG:28992.
*/
public static LatLon reportLatLon(LatLon osmLatLon) {
final double[] result = {osmLatLon.getX(), osmLatLon.getY()};
if (transform == null)
{
transform = IdentityTransform.create(2);
try {
CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326");
CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true);
transform = CRS.findMathTransform(osmCrs, crsReport);
} catch (FactoryException e) {
throw new UnsupportedOperationException(e);
}
}
try {
transform.transform(result, 0, result, 0, 1);
} catch (TransformException e) {
throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e);
}
return new LatLon(result[1], result[0]); // swap coordinated???
}
}
| SanderH/josm-nl-report | src/main/java/org/openstreetmap/josm/plugins/nl_pdok_report/utils/api/JsonNewReportEncoder.java | 1,725 | // Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC, | line_comment | nl | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api;
import java.util.Objects;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.transform.IdentityTransform;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG;
import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties;
/**
* Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not
* changed.
*/
public final class JsonNewReportEncoder {
private static MathTransform transform;
private JsonNewReportEncoder() {
// Private constructor to avoid instantiation
}
public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) {
LatLon reportLatLon = reportLatLon(report.getLatLon());
JsonObjectBuilder result = Json.createObjectBuilder();
Objects.requireNonNull(report);
result.add("type", "FeatureCollection");
result.add("name", "TerugmeldingGeneriek");
result
.add("crs", Json.createObjectBuilder()
.add("type", "name")
.add("properties", Json.createObjectBuilder()
.add("name", "urn:ogc:def:crs:EPSG::28992")));
result.add(
"features", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "Feature")
.addAll(getReport(report))
.add("geometry", Json.createObjectBuilder()
.add("type", "Point")
.add("coordinates", Json.createArrayBuilder()
.add(reportLatLon.getX())
.add(reportLatLon.getY())
)
)
)
);
return result;
}
private static JsonObjectBuilder getReport(ReportNewBAG report) {
JsonObjectBuilder result = Json.createObjectBuilder();
JsonObjectBuilder properties = Json.createObjectBuilder();
properties.add("registratie", report.getBaseRegistration());
// Verplicht. Keuze uit BGT,BAG,BRT of KLIC
// properties.add("product", ...);
// Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of
// TOP1000, anders veld weglaten.
properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString());
// Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt.
properties.add("omschrijving", report.getDescription());
// Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt
// openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters.
// properties.add("objectId", "");
// Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("objectType", "");
// Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment
// alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("klicmeldnummer", )
// Verplicht bij<SUF>
// anders veld weglaten.
// properties.add("EigenVeld2", "");
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC.
if (ReportProperties.USER_EMAIL.isSet()) {
properties.add("email", ReportProperties.USER_EMAIL.get());
// Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen.
// NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd."
}
if (!ReportProperties.USER_ORGANISATION.get().isEmpty())
{
properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get());
// Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra
// informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen.
}
// final JsonArrayBuilder bagChanges = Json.createArrayBuilder();
// for (File file : report.getFile) {
// bagChanges.add(encodeBAGChanges(img));
// }
result.add("properties", properties);
return result;
}
/**
* Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992.
*
* @param osmLatLon
* the {@link LatLon} containing coordinate in EPSG:4326
* @return the encoded {@link LatLon} coordinate in EPSG:28992.
*/
public static LatLon reportLatLon(LatLon osmLatLon) {
final double[] result = {osmLatLon.getX(), osmLatLon.getY()};
if (transform == null)
{
transform = IdentityTransform.create(2);
try {
CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326");
CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true);
transform = CRS.findMathTransform(osmCrs, crsReport);
} catch (FactoryException e) {
throw new UnsupportedOperationException(e);
}
}
try {
transform.transform(result, 0, result, 0, 1);
} catch (TransformException e) {
throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e);
}
return new LatLon(result[1], result[0]); // swap coordinated???
}
}
|
86981_1 | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.AnimatedSpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
/**
* @author Ralph Niels
* Een zwaardvis is een spelobject dat zelfstandig
* door de wereld beweegt
*/
public class Swordfish extends SpriteObject {
private WaterWorld world;
/**
* Constructor
* @param world Referentie naar de wereld
*/
public Swordfish(WaterWorld world) {
this(new Sprite("src/main/java/nl/han/ica/waterworld/media/swordfish.png"));
this.world=world;
}
/**
* Maak een Swordfish aan met een sprite
* @param sprite De sprite die aan dit object gekoppeld moet worden
*/
private Swordfish(Sprite sprite) {
super(sprite);
setxSpeed(-1);
}
@Override
public void update() {
if (getX()+getWidth()<=0) {
setX(world.getWidth());
}
}
}
| nickhartjes/OOPD-GameEngine | src/main/java/nl/han/ica/waterworld/Swordfish.java | 288 | /**
* Constructor
* @param world Referentie naar de wereld
*/ | block_comment | nl | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.AnimatedSpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
/**
* @author Ralph Niels
* Een zwaardvis is een spelobject dat zelfstandig
* door de wereld beweegt
*/
public class Swordfish extends SpriteObject {
private WaterWorld world;
/**
* Constructor
<SUF>*/
public Swordfish(WaterWorld world) {
this(new Sprite("src/main/java/nl/han/ica/waterworld/media/swordfish.png"));
this.world=world;
}
/**
* Maak een Swordfish aan met een sprite
* @param sprite De sprite die aan dit object gekoppeld moet worden
*/
private Swordfish(Sprite sprite) {
super(sprite);
setxSpeed(-1);
}
@Override
public void update() {
if (getX()+getWidth()<=0) {
setX(world.getWidth());
}
}
}
|
36826_17 | package chronos.utils;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.TreeRuleReturnScope;
import chronos.utils.exceptions.ChronosException;
import chronos.utils.symbols.ChronosIdentifierEntry;
import chronos.utils.symbols.ChronosSymbolTable;
/**
* De klasse ChronosCheckerToolbox</i> bevat (hulp)methoden die gebruikt kunnen worden
* door de ChronosChecker</i>. Zo zijn er bijvoorbeeld methoden om constanten en
* variabelen te declareren en om types van expressies te testen.
* @author Herman Slatman & Martijn Roo
*/
public class ChronosCheckerToolbox {
/**
* Een ChronosSymbolTable houdt ChronosIdentifierEntry's bij die informatie over Identifiers bevatten
*/
private ChronosSymbolTable table;
/**
* Constructor voor ChronosCheckerToolbox</i>
*/
public ChronosCheckerToolbox(){
table = new ChronosSymbolTable();
table.openScope(); //create the first level...IMPORTANT!
}
/**
* Geeft aan of een Identifier gedeclareerd is in de ChronosSymbolTable</>
* @param id de Identifier waarvoor gecheckt moet worden
* @return table.retrieve(id) != null
*/
public boolean isDeclared(String id){
return table.retrieve(id) != null;
}
/**
* Methode om String-representatie van de ChronosSymbolTable</i> op
* te vragen
* @return table.toString()
*/
public String printSymbolTable(){
return table.toString();
}
/**
* Methode die als doorgeefluik functioneert voor table.openScope()
*/
public void tbOpenScope(){
table.openScope();
}
/**
* Methode die als doorgeefluik functioneert voor table.closeScope()
*/
public void tbCloseScope(){
table.closeScope();
}
/**
* Geeft een String-representatie van het type van de CommonTree</i> ct
* @param ct de CommonTree</i> waarvan het type opgevraagd dient te worden
* @return "" || type van de ChronosIdentifierEntry</i> die correspondeert met ct.getText()
* @throws ChronosException wanneer de opgevraagde Identifier niet gedeclareerd is
*/
public String getType(CommonTree ct) throws ChronosException{
String res = "no_type";
if ( isDeclared(ct.getText())){
res = table.retrieve(ct.getText()).getType();
} else {
throw new ChronosException("[OPERAND " + createErrorMessage(ct) + "] ERROR: identifier " + ct.getText() + " was not declared before!");
}
return res;
}
/**
* Plaatst een 'const' in de ChronosSymbolTable</i>
* @param id de Identifier die bij de 'const' hoort
* @param idType het type van de Identifier
* @throws ChronosException wanneer er al een Identifier id bestaat in de ChronosSymbolTable</i>
*/
public void putConst(CommonTree id, String idType) throws ChronosException {
//logger.info("const " + id.getText() + " " + idType);
if ( !isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = new ChronosIdentifierEntry();
cid.setType(idType);
cid.setConstant();
table.enter(id.getText(), cid);
} else {
throw new ChronosException("[CONST. DECLARATION " + createErrorMessage(id) + "] ERROR: identifier " + id.getText() + " was already declared!");
}
}
/**
* Zal een 'var' in de ChronosSymbolTable</i> plaatsen
* @param id de Identifier die bij de 'var' hoort
* @param idType het type van de Identifier
* @throws ChronosException wanneer er al een Identifier id bestaat in de ChronosSymbolTable</i>
*/
public void putVar(CommonTree id, String idType) throws ChronosException {
if ( !isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = new ChronosIdentifierEntry();
cid.setType(idType);
table.enter(id.getText(), cid);
} else {
throw new ChronosException("[VAR. DECLARATION " + createErrorMessage(id) + "] ERROR: identifier " + id.getText() + " was already declared!");
}
}
/**
* Checkt of er niet geprobeerd wordt om een void type te printen
* @param type dat gecheckt moet worden of het void is
* @param e1 TreeRuleReturnScope</i> waarvan het type opgevraagd wordt
* @throws ChronosException wanneer er geprobeerd wordt om een void type te printen
*/
public void checkPrintVoid(String type, TreeRuleReturnScope e1) throws ChronosException{
if ( "void".equals(type) ){
throw new ChronosException("[PRINT " + createErrorMessage(e1) + "] ERROR: can't print void type!");
}
}
/**
* Checkt of een toewijzing correct is; d.w.z. of de types aan beide kanten van de toewijzing kloppen
* @param id de CommonTree</i> waarvoor het type gecheckt moet worden
* @param type Het type dat gecheckt dient te worden
* @return String die een representatie van het type voorstelt (voor multiple assignment)
* @throws ChronosException wanneer de Identifier niet bestaat, er een illegaal type wordt toegewezen of als een constante een waarde krijgt toegewezen
*/
public String checkBecomes(CommonTree id, String type) throws ChronosException {
String res = "";
if ( isDeclared(id.getText()) ){
ChronosIdentifierEntry entry = table.retrieve(id.getText());
if (!entry.isConstant()){
String idt = entry.getType();
if ( idt.equals(type) ){
res = idt;
} else {
String invalid = type;
if (invalid.equals("")){
invalid = "<invalid>";
}
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: illegal assignment of type "+invalid +" to " + idt + " "+ id.getText()+"!");
}
} else {
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: illegal assignment to const "+ id.getText()+"!");
}
} else {
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: " + id.getText() + " was not declared before!");
}
return res;
}
/**
* Set de Identifier op read, return het type van de Identifier
* @param id de CommonTree</i> waarvan de isRead geset moet worden
* @return de String-representatie van de gelezen Identfier
* @throws ChronosException wanneer de Identifier niet gevonden kon worden in de ChronosSymbolTable</i>
*/
public String getReadType(CommonTree id) throws ChronosException {
String res = "";
if ( isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = table.retrieve(id.getText());
cid.setRead();
res = cid.getType();
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: could not resolve the identifier " + id.getText() + " for reading!");
}
return res;
}
/**
* Geeft aan of de Identifier gedeclareerd is in de ChronosSymbolTable</i>
* @param id de Identifier die gecheckt moet worden
* @return table.retrieve(id) != null
* @throws ChronosException wanneer de Identifier niet gedeclareerd was
*/
public boolean checkRead(CommonTree id) throws ChronosException{
boolean res = false;
if ( isDeclared(id.getText()) ){
if ( !table.retrieve(id.getText()).isConstant() ){
res = true;
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: cannot read constant: " + id.getText() + "!");
}
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: identifier: " + id.getText() + " was not declared before!");
}
return res;
}
/**
* Controleert of het type van de TreeRuleReturnScope 'bool' is
* @param type het type waarvoor gecheckt moet worden of het een 'bool' type is
* @param ex de TreeRuleReturnScope</i> die bij het type hoort
* @return type
* @throws ChronosException wanneer type geen 'bool' is
*/
public String checkBool(String type, TreeRuleReturnScope ex) throws ChronosException{
String res = type;
if (!type.equals("bool")){
throw new ChronosException("[CHECKBOOL " + createErrorMessage(ex) + "] ERROR: illegal type found where bool was expected!");
}
return res;
}
/**
* Controleert of het type van de TreeRuleReturnScope 'int' is
* @param type het type waarvoor gecheckt moet worden of het een 'int' is
* @param ex de TreeRuleReturnScope</i> die bij het type hoort
* @return type
* @throws ChronosException wanneer type geen 'int' is
*/
public String checkInt(String type, TreeRuleReturnScope ex) throws ChronosException{
String res = type;
if (!type.equals("int")){
throw new ChronosException("[CHECKINT " + createErrorMessage(ex) + "] ERROR: illegal type found where int was expected!");
}
return res;
}
/**
* Vergelijkt de typen van twee verschillende TreeRuleReturnScopes
* @param type1 het type van de eerste TreeRuleReturnScope
* @param ex1 de eerste TreeRuleReturnScope
* @param type2 het type van de tweede TreeRuleReturnScope
* @param ex2 de tweede TreeRuleReturnScope
* @return type1
* @throws ChronosException wanneer de types niet met elkaar overeenkomen
*/
public String compareTypes(String type1, TreeRuleReturnScope ex1, String type2, TreeRuleReturnScope ex2) throws ChronosException{
String res = type1;
if (!type1.equals(type2)){
throw new ChronosException("[CHECKBIN " + createErrorMessage(ex1) + "] ERROR: type mismatch: "+ type1 +" cannot be compared to " + type2 +"!");
}
return res;
}
/**
* Maakt beschrijvingen van een CommonTree voor foutmeldingen voor de ChronosCheckerErrorReporter
* @param ct de CommonTree node waarvoor een foutmelding gemaakt dient te worden
* @return String die een representatie van de CommonTree beschrijft waar een fout is gevonden
*/
private String createErrorMessage(CommonTree ct){
CommonTree t = ((CommonTree)ct);
String res = new String();
if(t != null) {
res = "(" + t.getText() + " -> " + t.getLine() + ":" + t.getCharPositionInLine() + ")";
}
return res;
}
/**
* Maakt beschrijvingen van een CommonTree voor foutmeldingen voor de ChronosCheckerErrorReporter
* @param trrs de TreeRuleReturnScope waarvoor een foutmelding gemaakt dient te worden
* @return String die een representatie van de TreeRuleReturnScope beschrijft waar een fout is gevonden
*/
private String createErrorMessage(TreeRuleReturnScope trrs){
return createErrorMessage((CommonTree)trrs.getTree());
}
}
| hslatman/vb-eindopdracht | src/chronos/utils/ChronosCheckerToolbox.java | 2,842 | /**
* Controleert of het type van de TreeRuleReturnScope 'int' is
* @param type het type waarvoor gecheckt moet worden of het een 'int' is
* @param ex de TreeRuleReturnScope</i> die bij het type hoort
* @return type
* @throws ChronosException wanneer type geen 'int' is
*/ | block_comment | nl | package chronos.utils;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.TreeRuleReturnScope;
import chronos.utils.exceptions.ChronosException;
import chronos.utils.symbols.ChronosIdentifierEntry;
import chronos.utils.symbols.ChronosSymbolTable;
/**
* De klasse ChronosCheckerToolbox</i> bevat (hulp)methoden die gebruikt kunnen worden
* door de ChronosChecker</i>. Zo zijn er bijvoorbeeld methoden om constanten en
* variabelen te declareren en om types van expressies te testen.
* @author Herman Slatman & Martijn Roo
*/
public class ChronosCheckerToolbox {
/**
* Een ChronosSymbolTable houdt ChronosIdentifierEntry's bij die informatie over Identifiers bevatten
*/
private ChronosSymbolTable table;
/**
* Constructor voor ChronosCheckerToolbox</i>
*/
public ChronosCheckerToolbox(){
table = new ChronosSymbolTable();
table.openScope(); //create the first level...IMPORTANT!
}
/**
* Geeft aan of een Identifier gedeclareerd is in de ChronosSymbolTable</>
* @param id de Identifier waarvoor gecheckt moet worden
* @return table.retrieve(id) != null
*/
public boolean isDeclared(String id){
return table.retrieve(id) != null;
}
/**
* Methode om String-representatie van de ChronosSymbolTable</i> op
* te vragen
* @return table.toString()
*/
public String printSymbolTable(){
return table.toString();
}
/**
* Methode die als doorgeefluik functioneert voor table.openScope()
*/
public void tbOpenScope(){
table.openScope();
}
/**
* Methode die als doorgeefluik functioneert voor table.closeScope()
*/
public void tbCloseScope(){
table.closeScope();
}
/**
* Geeft een String-representatie van het type van de CommonTree</i> ct
* @param ct de CommonTree</i> waarvan het type opgevraagd dient te worden
* @return "" || type van de ChronosIdentifierEntry</i> die correspondeert met ct.getText()
* @throws ChronosException wanneer de opgevraagde Identifier niet gedeclareerd is
*/
public String getType(CommonTree ct) throws ChronosException{
String res = "no_type";
if ( isDeclared(ct.getText())){
res = table.retrieve(ct.getText()).getType();
} else {
throw new ChronosException("[OPERAND " + createErrorMessage(ct) + "] ERROR: identifier " + ct.getText() + " was not declared before!");
}
return res;
}
/**
* Plaatst een 'const' in de ChronosSymbolTable</i>
* @param id de Identifier die bij de 'const' hoort
* @param idType het type van de Identifier
* @throws ChronosException wanneer er al een Identifier id bestaat in de ChronosSymbolTable</i>
*/
public void putConst(CommonTree id, String idType) throws ChronosException {
//logger.info("const " + id.getText() + " " + idType);
if ( !isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = new ChronosIdentifierEntry();
cid.setType(idType);
cid.setConstant();
table.enter(id.getText(), cid);
} else {
throw new ChronosException("[CONST. DECLARATION " + createErrorMessage(id) + "] ERROR: identifier " + id.getText() + " was already declared!");
}
}
/**
* Zal een 'var' in de ChronosSymbolTable</i> plaatsen
* @param id de Identifier die bij de 'var' hoort
* @param idType het type van de Identifier
* @throws ChronosException wanneer er al een Identifier id bestaat in de ChronosSymbolTable</i>
*/
public void putVar(CommonTree id, String idType) throws ChronosException {
if ( !isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = new ChronosIdentifierEntry();
cid.setType(idType);
table.enter(id.getText(), cid);
} else {
throw new ChronosException("[VAR. DECLARATION " + createErrorMessage(id) + "] ERROR: identifier " + id.getText() + " was already declared!");
}
}
/**
* Checkt of er niet geprobeerd wordt om een void type te printen
* @param type dat gecheckt moet worden of het void is
* @param e1 TreeRuleReturnScope</i> waarvan het type opgevraagd wordt
* @throws ChronosException wanneer er geprobeerd wordt om een void type te printen
*/
public void checkPrintVoid(String type, TreeRuleReturnScope e1) throws ChronosException{
if ( "void".equals(type) ){
throw new ChronosException("[PRINT " + createErrorMessage(e1) + "] ERROR: can't print void type!");
}
}
/**
* Checkt of een toewijzing correct is; d.w.z. of de types aan beide kanten van de toewijzing kloppen
* @param id de CommonTree</i> waarvoor het type gecheckt moet worden
* @param type Het type dat gecheckt dient te worden
* @return String die een representatie van het type voorstelt (voor multiple assignment)
* @throws ChronosException wanneer de Identifier niet bestaat, er een illegaal type wordt toegewezen of als een constante een waarde krijgt toegewezen
*/
public String checkBecomes(CommonTree id, String type) throws ChronosException {
String res = "";
if ( isDeclared(id.getText()) ){
ChronosIdentifierEntry entry = table.retrieve(id.getText());
if (!entry.isConstant()){
String idt = entry.getType();
if ( idt.equals(type) ){
res = idt;
} else {
String invalid = type;
if (invalid.equals("")){
invalid = "<invalid>";
}
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: illegal assignment of type "+invalid +" to " + idt + " "+ id.getText()+"!");
}
} else {
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: illegal assignment to const "+ id.getText()+"!");
}
} else {
throw new ChronosException("[BECOMES " + createErrorMessage(id) + "] ERROR: " + id.getText() + " was not declared before!");
}
return res;
}
/**
* Set de Identifier op read, return het type van de Identifier
* @param id de CommonTree</i> waarvan de isRead geset moet worden
* @return de String-representatie van de gelezen Identfier
* @throws ChronosException wanneer de Identifier niet gevonden kon worden in de ChronosSymbolTable</i>
*/
public String getReadType(CommonTree id) throws ChronosException {
String res = "";
if ( isDeclared(id.getText()) ){
ChronosIdentifierEntry cid = table.retrieve(id.getText());
cid.setRead();
res = cid.getType();
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: could not resolve the identifier " + id.getText() + " for reading!");
}
return res;
}
/**
* Geeft aan of de Identifier gedeclareerd is in de ChronosSymbolTable</i>
* @param id de Identifier die gecheckt moet worden
* @return table.retrieve(id) != null
* @throws ChronosException wanneer de Identifier niet gedeclareerd was
*/
public boolean checkRead(CommonTree id) throws ChronosException{
boolean res = false;
if ( isDeclared(id.getText()) ){
if ( !table.retrieve(id.getText()).isConstant() ){
res = true;
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: cannot read constant: " + id.getText() + "!");
}
} else {
throw new ChronosException("[READ " + createErrorMessage(id) + "] ERROR: identifier: " + id.getText() + " was not declared before!");
}
return res;
}
/**
* Controleert of het type van de TreeRuleReturnScope 'bool' is
* @param type het type waarvoor gecheckt moet worden of het een 'bool' type is
* @param ex de TreeRuleReturnScope</i> die bij het type hoort
* @return type
* @throws ChronosException wanneer type geen 'bool' is
*/
public String checkBool(String type, TreeRuleReturnScope ex) throws ChronosException{
String res = type;
if (!type.equals("bool")){
throw new ChronosException("[CHECKBOOL " + createErrorMessage(ex) + "] ERROR: illegal type found where bool was expected!");
}
return res;
}
/**
* Controleert of het<SUF>*/
public String checkInt(String type, TreeRuleReturnScope ex) throws ChronosException{
String res = type;
if (!type.equals("int")){
throw new ChronosException("[CHECKINT " + createErrorMessage(ex) + "] ERROR: illegal type found where int was expected!");
}
return res;
}
/**
* Vergelijkt de typen van twee verschillende TreeRuleReturnScopes
* @param type1 het type van de eerste TreeRuleReturnScope
* @param ex1 de eerste TreeRuleReturnScope
* @param type2 het type van de tweede TreeRuleReturnScope
* @param ex2 de tweede TreeRuleReturnScope
* @return type1
* @throws ChronosException wanneer de types niet met elkaar overeenkomen
*/
public String compareTypes(String type1, TreeRuleReturnScope ex1, String type2, TreeRuleReturnScope ex2) throws ChronosException{
String res = type1;
if (!type1.equals(type2)){
throw new ChronosException("[CHECKBIN " + createErrorMessage(ex1) + "] ERROR: type mismatch: "+ type1 +" cannot be compared to " + type2 +"!");
}
return res;
}
/**
* Maakt beschrijvingen van een CommonTree voor foutmeldingen voor de ChronosCheckerErrorReporter
* @param ct de CommonTree node waarvoor een foutmelding gemaakt dient te worden
* @return String die een representatie van de CommonTree beschrijft waar een fout is gevonden
*/
private String createErrorMessage(CommonTree ct){
CommonTree t = ((CommonTree)ct);
String res = new String();
if(t != null) {
res = "(" + t.getText() + " -> " + t.getLine() + ":" + t.getCharPositionInLine() + ")";
}
return res;
}
/**
* Maakt beschrijvingen van een CommonTree voor foutmeldingen voor de ChronosCheckerErrorReporter
* @param trrs de TreeRuleReturnScope waarvoor een foutmelding gemaakt dient te worden
* @return String die een representatie van de TreeRuleReturnScope beschrijft waar een fout is gevonden
*/
private String createErrorMessage(TreeRuleReturnScope trrs){
return createErrorMessage((CommonTree)trrs.getTree());
}
}
|
101596_2 | /*
* 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 controller;
import java.util.Date;
import model.Asprak;
import model.Student;
import view.StudentView;
/**
*
* @author student
*/
public class StudentController {
private Asprak model;
private StudentView view;
public StudentController(Asprak model, StudentView view){
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public Date getStudentBirthDate() {
return model.getBirthDate();
}
public void setStudentBirthDate(Date tglLahir) {
model.setBirthDate(tglLahir);
}
/*public void updateView(){
view.printStudentDetails(model);
}*/
//Just For Asprak
public void setAsprakMatkul(String matkul) {
model.setMatkul(matkul);
}
public Date getAsprakJamPraktikum() {
return model.getJamPraktikum();
}
public void updateAsprakView() {
view.printAsprakDetails(model);
}
}
| williamhanugra/tugasprakPSBO | src/controller/StudentController.java | 398 | /*public void updateView(){
view.printStudentDetails(model);
}*/ | 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 controller;
import java.util.Date;
import model.Asprak;
import model.Student;
import view.StudentView;
/**
*
* @author student
*/
public class StudentController {
private Asprak model;
private StudentView view;
public StudentController(Asprak model, StudentView view){
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public Date getStudentBirthDate() {
return model.getBirthDate();
}
public void setStudentBirthDate(Date tglLahir) {
model.setBirthDate(tglLahir);
}
/*public void updateView(){<SUF>*/
//Just For Asprak
public void setAsprakMatkul(String matkul) {
model.setMatkul(matkul);
}
public Date getAsprakJamPraktikum() {
return model.getJamPraktikum();
}
public void updateAsprakView() {
view.printAsprakDetails(model);
}
}
|
56022_16 | package yolo;
import java.util.*;
public class KantineSimulatie_2 {
//Array van personen
public ArrayList<Persoon> personen = new ArrayList<>();
// kantine
private Kantine kantine;
// kantineaanbod
private KantineAanbod kantineaanbod;
// random generator
private Random random;
// aantal artikelen
private static final int AANTAL_ARTIKELEN = 4;
// artikelen
private static final String[] artikelnamen = new String[]
{"Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap"};
// prijzen
private static double[] artikelprijzen = new double[]{1.50, 2.10, 1.65, 1.65};
// minimum en maximum aantal artikelen per soort
private static final int MIN_ARTIKELEN_PER_SOORT = 10000;
private static final int MAX_ARTIKELEN_PER_SOORT = 20000;
// minimum en maximum aantal personen per dag
private static final int MIN_PERSONEN_PER_DAG = 50;
private static final int MAX_PERSONEN_PER_DAG = 100;
// minimum en maximum artikelen per persoon
private static final int MIN_ARTIKELEN_PER_PERSOON = 1;
private static final int MAX_ARTIKELEN_PER_PERSOON = 4;
private javax.persistence.EntityManager manager;
/**
* Constructor
*
*/
public KantineSimulatie_2(javax.persistence.EntityManager manager) {
kantine = new Kantine(manager);
random = new Random();
int[] hoeveelheden = getRandomArray(
AANTAL_ARTIKELEN,
MIN_ARTIKELEN_PER_SOORT,
MAX_ARTIKELEN_PER_SOORT);
kantineaanbod = new KantineAanbod(
artikelnamen, artikelprijzen, hoeveelheden, MIN_ARTIKELEN_PER_SOORT);
kantine.setKantineAanbod(kantineaanbod);
}
/**
* Methode om een array van random getallen liggend tussen
* min en max van de gegeven lengte te genereren
*
* @param lengte
* @param min
* @param max
* @return De array met random getallen
*/
private int[] getRandomArray(int lengte, int min, int max) {
int[] temp = new int[lengte];
for(int i = 0; i < lengte ;i++) {
temp[i] = getRandomValue(min, max);
}
return temp;
}
/**
* Methode om een random getal tussen min(incl)
* en max(incl) te genereren.
*
* @param min
* @param max
* @return Een random getal
*/
private int getRandomValue(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
/**
* Methode om op basis van een array van indexen voor de array
* artikelnamen de bijhorende array van artikelnamen te maken
*
* @param indexen
* @return De array met artikelnamen
*/
private String[] geefArtikelNamen(int[] indexen) {
String[] artikelen = new String[indexen.length];
for(int i = 0; i < indexen.length; i++) {
artikelen[i] = artikelnamen[indexen[i]];
}
return artikelen;
}
/**
* Deze methode simuleert een aantal dagen
* in het verloop van de kantine
*
* @param dagen
*/
public void simuleer(int dagen){
// for lus voor dagen
for(int i = 0; i < dagen; i++) {
// bedenk hoeveel personen vandaag binnen lopen
int aantalpersonen = getRandomValue(MIN_PERSONEN_PER_DAG,MAX_PERSONEN_PER_DAG) ;
// 100 personen worden hier gemaakt
for (int x = 0; x < 100; x++){
String bsn = "bsnnmmr"+x;
String vnaam = "voornaam"+x;
String anaam = "achternaam"+x;
Datum datum = new Datum(x%28,x%12,2000);
Contant contant = new Contant();
Pinpas pinpas = new Pinpas();
int manOfVrouw = getRandomValue(0,1);
char geslacht = ' ';
if (manOfVrouw == 0) geslacht = 'M';
else if (manOfVrouw == 1) geslacht = 'V';
// 89 Studenten worden hier gemaakt.
if (x<89) {
int studentenummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
String studierichting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
studierichting = "NSE";
} else if (random == 2) {
studierichting = "SE";
} else {
studierichting = "Bitm";
}
Student student = new Student(studentenummer,studierichting,bsn,vnaam,anaam,datum,geslacht);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een student een pinpas met geld.
student.setBetaalwijze(pinpas);
personen.add(student);
}
// 10 Docenten worden hiero gemaakt
else if (x<99) {
String alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM";
String afdeling = "";
String afkorting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
afdeling = "Talen";
} else if (random == 2) {
afdeling = "Management";
} else {
afdeling = "Programmeren";
}
for (int s = 0; s < 4; s++) {
afkorting += alphabet.charAt(getRandomValue(0,25));
}
Docent docent = new Docent(bsn,vnaam,anaam,datum,geslacht,afdeling,afkorting);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een Docent een pinpas met geld.
docent.setBetaalwijze(pinpas);
personen.add(docent);
}
// 1 Kantinemedewerker wordt hier gemaakt
else {
int medewerkersnummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
int r = getRandomValue(0,1);
boolean kassawaardig;
if (r==0) kassawaardig = true;
else kassawaardig = false;
KantineMedewerker kantineMedewerker = new KantineMedewerker(bsn,vnaam,anaam,datum,geslacht,medewerkersnummer,kassawaardig);
contant.setSaldo((double) getRandomValue(2,20)); // We geven hier een Kantine Medewerker contant geld.
kantineMedewerker.setBetaalwijze(contant);
personen.add(kantineMedewerker);
}
}
// laat de personen maar komen...
for(int j = 0; j < aantalpersonen; j++) {
// maak persoon en dienblad aan, koppel ze
// en bedenk hoeveel artikelen worden gepakt
Random rndm = new Random();
int r = rndm.nextInt(100);
Dienblad dienblad = new Dienblad();
dienblad.setPersoon(personen.get(r));
int aantalartikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON,MAX_ARTIKELEN_PER_PERSOON);
// genereer de "artikelnummers", dit zijn indexen
// van de artikelnamen
int[] tepakken = getRandomArray(
aantalartikelen, 0, AANTAL_ARTIKELEN-1);
// vind de artikelnamen op basis van
// de indexen hierboven
String[] artikelen = geefArtikelNamen(tepakken);
// loop de kantine binnen, pak de gewenste
// artikelen, sluit aan
kantine.loopPakSluitAan(personen.get(r),artikelen);
}
try{
Thread.sleep(500);
}catch (Exception e) {
System.out.println(e);
}
// verwerk rij voor de kassa
kantine.verwerkRijVoorKassa();
// druk de dagtotalen af en hoeveel personen binnen
// zijn gekomen(printf gebruiken)
System.out.println("Dag "+(i+1)+": Omzet van "+(Math.round(kantine.hoeveelheidGeldInKassa()*100))/100+" euro & "+kantine.aantalArtikelen()+" artikel afgerekend.");
// reset de kassa voor de volgende dag
kantine.resetKassa();
}
}
public static void main(String[] args) {
int[] getallen = {45, 56, 34, 39, 40, 31};
double[] omzet = {567.70, 498.25, 458.90};
double[] omzetPeriode = {321.35, 450.50, 210.45, 190.85, 193.25, 159.90, 214.25, 220.90, 201.90, 242.70, 260.35};
System.out.println(Administratie.berekenGemiddeldAantal(getallen)); //gem = 40.8333
System.out.println(Administratie.berekenGemiddeldeOmzet(omzet)); //gem = 508.2833
int dag = 0;
for(double i : Administratie.berekenDagOmzet(omzetPeriode)) {
System.out.println("Dag "+dag+": "+i);
dag++;
}
}
} | reneoun/KantineUnit | src/main/java/yolo/KantineSimulatie_2.java | 2,579 | // 1 Kantinemedewerker wordt hier gemaakt | line_comment | nl | package yolo;
import java.util.*;
public class KantineSimulatie_2 {
//Array van personen
public ArrayList<Persoon> personen = new ArrayList<>();
// kantine
private Kantine kantine;
// kantineaanbod
private KantineAanbod kantineaanbod;
// random generator
private Random random;
// aantal artikelen
private static final int AANTAL_ARTIKELEN = 4;
// artikelen
private static final String[] artikelnamen = new String[]
{"Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap"};
// prijzen
private static double[] artikelprijzen = new double[]{1.50, 2.10, 1.65, 1.65};
// minimum en maximum aantal artikelen per soort
private static final int MIN_ARTIKELEN_PER_SOORT = 10000;
private static final int MAX_ARTIKELEN_PER_SOORT = 20000;
// minimum en maximum aantal personen per dag
private static final int MIN_PERSONEN_PER_DAG = 50;
private static final int MAX_PERSONEN_PER_DAG = 100;
// minimum en maximum artikelen per persoon
private static final int MIN_ARTIKELEN_PER_PERSOON = 1;
private static final int MAX_ARTIKELEN_PER_PERSOON = 4;
private javax.persistence.EntityManager manager;
/**
* Constructor
*
*/
public KantineSimulatie_2(javax.persistence.EntityManager manager) {
kantine = new Kantine(manager);
random = new Random();
int[] hoeveelheden = getRandomArray(
AANTAL_ARTIKELEN,
MIN_ARTIKELEN_PER_SOORT,
MAX_ARTIKELEN_PER_SOORT);
kantineaanbod = new KantineAanbod(
artikelnamen, artikelprijzen, hoeveelheden, MIN_ARTIKELEN_PER_SOORT);
kantine.setKantineAanbod(kantineaanbod);
}
/**
* Methode om een array van random getallen liggend tussen
* min en max van de gegeven lengte te genereren
*
* @param lengte
* @param min
* @param max
* @return De array met random getallen
*/
private int[] getRandomArray(int lengte, int min, int max) {
int[] temp = new int[lengte];
for(int i = 0; i < lengte ;i++) {
temp[i] = getRandomValue(min, max);
}
return temp;
}
/**
* Methode om een random getal tussen min(incl)
* en max(incl) te genereren.
*
* @param min
* @param max
* @return Een random getal
*/
private int getRandomValue(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
/**
* Methode om op basis van een array van indexen voor de array
* artikelnamen de bijhorende array van artikelnamen te maken
*
* @param indexen
* @return De array met artikelnamen
*/
private String[] geefArtikelNamen(int[] indexen) {
String[] artikelen = new String[indexen.length];
for(int i = 0; i < indexen.length; i++) {
artikelen[i] = artikelnamen[indexen[i]];
}
return artikelen;
}
/**
* Deze methode simuleert een aantal dagen
* in het verloop van de kantine
*
* @param dagen
*/
public void simuleer(int dagen){
// for lus voor dagen
for(int i = 0; i < dagen; i++) {
// bedenk hoeveel personen vandaag binnen lopen
int aantalpersonen = getRandomValue(MIN_PERSONEN_PER_DAG,MAX_PERSONEN_PER_DAG) ;
// 100 personen worden hier gemaakt
for (int x = 0; x < 100; x++){
String bsn = "bsnnmmr"+x;
String vnaam = "voornaam"+x;
String anaam = "achternaam"+x;
Datum datum = new Datum(x%28,x%12,2000);
Contant contant = new Contant();
Pinpas pinpas = new Pinpas();
int manOfVrouw = getRandomValue(0,1);
char geslacht = ' ';
if (manOfVrouw == 0) geslacht = 'M';
else if (manOfVrouw == 1) geslacht = 'V';
// 89 Studenten worden hier gemaakt.
if (x<89) {
int studentenummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
String studierichting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
studierichting = "NSE";
} else if (random == 2) {
studierichting = "SE";
} else {
studierichting = "Bitm";
}
Student student = new Student(studentenummer,studierichting,bsn,vnaam,anaam,datum,geslacht);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een student een pinpas met geld.
student.setBetaalwijze(pinpas);
personen.add(student);
}
// 10 Docenten worden hiero gemaakt
else if (x<99) {
String alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM";
String afdeling = "";
String afkorting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
afdeling = "Talen";
} else if (random == 2) {
afdeling = "Management";
} else {
afdeling = "Programmeren";
}
for (int s = 0; s < 4; s++) {
afkorting += alphabet.charAt(getRandomValue(0,25));
}
Docent docent = new Docent(bsn,vnaam,anaam,datum,geslacht,afdeling,afkorting);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een Docent een pinpas met geld.
docent.setBetaalwijze(pinpas);
personen.add(docent);
}
// 1 Kantinemedewerker<SUF>
else {
int medewerkersnummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
int r = getRandomValue(0,1);
boolean kassawaardig;
if (r==0) kassawaardig = true;
else kassawaardig = false;
KantineMedewerker kantineMedewerker = new KantineMedewerker(bsn,vnaam,anaam,datum,geslacht,medewerkersnummer,kassawaardig);
contant.setSaldo((double) getRandomValue(2,20)); // We geven hier een Kantine Medewerker contant geld.
kantineMedewerker.setBetaalwijze(contant);
personen.add(kantineMedewerker);
}
}
// laat de personen maar komen...
for(int j = 0; j < aantalpersonen; j++) {
// maak persoon en dienblad aan, koppel ze
// en bedenk hoeveel artikelen worden gepakt
Random rndm = new Random();
int r = rndm.nextInt(100);
Dienblad dienblad = new Dienblad();
dienblad.setPersoon(personen.get(r));
int aantalartikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON,MAX_ARTIKELEN_PER_PERSOON);
// genereer de "artikelnummers", dit zijn indexen
// van de artikelnamen
int[] tepakken = getRandomArray(
aantalartikelen, 0, AANTAL_ARTIKELEN-1);
// vind de artikelnamen op basis van
// de indexen hierboven
String[] artikelen = geefArtikelNamen(tepakken);
// loop de kantine binnen, pak de gewenste
// artikelen, sluit aan
kantine.loopPakSluitAan(personen.get(r),artikelen);
}
try{
Thread.sleep(500);
}catch (Exception e) {
System.out.println(e);
}
// verwerk rij voor de kassa
kantine.verwerkRijVoorKassa();
// druk de dagtotalen af en hoeveel personen binnen
// zijn gekomen(printf gebruiken)
System.out.println("Dag "+(i+1)+": Omzet van "+(Math.round(kantine.hoeveelheidGeldInKassa()*100))/100+" euro & "+kantine.aantalArtikelen()+" artikel afgerekend.");
// reset de kassa voor de volgende dag
kantine.resetKassa();
}
}
public static void main(String[] args) {
int[] getallen = {45, 56, 34, 39, 40, 31};
double[] omzet = {567.70, 498.25, 458.90};
double[] omzetPeriode = {321.35, 450.50, 210.45, 190.85, 193.25, 159.90, 214.25, 220.90, 201.90, 242.70, 260.35};
System.out.println(Administratie.berekenGemiddeldAantal(getallen)); //gem = 40.8333
System.out.println(Administratie.berekenGemiddeldeOmzet(omzet)); //gem = 508.2833
int dag = 0;
for(double i : Administratie.berekenDagOmzet(omzetPeriode)) {
System.out.println("Dag "+dag+": "+i);
dag++;
}
}
} |
37276_3 | import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
/**
* Created by michael on 01-11-15.
*/
public class ValBewegingPaneel extends HBox {
private int startX, startY;
private int eindX, eindY;
private ValBewegingApp valBewegingApp;
private ControlePaneelNoord noordpaneel;
private Bal bal;
private BalView balView;
private BalController balController;
private final int PARTS = 12;
public ValBewegingPaneel(ValBewegingApp valBewegingApp, ControlePaneelNoord noordpaneel) {
this.valBewegingApp = valBewegingApp;
this.noordpaneel = noordpaneel;
this.bal = new Bal();
this.balView = new BalView(bal,this,noordpaneel);
this.balController = new BalController(this.bal, this.balView, this, noordpaneel);
Canvas canvas = new Canvas(500,500);
GraphicsContext gc = canvas.getGraphicsContext2D();
drawShapes(gc);
ControlePaneelZuid zuidpaneel = new ControlePaneelZuid(this.bal, this.balView, this.balController);
this.valBewegingApp.pane.setBottom(zuidpaneel);
getChildren().addAll(this.balView, canvas);
}
private void drawShapes(GraphicsContext gc) {
//teken het grid
this.startX = 500 / PARTS; // Om te zien hoeveel ruimte elk "deel" nodig heeft
this.startY = 500 / PARTS;
this.eindX = (PARTS - 1) * this.startX; //
this.eindY = (PARTS - 1) * this.startY; //
gc.setStroke(Color.BLUE);
gc.setLineWidth(1);
gc.strokeLine(this.startX, this.startY, this.eindX, this.startY);
gc.setLineDashes(5);
for (int te = 2; te <= (PARTS - 2); te++) {
gc.strokeLine(this.startX, te * this.startY, this.eindX, te * this.startY);
gc.strokeLine(te * this.startX, this.startY, te * this.startX, this.eindY);
}
gc.setLineDashes(30);
gc.strokeLine(this.startX, this.startY, this.eindX, this.startY);
}
/**
*
* @return X startwaarden
*/
public int getStartX() {
return this.startX;
}
/**
*
* @return Y startwaarden
*/
public int getStartY() {
return this.startY;
}
/**
*
* @return X eindwaarden
*/
public int getEindX() {
return this.eindX;
}
/**
*
* @return Y eindwaarden
*/
public int getEindY() {
return this.eindY;
}
/**
*
* @return
*/
public int getPARTS() {
return PARTS;
}
}
| mvankampen/FreeFall_MVC | src/ValBewegingPaneel.java | 829 | /**
*
* @return X startwaarden
*/ | block_comment | nl | import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
/**
* Created by michael on 01-11-15.
*/
public class ValBewegingPaneel extends HBox {
private int startX, startY;
private int eindX, eindY;
private ValBewegingApp valBewegingApp;
private ControlePaneelNoord noordpaneel;
private Bal bal;
private BalView balView;
private BalController balController;
private final int PARTS = 12;
public ValBewegingPaneel(ValBewegingApp valBewegingApp, ControlePaneelNoord noordpaneel) {
this.valBewegingApp = valBewegingApp;
this.noordpaneel = noordpaneel;
this.bal = new Bal();
this.balView = new BalView(bal,this,noordpaneel);
this.balController = new BalController(this.bal, this.balView, this, noordpaneel);
Canvas canvas = new Canvas(500,500);
GraphicsContext gc = canvas.getGraphicsContext2D();
drawShapes(gc);
ControlePaneelZuid zuidpaneel = new ControlePaneelZuid(this.bal, this.balView, this.balController);
this.valBewegingApp.pane.setBottom(zuidpaneel);
getChildren().addAll(this.balView, canvas);
}
private void drawShapes(GraphicsContext gc) {
//teken het grid
this.startX = 500 / PARTS; // Om te zien hoeveel ruimte elk "deel" nodig heeft
this.startY = 500 / PARTS;
this.eindX = (PARTS - 1) * this.startX; //
this.eindY = (PARTS - 1) * this.startY; //
gc.setStroke(Color.BLUE);
gc.setLineWidth(1);
gc.strokeLine(this.startX, this.startY, this.eindX, this.startY);
gc.setLineDashes(5);
for (int te = 2; te <= (PARTS - 2); te++) {
gc.strokeLine(this.startX, te * this.startY, this.eindX, te * this.startY);
gc.strokeLine(te * this.startX, this.startY, te * this.startX, this.eindY);
}
gc.setLineDashes(30);
gc.strokeLine(this.startX, this.startY, this.eindX, this.startY);
}
/**
*
* @return X startwaarden<SUF>*/
public int getStartX() {
return this.startX;
}
/**
*
* @return Y startwaarden
*/
public int getStartY() {
return this.startY;
}
/**
*
* @return X eindwaarden
*/
public int getEindX() {
return this.eindX;
}
/**
*
* @return Y eindwaarden
*/
public int getEindY() {
return this.eindY;
}
/**
*
* @return
*/
public int getPARTS() {
return PARTS;
}
}
|
206365_7 | package sr.unasat.bewakingsBedrijf.app.scherm.rooster;
//import javafx.scene.shape.Circle;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.Bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.BewakerDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.dag.Dag;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.dag.DagDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.post.Post;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.post.PostDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.Rooster;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.RoosterDatabase;
import sr.unasat.bewakingsBedrijf.app.scherm.algemeen.StartScherm;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.interfaces.RSAKey;
import java.util.*;
/**
* Created by Jair on 5/16/2016.
*/
public class RoosterScherm extends JFrame {
RoosterDatabase roosterDatabase = null;
PostDatabase postDatabase = null;
BewakerDatabase bewakerDatabase = null;
DagDatabase dagDatabase = null;
JPanel bewakerRoosterPan = new JPanel(new BorderLayout()), allRoosterPan = new JPanel(), homePan = new JPanel();
JTabbedPane jTabbedPane = new JTabbedPane(SwingConstants.LEFT);
ArrayList<Rooster> roosterArrayListObject = new ArrayList<>();
ArrayList<Integer> roosterArrayListID = new ArrayList<>();
ArrayList<Post> postArrayListObject = new ArrayList<>();
ArrayList<String> postArraylist = new ArrayList<>();
ArrayList<Dag> dagArrayListObject = new ArrayList<>();
ArrayList<String> dagtArraylist = new ArrayList<>();
ArrayList<Bewaker> bewakerArrayListObject = new ArrayList<>();
ArrayList<String> bewakerArrayListNames = new ArrayList<>();
JComboBox dagBox, postBox, bewakerBox;
private DefaultTableModel listTableModel;
private JTable outputTable;
ImageIcon icon = new ImageIcon(getClass().getResource("bewaker.png"));
ImageIcon homeIcon = new ImageIcon(getClass().getResource("home.png"));
ImageIcon roostersIcon = new ImageIcon(getClass().getResource("rooster.png"));
public RoosterScherm() {
//jTabbedPane.setBackground(new Color(10,126,192));
//jTabbedPane.setIconAt(0,icon);
// jTabbedPane.add(" all roosters ",allRoosterPan);
//jTabbedPane.add(" bewaker rooster ",bewakerRoosterPan);
jTabbedPane.setBackground(new Color(148, 178, 173));
jTabbedPane.addTab(" all roosters ", roostersIcon, allRoosterPan);
jTabbedPane.addTab("bewaker rooster", icon, bewakerRoosterPan);
jTabbedPane.addTab("home", homeIcon, homePan);
allroostersPanel();
add(jTabbedPane);
getContentPane().setBackground(new Color(7, 84, 127));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(900, 500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
jTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (allRoosterPan.isShowing()) {
allroostersPanel();
} else {
allRoosterPan.removeAll();
}
if (bewakerRoosterPan.isShowing()) {
bewakerRoosterPanel();
} else {
bewakerRoosterPan.removeAll();
}
if (homePan.isShowing()) {
setVisible(false);
new StartScherm();
}
}
});
}
public void allroostersPanel() {
buildArrays();
JPanel buttonPanel = new JPanel(new BorderLayout()), outputPanel = new JPanel(), viewAllButPanel = new JPanel(), buttonPanelOtther = new JPanel(new GridBagLayout());
JButton viewAllBut = new JButton("view all"), deleteBut = new JButton("delete selected rooster"),
updateBut = new JButton("update selected rooster"), addBut = new JButton("add new rooster"),
saveBut = new JButton("save added rooster");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(20, 20, 20, 20);
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
listTableModel = new DefaultTableModel();
String[] colnames = {"id", "bewaker", "post", "dag", "shift"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
outputTable = new JTable(null, colnamesV);
JScrollPane tablePanel = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
outputPanel.add(tablePanel);
outputTable.setBackground(new Color(148, 178, 173));
//creating comboboxes for table cell editors
dagBox = new JComboBox(new DefaultComboBoxModel<>(dagtArraylist.toArray()));
postBox = new JComboBox(new DefaultComboBoxModel<>(postArraylist.toArray()));
bewakerBox = new JComboBox(new DefaultComboBoxModel<>(bewakerArrayListNames.toArray()));
//{"id","bewaker", "post", "dag","shift"};
TableColumn bewColumn = outputTable.getColumnModel().getColumn(1);
bewColumn.setCellEditor(new DefaultCellEditor(bewakerBox));
TableColumn postColumn = outputTable.getColumnModel().getColumn(2);
postColumn.setCellEditor(new DefaultCellEditor(postBox));
TableColumn dagColumn = outputTable.getColumnModel().getColumn(3);
dagColumn.setCellEditor(new DefaultCellEditor(dagBox));
viewAllButPanel.add(viewAllBut);
gbc.gridx = 0;
gbc.gridy = 0;
buttonPanelOtther.add(addBut, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
buttonPanelOtther.add(saveBut, gbc);
gbc.gridx = 2;
buttonPanelOtther.add(updateBut, gbc);
gbc.gridx = 3;
buttonPanelOtther.add(deleteBut, gbc);
buttonPanelOtther.setBackground(new Color(7, 84, 127));
viewAllButPanel.setBackground(new Color(7, 84, 127));
buttonPanel.add(viewAllButPanel, BorderLayout.NORTH);
buttonPanel.add(buttonPanelOtther, BorderLayout.CENTER);
allRoosterPan.setLayout(new BorderLayout());
allRoosterPan.add(buttonPanel, BorderLayout.NORTH);
allRoosterPan.add(outputPanel, BorderLayout.CENTER);
viewAllBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAllBut();
}
});
addBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
listTableModel.addRow(new Object[]{null, null, null, null});
}
});
saveBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (outputTable.getValueAt(outputTable.getSelectedRow(), 0).toString() != null) {
JOptionPane.showMessageDialog(saveBut, " be sure to select the new row before saving");
}
} catch (Exception e1) {
//if(listTableModel.getValueAt(i, 2).equals(postArrayListObject.get(i).getDag()))
try {
Rooster rooster = new Rooster();
roosterDatabase = new RoosterDatabase();
bewakerDatabase = new BewakerDatabase();
postDatabase = new PostDatabase();
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
if (!dagDatabase.isInitialised()) {
dagDatabase.initialiseer();
}
// {"id","bewaker", "post", "dag","shift"};
buildArrays();
int selectedRow = outputTable.getSelectedRow();
for (int i = 0; i < bewakerArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 1).getCellEditorValue().toString().equals(bewakerArrayListObject.get(i).getBewaker_naam())) {
rooster.setBewaker_fk(bewakerDatabase.selectAll().get(i).getId());
i = bewakerArrayListObject.size() + 1;
}
}
for (int i = 0; i < postArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 2).getCellEditorValue().toString().equals(postArrayListObject.get(i).getPost_naam())) {
rooster.setPost_fk(postDatabase.selectAll().get(i).getId());
i = postArrayListObject.size() + 1;
}
}
for (int i = 0; i < dagArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 3).getCellEditorValue().toString().equals(dagArrayListObject.get(i).getDag())) {
rooster.setDag_fk(dagDatabase.selectAll().get(i).getId());
i = dagArrayListObject.size() + 1;
}
}
// {"id","bewaker", "post", "dag","shift"};
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
// Alleen als de roosteren database is geinitialiseerd dan verder
if (roosterDatabase.isInitialised()) {
roosterDatabase.insertRooster(rooster);
JOptionPane.showMessageDialog(saveBut, "rooster succesfully added");
}
// Initialiseer de studentDatabase alleen als het moet
} catch (Exception e2) {
JOptionPane.showMessageDialog(saveBut, " error ?????");
System.out.println(e2);
}
}
}
});
updateBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//if(listTableModel.getValueAt(i, 2).equals(postArrayListObject.get(i).getDag()))
Rooster rooster = new Rooster();
roosterDatabase = new RoosterDatabase();
bewakerDatabase = new BewakerDatabase();
postDatabase = new PostDatabase();
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
// {"id","bewaker", "post", "dag","shift"};
buildArrays();
int selectedRow = outputTable.getSelectedRow();
for (int i = 0; i < bewakerArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 1).getCellEditorValue().toString().equals(bewakerArrayListObject.get(i).getBewaker_naam())) {
rooster.setBewaker_fk(bewakerDatabase.selectAll().get(i).getId());
i = bewakerArrayListObject.size() + 1;
}
}
for (int i = 0; i < postArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 2).getCellEditorValue().toString().equals(postArrayListObject.get(i).getPost_naam())) {
rooster.setPost_fk(postDatabase.selectAll().get(i).getId());
i = postArrayListObject.size() + 1;
}
}
for (int i = 0; i < dagArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 3).getCellEditorValue().toString().equals(dagArrayListObject.get(i).getDag())) {
rooster.setDag_fk(dagDatabase.selectAll().get(i).getId());
i = dagArrayListObject.size() + 1;
}
}
int i = outputTable.getSelectedRow();
Object roosterIdObject = outputTable.getValueAt(i, 0);
String roosterIdString = roosterIdObject.toString();
int roosterID = Integer.parseInt(roosterIdString);
rooster.setId(roosterID);
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
roosterDatabase.updateRooster(rooster);
JOptionPane.showMessageDialog(updateBut, "rooster update succesful");
} else {
JOptionPane.showMessageDialog(updateBut, "rooster update succesful");
}
}
});
deleteBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null,
"Are you sure to delete rooster?", null, JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
int i = outputTable.getSelectedRow();
Object roosterIdObject = outputTable.getValueAt(i, 0);
String roosterIdString = roosterIdObject.toString();
int roosterID = Integer.parseInt(roosterIdString);
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
// Alleen als de studenten database is geinitialiseerd dan verder
if (roosterDatabase.isInitialised()) {
roosterDatabase.deleteRooster(roosterID);
listTableModel.removeRow(i);
JOptionPane.showMessageDialog(deleteBut, "rooster deleted");
allRoosterPan.removeAll();
allroostersPanel();
selectAllBut();
}
} else {
JOptionPane.showMessageDialog(deleteBut, "rooster is not deleted");
}
}
});
}
public void bewakerRoosterPanel() {
JPanel upperPanel = new JPanel(new GridBagLayout());
JPanel tablePanel = new JPanel();
JButton go = new JButton("go");
upperPanel.setBackground(new Color(7, 84, 127));
tablePanel.setBackground(new Color(7, 84, 127));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(5, 0, 5, 0);
JComboBox jComboBox = new JComboBox(new DefaultComboBoxModel(bewakerArrayListNames.toArray()));
JLabel viewRoosterLabel = new JLabel("select bewaker to view rooster");
viewRoosterLabel.setForeground(Color.white);
listTableModel = new DefaultTableModel();
String[] colnames = {"post", "dag", "tijd"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
JTable outputTable = new JTable(null, colnamesV);
JScrollPane tableScroll = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
tablePanel.add(tableScroll);
outputTable.setBackground(new Color(148, 178, 173));
gbc.gridx = 0;
gbc.gridy = 0;
upperPanel.add(viewRoosterLabel, gbc);
gbc.gridx = 0;
gbc.gridy = -1;
upperPanel.add(jComboBox, gbc);
gbc.gridx = 0;
gbc.gridy = -2;
upperPanel.add(go, gbc);
bewakerRoosterPan.add(upperPanel, BorderLayout.NORTH);
bewakerRoosterPan.add(tablePanel, BorderLayout.CENTER);
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buildArrays();
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListObject.get(i).getId();
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
int lastindex = roosterArrayListObject.get(roosterArrayListObject.size() - 1).getId();
for (int a = 0; a < lastindex + 1; a++) {
if (bewakerDatabase.selectBewaker(record).getId() == roosterDatabase.selectRooster(a).getBewaker_fk()) {
String[] colData = new String[3];
colData[0] = roosterDatabase.selectRooster(a).getPost().getPost_naam();
colData[1] = roosterDatabase.selectRooster(a).getDag().getDag();
colData[2] = roosterDatabase.selectRooster(a).getDag().getShift();
listTableModel.addRow(colData);
}
}
outputTable.setModel(listTableModel);
}
}
});
}
public void selectAllBut() {
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
java.util.List outputList = roosterDatabase.selectAll();
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
Iterator itrTable = outputList.iterator();
while (itrTable.hasNext()) {
Rooster record = (Rooster) itrTable.next();
String[] colData = new String[5];
colData[0] = Integer.valueOf(record.getId()).toString();
colData[1] = record.getBewaker().getBewaker_naam().toString();
colData[2] = record.getPost().getPost_naam().toString();
colData[3] = record.getDag().getDag().toString();
colData[4] = record.getDag().getShift().toString();
listTableModel.addRow(colData);
}
outputTable.setModel(listTableModel);
}
}
public void homePanel() {
}
public void buildArrays() {
roosterArrayListID.clear();
roosterArrayListObject.clear();
bewakerArrayListNames.clear();
bewakerArrayListObject.clear();
postArraylist.clear();
postArrayListObject.clear();
dagtArraylist.clear();
dagArrayListObject.clear();
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (postDatabase == null) {
postDatabase = new PostDatabase();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (dagDatabase == null) {
dagDatabase = new DagDatabase();
}
if (!dagDatabase.isInitialised()) {
dagDatabase.initialiseer();
}
// creating the roosterArraylists
Iterator<Rooster> itrRooster = roosterDatabase.selectAll().iterator();
while (itrRooster.hasNext()) {
Rooster i = (Rooster) itrRooster.next();
roosterArrayListObject.add(i);
}
//creating the postArraylists
Iterator<Post> itrPost = postDatabase.selectAll().iterator();
while (itrPost.hasNext()) {
Post i = (Post) itrPost.next();
postArrayListObject.add(i);
postArraylist.add(i.getPost_naam());
}
//creating the bewakerArraylists
Iterator<Bewaker> itrBewaker = bewakerDatabase.selectAll().iterator();
while (itrBewaker.hasNext()) {
Bewaker i = (Bewaker) itrBewaker.next();
bewakerArrayListObject.add(i);
bewakerArrayListNames.add(i.getBewaker_naam());
}
//creating the dagLists
Iterator<Dag> itrDag = dagDatabase.selectAll().iterator();
while (itrDag.hasNext()) {
Dag i = (Dag) itrDag.next();
dagArrayListObject.add(i);
dagtArraylist.add(i.getDag());
}
}
} | JairJosafath/BP | beroepsProduct/datakeeper/src/sr/unasat/bewakingsBedrijf/app/scherm/rooster/RoosterScherm.java | 5,232 | // Alleen als de roosteren database is geinitialiseerd dan verder | line_comment | nl | package sr.unasat.bewakingsBedrijf.app.scherm.rooster;
//import javafx.scene.shape.Circle;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.Bewaker;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.bewaker.BewakerDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.dag.Dag;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.dag.DagDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.post.Post;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.post.PostDatabase;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.Rooster;
import sr.unasat.bewakingsBedrijf.app.databaseConnection.rooster.RoosterDatabase;
import sr.unasat.bewakingsBedrijf.app.scherm.algemeen.StartScherm;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.interfaces.RSAKey;
import java.util.*;
/**
* Created by Jair on 5/16/2016.
*/
public class RoosterScherm extends JFrame {
RoosterDatabase roosterDatabase = null;
PostDatabase postDatabase = null;
BewakerDatabase bewakerDatabase = null;
DagDatabase dagDatabase = null;
JPanel bewakerRoosterPan = new JPanel(new BorderLayout()), allRoosterPan = new JPanel(), homePan = new JPanel();
JTabbedPane jTabbedPane = new JTabbedPane(SwingConstants.LEFT);
ArrayList<Rooster> roosterArrayListObject = new ArrayList<>();
ArrayList<Integer> roosterArrayListID = new ArrayList<>();
ArrayList<Post> postArrayListObject = new ArrayList<>();
ArrayList<String> postArraylist = new ArrayList<>();
ArrayList<Dag> dagArrayListObject = new ArrayList<>();
ArrayList<String> dagtArraylist = new ArrayList<>();
ArrayList<Bewaker> bewakerArrayListObject = new ArrayList<>();
ArrayList<String> bewakerArrayListNames = new ArrayList<>();
JComboBox dagBox, postBox, bewakerBox;
private DefaultTableModel listTableModel;
private JTable outputTable;
ImageIcon icon = new ImageIcon(getClass().getResource("bewaker.png"));
ImageIcon homeIcon = new ImageIcon(getClass().getResource("home.png"));
ImageIcon roostersIcon = new ImageIcon(getClass().getResource("rooster.png"));
public RoosterScherm() {
//jTabbedPane.setBackground(new Color(10,126,192));
//jTabbedPane.setIconAt(0,icon);
// jTabbedPane.add(" all roosters ",allRoosterPan);
//jTabbedPane.add(" bewaker rooster ",bewakerRoosterPan);
jTabbedPane.setBackground(new Color(148, 178, 173));
jTabbedPane.addTab(" all roosters ", roostersIcon, allRoosterPan);
jTabbedPane.addTab("bewaker rooster", icon, bewakerRoosterPan);
jTabbedPane.addTab("home", homeIcon, homePan);
allroostersPanel();
add(jTabbedPane);
getContentPane().setBackground(new Color(7, 84, 127));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(900, 500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
jTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (allRoosterPan.isShowing()) {
allroostersPanel();
} else {
allRoosterPan.removeAll();
}
if (bewakerRoosterPan.isShowing()) {
bewakerRoosterPanel();
} else {
bewakerRoosterPan.removeAll();
}
if (homePan.isShowing()) {
setVisible(false);
new StartScherm();
}
}
});
}
public void allroostersPanel() {
buildArrays();
JPanel buttonPanel = new JPanel(new BorderLayout()), outputPanel = new JPanel(), viewAllButPanel = new JPanel(), buttonPanelOtther = new JPanel(new GridBagLayout());
JButton viewAllBut = new JButton("view all"), deleteBut = new JButton("delete selected rooster"),
updateBut = new JButton("update selected rooster"), addBut = new JButton("add new rooster"),
saveBut = new JButton("save added rooster");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(20, 20, 20, 20);
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
listTableModel = new DefaultTableModel();
String[] colnames = {"id", "bewaker", "post", "dag", "shift"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
outputTable = new JTable(null, colnamesV);
JScrollPane tablePanel = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
outputPanel.add(tablePanel);
outputTable.setBackground(new Color(148, 178, 173));
//creating comboboxes for table cell editors
dagBox = new JComboBox(new DefaultComboBoxModel<>(dagtArraylist.toArray()));
postBox = new JComboBox(new DefaultComboBoxModel<>(postArraylist.toArray()));
bewakerBox = new JComboBox(new DefaultComboBoxModel<>(bewakerArrayListNames.toArray()));
//{"id","bewaker", "post", "dag","shift"};
TableColumn bewColumn = outputTable.getColumnModel().getColumn(1);
bewColumn.setCellEditor(new DefaultCellEditor(bewakerBox));
TableColumn postColumn = outputTable.getColumnModel().getColumn(2);
postColumn.setCellEditor(new DefaultCellEditor(postBox));
TableColumn dagColumn = outputTable.getColumnModel().getColumn(3);
dagColumn.setCellEditor(new DefaultCellEditor(dagBox));
viewAllButPanel.add(viewAllBut);
gbc.gridx = 0;
gbc.gridy = 0;
buttonPanelOtther.add(addBut, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
buttonPanelOtther.add(saveBut, gbc);
gbc.gridx = 2;
buttonPanelOtther.add(updateBut, gbc);
gbc.gridx = 3;
buttonPanelOtther.add(deleteBut, gbc);
buttonPanelOtther.setBackground(new Color(7, 84, 127));
viewAllButPanel.setBackground(new Color(7, 84, 127));
buttonPanel.add(viewAllButPanel, BorderLayout.NORTH);
buttonPanel.add(buttonPanelOtther, BorderLayout.CENTER);
allRoosterPan.setLayout(new BorderLayout());
allRoosterPan.add(buttonPanel, BorderLayout.NORTH);
allRoosterPan.add(outputPanel, BorderLayout.CENTER);
viewAllBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAllBut();
}
});
addBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
listTableModel.addRow(new Object[]{null, null, null, null});
}
});
saveBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (outputTable.getValueAt(outputTable.getSelectedRow(), 0).toString() != null) {
JOptionPane.showMessageDialog(saveBut, " be sure to select the new row before saving");
}
} catch (Exception e1) {
//if(listTableModel.getValueAt(i, 2).equals(postArrayListObject.get(i).getDag()))
try {
Rooster rooster = new Rooster();
roosterDatabase = new RoosterDatabase();
bewakerDatabase = new BewakerDatabase();
postDatabase = new PostDatabase();
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
if (!dagDatabase.isInitialised()) {
dagDatabase.initialiseer();
}
// {"id","bewaker", "post", "dag","shift"};
buildArrays();
int selectedRow = outputTable.getSelectedRow();
for (int i = 0; i < bewakerArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 1).getCellEditorValue().toString().equals(bewakerArrayListObject.get(i).getBewaker_naam())) {
rooster.setBewaker_fk(bewakerDatabase.selectAll().get(i).getId());
i = bewakerArrayListObject.size() + 1;
}
}
for (int i = 0; i < postArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 2).getCellEditorValue().toString().equals(postArrayListObject.get(i).getPost_naam())) {
rooster.setPost_fk(postDatabase.selectAll().get(i).getId());
i = postArrayListObject.size() + 1;
}
}
for (int i = 0; i < dagArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 3).getCellEditorValue().toString().equals(dagArrayListObject.get(i).getDag())) {
rooster.setDag_fk(dagDatabase.selectAll().get(i).getId());
i = dagArrayListObject.size() + 1;
}
}
// {"id","bewaker", "post", "dag","shift"};
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
// Alleen als<SUF>
if (roosterDatabase.isInitialised()) {
roosterDatabase.insertRooster(rooster);
JOptionPane.showMessageDialog(saveBut, "rooster succesfully added");
}
// Initialiseer de studentDatabase alleen als het moet
} catch (Exception e2) {
JOptionPane.showMessageDialog(saveBut, " error ?????");
System.out.println(e2);
}
}
}
});
updateBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//if(listTableModel.getValueAt(i, 2).equals(postArrayListObject.get(i).getDag()))
Rooster rooster = new Rooster();
roosterDatabase = new RoosterDatabase();
bewakerDatabase = new BewakerDatabase();
postDatabase = new PostDatabase();
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
// {"id","bewaker", "post", "dag","shift"};
buildArrays();
int selectedRow = outputTable.getSelectedRow();
for (int i = 0; i < bewakerArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 1).getCellEditorValue().toString().equals(bewakerArrayListObject.get(i).getBewaker_naam())) {
rooster.setBewaker_fk(bewakerDatabase.selectAll().get(i).getId());
i = bewakerArrayListObject.size() + 1;
}
}
for (int i = 0; i < postArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 2).getCellEditorValue().toString().equals(postArrayListObject.get(i).getPost_naam())) {
rooster.setPost_fk(postDatabase.selectAll().get(i).getId());
i = postArrayListObject.size() + 1;
}
}
for (int i = 0; i < dagArrayListObject.size(); i++) {
if (outputTable.getCellEditor(selectedRow, 3).getCellEditorValue().toString().equals(dagArrayListObject.get(i).getDag())) {
rooster.setDag_fk(dagDatabase.selectAll().get(i).getId());
i = dagArrayListObject.size() + 1;
}
}
int i = outputTable.getSelectedRow();
Object roosterIdObject = outputTable.getValueAt(i, 0);
String roosterIdString = roosterIdObject.toString();
int roosterID = Integer.parseInt(roosterIdString);
rooster.setId(roosterID);
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
roosterDatabase.updateRooster(rooster);
JOptionPane.showMessageDialog(updateBut, "rooster update succesful");
} else {
JOptionPane.showMessageDialog(updateBut, "rooster update succesful");
}
}
});
deleteBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null,
"Are you sure to delete rooster?", null, JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
int i = outputTable.getSelectedRow();
Object roosterIdObject = outputTable.getValueAt(i, 0);
String roosterIdString = roosterIdObject.toString();
int roosterID = Integer.parseInt(roosterIdString);
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
// Alleen als de studenten database is geinitialiseerd dan verder
if (roosterDatabase.isInitialised()) {
roosterDatabase.deleteRooster(roosterID);
listTableModel.removeRow(i);
JOptionPane.showMessageDialog(deleteBut, "rooster deleted");
allRoosterPan.removeAll();
allroostersPanel();
selectAllBut();
}
} else {
JOptionPane.showMessageDialog(deleteBut, "rooster is not deleted");
}
}
});
}
public void bewakerRoosterPanel() {
JPanel upperPanel = new JPanel(new GridBagLayout());
JPanel tablePanel = new JPanel();
JButton go = new JButton("go");
upperPanel.setBackground(new Color(7, 84, 127));
tablePanel.setBackground(new Color(7, 84, 127));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets.set(5, 0, 5, 0);
JComboBox jComboBox = new JComboBox(new DefaultComboBoxModel(bewakerArrayListNames.toArray()));
JLabel viewRoosterLabel = new JLabel("select bewaker to view rooster");
viewRoosterLabel.setForeground(Color.white);
listTableModel = new DefaultTableModel();
String[] colnames = {"post", "dag", "tijd"};
Vector colnamesV = new Vector(Arrays.asList(colnames));
JTable outputTable = new JTable(null, colnamesV);
JScrollPane tableScroll = new JScrollPane(outputTable);
tablePanel.setPreferredSize(new Dimension(800, 150));
tablePanel.add(tableScroll);
outputTable.setBackground(new Color(148, 178, 173));
gbc.gridx = 0;
gbc.gridy = 0;
upperPanel.add(viewRoosterLabel, gbc);
gbc.gridx = 0;
gbc.gridy = -1;
upperPanel.add(jComboBox, gbc);
gbc.gridx = 0;
gbc.gridy = -2;
upperPanel.add(go, gbc);
bewakerRoosterPan.add(upperPanel, BorderLayout.NORTH);
bewakerRoosterPan.add(tablePanel, BorderLayout.CENTER);
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buildArrays();
int i = jComboBox.getSelectedIndex();
int record = bewakerArrayListObject.get(i).getId();
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
int lastindex = roosterArrayListObject.get(roosterArrayListObject.size() - 1).getId();
for (int a = 0; a < lastindex + 1; a++) {
if (bewakerDatabase.selectBewaker(record).getId() == roosterDatabase.selectRooster(a).getBewaker_fk()) {
String[] colData = new String[3];
colData[0] = roosterDatabase.selectRooster(a).getPost().getPost_naam();
colData[1] = roosterDatabase.selectRooster(a).getDag().getDag();
colData[2] = roosterDatabase.selectRooster(a).getDag().getShift();
listTableModel.addRow(colData);
}
}
outputTable.setModel(listTableModel);
}
}
});
}
public void selectAllBut() {
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
// Initialiseer de roosterDatabase alleen als het moet
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (roosterDatabase.isInitialised()) {
java.util.List outputList = roosterDatabase.selectAll();
listTableModel = (DefaultTableModel) outputTable.getModel();
listTableModel.setRowCount(0);
Iterator itrTable = outputList.iterator();
while (itrTable.hasNext()) {
Rooster record = (Rooster) itrTable.next();
String[] colData = new String[5];
colData[0] = Integer.valueOf(record.getId()).toString();
colData[1] = record.getBewaker().getBewaker_naam().toString();
colData[2] = record.getPost().getPost_naam().toString();
colData[3] = record.getDag().getDag().toString();
colData[4] = record.getDag().getShift().toString();
listTableModel.addRow(colData);
}
outputTable.setModel(listTableModel);
}
}
public void homePanel() {
}
public void buildArrays() {
roosterArrayListID.clear();
roosterArrayListObject.clear();
bewakerArrayListNames.clear();
bewakerArrayListObject.clear();
postArraylist.clear();
postArrayListObject.clear();
dagtArraylist.clear();
dagArrayListObject.clear();
if (roosterDatabase == null) {
roosterDatabase = new RoosterDatabase();
}
if (!roosterDatabase.isInitialised()) {
roosterDatabase.initialiseer();
}
if (postDatabase == null) {
postDatabase = new PostDatabase();
}
if (!postDatabase.isInitialised()) {
postDatabase.initialiseer();
}
if (bewakerDatabase == null) {
bewakerDatabase = new BewakerDatabase();
}
if (!bewakerDatabase.isInitialised()) {
bewakerDatabase.initialiseer();
}
if (dagDatabase == null) {
dagDatabase = new DagDatabase();
}
if (!dagDatabase.isInitialised()) {
dagDatabase.initialiseer();
}
// creating the roosterArraylists
Iterator<Rooster> itrRooster = roosterDatabase.selectAll().iterator();
while (itrRooster.hasNext()) {
Rooster i = (Rooster) itrRooster.next();
roosterArrayListObject.add(i);
}
//creating the postArraylists
Iterator<Post> itrPost = postDatabase.selectAll().iterator();
while (itrPost.hasNext()) {
Post i = (Post) itrPost.next();
postArrayListObject.add(i);
postArraylist.add(i.getPost_naam());
}
//creating the bewakerArraylists
Iterator<Bewaker> itrBewaker = bewakerDatabase.selectAll().iterator();
while (itrBewaker.hasNext()) {
Bewaker i = (Bewaker) itrBewaker.next();
bewakerArrayListObject.add(i);
bewakerArrayListNames.add(i.getBewaker_naam());
}
//creating the dagLists
Iterator<Dag> itrDag = dagDatabase.selectAll().iterator();
while (itrDag.hasNext()) {
Dag i = (Dag) itrDag.next();
dagArrayListObject.add(i);
dagtArraylist.add(i.getDag());
}
}
} |
105601_6 | /**
* Das ist die "Hauptklasse" des Roboter Programms
* Alle weiteren Klassen werden hier aufgerufen
* @Author Chris
* @version 2019.03.013
*/
package team02.chris;
import ch.ntb.inf.deep.runtime.ppc32.Task;
import team02.*;
import team02.vorlagen.*;
import team02.vorlagen.Sharp;
import static team02.Zustand.*;
public class Main extends Task implements IO,Systems
{
private Zustand zustand = SETUP;
private Zustand letzter_Zustand;
/**
* Initialisieren der Tasks
*/
static
{
try
{
Task task = new Main();
task.period = Konstanten.TASK_PERIOD;
Task.install(task);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Konstruktor
*/
public Main()
{
IN_Taster1.set(true);
}
/**
* diagrammDummy erzeugt k�nstlich Abhaengigkeiten fuer Klassendiagramm
* */
protected void diagrammDummy(WurfSystem wurfsystem,BewegungsSystem bewegungsSystem,DebugSystem debugSystem,GegnerSystem gegnerSystem,WlanSystem wlanSystem)
{
}
/**
* Methode die Zyklisch aufgerufen wird
*/
public void action()
{
update();
if (Konstanten.DEBUG) //wird nur aufgerufen wenn Debug aktiviert ist
{
}
if (Konstanten.TEST)
{
}
//Fehler erkannt
if(false)
{
letzter_Zustand = zustand;
zustand = FEHLER;
}
zustand(); //Zustaende gemaess Zustandsdiagramm
}
/**
* Schrittkette
*/
private void zustand()
{
switch (zustand)
{
case SETUP: //Dies ist der Startzustand
{
setup();
break;
}
case SPIEL_BEGINNT: //Kommentar
{
spiel_beginnt();
break;
}
case ROB_HAT_KEIN_BALL: //Roboter hat keinen Ball
{
rob_hat_kein_ball();
break;
}
case ROB_FAEHRT: //Roboter faehrt
{
rob_faehrt();
break;
}
case ROB_HAT_BALL: //Roboter hat Ball
{
rob_hat_ball();
break;
}
case ROB_POSITION_ERREICHT: //Roboter hat Position erreicht
{
rob_position_erreicht();
break;
}
case KORB_WURF: //Korb Wurf
{
korb_wurf();
break;
}
case KURZER_WURF: //Kurzer Wurf
{
kurzer_wurf();
break;
}
case LANGER_WURF: //Langer Wurf
{
langer_wurf();
break;
}
case ENDE:
{
ende();
break;
}
case FEHLER:
{
fehler();
break;
}
default:
{
zustand = FEHLER;
break;
}
}
}
/**
* Setup Methode
*/
private void setup()
{
if(false) //Weiterschaltbedingung
{
zustand = SPIEL_BEGINNT;
}
}
/**
* Spiel beginnt Zustand
*/
private void spiel_beginnt()
{
if(false)
{
zustand = ROB_HAT_BALL;
}
else if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* Rob Hat kein Ball Zustand
*/
private void rob_hat_kein_ball()
{
if (false)
{
zustand = ROB_FAEHRT;
}
}
/**
* Rob Faehrt Zustand
*/
private void rob_faehrt()
{
if(false)
{
zustand = ROB_POSITION_ERREICHT;
}
}
/**
* Rob Hat Ball Zustand
*/
private void rob_hat_ball()
{
if(false)
{
zustand = KORB_WURF;
}
else if(false)
{
zustand = LANGER_WURF;
}
else if (false)
{
zustand = KURZER_WURF;
}
}
/**
* Rob Position Erreicht Zustand
*/
private void rob_position_erreicht()
{
if(false)
{
zustand = ROB_HAT_BALL;
}
}
/**
* Korb Wurf Zustand
*/
private void korb_wurf()
{
if(false)
{
zustand = ENDE;
}
}
/**
* Kurzer Wurf Zustand
*/
private void kurzer_wurf()
{
if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* Langer Wurf Zustand
*/
private void langer_wurf()
{
if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* End Zustand
*/
private void ende()
{
}
/**
* Fehler Zustand
*/
private void fehler()
{
}
/**
* Ruft alle anderen update methoden auf
*/
private void update()
{
bewegungsSystem.update();
debugSystem.update();
gegnerSystem.update();
wlanSystem.update();
wurfSystem.update();
}
}
| elevator4096/SysP19_Team02_Software | src/team02/chris/Main.java | 1,505 | //Zustaende gemaess Zustandsdiagramm | line_comment | nl | /**
* Das ist die "Hauptklasse" des Roboter Programms
* Alle weiteren Klassen werden hier aufgerufen
* @Author Chris
* @version 2019.03.013
*/
package team02.chris;
import ch.ntb.inf.deep.runtime.ppc32.Task;
import team02.*;
import team02.vorlagen.*;
import team02.vorlagen.Sharp;
import static team02.Zustand.*;
public class Main extends Task implements IO,Systems
{
private Zustand zustand = SETUP;
private Zustand letzter_Zustand;
/**
* Initialisieren der Tasks
*/
static
{
try
{
Task task = new Main();
task.period = Konstanten.TASK_PERIOD;
Task.install(task);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Konstruktor
*/
public Main()
{
IN_Taster1.set(true);
}
/**
* diagrammDummy erzeugt k�nstlich Abhaengigkeiten fuer Klassendiagramm
* */
protected void diagrammDummy(WurfSystem wurfsystem,BewegungsSystem bewegungsSystem,DebugSystem debugSystem,GegnerSystem gegnerSystem,WlanSystem wlanSystem)
{
}
/**
* Methode die Zyklisch aufgerufen wird
*/
public void action()
{
update();
if (Konstanten.DEBUG) //wird nur aufgerufen wenn Debug aktiviert ist
{
}
if (Konstanten.TEST)
{
}
//Fehler erkannt
if(false)
{
letzter_Zustand = zustand;
zustand = FEHLER;
}
zustand(); //Zustaende gemaess<SUF>
}
/**
* Schrittkette
*/
private void zustand()
{
switch (zustand)
{
case SETUP: //Dies ist der Startzustand
{
setup();
break;
}
case SPIEL_BEGINNT: //Kommentar
{
spiel_beginnt();
break;
}
case ROB_HAT_KEIN_BALL: //Roboter hat keinen Ball
{
rob_hat_kein_ball();
break;
}
case ROB_FAEHRT: //Roboter faehrt
{
rob_faehrt();
break;
}
case ROB_HAT_BALL: //Roboter hat Ball
{
rob_hat_ball();
break;
}
case ROB_POSITION_ERREICHT: //Roboter hat Position erreicht
{
rob_position_erreicht();
break;
}
case KORB_WURF: //Korb Wurf
{
korb_wurf();
break;
}
case KURZER_WURF: //Kurzer Wurf
{
kurzer_wurf();
break;
}
case LANGER_WURF: //Langer Wurf
{
langer_wurf();
break;
}
case ENDE:
{
ende();
break;
}
case FEHLER:
{
fehler();
break;
}
default:
{
zustand = FEHLER;
break;
}
}
}
/**
* Setup Methode
*/
private void setup()
{
if(false) //Weiterschaltbedingung
{
zustand = SPIEL_BEGINNT;
}
}
/**
* Spiel beginnt Zustand
*/
private void spiel_beginnt()
{
if(false)
{
zustand = ROB_HAT_BALL;
}
else if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* Rob Hat kein Ball Zustand
*/
private void rob_hat_kein_ball()
{
if (false)
{
zustand = ROB_FAEHRT;
}
}
/**
* Rob Faehrt Zustand
*/
private void rob_faehrt()
{
if(false)
{
zustand = ROB_POSITION_ERREICHT;
}
}
/**
* Rob Hat Ball Zustand
*/
private void rob_hat_ball()
{
if(false)
{
zustand = KORB_WURF;
}
else if(false)
{
zustand = LANGER_WURF;
}
else if (false)
{
zustand = KURZER_WURF;
}
}
/**
* Rob Position Erreicht Zustand
*/
private void rob_position_erreicht()
{
if(false)
{
zustand = ROB_HAT_BALL;
}
}
/**
* Korb Wurf Zustand
*/
private void korb_wurf()
{
if(false)
{
zustand = ENDE;
}
}
/**
* Kurzer Wurf Zustand
*/
private void kurzer_wurf()
{
if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* Langer Wurf Zustand
*/
private void langer_wurf()
{
if(false)
{
zustand = ROB_HAT_KEIN_BALL;
}
}
/**
* End Zustand
*/
private void ende()
{
}
/**
* Fehler Zustand
*/
private void fehler()
{
}
/**
* Ruft alle anderen update methoden auf
*/
private void update()
{
bewegungsSystem.update();
debugSystem.update();
gegnerSystem.update();
wlanSystem.update();
wurfSystem.update();
}
}
|
14086_45 | /* Project Supermarkt - OOP & Software Ontwerp
* Supermarkt.java
* Hidde Westerhof | i2A
* In samenwerking met:
* Rik de Boer
* Tjipke van der Heide
* Yannick Strobl
*/
/* TODO LIST!!!!!!
* Overgang afdeling voordeelpad
* Operators op verschillende plekken
* Geenbijstand moet uitgewerkt worden
* Het pakken van producten uit schappen en of afdeling.
* Het afrekenen
* Hibernate
* JavaDOCS
* Astah
* Kan magazijn weg?
*/
package supermarkt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
*
* @author Driving Ghost
*/
public class Supermarkt {
static ArrayList<Werknemer> werkActief = new ArrayList<>(); //Werknemers die wat aan het doen zijn
static ArrayList<Werknemer> werkPauze = new ArrayList<>(); //Werknemers die niks aan het doen zijn! Arbeiten >:(!
static ArrayList<String> toDo = new ArrayList<>(); //een lijst van taken die werknemers nog moeten doen
static ArrayList<Kassa> kassas = new ArrayList<>(); //een lijst van mogelijke kassas
static ArrayList<Pad> paden = new ArrayList<>(); //een lijst van alle paden
static ArrayList<Afdeling> afdelingen = new ArrayList<>(); //een lijst van alle afdelingen
static ArrayList<Klant> klanten = new ArrayList<>(); //Lijst van alle klanten (static want hij wordt in static methoden aangeroepen)
static ArrayList<String> namen = new ArrayList<>(); //Lijst met alle namen van een .txt file. Gebruikt door Werknemers en Klanten.
static ArrayList<Artikel> inventaris = new ArrayList<>(); //Lijst met alle artikelen in de winkel.
//static Voordeelpad vdpad;
static Magazijn magazijn;
private static ArrayList<ArrayList<Klant>> klanten2;
/**
* Main methode, start het hele gebeuren op commando van de GUI.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
///Toont de GUI klasse.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GUI());
frame.pack();
frame.setVisible(true);
}
});
initPad(); // Vult de padenlijst
initAfd(); // Vult de afdelingenlijst
initNames(); // Vult de namenlijst
initJobs(); // Vult de todoList met inititele taken
initInventaris(); // Vult de Inventaris met mogelijke producten
initKassas(); // Vult kassalijst met kassas, zonder operators.
Random r = new Random(); // Maakt Random aan
boolean limitset = false; // Check of GUI de limit gezet heeft
double limit = 8.0; // Standaard limiet waaraan moet worden voldaan.
for (int i = 0; i < 4; i++) {
werkPauze.add(new Werknemer());
}
// paden.add();
while (true) {
if (limitset) {
try {
Thread.sleep(100); //voor debug redenen
Double timed = r.nextDouble(); //onze random kans
generateKlant(timed, limit, r); //maakt klanten aan
} catch (Exception e) {
System.out.println(e.getMessage());
break; //we stoppen met de simulatie.
}
updateGUI(paden, afdelingen); //update Graphical User Interface met klantinformatie.
geenBijstand(); //zet medewerkers aan het werk.
koopPaden(); //update klanten in paden
koopAfdelingen(); //update klanten in afdelingen
koopVoordeel(); //update klanten in voordeelpad.
betaalProducten();
} else {
System.out.print(""); //Dit is nodig voor de Thread.
limitset = GUI.limitset;
limit = GUI.limit;
}
}
}
public static void generateKlant(double timed, double limit, Random r) {
if (timed > limit) {
int itop = r.nextInt(10);
//Check of itop negatief is, kan namelijk niet een negatief aantal klanten toevoegen
if (itop < 0) {
itop *= -1;
}
//voegt een aantal klanten toe, afhangend van het nummer dat bij itop gemaakt is.
for (int i = 0; i < itop; i++) {
paden.get(0).klanten.add(Supermarkt.maakKlant());
}
//limitcheck.
if (limit <= GUI.limit) {
limit += 0.1;
}
} else { //geen klant is toeworden gevoegd.
limit -= 0.05;
}
}
/**
* updateGUI
*
* @param paden alle paden, artikelen, en voordeelpad
*/
public static void updateGUI(ArrayList<Pad> paden, ArrayList<Afdeling> afdelingen) {
GUI.addKlant(paden, afdelingen);
}
public static void koopPaden() {
for (Pad p : paden) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : p.klanten) {
k.winkelen(p);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
p.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Pad p : paden) {
klanten2.add(p.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//beweging van laatste pad naar afdeling.
if (!(paden.get(paden.size() - 1)).klanten.isEmpty()) { //if last pad !empty
paden.get(paden.size() - 1).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(0).klanten = klanten2.get(paden.size() - 1);
klanten2.set(paden.size() - 1, new ArrayList<Klant>());
}
//daadwerkelijke beweging tussen paden
for (int i = 0; i < paden.size(); i++) {
if (i == (0)) {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(paden.size() - 1);//
} else {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopAfdelingen() {
for (Afdeling a : afdelingen) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : a.klanten) {
k.winkelen(a);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
a.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Afdeling a : afdelingen) {
klanten2.add(a.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//daadwerkelijke beweging.
for (int i = 0; i < afdelingen.size(); i++) {
if (i == (0)) {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(afdelingen.size() - 1);//
} else {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopVoordeel() {
}
public static void betaalProducten(){
for(Kassa k : kassas){
k.scanArtikelen();
}
}
public static void gaKassa(Klant K) {
int beste = kassas.get(0).klanten.size();
int kassaIndex = 0;
for (int i = 0; i < kassas.size(); i++) {
if (kassas.get(i).klanten.size() < beste && kassas.get(i).operator != null) {
kassaIndex = i;
}
}
kassas.get(kassaIndex).klanten.add(K);
}
/**
* initNames voegt namen toe aan de static lijst Namen. Hieruit haalt de
* klasse Klant en Werknemer zijn naam.
*/
public static void initNames() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(Supermarkt.class.getResourceAsStream("randomnames.txt")));
String line;
while ((line = br.readLine()) != null) {
namen.add(line);
}
br.close();
} catch (IOException e) {
//System.out.println(e.getMessage());
}
}
/**
* *
* Initialiseert de inventaris van de winkel. Heeft effect op (nog niks)
* klant zijn wishlist, pad zijn inventaris, afdeling zijn inventaris.
*/
public static void initInventaris() {
for (int i = 0; i < Supermarkt.paden.size(); i++) {
for (int x = 0; x < paden.get(i).artikelen.size(); x += 10) {
inventaris.add(paden.get(i).artikelen.get(x));
}
}
for (int i = 0; i < Supermarkt.afdelingen.size(); i++) {
for (int x = 0; x < afdelingen.get(i).artikelen.size(); x += 5) {
inventaris.add(afdelingen.get(i).artikelen.get(x));
}
}
}
/**
*
*/
public static void initKassas(){
for(int i = 0; i < GUI.kassa; i++){
kassas.add(new Kassa());
}
}
/**
* *
* InitJobs vult de lijst toDo met dingen die nog gedaan moeten worden in de
* opstart van het programma.
*
*/
public static void initJobs() {
toDo.add("Brood");
toDo.add("Kaas");
toDo.add("Kassa");
}
/**
* initPad is het maken van alle paden vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een pad aangemaakt
*/
public static void initPad() {
ArrayList<String> vars = new ArrayList<>();
vars.add("koekjes");
vars.add("azie");
vars.add("drank");
vars.add("zuivel");
vars.add("snoep");
for (int i = 0; i < vars.size(); i++) {
paden.add(new Pad(vars.get(i), 2, 10));
}
//vdp = new Voordeelpad();
}
/**
* initAfd is het maken van alle afdelingen vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een afdelingstype aangemaakt
*/
public static void initAfd() {
ArrayList<String> vars = new ArrayList<>();
vars.add("deegwaar");
vars.add("fruit");
vars.add("vleeswaar");
vars.add("zuivel");
for (int i = 0; i < vars.size(); i++) {
afdelingen.add(new Afdeling(vars.get(i), 1, 5));
}
}
/**
*
* geenBijstand methode zorgt ervoor dat werknemers in de werkPauze in
* werkActief komen te staan met een functie.
*
* @param werkPauze Lijst met non-actieve werknemers
* @param toDo lijst met dingen die er gedaan moeten worden
*/
public static void geenBijstand() {
try {
if (!werkPauze.isEmpty()) {
if (!toDo.isEmpty()) {
werkPauze.get(0).taak = toDo.get(0);
werkActief.add(werkPauze.get(0));
// System.out.println(werkPauze.get(0).Naam + " is now going to do job: " + werkPauze.get(0).taak);
werkPauze.remove(0);
toDo.remove(0);
} else {
//System.out.println(werkPauze.get(0).Naam + " has no dedicated task. Checking stocks.");
werkPauze.get(0).taak = "bijvullen";
werkActief.add(werkPauze.get(0));
werkPauze.remove(0);
}
}
} catch (Exception e) {
}
}
/**
* *
* maakKlant methode voegt klanten toe aan de klanten lijst
*
* @return een nieuw aangemaakte klant
*/
public static Klant maakKlant() {
try {
Klant k = new Klant();
klanten.add(k);
return k;
} catch (Exception E) {
System.out.println(E.getMessage());
}
return null;
}
}
| vancha/Containing | JavaApplication2/src/supermarkt/Supermarkt.java | 3,899 | //om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
| line_comment | nl | /* Project Supermarkt - OOP & Software Ontwerp
* Supermarkt.java
* Hidde Westerhof | i2A
* In samenwerking met:
* Rik de Boer
* Tjipke van der Heide
* Yannick Strobl
*/
/* TODO LIST!!!!!!
* Overgang afdeling voordeelpad
* Operators op verschillende plekken
* Geenbijstand moet uitgewerkt worden
* Het pakken van producten uit schappen en of afdeling.
* Het afrekenen
* Hibernate
* JavaDOCS
* Astah
* Kan magazijn weg?
*/
package supermarkt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
*
* @author Driving Ghost
*/
public class Supermarkt {
static ArrayList<Werknemer> werkActief = new ArrayList<>(); //Werknemers die wat aan het doen zijn
static ArrayList<Werknemer> werkPauze = new ArrayList<>(); //Werknemers die niks aan het doen zijn! Arbeiten >:(!
static ArrayList<String> toDo = new ArrayList<>(); //een lijst van taken die werknemers nog moeten doen
static ArrayList<Kassa> kassas = new ArrayList<>(); //een lijst van mogelijke kassas
static ArrayList<Pad> paden = new ArrayList<>(); //een lijst van alle paden
static ArrayList<Afdeling> afdelingen = new ArrayList<>(); //een lijst van alle afdelingen
static ArrayList<Klant> klanten = new ArrayList<>(); //Lijst van alle klanten (static want hij wordt in static methoden aangeroepen)
static ArrayList<String> namen = new ArrayList<>(); //Lijst met alle namen van een .txt file. Gebruikt door Werknemers en Klanten.
static ArrayList<Artikel> inventaris = new ArrayList<>(); //Lijst met alle artikelen in de winkel.
//static Voordeelpad vdpad;
static Magazijn magazijn;
private static ArrayList<ArrayList<Klant>> klanten2;
/**
* Main methode, start het hele gebeuren op commando van de GUI.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
///Toont de GUI klasse.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GUI());
frame.pack();
frame.setVisible(true);
}
});
initPad(); // Vult de padenlijst
initAfd(); // Vult de afdelingenlijst
initNames(); // Vult de namenlijst
initJobs(); // Vult de todoList met inititele taken
initInventaris(); // Vult de Inventaris met mogelijke producten
initKassas(); // Vult kassalijst met kassas, zonder operators.
Random r = new Random(); // Maakt Random aan
boolean limitset = false; // Check of GUI de limit gezet heeft
double limit = 8.0; // Standaard limiet waaraan moet worden voldaan.
for (int i = 0; i < 4; i++) {
werkPauze.add(new Werknemer());
}
// paden.add();
while (true) {
if (limitset) {
try {
Thread.sleep(100); //voor debug redenen
Double timed = r.nextDouble(); //onze random kans
generateKlant(timed, limit, r); //maakt klanten aan
} catch (Exception e) {
System.out.println(e.getMessage());
break; //we stoppen met de simulatie.
}
updateGUI(paden, afdelingen); //update Graphical User Interface met klantinformatie.
geenBijstand(); //zet medewerkers aan het werk.
koopPaden(); //update klanten in paden
koopAfdelingen(); //update klanten in afdelingen
koopVoordeel(); //update klanten in voordeelpad.
betaalProducten();
} else {
System.out.print(""); //Dit is nodig voor de Thread.
limitset = GUI.limitset;
limit = GUI.limit;
}
}
}
public static void generateKlant(double timed, double limit, Random r) {
if (timed > limit) {
int itop = r.nextInt(10);
//Check of itop negatief is, kan namelijk niet een negatief aantal klanten toevoegen
if (itop < 0) {
itop *= -1;
}
//voegt een aantal klanten toe, afhangend van het nummer dat bij itop gemaakt is.
for (int i = 0; i < itop; i++) {
paden.get(0).klanten.add(Supermarkt.maakKlant());
}
//limitcheck.
if (limit <= GUI.limit) {
limit += 0.1;
}
} else { //geen klant is toeworden gevoegd.
limit -= 0.05;
}
}
/**
* updateGUI
*
* @param paden alle paden, artikelen, en voordeelpad
*/
public static void updateGUI(ArrayList<Pad> paden, ArrayList<Afdeling> afdelingen) {
GUI.addKlant(paden, afdelingen);
}
public static void koopPaden() {
for (Pad p : paden) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : p.klanten) {
k.winkelen(p);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
p.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Pad p : paden) {
klanten2.add(p.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//beweging van laatste pad naar afdeling.
if (!(paden.get(paden.size() - 1)).klanten.isEmpty()) { //if last pad !empty
paden.get(paden.size() - 1).klanten = new ArrayList<>();//om te<SUF>
afdelingen.get(0).klanten = klanten2.get(paden.size() - 1);
klanten2.set(paden.size() - 1, new ArrayList<Klant>());
}
//daadwerkelijke beweging tussen paden
for (int i = 0; i < paden.size(); i++) {
if (i == (0)) {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(paden.size() - 1);//
} else {
paden.get(i).klanten = new ArrayList<>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
paden.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopAfdelingen() {
for (Afdeling a : afdelingen) {
//eerst wordt voor elke klant in een pad de winkelen methode aangeroepen, daarna worden ze verwerkt.
for (Klant k : a.klanten) {
k.winkelen(a);
if (k.wishlist.isEmpty()) {//hebben ze niks in hun wishlist?
a.klanten.remove(k);//move!
gaKassa(k);
klanten.remove(k);
break;
}
}
}
//nu worden de klanten die zijn overgebleven verplaatst naar hun aansluitende gangpad.
//kopie.
klanten2 = new ArrayList<ArrayList<Klant>>();//kopie van de klantenlijst van elk pad.
for (Afdeling a : afdelingen) {
klanten2.add(a.klanten);//voegt de klantenlijst van elk pad aan klanten2 toe
}
//daadwerkelijke beweging.
for (int i = 0; i < afdelingen.size(); i++) {
if (i == (0)) {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(afdelingen.size() - 1);//
} else {
afdelingen.get(i).klanten = new ArrayList<Klant>();//om te zorgen dat er niks in blijft staan,maakt het pad ff leeg.
afdelingen.get(i).klanten = klanten2.get(i - 1);
}
}
klanten2 = new ArrayList<ArrayList<Klant>>();//zet de klantenbackup weer op leeg voor de volgende iteratie.
}
public static void koopVoordeel() {
}
public static void betaalProducten(){
for(Kassa k : kassas){
k.scanArtikelen();
}
}
public static void gaKassa(Klant K) {
int beste = kassas.get(0).klanten.size();
int kassaIndex = 0;
for (int i = 0; i < kassas.size(); i++) {
if (kassas.get(i).klanten.size() < beste && kassas.get(i).operator != null) {
kassaIndex = i;
}
}
kassas.get(kassaIndex).klanten.add(K);
}
/**
* initNames voegt namen toe aan de static lijst Namen. Hieruit haalt de
* klasse Klant en Werknemer zijn naam.
*/
public static void initNames() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(Supermarkt.class.getResourceAsStream("randomnames.txt")));
String line;
while ((line = br.readLine()) != null) {
namen.add(line);
}
br.close();
} catch (IOException e) {
//System.out.println(e.getMessage());
}
}
/**
* *
* Initialiseert de inventaris van de winkel. Heeft effect op (nog niks)
* klant zijn wishlist, pad zijn inventaris, afdeling zijn inventaris.
*/
public static void initInventaris() {
for (int i = 0; i < Supermarkt.paden.size(); i++) {
for (int x = 0; x < paden.get(i).artikelen.size(); x += 10) {
inventaris.add(paden.get(i).artikelen.get(x));
}
}
for (int i = 0; i < Supermarkt.afdelingen.size(); i++) {
for (int x = 0; x < afdelingen.get(i).artikelen.size(); x += 5) {
inventaris.add(afdelingen.get(i).artikelen.get(x));
}
}
}
/**
*
*/
public static void initKassas(){
for(int i = 0; i < GUI.kassa; i++){
kassas.add(new Kassa());
}
}
/**
* *
* InitJobs vult de lijst toDo met dingen die nog gedaan moeten worden in de
* opstart van het programma.
*
*/
public static void initJobs() {
toDo.add("Brood");
toDo.add("Kaas");
toDo.add("Kassa");
}
/**
* initPad is het maken van alle paden vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een pad aangemaakt
*/
public static void initPad() {
ArrayList<String> vars = new ArrayList<>();
vars.add("koekjes");
vars.add("azie");
vars.add("drank");
vars.add("zuivel");
vars.add("snoep");
for (int i = 0; i < vars.size(); i++) {
paden.add(new Pad(vars.get(i), 2, 10));
}
//vdp = new Voordeelpad();
}
/**
* initAfd is het maken van alle afdelingen vars worden eerst hardcoded
* toegevoegd aan een variatielijst voor elke variatie in deze lijst wordt
* een afdelingstype aangemaakt
*/
public static void initAfd() {
ArrayList<String> vars = new ArrayList<>();
vars.add("deegwaar");
vars.add("fruit");
vars.add("vleeswaar");
vars.add("zuivel");
for (int i = 0; i < vars.size(); i++) {
afdelingen.add(new Afdeling(vars.get(i), 1, 5));
}
}
/**
*
* geenBijstand methode zorgt ervoor dat werknemers in de werkPauze in
* werkActief komen te staan met een functie.
*
* @param werkPauze Lijst met non-actieve werknemers
* @param toDo lijst met dingen die er gedaan moeten worden
*/
public static void geenBijstand() {
try {
if (!werkPauze.isEmpty()) {
if (!toDo.isEmpty()) {
werkPauze.get(0).taak = toDo.get(0);
werkActief.add(werkPauze.get(0));
// System.out.println(werkPauze.get(0).Naam + " is now going to do job: " + werkPauze.get(0).taak);
werkPauze.remove(0);
toDo.remove(0);
} else {
//System.out.println(werkPauze.get(0).Naam + " has no dedicated task. Checking stocks.");
werkPauze.get(0).taak = "bijvullen";
werkActief.add(werkPauze.get(0));
werkPauze.remove(0);
}
}
} catch (Exception e) {
}
}
/**
* *
* maakKlant methode voegt klanten toe aan de klanten lijst
*
* @return een nieuw aangemaakte klant
*/
public static Klant maakKlant() {
try {
Klant k = new Klant();
klanten.add(k);
return k;
} catch (Exception E) {
System.out.println(E.getMessage());
}
return null;
}
}
|
61153_3 | package be.kdg.tic_tac_toe.model;
import java.util.Random;
public class NPC extends Player {
//de vars initializeren
private static final int MIN = -1000;
private static final int MAX = 1000;
private Random random;
private final boolean ai;
NPC(boolean ai) {
//geef een naam aan de ai genaamd bot
super("Bot");
// de ai die meegegeven word is de ai van de vars
this.ai = ai;
// als deze ai niet degene is die meegegeven is dan moet je een random gebruiken
if (!ai){
this.random = new Random();
}
}
String playNPC(Board board, Sort currentSort) {
//als de keuze ai is dan moet de minimax aangesproken worden en de beste move uitgevoerd worden
if (ai){
return this.bestMove(board, currentSort);
//word de ai niet aangesproken dan moet de makkelijke computer spelen en dus een gewone random gooien voor de plaats
}else{
return this.randomMove(board, currentSort);
}
}
private String randomMove(Board board, Sort currentSort){
// de size van het bord is zo groot als de lengte van de pieces aan mekaar
int size = board.getPieces().length;
int x;
int y;
//zolang de pieces niet gelijk zijn aan null dan moet je een random x en y waarde kiezen binnen de size om een piece op te zetten
do {
x = random.nextInt(size);
y = random.nextInt(size);
}while (board.getPieces()[y][x] != null);
// de functie place word aangeroepen en de current sort(x of O) word geplaatst op de gekozen y en x coordinaten
board.place(currentSort, y, x);
return String.format("%s=%d-%d;", currentSort, y, x);
}
private boolean movesAble(Board board) {
//het bord opnieuw tekenen met al de veranderingen
return board.draw();
}
private int evaluation(Board board, Sort ownSort, Sort opponent) {
//minimax
if (board.win(ownSort)) {
return +10;
} else if (board.win(opponent)) {
return -10;
}
return 0;
}
//determine the best value to play
private int minimax(Board board, int depth, boolean max, Sort ownSort, int alpha, int beta) {
Piece[][] pieces = board.getPieces();
Sort opponent = Sort.oppositSort(ownSort);
int score;
//get the score of the current board
if (max) {
score = evaluation(board, ownSort, opponent);
} else {
score = -evaluation(board, opponent, ownSort);
}
if (score == 10) {
return score - depth;
} else if (score == -10) {
return score + depth;
} else if (movesAble(board)) {
return 0;
//if the NPC is the maximizer
} else if (max) {
int best = MIN;
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
//place a temporary piece on the copy board
board.setPiece(y, x, ownSort);
//calculate the value of this move
int value = minimax(board, ++depth, false, ownSort, alpha, beta);
//determine the best move
best = Math.max(best, value);
alpha = Math.max(alpha, best);
//set the piece on the board back to null
board.setPieceNull(y, x);
if (beta <= alpha) {
break;
}
}
}
}
return best;
//if the NPC is the minimizer
} else {
int best = MAX;
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
//place a temporary piece on the copy board
board.setPiece(y, x, opponent);
//calculate the value of this move
int value = minimax(board, ++depth, true, ownSort, alpha, beta);
best = Math.min(best, value);
beta = Math.min(beta, best);
//set the piece on the board back to null
board.setPieceNull(y, x);
if (beta <= alpha) {
break;
}
}
}
}
return best;
}
}
private String bestMove(Board board, Sort ownSort) {
Piece[][] pieces = board.getPieces();
boolean max;
//is the NPC the maximizer?
max = ownSort.equals(Sort.X);
int bestVal = MIN;
int column = -1;
int row = -1;
System.out.println("Thinking...");
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
board.setPiece(y, x, ownSort);
int moveVal = minimax(board, 0, max, ownSort, MIN, MAX);
board.setPieceNull(y, x);
if (moveVal > bestVal) {
row = x;
column = y;
bestVal = moveVal;
}
}
}
}
board.place(ownSort, column, row);
return String.format("%s=%d-%d;", ownSort, column, row);
}
} | zouffke/TicTacToeFX | src/main/java/be/kdg/tic_tac_toe/model/NPC.java | 1,459 | // als deze ai niet degene is die meegegeven is dan moet je een random gebruiken | line_comment | nl | package be.kdg.tic_tac_toe.model;
import java.util.Random;
public class NPC extends Player {
//de vars initializeren
private static final int MIN = -1000;
private static final int MAX = 1000;
private Random random;
private final boolean ai;
NPC(boolean ai) {
//geef een naam aan de ai genaamd bot
super("Bot");
// de ai die meegegeven word is de ai van de vars
this.ai = ai;
// als deze<SUF>
if (!ai){
this.random = new Random();
}
}
String playNPC(Board board, Sort currentSort) {
//als de keuze ai is dan moet de minimax aangesproken worden en de beste move uitgevoerd worden
if (ai){
return this.bestMove(board, currentSort);
//word de ai niet aangesproken dan moet de makkelijke computer spelen en dus een gewone random gooien voor de plaats
}else{
return this.randomMove(board, currentSort);
}
}
private String randomMove(Board board, Sort currentSort){
// de size van het bord is zo groot als de lengte van de pieces aan mekaar
int size = board.getPieces().length;
int x;
int y;
//zolang de pieces niet gelijk zijn aan null dan moet je een random x en y waarde kiezen binnen de size om een piece op te zetten
do {
x = random.nextInt(size);
y = random.nextInt(size);
}while (board.getPieces()[y][x] != null);
// de functie place word aangeroepen en de current sort(x of O) word geplaatst op de gekozen y en x coordinaten
board.place(currentSort, y, x);
return String.format("%s=%d-%d;", currentSort, y, x);
}
private boolean movesAble(Board board) {
//het bord opnieuw tekenen met al de veranderingen
return board.draw();
}
private int evaluation(Board board, Sort ownSort, Sort opponent) {
//minimax
if (board.win(ownSort)) {
return +10;
} else if (board.win(opponent)) {
return -10;
}
return 0;
}
//determine the best value to play
private int minimax(Board board, int depth, boolean max, Sort ownSort, int alpha, int beta) {
Piece[][] pieces = board.getPieces();
Sort opponent = Sort.oppositSort(ownSort);
int score;
//get the score of the current board
if (max) {
score = evaluation(board, ownSort, opponent);
} else {
score = -evaluation(board, opponent, ownSort);
}
if (score == 10) {
return score - depth;
} else if (score == -10) {
return score + depth;
} else if (movesAble(board)) {
return 0;
//if the NPC is the maximizer
} else if (max) {
int best = MIN;
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
//place a temporary piece on the copy board
board.setPiece(y, x, ownSort);
//calculate the value of this move
int value = minimax(board, ++depth, false, ownSort, alpha, beta);
//determine the best move
best = Math.max(best, value);
alpha = Math.max(alpha, best);
//set the piece on the board back to null
board.setPieceNull(y, x);
if (beta <= alpha) {
break;
}
}
}
}
return best;
//if the NPC is the minimizer
} else {
int best = MAX;
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
//place a temporary piece on the copy board
board.setPiece(y, x, opponent);
//calculate the value of this move
int value = minimax(board, ++depth, true, ownSort, alpha, beta);
best = Math.min(best, value);
beta = Math.min(beta, best);
//set the piece on the board back to null
board.setPieceNull(y, x);
if (beta <= alpha) {
break;
}
}
}
}
return best;
}
}
private String bestMove(Board board, Sort ownSort) {
Piece[][] pieces = board.getPieces();
boolean max;
//is the NPC the maximizer?
max = ownSort.equals(Sort.X);
int bestVal = MIN;
int column = -1;
int row = -1;
System.out.println("Thinking...");
for (int y = 0; y < pieces.length; y++) {
for (int x = 0; x < pieces[y].length; x++) {
if (pieces[y][x] == null) {
board.setPiece(y, x, ownSort);
int moveVal = minimax(board, 0, max, ownSort, MIN, MAX);
board.setPieceNull(y, x);
if (moveVal > bestVal) {
row = x;
column = y;
bestVal = moveVal;
}
}
}
}
board.place(ownSort, column, row);
return String.format("%s=%d-%d;", ownSort, column, row);
}
} |
71971_12 | package kapsalon.nl.services;
import kapsalon.nl.exceptions.RecordNotFoundException;
import kapsalon.nl.models.dto.AppointmentDTO;
import kapsalon.nl.models.dto.UpdateAppointmentByOwnerDTO;
import kapsalon.nl.models.entity.*;
import kapsalon.nl.repo.*;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class AppointmentServiceImpl implements AppointmentService {
private final AppointmentRepository appointmentRepository;
private final BarberRepository barberRepository;
private final UserRepository userRepository;
private final KapsalonRepository kapsalonRepository;
private final DienstRepository dienstRepository;
private final PdfService pdfService;
public AppointmentServiceImpl (AppointmentRepository appointmentRepository, BarberRepository barberRepository, UserRepository userRepository, KapsalonRepository kapsalonRepository, DienstRepository dienstRepository, PdfService pdfService){
this.appointmentRepository = appointmentRepository;
this.barberRepository = barberRepository;
this.userRepository = userRepository;
this.kapsalonRepository = kapsalonRepository;
this.dienstRepository =dienstRepository;
this.pdfService = pdfService;
}
@Override
public byte[] generatePdfForAppointment(Long id) throws IOException {
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de afspraak op basis van het opgegeven ID
AppointmentDTO appointmentDTO = getAppointmentById(id);
// Controleer of de afspraak bestaat
if (appointmentDTO != null ) {
// Controleer of de ingelogde gebruiker de eigenaar van de afspraak of de costomer is
if (!appointmentDTO.getSelectedKapsalon().getOwner().equals(loggedInUsername) && !appointmentDTO.getUser().getUsername().equals(loggedInUsername)) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak te bekijken.");
}
// Controleer of de status van de afspraak 'approved' is
if(!appointmentDTO.getStatus().equals("APPROVED")){
throw new AccessDeniedException("De status van de afspraak is nog niet 'approved'.");
}
// Controleer of de appointment wordt betaald
if(!appointmentDTO.isPaid() == true){
throw new AccessDeniedException("De afspraak is nog niet betaald.");
}
byte[] pdfBytes = pdfService.generatePdf(appointmentDTO);
String fileName = "appointment_" + id + ".pdf";
String filePath = "src/main/resources/invoices/" + fileName;
savePdfToFileSystem(pdfBytes, filePath);
// Genereer de PDF voor de afspraak en retourneer deze
return pdfService.generatePdf(appointmentDTO);
}
else {
throw new RecordNotFoundException("Appointment not found with id: " + id);
}
}
public void savePdfToFileSystem(byte[] pdfBytes, String filePath) throws IOException {
Files.write(Paths.get(filePath), pdfBytes);
}
@Override
public List<AppointmentDTO> getAllAppointment() {
List<Appointment> entityList = appointmentRepository.findAll();
List<AppointmentDTO> dtoList = new ArrayList<>();
for (Appointment entity : entityList) {
dtoList.add(fromEntityToDto(entity));
}
return dtoList;
}
@Override
public AppointmentDTO getAppointmentById(Long id) {
Appointment appointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
return fromEntityToDto(appointment);
}
@Override
public AppointmentDTO createAppointment(AppointmentDTO dto) {
// Zoek de kapsalon op basis van de geselecteerde kapsalon-ID
Kapsalon kapsalon = kapsalonRepository.findById(dto.getSelectedKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getSelectedKapsalon().getId()));
// Zoek de kapper op basis van de geselecteerde kapper-ID
Barber kapper = barberRepository.findById(dto.getSelectedBarber().getId())
.orElseThrow(() -> new RecordNotFoundException("Barber not found with id: " + dto.getSelectedBarber().getId()));
// Controleer of de kapper beschikbaar is
if (!kapper.isAvailable()) {
throw new AccessDeniedException("De geselecteerde kapper is niet beschikbaar.");
}
// Controleer of de kapper bij de geselecteerde kapsalon werkt
if (!kapper.getKapsalon().getId().equals(kapsalon.getId())) {
throw new AccessDeniedException("De geselecteerde kapper werkt niet bij de geselecteerde kapsalon.");
}
// Zoek de dienst op basis van de geselecteerde dienst-ID
Dienst dienst = dienstRepository.findById(dto.getSelectedDienst().getId())
.orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dto.getSelectedDienst().getId()));
// Controleer of de geselecteerde kapper de geselecteerde dienst aanbiedt
if (!kapper.getDiensten().contains(dienst)) {
throw new AccessDeniedException("De geselecteerde kapper biedt de geselecteerde dienst niet aan.");
}
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de ingelogde gebruiker op
User loggedInUser = userRepository.findByUsername(loggedInUsername)
.orElseThrow(() -> new RecordNotFoundException("Ingelogde gebruiker niet gevonden: " + loggedInUsername));
// Maak een nieuwe afspraakentiteit
Appointment entity = fromDtoToEntity(dto);
entity.setSelectedKapsalon(kapsalon);
entity.setSelectedBarber(kapper);
entity.setSelectedDienst(dienst);
entity.setUser(loggedInUser);
// Stel de standaardstatus in op "PENDING"
entity.setStatus(Status.PENDING);
// Stel de standaar isPaid in op false
entity.setPaid(false);
// Sla de afspraak op
Appointment savedAppointment = appointmentRepository.save(entity);
// Converteer de opgeslagen afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(savedAppointment);
}
@Override
public AppointmentDTO updateAppointment(Long id, AppointmentDTO dto) {
// Zoek de afspraak op basis van het opgegeven ID
Appointment existingAppointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
// Haal de huidige ingelogde gebruiker op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de ingelogde gebruiker op
User loggedInUser = userRepository.findByUsername(loggedInUsername)
.orElseThrow(() -> new RecordNotFoundException("Ingelogde gebruiker niet gevonden: " + loggedInUsername));
// Controleer of de ingelogde gebruiker overeenkomt met de klant van de bestaande afspraak
if (!existingAppointment.getUser().getUsername().equals(loggedInUser.getUsername())) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak bij te werken. check je afspraak ID");
}
// Zoek de kapsalon op basis van de geselecteerde kapsalon-ID
Kapsalon kapsalon = kapsalonRepository.findById(dto.getSelectedKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getSelectedKapsalon().getId()));
// Zoek de kapper op basis van de geselecteerde kapper-ID
Barber kapper = barberRepository.findById(dto.getSelectedBarber().getId())
.orElseThrow(() -> new RecordNotFoundException("Barber not found with id: " + dto.getSelectedBarber().getId()));
// Controleer of de kapper beschikbaar is
if (!kapper.isAvailable()) {
throw new AccessDeniedException("De geselecteerde kapper is niet beschikbaar.");
}
// Controleer of de kapper bij de geselecteerde kapsalon werkt
if (!kapper.getKapsalon().getId().equals(kapsalon.getId())) {
throw new AccessDeniedException("De geselecteerde kapper werkt niet bij de geselecteerde kapsalon.");
}
// Zoek de dienst op basis van de geselecteerde dienst-ID
Dienst dienst = dienstRepository.findById(dto.getSelectedDienst().getId())
.orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dto.getSelectedDienst().getId()));
// Controleer of de geselecteerde kapper de geselecteerde dienst aanbiedt
if (!kapper.getDiensten().contains(dienst)) {
throw new AccessDeniedException("De geselecteerde kapper biedt de geselecteerde dienst niet aan.");
}
// Update de gegevens van de bestaande afspraak met de nieuwe DTO-gegevens
existingAppointment.setAppointmentDate(dto.getAppointmentDate());
existingAppointment.setAppointmentTime(dto.getAppointmentTime());
existingAppointment.setSelectedKapsalon(kapsalon);
existingAppointment.setSelectedBarber(kapper);
existingAppointment.setSelectedDienst(dienst);
existingAppointment.setUser(loggedInUser);
existingAppointment.setPaid(dto.isPaid()); // afhankelijk van je DTO
// Sla de bijgewerkte afspraak op
Appointment updatedAppointment = appointmentRepository.save(existingAppointment);
// Converteer de bijgewerkte afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(updatedAppointment);
}
@Override
public AppointmentDTO updateAppointmentByOwner(Long id, UpdateAppointmentByOwnerDTO dto) {
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de kapsalons van de ingelogde gebruiker (eigenaar)
Optional<Kapsalon> ownerKapsalons = kapsalonRepository.findByOwner(loggedInUsername);
// Zoek de afspraak op basis van het opgegeven ID
Appointment existingAppointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
// Controleer of de ingelogde gebruiker de eigenaar is van de kapsalon waar de afspraak toe behoort
boolean isOwnerAppointment = ownerKapsalons.stream()
.anyMatch(kapsalon -> kapsalon.getId().equals(existingAppointment.getSelectedKapsalon().getId()));
if (!isOwnerAppointment) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak bij te werken. deze afspraak hoort niet bij je Kapsalon");
}
// Update de status en isPaid van de afspraak
existingAppointment.setStatus(Status.valueOf(dto.getStatus()));
existingAppointment.setPaid(dto.isPaid());
// Sla de bijgewerkte afspraak op
Appointment updatedAppointment = appointmentRepository.save(existingAppointment);
// Converteer de bijgewerkte afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(updatedAppointment);
}
@Override
public void deleteAppointment(Long id) {
Appointment appointment= appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
appointmentRepository.delete(appointment);
}
public AppointmentDTO fromEntityToDto(Appointment entity){
AppointmentDTO dto = new AppointmentDTO();
dto.setId(entity.getId());
dto.setSelectedKapsalon(entity.getSelectedKapsalon());
dto.setSelectedDienst(entity.getSelectedDienst());
dto.setSelectedBarber(entity.getSelectedBarber());
dto.setAppointmentDate(entity.getAppointmentDate());
dto.setAppointmentTime(entity.getAppointmentTime());
dto.setUser(entity.getUser());
dto.setStatus(entity.getStatus().getDisplayName());
dto.setPaid(entity.isPaid());
return dto;
}
public static Appointment fromDtoToEntity(AppointmentDTO dto) {
Appointment entity = new Appointment();
entity.setId(dto.getId());
entity.setSelectedKapsalon(dto.getSelectedKapsalon());
entity.setSelectedDienst(dto.getSelectedDienst());
entity.setSelectedBarber(dto.getSelectedBarber());
entity.setAppointmentDate(dto.getAppointmentDate());
entity.setAppointmentTime(dto.getAppointmentTime());
// entity.setUser(dto.getUser());
// entity.setStatus(Status.valueOf(dto.getStatus()));
// entity.setPaid(dto.isPaid());
return entity;
}
}
| tamer4k/kapsalon | src/main/java/kapsalon/nl/services/AppointmentServiceImpl.java | 3,008 | // Controleer of de geselecteerde kapper de geselecteerde dienst aanbiedt | line_comment | nl | package kapsalon.nl.services;
import kapsalon.nl.exceptions.RecordNotFoundException;
import kapsalon.nl.models.dto.AppointmentDTO;
import kapsalon.nl.models.dto.UpdateAppointmentByOwnerDTO;
import kapsalon.nl.models.entity.*;
import kapsalon.nl.repo.*;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class AppointmentServiceImpl implements AppointmentService {
private final AppointmentRepository appointmentRepository;
private final BarberRepository barberRepository;
private final UserRepository userRepository;
private final KapsalonRepository kapsalonRepository;
private final DienstRepository dienstRepository;
private final PdfService pdfService;
public AppointmentServiceImpl (AppointmentRepository appointmentRepository, BarberRepository barberRepository, UserRepository userRepository, KapsalonRepository kapsalonRepository, DienstRepository dienstRepository, PdfService pdfService){
this.appointmentRepository = appointmentRepository;
this.barberRepository = barberRepository;
this.userRepository = userRepository;
this.kapsalonRepository = kapsalonRepository;
this.dienstRepository =dienstRepository;
this.pdfService = pdfService;
}
@Override
public byte[] generatePdfForAppointment(Long id) throws IOException {
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de afspraak op basis van het opgegeven ID
AppointmentDTO appointmentDTO = getAppointmentById(id);
// Controleer of de afspraak bestaat
if (appointmentDTO != null ) {
// Controleer of de ingelogde gebruiker de eigenaar van de afspraak of de costomer is
if (!appointmentDTO.getSelectedKapsalon().getOwner().equals(loggedInUsername) && !appointmentDTO.getUser().getUsername().equals(loggedInUsername)) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak te bekijken.");
}
// Controleer of de status van de afspraak 'approved' is
if(!appointmentDTO.getStatus().equals("APPROVED")){
throw new AccessDeniedException("De status van de afspraak is nog niet 'approved'.");
}
// Controleer of de appointment wordt betaald
if(!appointmentDTO.isPaid() == true){
throw new AccessDeniedException("De afspraak is nog niet betaald.");
}
byte[] pdfBytes = pdfService.generatePdf(appointmentDTO);
String fileName = "appointment_" + id + ".pdf";
String filePath = "src/main/resources/invoices/" + fileName;
savePdfToFileSystem(pdfBytes, filePath);
// Genereer de PDF voor de afspraak en retourneer deze
return pdfService.generatePdf(appointmentDTO);
}
else {
throw new RecordNotFoundException("Appointment not found with id: " + id);
}
}
public void savePdfToFileSystem(byte[] pdfBytes, String filePath) throws IOException {
Files.write(Paths.get(filePath), pdfBytes);
}
@Override
public List<AppointmentDTO> getAllAppointment() {
List<Appointment> entityList = appointmentRepository.findAll();
List<AppointmentDTO> dtoList = new ArrayList<>();
for (Appointment entity : entityList) {
dtoList.add(fromEntityToDto(entity));
}
return dtoList;
}
@Override
public AppointmentDTO getAppointmentById(Long id) {
Appointment appointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
return fromEntityToDto(appointment);
}
@Override
public AppointmentDTO createAppointment(AppointmentDTO dto) {
// Zoek de kapsalon op basis van de geselecteerde kapsalon-ID
Kapsalon kapsalon = kapsalonRepository.findById(dto.getSelectedKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getSelectedKapsalon().getId()));
// Zoek de kapper op basis van de geselecteerde kapper-ID
Barber kapper = barberRepository.findById(dto.getSelectedBarber().getId())
.orElseThrow(() -> new RecordNotFoundException("Barber not found with id: " + dto.getSelectedBarber().getId()));
// Controleer of de kapper beschikbaar is
if (!kapper.isAvailable()) {
throw new AccessDeniedException("De geselecteerde kapper is niet beschikbaar.");
}
// Controleer of de kapper bij de geselecteerde kapsalon werkt
if (!kapper.getKapsalon().getId().equals(kapsalon.getId())) {
throw new AccessDeniedException("De geselecteerde kapper werkt niet bij de geselecteerde kapsalon.");
}
// Zoek de dienst op basis van de geselecteerde dienst-ID
Dienst dienst = dienstRepository.findById(dto.getSelectedDienst().getId())
.orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dto.getSelectedDienst().getId()));
// Controleer of<SUF>
if (!kapper.getDiensten().contains(dienst)) {
throw new AccessDeniedException("De geselecteerde kapper biedt de geselecteerde dienst niet aan.");
}
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de ingelogde gebruiker op
User loggedInUser = userRepository.findByUsername(loggedInUsername)
.orElseThrow(() -> new RecordNotFoundException("Ingelogde gebruiker niet gevonden: " + loggedInUsername));
// Maak een nieuwe afspraakentiteit
Appointment entity = fromDtoToEntity(dto);
entity.setSelectedKapsalon(kapsalon);
entity.setSelectedBarber(kapper);
entity.setSelectedDienst(dienst);
entity.setUser(loggedInUser);
// Stel de standaardstatus in op "PENDING"
entity.setStatus(Status.PENDING);
// Stel de standaar isPaid in op false
entity.setPaid(false);
// Sla de afspraak op
Appointment savedAppointment = appointmentRepository.save(entity);
// Converteer de opgeslagen afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(savedAppointment);
}
@Override
public AppointmentDTO updateAppointment(Long id, AppointmentDTO dto) {
// Zoek de afspraak op basis van het opgegeven ID
Appointment existingAppointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
// Haal de huidige ingelogde gebruiker op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de ingelogde gebruiker op
User loggedInUser = userRepository.findByUsername(loggedInUsername)
.orElseThrow(() -> new RecordNotFoundException("Ingelogde gebruiker niet gevonden: " + loggedInUsername));
// Controleer of de ingelogde gebruiker overeenkomt met de klant van de bestaande afspraak
if (!existingAppointment.getUser().getUsername().equals(loggedInUser.getUsername())) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak bij te werken. check je afspraak ID");
}
// Zoek de kapsalon op basis van de geselecteerde kapsalon-ID
Kapsalon kapsalon = kapsalonRepository.findById(dto.getSelectedKapsalon().getId())
.orElseThrow(() -> new RecordNotFoundException("Kapsalon not found with id: " + dto.getSelectedKapsalon().getId()));
// Zoek de kapper op basis van de geselecteerde kapper-ID
Barber kapper = barberRepository.findById(dto.getSelectedBarber().getId())
.orElseThrow(() -> new RecordNotFoundException("Barber not found with id: " + dto.getSelectedBarber().getId()));
// Controleer of de kapper beschikbaar is
if (!kapper.isAvailable()) {
throw new AccessDeniedException("De geselecteerde kapper is niet beschikbaar.");
}
// Controleer of de kapper bij de geselecteerde kapsalon werkt
if (!kapper.getKapsalon().getId().equals(kapsalon.getId())) {
throw new AccessDeniedException("De geselecteerde kapper werkt niet bij de geselecteerde kapsalon.");
}
// Zoek de dienst op basis van de geselecteerde dienst-ID
Dienst dienst = dienstRepository.findById(dto.getSelectedDienst().getId())
.orElseThrow(() -> new RecordNotFoundException("Dienst not found with id: " + dto.getSelectedDienst().getId()));
// Controleer of de geselecteerde kapper de geselecteerde dienst aanbiedt
if (!kapper.getDiensten().contains(dienst)) {
throw new AccessDeniedException("De geselecteerde kapper biedt de geselecteerde dienst niet aan.");
}
// Update de gegevens van de bestaande afspraak met de nieuwe DTO-gegevens
existingAppointment.setAppointmentDate(dto.getAppointmentDate());
existingAppointment.setAppointmentTime(dto.getAppointmentTime());
existingAppointment.setSelectedKapsalon(kapsalon);
existingAppointment.setSelectedBarber(kapper);
existingAppointment.setSelectedDienst(dienst);
existingAppointment.setUser(loggedInUser);
existingAppointment.setPaid(dto.isPaid()); // afhankelijk van je DTO
// Sla de bijgewerkte afspraak op
Appointment updatedAppointment = appointmentRepository.save(existingAppointment);
// Converteer de bijgewerkte afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(updatedAppointment);
}
@Override
public AppointmentDTO updateAppointmentByOwner(Long id, UpdateAppointmentByOwnerDTO dto) {
// Haal de ingelogde gebruikersnaam op
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String loggedInUsername = authentication.getName();
// Zoek de kapsalons van de ingelogde gebruiker (eigenaar)
Optional<Kapsalon> ownerKapsalons = kapsalonRepository.findByOwner(loggedInUsername);
// Zoek de afspraak op basis van het opgegeven ID
Appointment existingAppointment = appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
// Controleer of de ingelogde gebruiker de eigenaar is van de kapsalon waar de afspraak toe behoort
boolean isOwnerAppointment = ownerKapsalons.stream()
.anyMatch(kapsalon -> kapsalon.getId().equals(existingAppointment.getSelectedKapsalon().getId()));
if (!isOwnerAppointment) {
throw new AccessDeniedException("U heeft geen toestemming om deze afspraak bij te werken. deze afspraak hoort niet bij je Kapsalon");
}
// Update de status en isPaid van de afspraak
existingAppointment.setStatus(Status.valueOf(dto.getStatus()));
existingAppointment.setPaid(dto.isPaid());
// Sla de bijgewerkte afspraak op
Appointment updatedAppointment = appointmentRepository.save(existingAppointment);
// Converteer de bijgewerkte afspraak terug naar een DTO en retourneer deze
return fromEntityToDto(updatedAppointment);
}
@Override
public void deleteAppointment(Long id) {
Appointment appointment= appointmentRepository.findById(id)
.orElseThrow(() -> new RecordNotFoundException("Appointment not found with id: " + id));
appointmentRepository.delete(appointment);
}
public AppointmentDTO fromEntityToDto(Appointment entity){
AppointmentDTO dto = new AppointmentDTO();
dto.setId(entity.getId());
dto.setSelectedKapsalon(entity.getSelectedKapsalon());
dto.setSelectedDienst(entity.getSelectedDienst());
dto.setSelectedBarber(entity.getSelectedBarber());
dto.setAppointmentDate(entity.getAppointmentDate());
dto.setAppointmentTime(entity.getAppointmentTime());
dto.setUser(entity.getUser());
dto.setStatus(entity.getStatus().getDisplayName());
dto.setPaid(entity.isPaid());
return dto;
}
public static Appointment fromDtoToEntity(AppointmentDTO dto) {
Appointment entity = new Appointment();
entity.setId(dto.getId());
entity.setSelectedKapsalon(dto.getSelectedKapsalon());
entity.setSelectedDienst(dto.getSelectedDienst());
entity.setSelectedBarber(dto.getSelectedBarber());
entity.setAppointmentDate(dto.getAppointmentDate());
entity.setAppointmentTime(dto.getAppointmentTime());
// entity.setUser(dto.getUser());
// entity.setStatus(Status.valueOf(dto.getStatus()));
// entity.setPaid(dto.isPaid());
return entity;
}
}
|
122199_16 | // github.com/RodneyShag
import java.util.Scanner;
import java.math.BigInteger;
// Case 1: If N is not a power of 2, reduce the counter by the largest power of 2 less than N
//
// This is equivalent to turning the most significant 1 in N to 0. This operation will keep
// repeating until we reach Case 2. To count the number of times we have to do Case 1's operation
// we can count the number of 1s in our original number (except for the least significant 1).
// Case 2: If N is a power of 2, we must "reduce the counter by half of N".
//
// This is equivalent of doing a right shift. This operation keeps repeating until the game ends.
// The number of right shifts we do depends on the number of trailing 0s.
// Additional optimization:
//
// Instead of counting the number of times Case 1 and Case 2 happen separately, we can just
// calculate the number of 1s in N-1. This is because subtracting 1 from our number will turn
// all of the trailing 0s (which we wanted to count) into 1s that we can count (for example:
// 10000 would become 01111)
// Example:
//
// 10110100 Case 1
// 110100 Case 1
// 10100 Case 1
// 100 Case 2
// 10 Case 2
// 1 Done
//
// We had 5 operations total. Directly applying our algorithm would look like this:
//
// Original Number: 10110100
// Number - 1 : 10110011 and the number of 1s is 5
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while (T-- > 0) {
BigInteger N = new BigInteger(scan.next());
N = N.subtract(BigInteger.ONE);
System.out.println(N.bitCount() % 2 == 0 ? "Richard" : "Louise");
}
scan.close();
}
}
| RodneyShag/HackerRank_solutions | Algorithms/Bit Manipulation/Counter game/Solution.java | 546 | // 1 Done | line_comment | nl | // github.com/RodneyShag
import java.util.Scanner;
import java.math.BigInteger;
// Case 1: If N is not a power of 2, reduce the counter by the largest power of 2 less than N
//
// This is equivalent to turning the most significant 1 in N to 0. This operation will keep
// repeating until we reach Case 2. To count the number of times we have to do Case 1's operation
// we can count the number of 1s in our original number (except for the least significant 1).
// Case 2: If N is a power of 2, we must "reduce the counter by half of N".
//
// This is equivalent of doing a right shift. This operation keeps repeating until the game ends.
// The number of right shifts we do depends on the number of trailing 0s.
// Additional optimization:
//
// Instead of counting the number of times Case 1 and Case 2 happen separately, we can just
// calculate the number of 1s in N-1. This is because subtracting 1 from our number will turn
// all of the trailing 0s (which we wanted to count) into 1s that we can count (for example:
// 10000 would become 01111)
// Example:
//
// 10110100 Case 1
// 110100 Case 1
// 10100 Case 1
// 100 Case 2
// 10 Case 2
// 1 <SUF>
//
// We had 5 operations total. Directly applying our algorithm would look like this:
//
// Original Number: 10110100
// Number - 1 : 10110011 and the number of 1s is 5
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while (T-- > 0) {
BigInteger N = new BigInteger(scan.next());
N = N.subtract(BigInteger.ONE);
System.out.println(N.bitCount() % 2 == 0 ? "Richard" : "Louise");
}
scan.close();
}
}
|
169882_0 | package com.ilionx.cyclists.api;
import com.ilionx.cyclists.model.Cyclist;
import com.ilionx.cyclists.service.CyclistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/cyclists")
public class CyclistController {
@Autowired
private CyclistService cyclistService;
@GetMapping
public ResponseEntity<List<Cyclist>> findAllCyclists() {
return ResponseEntity.ok(this.cyclistService.findAll());
}
@PostMapping
public ResponseEntity<Cyclist> create(@RequestBody Cyclist cyclist) {
// eventueel ResponseEntity.created(...) maar dat behandelen we later evt.
return ResponseEntity.ok(cyclistService.save(cyclist));
}
@GetMapping("{id}")
public ResponseEntity<Cyclist> findById (@PathVariable Long id) {
Optional<Cyclist> optionalCyclist = this.cyclistService.findById(id);
if (optionalCyclist.isPresent()) {
return ResponseEntity.ok(optionalCyclist.get());
}
else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping ("{id}")
public ResponseEntity<Cyclist> deleteById (@PathVariable Long id) {
this.cyclistService.deleteById(id);
return ResponseEntity.noContent().build();
}
@PutMapping("{id}")
public ResponseEntity<Cyclist> updateCyclistById (@PathVariable Long id, @RequestBody Cyclist desiredCyclist) {
Optional<Cyclist> optionalCyclist = this.cyclistService.update(desiredCyclist, id);
if (optionalCyclist.isPresent()) {
return ResponseEntity.ok(optionalCyclist.get());
}
else {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/name/{name}")
public ResponseEntity<List<Cyclist>> findByName (@PathVariable String name) {
return ResponseEntity.ok(this.cyclistService.findByName(name));
}
}
| RobertFloor/cyclists | src/main/java/com/ilionx/cyclists/api/CyclistController.java | 516 | // eventueel ResponseEntity.created(...) maar dat behandelen we later evt. | line_comment | nl | package com.ilionx.cyclists.api;
import com.ilionx.cyclists.model.Cyclist;
import com.ilionx.cyclists.service.CyclistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/cyclists")
public class CyclistController {
@Autowired
private CyclistService cyclistService;
@GetMapping
public ResponseEntity<List<Cyclist>> findAllCyclists() {
return ResponseEntity.ok(this.cyclistService.findAll());
}
@PostMapping
public ResponseEntity<Cyclist> create(@RequestBody Cyclist cyclist) {
// eventueel ResponseEntity.created(...)<SUF>
return ResponseEntity.ok(cyclistService.save(cyclist));
}
@GetMapping("{id}")
public ResponseEntity<Cyclist> findById (@PathVariable Long id) {
Optional<Cyclist> optionalCyclist = this.cyclistService.findById(id);
if (optionalCyclist.isPresent()) {
return ResponseEntity.ok(optionalCyclist.get());
}
else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping ("{id}")
public ResponseEntity<Cyclist> deleteById (@PathVariable Long id) {
this.cyclistService.deleteById(id);
return ResponseEntity.noContent().build();
}
@PutMapping("{id}")
public ResponseEntity<Cyclist> updateCyclistById (@PathVariable Long id, @RequestBody Cyclist desiredCyclist) {
Optional<Cyclist> optionalCyclist = this.cyclistService.update(desiredCyclist, id);
if (optionalCyclist.isPresent()) {
return ResponseEntity.ok(optionalCyclist.get());
}
else {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/name/{name}")
public ResponseEntity<List<Cyclist>> findByName (@PathVariable String name) {
return ResponseEntity.ok(this.cyclistService.findByName(name));
}
}
|
97347_6 | /*
* 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 containing.Vehicle;
import containing.Command;
import containing.CommandHandler;
import containing.Container;
import containing.Exceptions.AgvNotAvailable;
import containing.Exceptions.CargoOutOfBoundsException;
import containing.Exceptions.ContainerNotFoundException;
import containing.Exceptions.VehicleOverflowException;
import containing.Platform.Platform;
import containing.Road.Road;
import static containing.Road.Road.getPathLength;
import containing.Road.Route;
import containing.Settings;
import containing.Vector3f;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
* @author Robert
*/
public abstract class Crane extends InternVehicle {
protected int timeCountDown = 0;
protected final static int CAPICITY = 1;
protected int counter;
protected final float SECURETIME = 0.5f * 60;
//testvariables -> for every crane and container different
private final int liftTimeMin = 0 * 60;
private final float liftTimeMax = 3.5f * 60;
private final float dropTimeMin = 0 * 60;
private final float dropTimeMax = 3.5f * 60;
private final float moveContainerSpeed = 5; //meter per seconde
protected float loadTime; //11*100
protected float unloadTime;
private float resetTime;
private AGV agvToUnload = null;
boolean readyForNextContainer = true;
protected final int metersToNextAgvSpot = 10;
public float width;
public float length;
public Crane(Vector3f startPosition, Platform platform, Type type, float width, float length){
super(CAPICITY, startPosition, platform, type);
this.width = width;
this.length = length;
}
@Override
public Container unload()
{
Container container = null;
try
{
container = super.unload();
}
catch (Exception e)
{
}
return container;
}
public void unload(AGV agv) throws VehicleOverflowException, ContainerNotFoundException, CargoOutOfBoundsException{
try
{
this.agvToUnload = agv;
agv.load(super.unload());
if (this.getVehicleType() != Type.STORAGECRANE){
HashMap<String, Object> map = new HashMap<>();
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("AGVID", agv.getID());
map.put("duration", 2000);
//map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("unloadCrane", map));}
}
catch(Exception e){ throw e; }
//platform moet agv volgende route geven
}
public float getPathLength(List<Vector3f> weg){
if (weg.size() > 1){
if (weg.get(0).x != weg.get(1).x){ return Math.abs(weg.get(1).x - weg.get(0).x) + getPathLength(weg.subList(1, weg.size()));}
return Math.abs(weg.get(1).z - weg.get(0).z) + getPathLength(weg.subList(1, weg.size()));
}
else return 0;
}
public void moveToContainer(ExternVehicle ev, int column) throws AgvNotAvailable
{
System.out.println("column : " + column);
List<Vector3f> route = new ArrayList<>();
route.add(this.position);
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (this.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, this.getPosition().y, this.getPosition().z);
route.add(haha); //??
System.out.println("route x: " + haha.toString());
break;
case Z:
// hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook
Vector3f hihi = new Vector3f(this.getPosition().x, this.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f);
route.add(hihi); //??
System.out.println("route z: " + hihi.toString());
break;
//caseY?
}
/*
this.currentSpeed = (this.isLoaded) ? this.maxSpeedLoaded : this.maxSpeedUnloaded;
float duration = (this.getPathLength(route)*10)/(float)((float)this.getCurrentSpeed()*1000f/3600f);
HashMap<String, Object> map = new HashMap<>();
map.put("id", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("motionPath", route);
map.put("duration", duration);
map.put("speed", currentSpeed);
*/
this.route = new Route(route,Road.getPathLength(route));
followRoute(this.route);
//CommandHandler.addCommand(new Command("moveCrane", map));
this.status = Status.MOVING;
}
public void load(ExternVehicle ev, int column) throws Exception
{
for (Integer row : ev.getUnloadOrderY(column))
{
for (Container container : ev.getGrid()[column][row])
{
while (readyForNextContainer == false){}
try
{
if (container != null)
{
readyForNextContainer = false;
//ask agv!
super.load(ev.unload(container));
this.loadTime = ((Math.abs(this.position.y-container.getArrivalPosition().y) / (this.moveContainerSpeed *1000f/3600f)/100f))//move gripper to position of container
//+ this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) //droptime depended on z position of container //???
+ this.SECURETIME
+ this.liftTimeMin + (this.liftTimeMax - this.liftTimeMin) / ((int)container.getArrivalPosition().z + 1) //lifttime depended on z position of container
+ Math.abs((this.position.y-container.getArrivalPosition().y) / ((this.moveContainerSpeed *1000f/3600f)/100f));
this.status = Status.LOADING;
this.loadTime = 12*10;
this.unloadTime = (this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) + this.SECURETIME) * 100;
HashMap<String, Object> map = new HashMap<>();
this.unloadTime = 6*10;
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("clientid", ev.getID());
map.put("duration", this.loadTime);
map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("loadCrane", map));
}
}
catch(Exception e)
{
throw e;
}
}
}
ev.updateColumn(column, true);
this.isAvailable = true;
}
public void load(Container container, ExternVehicle ev) throws VehicleOverflowException, CargoOutOfBoundsException, Exception{ //container from extern verhicle
try
{
super.load(ev.unload(container));
this.loadTime = ((Math.abs(this.position.y-container.getArrivalPosition().y) / (this.moveContainerSpeed *1000f/3600f)/100f))//move gripper to position of container
//+ this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) //droptime depended on z position of container //???
+ this.SECURETIME
+ this.liftTimeMin + (this.liftTimeMax - this.liftTimeMin) / ((int)container.getArrivalPosition().z + 1) //lifttime depended on z position of container
+ Math.abs((this.position.y-container.getArrivalPosition().y) / ((this.moveContainerSpeed *1000f/3600f)/100f));
this.status = Status.LOADING;
this.unloadTime = (this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) + this.SECURETIME) * 100;
this.loadTime = 12*10;
this.unloadTime = 10*10;
if (this.getVehicleType() != Type.STORAGECRANE){
HashMap<String, Object> map = new HashMap<>();
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("clientid", ev.getID());
map.put("duration", this.loadTime);
map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("loadCrane", map));
}
}
catch(Exception e)
{
throw e;
}
//this.timeCountDown = (int) liftTimeMax;
//update: while (this.timeCounter < starttime + liftTimeMax + moveContainerSpeed * 2){} //aan het laden
//roep evt nieuwe agv aan (op zelfde parkeerplaats of op parkeerplaats opzij [moet platform doen]
}
public void move(int direction) //-1 is left 1 is right
{
//override this method for truckcrane
List<Vector3f> route = new ArrayList<>();
route.add(this.position);
if (direction == -1)
{ //trein z anders x
route.add(new Vector3f(this.position.x + Container.depth, this.position.y, this.position.z));
}
else
{
route.add(new Vector3f(this.position.x + Container.depth, this.position.y, this.position.z));
}
this.currentSpeed = (this.isLoaded) ? this.maxSpeedLoaded : this.maxSpeedUnloaded;
HashMap<String, Object> map = new HashMap<>();
map.put("id", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("motionPath", route);
map.put("speed", currentSpeed);
this.route = new Route(route,Road.getPathLength(route));
CommandHandler.addCommand(new Command("moveCrane", map));
}
@Override
public void update()
{
/*
if (this.getVehicleType() == Type.STORAGECRANE)
{
System.out.println("StorageCraneYes");
StorageCrane sc = (StorageCrane) this;
sc.update();
}
else{*/
super.update();
if (this.status == Status.LOADING )
{
this.loadTime--;
if (this.loadTime <= 0)
{
this.status = Status.UNLOADING;
//command simulator
}
}
if (this.status == Status.UNLOADING && this.agvToUnload != null)
{
this.unloadTime--;
if (this.unloadTime <= 0)
{
try
{
this.unload(agvToUnload);
}
catch(Exception e){ System.out.println(e.getMessage()); }
this.agvToUnload = null;
//this.currentPlatform.getAGV(this.getPosition());
this.status = Status.WAITING;
readyForNextContainer = true;
//new load
}
}
}
public void setAGV(AGV agv){ this.agvToUnload = agv; }
//methode opzij in subclasses waarvoor geldig is
}
| robertdj20/Containing | Containing/src/containing/Vehicle/Crane.java | 3,244 | // hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook | 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 containing.Vehicle;
import containing.Command;
import containing.CommandHandler;
import containing.Container;
import containing.Exceptions.AgvNotAvailable;
import containing.Exceptions.CargoOutOfBoundsException;
import containing.Exceptions.ContainerNotFoundException;
import containing.Exceptions.VehicleOverflowException;
import containing.Platform.Platform;
import containing.Road.Road;
import static containing.Road.Road.getPathLength;
import containing.Road.Route;
import containing.Settings;
import containing.Vector3f;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
* @author Robert
*/
public abstract class Crane extends InternVehicle {
protected int timeCountDown = 0;
protected final static int CAPICITY = 1;
protected int counter;
protected final float SECURETIME = 0.5f * 60;
//testvariables -> for every crane and container different
private final int liftTimeMin = 0 * 60;
private final float liftTimeMax = 3.5f * 60;
private final float dropTimeMin = 0 * 60;
private final float dropTimeMax = 3.5f * 60;
private final float moveContainerSpeed = 5; //meter per seconde
protected float loadTime; //11*100
protected float unloadTime;
private float resetTime;
private AGV agvToUnload = null;
boolean readyForNextContainer = true;
protected final int metersToNextAgvSpot = 10;
public float width;
public float length;
public Crane(Vector3f startPosition, Platform platform, Type type, float width, float length){
super(CAPICITY, startPosition, platform, type);
this.width = width;
this.length = length;
}
@Override
public Container unload()
{
Container container = null;
try
{
container = super.unload();
}
catch (Exception e)
{
}
return container;
}
public void unload(AGV agv) throws VehicleOverflowException, ContainerNotFoundException, CargoOutOfBoundsException{
try
{
this.agvToUnload = agv;
agv.load(super.unload());
if (this.getVehicleType() != Type.STORAGECRANE){
HashMap<String, Object> map = new HashMap<>();
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("AGVID", agv.getID());
map.put("duration", 2000);
//map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("unloadCrane", map));}
}
catch(Exception e){ throw e; }
//platform moet agv volgende route geven
}
public float getPathLength(List<Vector3f> weg){
if (weg.size() > 1){
if (weg.get(0).x != weg.get(1).x){ return Math.abs(weg.get(1).x - weg.get(0).x) + getPathLength(weg.subList(1, weg.size()));}
return Math.abs(weg.get(1).z - weg.get(0).z) + getPathLength(weg.subList(1, weg.size()));
}
else return 0;
}
public void moveToContainer(ExternVehicle ev, int column) throws AgvNotAvailable
{
System.out.println("column : " + column);
List<Vector3f> route = new ArrayList<>();
route.add(this.position);
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (this.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, this.getPosition().y, this.getPosition().z);
route.add(haha); //??
System.out.println("route x: " + haha.toString());
break;
case Z:
// hardcoded voor<SUF>
Vector3f hihi = new Vector3f(this.getPosition().x, this.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f);
route.add(hihi); //??
System.out.println("route z: " + hihi.toString());
break;
//caseY?
}
/*
this.currentSpeed = (this.isLoaded) ? this.maxSpeedLoaded : this.maxSpeedUnloaded;
float duration = (this.getPathLength(route)*10)/(float)((float)this.getCurrentSpeed()*1000f/3600f);
HashMap<String, Object> map = new HashMap<>();
map.put("id", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("motionPath", route);
map.put("duration", duration);
map.put("speed", currentSpeed);
*/
this.route = new Route(route,Road.getPathLength(route));
followRoute(this.route);
//CommandHandler.addCommand(new Command("moveCrane", map));
this.status = Status.MOVING;
}
public void load(ExternVehicle ev, int column) throws Exception
{
for (Integer row : ev.getUnloadOrderY(column))
{
for (Container container : ev.getGrid()[column][row])
{
while (readyForNextContainer == false){}
try
{
if (container != null)
{
readyForNextContainer = false;
//ask agv!
super.load(ev.unload(container));
this.loadTime = ((Math.abs(this.position.y-container.getArrivalPosition().y) / (this.moveContainerSpeed *1000f/3600f)/100f))//move gripper to position of container
//+ this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) //droptime depended on z position of container //???
+ this.SECURETIME
+ this.liftTimeMin + (this.liftTimeMax - this.liftTimeMin) / ((int)container.getArrivalPosition().z + 1) //lifttime depended on z position of container
+ Math.abs((this.position.y-container.getArrivalPosition().y) / ((this.moveContainerSpeed *1000f/3600f)/100f));
this.status = Status.LOADING;
this.loadTime = 12*10;
this.unloadTime = (this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) + this.SECURETIME) * 100;
HashMap<String, Object> map = new HashMap<>();
this.unloadTime = 6*10;
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("clientid", ev.getID());
map.put("duration", this.loadTime);
map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("loadCrane", map));
}
}
catch(Exception e)
{
throw e;
}
}
}
ev.updateColumn(column, true);
this.isAvailable = true;
}
public void load(Container container, ExternVehicle ev) throws VehicleOverflowException, CargoOutOfBoundsException, Exception{ //container from extern verhicle
try
{
super.load(ev.unload(container));
this.loadTime = ((Math.abs(this.position.y-container.getArrivalPosition().y) / (this.moveContainerSpeed *1000f/3600f)/100f))//move gripper to position of container
//+ this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) //droptime depended on z position of container //???
+ this.SECURETIME
+ this.liftTimeMin + (this.liftTimeMax - this.liftTimeMin) / ((int)container.getArrivalPosition().z + 1) //lifttime depended on z position of container
+ Math.abs((this.position.y-container.getArrivalPosition().y) / ((this.moveContainerSpeed *1000f/3600f)/100f));
this.status = Status.LOADING;
this.unloadTime = (this.dropTimeMin + (this.dropTimeMax - this.dropTimeMin) / ((int)container.getArrivalPosition().z + 1) + this.SECURETIME) * 100;
this.loadTime = 12*10;
this.unloadTime = 10*10;
if (this.getVehicleType() != Type.STORAGECRANE){
HashMap<String, Object> map = new HashMap<>();
map.put("craneid", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("clientid", ev.getID());
map.put("duration", this.loadTime);
map.put("container", cargo.get(0));
CommandHandler.addCommand(new Command("loadCrane", map));
}
}
catch(Exception e)
{
throw e;
}
//this.timeCountDown = (int) liftTimeMax;
//update: while (this.timeCounter < starttime + liftTimeMax + moveContainerSpeed * 2){} //aan het laden
//roep evt nieuwe agv aan (op zelfde parkeerplaats of op parkeerplaats opzij [moet platform doen]
}
public void move(int direction) //-1 is left 1 is right
{
//override this method for truckcrane
List<Vector3f> route = new ArrayList<>();
route.add(this.position);
if (direction == -1)
{ //trein z anders x
route.add(new Vector3f(this.position.x + Container.depth, this.position.y, this.position.z));
}
else
{
route.add(new Vector3f(this.position.x + Container.depth, this.position.y, this.position.z));
}
this.currentSpeed = (this.isLoaded) ? this.maxSpeedLoaded : this.maxSpeedUnloaded;
HashMap<String, Object> map = new HashMap<>();
map.put("id", this.getID());
map.put("vehicleType", this.getVehicleType());
map.put("motionPath", route);
map.put("speed", currentSpeed);
this.route = new Route(route,Road.getPathLength(route));
CommandHandler.addCommand(new Command("moveCrane", map));
}
@Override
public void update()
{
/*
if (this.getVehicleType() == Type.STORAGECRANE)
{
System.out.println("StorageCraneYes");
StorageCrane sc = (StorageCrane) this;
sc.update();
}
else{*/
super.update();
if (this.status == Status.LOADING )
{
this.loadTime--;
if (this.loadTime <= 0)
{
this.status = Status.UNLOADING;
//command simulator
}
}
if (this.status == Status.UNLOADING && this.agvToUnload != null)
{
this.unloadTime--;
if (this.unloadTime <= 0)
{
try
{
this.unload(agvToUnload);
}
catch(Exception e){ System.out.println(e.getMessage()); }
this.agvToUnload = null;
//this.currentPlatform.getAGV(this.getPosition());
this.status = Status.WAITING;
readyForNextContainer = true;
//new load
}
}
}
public void setAGV(AGV agv){ this.agvToUnload = agv; }
//methode opzij in subclasses waarvoor geldig is
}
|
33163_19 | package nl.utwente.di.gradeManager.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.utwente.di.gradeManager.db.GradesDB;
import nl.utwente.di.gradeManager.db.LoginDB;
import nl.utwente.di.gradeManager.model.Assignment;
import nl.utwente.di.gradeManager.model.AssignmentResult;
import nl.utwente.di.gradeManager.model.Course;
import nl.utwente.di.gradeManager.model.Module;
import nl.utwente.di.gradeManager.model.Student;
import nl.utwente.di.gradeManager.model.Teacher;
public class DocentTabel extends HttpServlet {
//Variabelen aanmaken die gebruikt worden in deze klasse
private final String jsp_address = "Docent.jsp";
private List<AssignmentResult> results;
private List<Assignment> assignments;
private List<Course> courses;
private List<Module> docentmodules;
private StudentModules modules;
private List<Student> students;
private Module module;
private Teacher docent;
//Alle informatie uit de database halen en in de locale variablen zetten zodat ze doorgestuurd kunnen worden
protected void setInfo(int personID, int moduleID, int moduleYear){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de docent opzoeken voor navigatiebalk
modules = new StudentModules(personID, docentmodules);
//Informatie van de huidig ingelogde docent opzoeken
docent = gradesDB.getTeacher(personID);
//Informatie van de module in de database opzoeken
module = gradesDB.getModule(moduleID, moduleYear);
//Alle vakken die bij de module horen opzoeken
courses = gradesDB.getCoursesForModule(moduleID);
//Alle studenten uit de database halen, zodat de studentID`s omgezet kunnen worden naar namen
students = gradesDB.getStudents();
/**Tijdelijke Assingment lijst aanmaken.
*Moet een arraylist zijn zodat we assignments aan de lijst kunnen toevoegen.
*De variable 'assignments' is een List<Assignment>, hier kunnen we geen extra assignments aan toevoegen nadat we de database-query
*voor 1 vak hebben uitgevoerd
*Daarom hebben de assignmemtList, we lopen elk vak van de module door, en voegen alle assignments van die vakken toe aan de lijst.
*/
List<Assignment> assignmentList = new ArrayList<Assignment>();
//For-loop voor alle vakken van de module
for(int i = 0; i < courses.size(); i++){
//Vraagt alle assignments van 1 vak op
assignments = gradesDB.getAssignmentsForCourse(courses.get(i).getCourseCode(), courses.get(i).getYear());
//Als er assignments zijn, toevoegen aan assignmentlist
if (assignments != null){
//For-loop voor alle assignments in de lijst
for (int j = 0; j < assignments.size(); j++) {
//Assignment toevoegen aan de tijdelijke lijst
if(assignments.get(j) != null){
assignmentList.add(assignments.get(j));
}
}
}
}
//Tijdelijke assignmentlist omzetten naar de uiteindelijke 'assignment' lijst
assignments = assignmentList;
/**
* Tijdelijke AssignmentResult lijst aanmaken
* 'resultList' is een arraylist zodat er element aan toegevoegd kunnen worden
* Dan alle resultaten van alle assignments toevoegen aan de tijdelijke lijst
* Daarna weer tijdelijke lijst terugzetten naar de officiele 'results' AssignmentResult lijst
*/
List<AssignmentResult> resultList = new ArrayList<AssignmentResult>();
//Alle assignments doorlopen
//Alle assignments van alle vakken staan al in de lijst, dus hoeven geen vak te specificeren
for(int i = 0; i < assignments.size(); i++){
//Alle resultaten van een assignment opvragen
results = gradesDB.getResultsForAssignment( assignments.get(i).getAssignmentID());
//Als er resultaten zijn, deze toevoegen aan de 'resultList'
if (results != null){
//Alle resultaten doorlopen
for (int j = 0; j < results.size(); j++) {
//Resultaat toevoegen aan de tijdelijke lijst
if(results.get(j) != null){
resultList.add(results.get(j));
}
}
}
}
//Tijdelijke lijst weer omzetten naar de definitieve lijst
results = resultList;
}finally{
//Database connectie sluiten
gradesDB.closeConnection();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Alle variabelen aanmaken die nodig zijn om de 'setInfo' methode aan te roepen
Integer moduleid;
Integer moduleyear;
Integer SID;
//De sessie van de gebruiker opvragen. Als er geen sessie bestaat, deze niet aanmaken
HttpSession session = request.getSession(false);
//Het ID van de sessie opvragen
if(session != null){
String sessionid = session.getId();
//Database connectie aanmaken
LoginDB logindb = new LoginDB();
try{
//Het studentnummer verbonden aan de huidige sessie in de variabele 'SID' zetten
SID = Integer.parseInt(logindb.getLoggedInPersonid(sessionid).substring(1));
}finally{
//Database connectie afsluiten
logindb.closeConnection();
}
//Als er geen moduleid en moduleyear in de URL wordt gespecificeerd, de meest recente module van de docent opzoeken en die tonen
if (request.getParameter("moduleid") == null || request.getParameter("moduleyear") == null){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de gebruiker opvragen
docentmodules = gradesDB.getModulesForDocent(SID);
//getModulecode sorteert automatisch op de meest recente module, dus eerste resultaat is de module die getoont moet worden
moduleid = docentmodules.get(0).getModulecode();
moduleyear = docentmodules.get(0).getYear();
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}else{
//Als er wel een module-id&jaar wordt gespecificeerd, deze uit de URL halen en de locale variabelen stoppen
moduleid = Integer.parseInt(request.getParameter("moduleid"));
moduleyear = Integer.parseInt(request.getParameter("moduleyear"));
}
//SetInfo aanroepen zodat alle gegevens uit de database getrokken worden en de beans gevuld kunnen worden
setInfo(SID, moduleid, moduleyear);
if(docent!= null && modules != null && module != null && courses != null && assignments != null && results != null){
//Informatie van de module meegeven voor de JSP pagina
request.setAttribute("moduletoShow", module);
//Informatie over de docent meegeven aan de JSP pagina
request.setAttribute("docent", docent);
//Alle modules van de docent meegeven aan de JSP pagina voor de navigatiebalk
request.setAttribute("docentModules", modules);
//Bean aanmaken met de lijst van vakken die de docent kan zien
StudentCourses beanSC = new StudentCourses(SID, courses);
//De bean meegeven aan de JSP pagina
request.setAttribute("coursestoShow", beanSC);
//Bean aanmaken met alle assignments van alle vakken van de module
CourseAssignments beanCA = new CourseAssignments("Dit is een vak", assignments);
//De bean meegeven aan de JSP pagina
request.setAttribute("assignmentstoShow", beanCA);
request.setAttribute("docentModules", modules);//Bean aanmaken voor alle resultaten die behaald zijn
StudentAssignments beanSA = new StudentAssignments("Dit is een resultaat", results);
//De bean meegeven aan de JSP pagina
request.setAttribute("resultstoShow", beanSA);
//Alle studenten die het vak volgen in een bean stoppen
AllStudents beanCS = new AllStudents("Dit is een student", students);
//De bean meegeven aan de JSP pagina
request.setAttribute("studentstoShow", beanCS);
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher(jsp_address);
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}
}
| utwente-di/di19 | gradeManager/src/main/java/nl/utwente/di/gradeManager/servlets/DocentTabel.java | 2,271 | //Als er resultaten zijn, deze toevoegen aan de 'resultList' | line_comment | nl | package nl.utwente.di.gradeManager.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.utwente.di.gradeManager.db.GradesDB;
import nl.utwente.di.gradeManager.db.LoginDB;
import nl.utwente.di.gradeManager.model.Assignment;
import nl.utwente.di.gradeManager.model.AssignmentResult;
import nl.utwente.di.gradeManager.model.Course;
import nl.utwente.di.gradeManager.model.Module;
import nl.utwente.di.gradeManager.model.Student;
import nl.utwente.di.gradeManager.model.Teacher;
public class DocentTabel extends HttpServlet {
//Variabelen aanmaken die gebruikt worden in deze klasse
private final String jsp_address = "Docent.jsp";
private List<AssignmentResult> results;
private List<Assignment> assignments;
private List<Course> courses;
private List<Module> docentmodules;
private StudentModules modules;
private List<Student> students;
private Module module;
private Teacher docent;
//Alle informatie uit de database halen en in de locale variablen zetten zodat ze doorgestuurd kunnen worden
protected void setInfo(int personID, int moduleID, int moduleYear){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de docent opzoeken voor navigatiebalk
modules = new StudentModules(personID, docentmodules);
//Informatie van de huidig ingelogde docent opzoeken
docent = gradesDB.getTeacher(personID);
//Informatie van de module in de database opzoeken
module = gradesDB.getModule(moduleID, moduleYear);
//Alle vakken die bij de module horen opzoeken
courses = gradesDB.getCoursesForModule(moduleID);
//Alle studenten uit de database halen, zodat de studentID`s omgezet kunnen worden naar namen
students = gradesDB.getStudents();
/**Tijdelijke Assingment lijst aanmaken.
*Moet een arraylist zijn zodat we assignments aan de lijst kunnen toevoegen.
*De variable 'assignments' is een List<Assignment>, hier kunnen we geen extra assignments aan toevoegen nadat we de database-query
*voor 1 vak hebben uitgevoerd
*Daarom hebben de assignmemtList, we lopen elk vak van de module door, en voegen alle assignments van die vakken toe aan de lijst.
*/
List<Assignment> assignmentList = new ArrayList<Assignment>();
//For-loop voor alle vakken van de module
for(int i = 0; i < courses.size(); i++){
//Vraagt alle assignments van 1 vak op
assignments = gradesDB.getAssignmentsForCourse(courses.get(i).getCourseCode(), courses.get(i).getYear());
//Als er assignments zijn, toevoegen aan assignmentlist
if (assignments != null){
//For-loop voor alle assignments in de lijst
for (int j = 0; j < assignments.size(); j++) {
//Assignment toevoegen aan de tijdelijke lijst
if(assignments.get(j) != null){
assignmentList.add(assignments.get(j));
}
}
}
}
//Tijdelijke assignmentlist omzetten naar de uiteindelijke 'assignment' lijst
assignments = assignmentList;
/**
* Tijdelijke AssignmentResult lijst aanmaken
* 'resultList' is een arraylist zodat er element aan toegevoegd kunnen worden
* Dan alle resultaten van alle assignments toevoegen aan de tijdelijke lijst
* Daarna weer tijdelijke lijst terugzetten naar de officiele 'results' AssignmentResult lijst
*/
List<AssignmentResult> resultList = new ArrayList<AssignmentResult>();
//Alle assignments doorlopen
//Alle assignments van alle vakken staan al in de lijst, dus hoeven geen vak te specificeren
for(int i = 0; i < assignments.size(); i++){
//Alle resultaten van een assignment opvragen
results = gradesDB.getResultsForAssignment( assignments.get(i).getAssignmentID());
//Als er<SUF>
if (results != null){
//Alle resultaten doorlopen
for (int j = 0; j < results.size(); j++) {
//Resultaat toevoegen aan de tijdelijke lijst
if(results.get(j) != null){
resultList.add(results.get(j));
}
}
}
}
//Tijdelijke lijst weer omzetten naar de definitieve lijst
results = resultList;
}finally{
//Database connectie sluiten
gradesDB.closeConnection();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Alle variabelen aanmaken die nodig zijn om de 'setInfo' methode aan te roepen
Integer moduleid;
Integer moduleyear;
Integer SID;
//De sessie van de gebruiker opvragen. Als er geen sessie bestaat, deze niet aanmaken
HttpSession session = request.getSession(false);
//Het ID van de sessie opvragen
if(session != null){
String sessionid = session.getId();
//Database connectie aanmaken
LoginDB logindb = new LoginDB();
try{
//Het studentnummer verbonden aan de huidige sessie in de variabele 'SID' zetten
SID = Integer.parseInt(logindb.getLoggedInPersonid(sessionid).substring(1));
}finally{
//Database connectie afsluiten
logindb.closeConnection();
}
//Als er geen moduleid en moduleyear in de URL wordt gespecificeerd, de meest recente module van de docent opzoeken en die tonen
if (request.getParameter("moduleid") == null || request.getParameter("moduleyear") == null){
//Database connectie aanmaken
GradesDB gradesDB = new GradesDB();
try{
//Alle modules van de gebruiker opvragen
docentmodules = gradesDB.getModulesForDocent(SID);
//getModulecode sorteert automatisch op de meest recente module, dus eerste resultaat is de module die getoont moet worden
moduleid = docentmodules.get(0).getModulecode();
moduleyear = docentmodules.get(0).getYear();
}finally{
//Database connectie afsluiten
gradesDB.closeConnection();
}
}else{
//Als er wel een module-id&jaar wordt gespecificeerd, deze uit de URL halen en de locale variabelen stoppen
moduleid = Integer.parseInt(request.getParameter("moduleid"));
moduleyear = Integer.parseInt(request.getParameter("moduleyear"));
}
//SetInfo aanroepen zodat alle gegevens uit de database getrokken worden en de beans gevuld kunnen worden
setInfo(SID, moduleid, moduleyear);
if(docent!= null && modules != null && module != null && courses != null && assignments != null && results != null){
//Informatie van de module meegeven voor de JSP pagina
request.setAttribute("moduletoShow", module);
//Informatie over de docent meegeven aan de JSP pagina
request.setAttribute("docent", docent);
//Alle modules van de docent meegeven aan de JSP pagina voor de navigatiebalk
request.setAttribute("docentModules", modules);
//Bean aanmaken met de lijst van vakken die de docent kan zien
StudentCourses beanSC = new StudentCourses(SID, courses);
//De bean meegeven aan de JSP pagina
request.setAttribute("coursestoShow", beanSC);
//Bean aanmaken met alle assignments van alle vakken van de module
CourseAssignments beanCA = new CourseAssignments("Dit is een vak", assignments);
//De bean meegeven aan de JSP pagina
request.setAttribute("assignmentstoShow", beanCA);
request.setAttribute("docentModules", modules);//Bean aanmaken voor alle resultaten die behaald zijn
StudentAssignments beanSA = new StudentAssignments("Dit is een resultaat", results);
//De bean meegeven aan de JSP pagina
request.setAttribute("resultstoShow", beanSA);
//Alle studenten die het vak volgen in een bean stoppen
AllStudents beanCS = new AllStudents("Dit is een student", students);
//De bean meegeven aan de JSP pagina
request.setAttribute("studentstoShow", beanCS);
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher(jsp_address);
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}else{
//Juiste JSP pagina specificeren om naar door te sturen
RequestDispatcher dispatcher = request.getRequestDispatcher("login");
//Daadwerkelijk alles doorsturen
dispatcher.forward(request, response);
}
}
}
|
25642_1 | package controller;
import java.util.ArrayList;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import model.Docent;
import model.Opleiding;
import model.Vak;
import server.Conversation;
import server.Handler;
public class DocentController implements Handler {
private Opleiding informatieSysteem;
/**
* De DocentController klasse moet alle docent-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public DocentController(Opleiding infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {
mijnVakken(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void mijnVakken(Conversation conversation) {
JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String gebruikersnaam = jsonObjectIn.getString("username");
Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!
ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!
if(vakken == null) {
System.out.println("Vakken zijn leeg");
}
JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met...
for (Vak v : vakken) {
jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object...
.add("vakcode", v.getVakCode())
.add("vaknaam", v.getVakNaam()));
}
conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!
}
}
| FullCount/PrIS | src/controller/DocentController.java | 583 | /**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/ | block_comment | nl | package controller;
import java.util.ArrayList;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import model.Docent;
import model.Opleiding;
import model.Vak;
import server.Conversation;
import server.Handler;
public class DocentController implements Handler {
private Opleiding informatieSysteem;
/**
* De DocentController klasse moet alle docent-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public DocentController(Opleiding infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {
mijnVakken(conversation);
}
}
/**
* Deze methode haalt<SUF>*/
private void mijnVakken(Conversation conversation) {
JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String gebruikersnaam = jsonObjectIn.getString("username");
Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!
ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!
if(vakken == null) {
System.out.println("Vakken zijn leeg");
}
JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met...
for (Vak v : vakken) {
jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object...
.add("vakcode", v.getVakCode())
.add("vaknaam", v.getVakNaam()));
}
conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!
}
}
|