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
|
---|---|---|---|---|---|---|---|---|
96975_6 | /*
* 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 sources.formatreaders;
import java.util.List;
import model.EmbeddedMediaObject;
import model.EmbeddedMediaObject.MediaVersion;
import model.EmbeddedMediaObject.WithMediaRights;
import model.EmbeddedMediaObject.WithMediaType;
import model.basicDataTypes.Language;
import model.basicDataTypes.LiteralOrResource;
import model.basicDataTypes.MultiLiteralOrResource;
import model.basicDataTypes.ProvenanceInfo;
import model.basicDataTypes.Resource;
import model.resources.CulturalObject;
import model.resources.CulturalObject.CulturalObjectData;
import search.FiltersFields;
import search.Sources;
import sources.FilterValuesMap;
import sources.core.Utils;
import sources.utils.JsonContextRecord;
import sources.utils.StringUtils;
public class RijksmuseumItemRecordFormatter extends CulturalRecordFormatter {
public RijksmuseumItemRecordFormatter() {
super(FilterValuesMap.getMap(Sources.Rijksmuseum));
object = new CulturalObject();
}
@Override
public CulturalObject fillObjectFrom(JsonContextRecord rec) {
CulturalObjectData model = (CulturalObjectData) object.getDescriptiveData();
rec.enterContext("artObject");
String id = rec.getStringValue("objectNumber");
Language[] language = null;
List<String> langs = rec.getStringArrayValue("language");
if (Utils.hasInfo(langs)){
language = new Language[langs.size()];
for (int i = 0; i < langs.size(); i++) {
language[i] = Language.getLanguage(langs.get(i));
}
}
if (!Utils.hasInfo(language)){
language = getLanguagesFromText(rec.getStringValue("title"),
rec.getStringValue("titles"),
rec.getStringValue("longTitle"),
rec.getStringValue("description"));
}
rec.setLanguages(language);
model.setDclanguage(StringUtils.getLiteralLanguages(language));
// List<Object> vals =
// getValuesMap().translateToCommon(CommonFilters.TYPE.getId(),
// rec.getStringValue("ProvidedCHO.type"));
// WithMediaType type = WithMediaType.getType(vals.get(0).toString());
// model.setDcidentifier(rec.getMultiLiteralOrResourceValue("dcIdentifier"));
// model.setDccoverage(rec.getMultiLiteralOrResourceValue("dcCoverage"));
// model.setDcrights(rec.getMultiLiteralOrResourceValue("dcRights"));
// model.setDctermsspatial(rec.getMultiLiteralOrResourceValue("location","classification.places"));
model.setCountry(new MultiLiteralOrResource(Language.EN,"Netherlands"));
model.setCity(new MultiLiteralOrResource(Language.EN,"Amsterdam"));
model.setCoordinates(StringUtils.getPoint("52.36", "4.885278"));
// model.setDccreated(rec.getWithDateArrayValue("dctermsCreated"));
// model.setDcformat(rec.getMultiLiteralOrResourceValue("dcFormat"));
// model.setDctermsmedium(rec.getMultiLiteralOrResourceValue("dctermsMedium"));
// model.setIsRelatedTo(rec.getMultiLiteralOrResourceValue("edmIsRelatedTo"));
model.setDccreator(rec.getMultiLiteralOrResourceValue("principalMaker"));
model.setDccontributor(rec.getMultiLiteralOrResourceValue("makers[.*].name"));
model.setKeywords(rec.getMultiLiteralOrResourceValue("classification.iconClassDescription","materials","techniques","objectTypes"));
model.setLabel(rec.getMultiLiteralValue("title", "titles","longTitle"));
model.setDescription(rec.getMultiLiteralValue("description","subTitle","scLabelLine"));
model.setDates(StringUtils.getDates(rec.getStringArrayValue("dating.year")));
List<String> types = rec.getStringArrayValue("objectTypes");
WithMediaType type = null;
for (String string : types) {
type = WithMediaType.getType(getValuesMap().translateToCommon(FiltersFields.TYPE.getFilterId(), string).get(0).toString());
if (type.isKnown()){
break;
}
}
// model.setDctype(rec.getMultiLiteralOrResourceValue("WebResource.type"));
// model.setDccontributor(rec.getMultiLiteralOrResourceValue("dcContributor"));
// LiteralOrResource rights = rec.getLiteralOrResourceValue("WebResource.rights");
// WithMediaRights withMediaRights = rights == null ? null
// : (WithMediaRights) getValuesMap().translateToCommon(CommonFilters.RIGHTS.getId(), rights.getURI())
// .get(0);
// model.getDates().addAll(rec.getWithDateArrayValue("dcDate"));
// model.setIsShownAt(rec.getLiteralOrResourceValue("Aggregation.isShownAt"));
// model.setIsShownBy(rec.getLiteralOrResourceValue("Aggregation.isShownBy"));
object.addToProvenance(new ProvenanceInfo(Sources.Rijksmuseum.toString(),
"https://www.rijksmuseum.nl/en/collection/" + id, id));
// List<String> theViews = rec.getStringArrayValue("hasView");
// model.getDates().addAll(rec.getWithDateArrayValue("year"));
Resource isShownBy = model.getIsShownBy();
String uri2 = isShownBy == null ? null : isShownBy.toString();
String uri3 = rec.getStringValue("webImage.url");
if (Utils.hasInfo(uri3)) {
EmbeddedMediaObject medThumb = new EmbeddedMediaObject();
medThumb.setUrl(uri3);
medThumb.setWidth(rec.getIntValue("webImage.width"));
medThumb.setHeight(rec.getIntValue("webImage.height"));
medThumb.setType(type);
medThumb.setOriginalRights(new LiteralOrResource("http://creativecommons.org/publicdomain/zero/1.0/deed.en"));
medThumb.setWithRights(WithMediaRights.Public);
object.addMedia(MediaVersion.Original, medThumb);
}
return object;
}
}
| ails-lab/with | app/sources/formatreaders/RijksmuseumItemRecordFormatter.java | 1,607 | //www.rijksmuseum.nl/en/collection/" + id, id)); | line_comment | nl | /*
* 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 sources.formatreaders;
import java.util.List;
import model.EmbeddedMediaObject;
import model.EmbeddedMediaObject.MediaVersion;
import model.EmbeddedMediaObject.WithMediaRights;
import model.EmbeddedMediaObject.WithMediaType;
import model.basicDataTypes.Language;
import model.basicDataTypes.LiteralOrResource;
import model.basicDataTypes.MultiLiteralOrResource;
import model.basicDataTypes.ProvenanceInfo;
import model.basicDataTypes.Resource;
import model.resources.CulturalObject;
import model.resources.CulturalObject.CulturalObjectData;
import search.FiltersFields;
import search.Sources;
import sources.FilterValuesMap;
import sources.core.Utils;
import sources.utils.JsonContextRecord;
import sources.utils.StringUtils;
public class RijksmuseumItemRecordFormatter extends CulturalRecordFormatter {
public RijksmuseumItemRecordFormatter() {
super(FilterValuesMap.getMap(Sources.Rijksmuseum));
object = new CulturalObject();
}
@Override
public CulturalObject fillObjectFrom(JsonContextRecord rec) {
CulturalObjectData model = (CulturalObjectData) object.getDescriptiveData();
rec.enterContext("artObject");
String id = rec.getStringValue("objectNumber");
Language[] language = null;
List<String> langs = rec.getStringArrayValue("language");
if (Utils.hasInfo(langs)){
language = new Language[langs.size()];
for (int i = 0; i < langs.size(); i++) {
language[i] = Language.getLanguage(langs.get(i));
}
}
if (!Utils.hasInfo(language)){
language = getLanguagesFromText(rec.getStringValue("title"),
rec.getStringValue("titles"),
rec.getStringValue("longTitle"),
rec.getStringValue("description"));
}
rec.setLanguages(language);
model.setDclanguage(StringUtils.getLiteralLanguages(language));
// List<Object> vals =
// getValuesMap().translateToCommon(CommonFilters.TYPE.getId(),
// rec.getStringValue("ProvidedCHO.type"));
// WithMediaType type = WithMediaType.getType(vals.get(0).toString());
// model.setDcidentifier(rec.getMultiLiteralOrResourceValue("dcIdentifier"));
// model.setDccoverage(rec.getMultiLiteralOrResourceValue("dcCoverage"));
// model.setDcrights(rec.getMultiLiteralOrResourceValue("dcRights"));
// model.setDctermsspatial(rec.getMultiLiteralOrResourceValue("location","classification.places"));
model.setCountry(new MultiLiteralOrResource(Language.EN,"Netherlands"));
model.setCity(new MultiLiteralOrResource(Language.EN,"Amsterdam"));
model.setCoordinates(StringUtils.getPoint("52.36", "4.885278"));
// model.setDccreated(rec.getWithDateArrayValue("dctermsCreated"));
// model.setDcformat(rec.getMultiLiteralOrResourceValue("dcFormat"));
// model.setDctermsmedium(rec.getMultiLiteralOrResourceValue("dctermsMedium"));
// model.setIsRelatedTo(rec.getMultiLiteralOrResourceValue("edmIsRelatedTo"));
model.setDccreator(rec.getMultiLiteralOrResourceValue("principalMaker"));
model.setDccontributor(rec.getMultiLiteralOrResourceValue("makers[.*].name"));
model.setKeywords(rec.getMultiLiteralOrResourceValue("classification.iconClassDescription","materials","techniques","objectTypes"));
model.setLabel(rec.getMultiLiteralValue("title", "titles","longTitle"));
model.setDescription(rec.getMultiLiteralValue("description","subTitle","scLabelLine"));
model.setDates(StringUtils.getDates(rec.getStringArrayValue("dating.year")));
List<String> types = rec.getStringArrayValue("objectTypes");
WithMediaType type = null;
for (String string : types) {
type = WithMediaType.getType(getValuesMap().translateToCommon(FiltersFields.TYPE.getFilterId(), string).get(0).toString());
if (type.isKnown()){
break;
}
}
// model.setDctype(rec.getMultiLiteralOrResourceValue("WebResource.type"));
// model.setDccontributor(rec.getMultiLiteralOrResourceValue("dcContributor"));
// LiteralOrResource rights = rec.getLiteralOrResourceValue("WebResource.rights");
// WithMediaRights withMediaRights = rights == null ? null
// : (WithMediaRights) getValuesMap().translateToCommon(CommonFilters.RIGHTS.getId(), rights.getURI())
// .get(0);
// model.getDates().addAll(rec.getWithDateArrayValue("dcDate"));
// model.setIsShownAt(rec.getLiteralOrResourceValue("Aggregation.isShownAt"));
// model.setIsShownBy(rec.getLiteralOrResourceValue("Aggregation.isShownBy"));
object.addToProvenance(new ProvenanceInfo(Sources.Rijksmuseum.toString(),
"https://www.rijksmuseum.nl/en/collection/" +<SUF>
// List<String> theViews = rec.getStringArrayValue("hasView");
// model.getDates().addAll(rec.getWithDateArrayValue("year"));
Resource isShownBy = model.getIsShownBy();
String uri2 = isShownBy == null ? null : isShownBy.toString();
String uri3 = rec.getStringValue("webImage.url");
if (Utils.hasInfo(uri3)) {
EmbeddedMediaObject medThumb = new EmbeddedMediaObject();
medThumb.setUrl(uri3);
medThumb.setWidth(rec.getIntValue("webImage.width"));
medThumb.setHeight(rec.getIntValue("webImage.height"));
medThumb.setType(type);
medThumb.setOriginalRights(new LiteralOrResource("http://creativecommons.org/publicdomain/zero/1.0/deed.en"));
medThumb.setWithRights(WithMediaRights.Public);
object.addMedia(MediaVersion.Original, medThumb);
}
return object;
}
}
|
20525_3 | package bozels.panels;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import jbox.ExplosionRayCastCallback;
import jbox.Lijntjes;
import modellen.SpelModel;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
/**
*
* @author Titouan Vervack
*/
public class SpelPanel extends JPanel implements ChangeListener, MouseListener, MouseMotionListener {
private SpelModel model;
private int loper = 1;
private Body body;
private static final int VERHOGING = 100;
private float katapultX;
private float katapultY;
private boolean drawElastiek = true;
private int powerup = 1;
private ImageIcon achtergrond;
private ExplosionRayCastCallback raycast;
public SpelPanel(SpelModel model) {
this.model = model;
model.addChangeListener(this);
setPreferredSize(new Dimension(1024, 450));
model.setPanel(this);
addMouseListener(this);
addMouseMotionListener(this);
//Maak een achtergrond
achtergrond = new ImageIcon(SpelPanel.class.getResource("./darksunshine.png"));
}
//Teken alles
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Teken telkens de achtergrond
if (achtergrond != null) {
g.drawImage(achtergrond.getImage(), 0, 0, getWidth(), getHeight(), null);
}
//Zet de standaard coordinaten van de katpult
katapultX = model.getKatapultX() * 7f;
katapultY = 450 - (model.getKatapultY() * 7f) - VERHOGING;
//Stel de anti-aliasing in
RenderingHints aA = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Stel de huidige bozel in
Body bozel = model.getBozels().get(loper);
//Overloop alle bodies
for (Iterator it = model.getBodies().keySet().iterator(); it.hasNext();) {
Body blok = (Body) it.next();
if (blok != null) {
//Maak een nieuwe grapics en stel de kleur in
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(model.getMap().get((String) model.getBodies().get(blok)).getColor());
//Kijk of slapende objecten een andere kleur moeten krijgen zoja, verander de kleur
if (!blok.isAwake() && model.getAwake()) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
}
//Sla de postitie van de huidige blok op
Vec2 pos = blok.getPosition().mul(7);
g2.addRenderingHints(aA);
//Teken een cirkel
if (blok.getFixtureList().getShape() instanceof CircleShape) {
CircleShape shape = (CircleShape) blok.getFixtureList().getShape();
//Vraag de straal op aan JBox
int r = (int) (shape.m_radius * 7);
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
g2.translate((int) (pos.x), (int) (450 - pos.y));
g2.fillOval(-r, -r, r * 2, r * 2);
} else {
PolygonShape shape = (PolygonShape) blok.getFixtureList().getShape();
//Vraag de hoekpunten op aan JBox
//Teken een driehoek
if (shape.m_vertexCount != 4) {
float h = (float) (14 / Math.sqrt(4.0f / 3.0f));
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
int[] xs = {0, -7, 7};
int[] ys = {-Math.round(h * (2f / 3f)), (int) -Math.round(-h / 3), (int) -Math.round(-h / 3)};
g2.translate((int) pos.x, (int) (450 - pos.y));
g2.rotate(-blok.getAngle());
g2.drawPolygon(xs, ys, shape.m_vertexCount);
//Teken een rechthoek
} else {
//Vraag de breedte en de hoogte op aan JBox
float breedte = shape.m_vertices[2].x * 14;
float hoogte = shape.m_vertices[2].y * 14;
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
g2.translate((int) pos.x, (int) (450 - pos.y));
g2.rotate(-blok.getAngle());
g2.fillRect((int) -(breedte / 2), (int) -(hoogte / 2), (int) breedte, (int) hoogte);
}
}
//Teken indien nodig zwaartepunt
if (model.getDrawZwaartepunt()) {
g2.setColor(Color.RED);
g2.fillOval(-2, -2, 4, 4);
}
g.setColor(Color.RED);
//Teken indien nodig elastiek naar de bozel anders naar het middelpunt van de katapult
if (drawElastiek) {
g.drawLine((int) katapultX, (int) katapultY, (int) bozel.getPosition().x * 7, (int) (450 - (bozel.getPosition().y * 7)));
} else {
g.drawLine((int) katapultX, (int) katapultY, (int) katapultX, (int) katapultY);
}
//Teken indien nodig de snelheid, in een andere graphics want de vorige is al getranslate/rotate
if (model.getDrawSnelheid() && blok.isAwake()) {
Graphics2D g3 = (Graphics2D) g.create();
g3.setColor(Color.MAGENTA);
g3.translate(pos.x, 450 - pos.y);
g3.drawLine(0, 0, (int) (blok.getLinearVelocity().x * 7), (int) -(blok.getLinearVelocity().y * 7));
}
//Teken indien nodig de rays
if (model.getDrawRays() && raycast != null) {
for (Lijntjes r : raycast.getRays()) {
g.drawLine((int) r.getBegin().x * 7, (int) (450 - (r.getBegin().y * 7)), (int) r.getKracht().x * 7, (int) (450 - (r.getKracht().y * 7)));
}
}
}
}
if (body != null) {
//Als dit niet de laatste bozel is
if (model.getBozels().get(loper + 1) != null) {
//Als de bozel in vlucht is
if (!body.isAwake()) {
//Verwijder de bozel uit de nodige mappen en in de wereld en zet de powerup weer op 1
destroyBody(body);
//Stel de volgende bozel in
loper++;
body = model.getBozels().get(loper);
//Laat de volgende bozel klaarzetten en teken de elastiek naar de bozel
model.setFirst(true);
drawElastiek = true;
}
//Als dit de laatste bozel is
} else {
//Als de bozel in vlucht is
if (!body.isAwake()) {
destroyBody(body);
loper = 0;
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (body != null) {
//Als het het een witte/zwarte bozel is doe hem ontploffen op een muisklik
if ("white".equals(model.getBodies().get(body)) || "black".equals(model.getBodies().get(body))) {
Vec2 pos = body.getPosition();
raycast = new ExplosionRayCastCallback(pos);
for (int i = 0; i < 72; i++) {
try {
float hoek = (float) (Math.PI / 36 * i);
float x1 = (float) (Math.cos(hoek) * 10.0f) + pos.x;
float y1 = (float) (Math.sin(hoek) * 10.0f) + pos.y;
Vec2 positie2 = new Vec2(x1, y1);
model.getWorld().raycast(raycast, pos, positie2);
raycast.addRay();
} catch (NullPointerException ex) {
}
}
raycast.explode();
model.setRaycast(raycast);
//Verwijder de ontplofte bozel en zet de volgende klaar
body.setAwake(true);
if (model.getBozels().get(loper + 1) != null) {
model.setFirst(true);
drawElastiek = true;
destroyBody(body);
loper++;
body = model.getBozels().get(loper);
} else {
destroyBody(body);
loper = 0;
}
//Verdrievoudig de kracht van de bozel indien hij geel is en doe -1 op powerup zodat hij het niet opnieuw kan gebruiken
} else if ("yellow".equals(model.getBodies().get(body)) && powerup > 0) {
body.setLinearVelocity(body.getLinearVelocity().mul(3f));
powerup--;
//Verwijder de gewone bozel, zodat je niet moet wachten tot hij slaapt, en zet de volgende klaar
} else {
destroyBody(body);
if (model.getBozels().get(loper + 1) != null) {
loper++;
body = model.getBozels().get(loper);
model.setFirst(true);
drawElastiek = true;
} else {
model.setFirst(true);
loper = 0;
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
body = model.getBozels().get(loper);
if (body != null) {
//Als de bozel niet in vlucht is
if (!body.isActive()) {
float x = e.getX();
float y = (450 - e.getY());
if (!model.getBozels().isEmpty()) {
//Formules zoals ze in de pdf te vinden zijn
Vec2 r1 = new Vec2(x / 7, y / 7);
Vec2 r0 = new Vec2(model.getKatapultX(), model.getKatapultY() + (VERHOGING / 7));
Vec2 rd = r0.sub(r1);
Vec2 elastiek = rd.mul(Math.min(rd.normalize(), 7.0f));
Vec2 multi = rd.mul((float) elastiek.length());
Vec2 pos = r0.sub(multi);
verplaatsBody(body, pos.x * 7, pos.y * 7);
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
//Formules zoals ze in de pdf te vinden zijn
if (!body.isActive()) {
//Reken de kracht uit en voer hem uit op de bozel
body.setActive(true);
drawElastiek = false;
float x = katapultX - e.getX();
float y = katapultY - e.getY();
Vec2 vec = new Vec2(x, y);
float len = vec.length();
Vec2 l = new Vec2(x * len, 450 - y * len);
body.setLinearVelocity(l.mul(model.getLanceerkracht() / 10000000));
}
}
//Verplaats de body
public void verplaatsBody(Body b, float x, float y) {
b.setTransform(new Vec2(x / 7, y / 7), b.getAngle());
}
@Override
public void mouseDragged(MouseEvent e) {
//Als de bozel niet in vlucht is
if (!body.isActive()) {
float x = e.getX();
float y = (450 - e.getY());
if (!model.getBozels().isEmpty()) {
//Formules zoals ze in de pdf te vinden zijn
Vec2 r1 = new Vec2(x / 7, y / 7);
Vec2 r0 = new Vec2(model.getKatapultX(), model.getKatapultY() + (VERHOGING / 7));
Vec2 rd = r0.sub(r1);
Vec2 elastiek = rd.mul(Math.min(rd.normalize(), 7.0f));
Vec2 multi = rd.mul((float) elastiek.length());
Vec2 pos = r0.sub(multi);
verplaatsBody(body, pos.x * 7, pos.y * 7);
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
//Zet de variabelen terug naar hun originele waarden wanneer het spel herstart wordt
@Override
public void stateChanged(ChangeEvent e) {
//Om zeker te zijn dat er een herstart is geweest, dit wordt ook opgeroepen wanneer een ander element in de JList wordt geselecteerd
if (model.getBozels().isEmpty()) {
loper = 1;
powerup = 1;
drawElastiek = true;
repaint();
}
}
//Verwijder eeen bozel
public void destroyBody(Body b) {
model.getBodies().remove(b);
model.getDestroy().push(b);
model.getBozels().remove(loper);
powerup = 1;
}
} | tivervac/UGentProjects | Bozels/src/bozels/panels/SpelPanel.java | 3,922 | //Zet de standaard coordinaten van de katpult | line_comment | nl | package bozels.panels;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import jbox.ExplosionRayCastCallback;
import jbox.Lijntjes;
import modellen.SpelModel;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
/**
*
* @author Titouan Vervack
*/
public class SpelPanel extends JPanel implements ChangeListener, MouseListener, MouseMotionListener {
private SpelModel model;
private int loper = 1;
private Body body;
private static final int VERHOGING = 100;
private float katapultX;
private float katapultY;
private boolean drawElastiek = true;
private int powerup = 1;
private ImageIcon achtergrond;
private ExplosionRayCastCallback raycast;
public SpelPanel(SpelModel model) {
this.model = model;
model.addChangeListener(this);
setPreferredSize(new Dimension(1024, 450));
model.setPanel(this);
addMouseListener(this);
addMouseMotionListener(this);
//Maak een achtergrond
achtergrond = new ImageIcon(SpelPanel.class.getResource("./darksunshine.png"));
}
//Teken alles
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Teken telkens de achtergrond
if (achtergrond != null) {
g.drawImage(achtergrond.getImage(), 0, 0, getWidth(), getHeight(), null);
}
//Zet de<SUF>
katapultX = model.getKatapultX() * 7f;
katapultY = 450 - (model.getKatapultY() * 7f) - VERHOGING;
//Stel de anti-aliasing in
RenderingHints aA = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Stel de huidige bozel in
Body bozel = model.getBozels().get(loper);
//Overloop alle bodies
for (Iterator it = model.getBodies().keySet().iterator(); it.hasNext();) {
Body blok = (Body) it.next();
if (blok != null) {
//Maak een nieuwe grapics en stel de kleur in
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(model.getMap().get((String) model.getBodies().get(blok)).getColor());
//Kijk of slapende objecten een andere kleur moeten krijgen zoja, verander de kleur
if (!blok.isAwake() && model.getAwake()) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
}
//Sla de postitie van de huidige blok op
Vec2 pos = blok.getPosition().mul(7);
g2.addRenderingHints(aA);
//Teken een cirkel
if (blok.getFixtureList().getShape() instanceof CircleShape) {
CircleShape shape = (CircleShape) blok.getFixtureList().getShape();
//Vraag de straal op aan JBox
int r = (int) (shape.m_radius * 7);
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
g2.translate((int) (pos.x), (int) (450 - pos.y));
g2.fillOval(-r, -r, r * 2, r * 2);
} else {
PolygonShape shape = (PolygonShape) blok.getFixtureList().getShape();
//Vraag de hoekpunten op aan JBox
//Teken een driehoek
if (shape.m_vertexCount != 4) {
float h = (float) (14 / Math.sqrt(4.0f / 3.0f));
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
int[] xs = {0, -7, 7};
int[] ys = {-Math.round(h * (2f / 3f)), (int) -Math.round(-h / 3), (int) -Math.round(-h / 3)};
g2.translate((int) pos.x, (int) (450 - pos.y));
g2.rotate(-blok.getAngle());
g2.drawPolygon(xs, ys, shape.m_vertexCount);
//Teken een rechthoek
} else {
//Vraag de breedte en de hoogte op aan JBox
float breedte = shape.m_vertices[2].x * 14;
float hoogte = shape.m_vertices[2].y * 14;
//Als de huidige blok gelijk is aan de huidige bozel en de bozel mag op de katapult geplaatst worden
if (bozel.equals(blok) && model.getFirst()) {
//Verplaats de bozel naar de katapult en zeg dat de volgende dit niet mag doen
blok.m_xf.position.set(new Vec2(katapultX / 7, (model.getKatapultY() * 7 + VERHOGING) / 7));
model.setFirst(false);
}
g2.translate((int) pos.x, (int) (450 - pos.y));
g2.rotate(-blok.getAngle());
g2.fillRect((int) -(breedte / 2), (int) -(hoogte / 2), (int) breedte, (int) hoogte);
}
}
//Teken indien nodig zwaartepunt
if (model.getDrawZwaartepunt()) {
g2.setColor(Color.RED);
g2.fillOval(-2, -2, 4, 4);
}
g.setColor(Color.RED);
//Teken indien nodig elastiek naar de bozel anders naar het middelpunt van de katapult
if (drawElastiek) {
g.drawLine((int) katapultX, (int) katapultY, (int) bozel.getPosition().x * 7, (int) (450 - (bozel.getPosition().y * 7)));
} else {
g.drawLine((int) katapultX, (int) katapultY, (int) katapultX, (int) katapultY);
}
//Teken indien nodig de snelheid, in een andere graphics want de vorige is al getranslate/rotate
if (model.getDrawSnelheid() && blok.isAwake()) {
Graphics2D g3 = (Graphics2D) g.create();
g3.setColor(Color.MAGENTA);
g3.translate(pos.x, 450 - pos.y);
g3.drawLine(0, 0, (int) (blok.getLinearVelocity().x * 7), (int) -(blok.getLinearVelocity().y * 7));
}
//Teken indien nodig de rays
if (model.getDrawRays() && raycast != null) {
for (Lijntjes r : raycast.getRays()) {
g.drawLine((int) r.getBegin().x * 7, (int) (450 - (r.getBegin().y * 7)), (int) r.getKracht().x * 7, (int) (450 - (r.getKracht().y * 7)));
}
}
}
}
if (body != null) {
//Als dit niet de laatste bozel is
if (model.getBozels().get(loper + 1) != null) {
//Als de bozel in vlucht is
if (!body.isAwake()) {
//Verwijder de bozel uit de nodige mappen en in de wereld en zet de powerup weer op 1
destroyBody(body);
//Stel de volgende bozel in
loper++;
body = model.getBozels().get(loper);
//Laat de volgende bozel klaarzetten en teken de elastiek naar de bozel
model.setFirst(true);
drawElastiek = true;
}
//Als dit de laatste bozel is
} else {
//Als de bozel in vlucht is
if (!body.isAwake()) {
destroyBody(body);
loper = 0;
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (body != null) {
//Als het het een witte/zwarte bozel is doe hem ontploffen op een muisklik
if ("white".equals(model.getBodies().get(body)) || "black".equals(model.getBodies().get(body))) {
Vec2 pos = body.getPosition();
raycast = new ExplosionRayCastCallback(pos);
for (int i = 0; i < 72; i++) {
try {
float hoek = (float) (Math.PI / 36 * i);
float x1 = (float) (Math.cos(hoek) * 10.0f) + pos.x;
float y1 = (float) (Math.sin(hoek) * 10.0f) + pos.y;
Vec2 positie2 = new Vec2(x1, y1);
model.getWorld().raycast(raycast, pos, positie2);
raycast.addRay();
} catch (NullPointerException ex) {
}
}
raycast.explode();
model.setRaycast(raycast);
//Verwijder de ontplofte bozel en zet de volgende klaar
body.setAwake(true);
if (model.getBozels().get(loper + 1) != null) {
model.setFirst(true);
drawElastiek = true;
destroyBody(body);
loper++;
body = model.getBozels().get(loper);
} else {
destroyBody(body);
loper = 0;
}
//Verdrievoudig de kracht van de bozel indien hij geel is en doe -1 op powerup zodat hij het niet opnieuw kan gebruiken
} else if ("yellow".equals(model.getBodies().get(body)) && powerup > 0) {
body.setLinearVelocity(body.getLinearVelocity().mul(3f));
powerup--;
//Verwijder de gewone bozel, zodat je niet moet wachten tot hij slaapt, en zet de volgende klaar
} else {
destroyBody(body);
if (model.getBozels().get(loper + 1) != null) {
loper++;
body = model.getBozels().get(loper);
model.setFirst(true);
drawElastiek = true;
} else {
model.setFirst(true);
loper = 0;
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
body = model.getBozels().get(loper);
if (body != null) {
//Als de bozel niet in vlucht is
if (!body.isActive()) {
float x = e.getX();
float y = (450 - e.getY());
if (!model.getBozels().isEmpty()) {
//Formules zoals ze in de pdf te vinden zijn
Vec2 r1 = new Vec2(x / 7, y / 7);
Vec2 r0 = new Vec2(model.getKatapultX(), model.getKatapultY() + (VERHOGING / 7));
Vec2 rd = r0.sub(r1);
Vec2 elastiek = rd.mul(Math.min(rd.normalize(), 7.0f));
Vec2 multi = rd.mul((float) elastiek.length());
Vec2 pos = r0.sub(multi);
verplaatsBody(body, pos.x * 7, pos.y * 7);
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
//Formules zoals ze in de pdf te vinden zijn
if (!body.isActive()) {
//Reken de kracht uit en voer hem uit op de bozel
body.setActive(true);
drawElastiek = false;
float x = katapultX - e.getX();
float y = katapultY - e.getY();
Vec2 vec = new Vec2(x, y);
float len = vec.length();
Vec2 l = new Vec2(x * len, 450 - y * len);
body.setLinearVelocity(l.mul(model.getLanceerkracht() / 10000000));
}
}
//Verplaats de body
public void verplaatsBody(Body b, float x, float y) {
b.setTransform(new Vec2(x / 7, y / 7), b.getAngle());
}
@Override
public void mouseDragged(MouseEvent e) {
//Als de bozel niet in vlucht is
if (!body.isActive()) {
float x = e.getX();
float y = (450 - e.getY());
if (!model.getBozels().isEmpty()) {
//Formules zoals ze in de pdf te vinden zijn
Vec2 r1 = new Vec2(x / 7, y / 7);
Vec2 r0 = new Vec2(model.getKatapultX(), model.getKatapultY() + (VERHOGING / 7));
Vec2 rd = r0.sub(r1);
Vec2 elastiek = rd.mul(Math.min(rd.normalize(), 7.0f));
Vec2 multi = rd.mul((float) elastiek.length());
Vec2 pos = r0.sub(multi);
verplaatsBody(body, pos.x * 7, pos.y * 7);
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
//Zet de variabelen terug naar hun originele waarden wanneer het spel herstart wordt
@Override
public void stateChanged(ChangeEvent e) {
//Om zeker te zijn dat er een herstart is geweest, dit wordt ook opgeroepen wanneer een ander element in de JList wordt geselecteerd
if (model.getBozels().isEmpty()) {
loper = 1;
powerup = 1;
drawElastiek = true;
repaint();
}
}
//Verwijder eeen bozel
public void destroyBody(Body b) {
model.getBodies().remove(b);
model.getDestroy().push(b);
model.getBozels().remove(loper);
powerup = 1;
}
} |
11651_3 | package oplossing;
public class Ss233Node<E extends Comparable<E>> extends Node<E>{
private Ss233Node<E> leftChild;
private Ss233Node<E> middleChild;
private Ss233Node<E> rightChild;
public Ss233Node(E leftValue, E rightValue) {
super(leftValue, rightValue);
}
public Ss233Node<E> getChild(E o) {
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
return getLeftChild();
}
if (hasRightValue() && rightValue.compareTo(o) < 0) {
return getRightChild();
}
return getMiddleChild();
}
public void setChild(Ss233Node<E> newNode){
E o = newNode.leftValue;
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
setLeftChild(newNode);
} else if (hasRightValue() && rightValue.compareTo(o) < 0) {
setRightChild(newNode);
} else {
setMiddleChild(newNode);
}
}
public void setSplayValue(E value) {
if (leftValue == null) {
leftValue = value;
} else if (rightValue == null) {
rightValue = value;
}
}
/**
* [ A B ] (deze node) [ B ]
* \ -> / \
* [ C ] [ A ] [ C ]
*/
public void redistribute1() {
Ss233Node<E> linker = new Ss233Node<E>(leftValue, null);
linker.setLeftChild(getLeftChild());
linker.setMiddleChild(getMiddleChild());
leftValue = rightValue;
rightValue = null;
setMiddleChild(getRightChild());
setRightChild(null);
setLeftChild(linker);
}
/**
* [ B C ] [ B ]
* / -> / \
* [ A ] [ A ] [ C ]
*/
public void redistribute2() {
Ss233Node<E> rechter = new Ss233Node<>(rightValue, null);
rechter.setLeftChild(getMiddleChild());
rechter.setMiddleChild(getRightChild());
rightValue = null;
setMiddleChild(rechter);
}
/**
* [ A C ] [ B ]
* | -> / \
* [ B ] [ A ] [ C ]
*/
public void redistribute3() {
Ss233Node<E> linker = new Ss233Node<>(leftValue, null);
linker.setLeftChild(getLeftChild());
linker.setMiddleChild(getMiddleChild().getLeftChild());
Ss233Node<E> rechter = new Ss233Node<>(rightValue, null);
rechter.setLeftChild(getMiddleChild().getLeftChild());
rechter.setMiddleChild(getRightChild());
rightValue = null;
setRightChild(null);
leftValue = getMiddleChild().leftValue;
setLeftChild(linker);
setMiddleChild(rechter);
}
/**
* Gegeven een van deze node zijn drie kinderen, zet hem op een andere waarde
* @param child het kind dat een andere node zal worden
* @param to de node waarin child zal veranderen
*/
public void setChildTo(Ss233Node<E> child, Ss233Node<E> to) {
if (getLeftChild() == child) {
setLeftChild(to);
} else if (getMiddleChild() == child) {
setMiddleChild(to);
} else if (getRightChild() == child) {
setRightChild(to);
}
}
/**
* @param e Het element waarvan we willen weten of hij een in order successor heeft
* @return of het element e een in order successor heeft
*/
public boolean hasInOrderSuccessor(E e) {
return (leftValue.compareTo(e) == 0 && getMiddleChild() != null) ||
(hasRightValue() && rightValue.compareTo(e) == 0 && getRightChild() != null);
}
public Ss233Node<E> getLeftChild() {
return leftChild;
}
public void setLeftChild(Ss233Node<E> leftChild) {
this.leftChild = leftChild;
}
public Ss233Node<E> getMiddleChild() {
return middleChild;
}
public void setMiddleChild(Ss233Node<E> middleChild) {
this.middleChild = middleChild;
}
public Ss233Node<E> getRightChild() {
return rightChild;
}
public void setRightChild(Ss233Node<E> rightChild) {
this.rightChild = rightChild;
}
}
| lbarraga/TwoThreeTree | src/oplossing/Ss233Node.java | 1,227 | /**
* Gegeven een van deze node zijn drie kinderen, zet hem op een andere waarde
* @param child het kind dat een andere node zal worden
* @param to de node waarin child zal veranderen
*/ | block_comment | nl | package oplossing;
public class Ss233Node<E extends Comparable<E>> extends Node<E>{
private Ss233Node<E> leftChild;
private Ss233Node<E> middleChild;
private Ss233Node<E> rightChild;
public Ss233Node(E leftValue, E rightValue) {
super(leftValue, rightValue);
}
public Ss233Node<E> getChild(E o) {
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
return getLeftChild();
}
if (hasRightValue() && rightValue.compareTo(o) < 0) {
return getRightChild();
}
return getMiddleChild();
}
public void setChild(Ss233Node<E> newNode){
E o = newNode.leftValue;
if (hasLeftValue() && leftValue.compareTo(o) > 0) {
setLeftChild(newNode);
} else if (hasRightValue() && rightValue.compareTo(o) < 0) {
setRightChild(newNode);
} else {
setMiddleChild(newNode);
}
}
public void setSplayValue(E value) {
if (leftValue == null) {
leftValue = value;
} else if (rightValue == null) {
rightValue = value;
}
}
/**
* [ A B ] (deze node) [ B ]
* \ -> / \
* [ C ] [ A ] [ C ]
*/
public void redistribute1() {
Ss233Node<E> linker = new Ss233Node<E>(leftValue, null);
linker.setLeftChild(getLeftChild());
linker.setMiddleChild(getMiddleChild());
leftValue = rightValue;
rightValue = null;
setMiddleChild(getRightChild());
setRightChild(null);
setLeftChild(linker);
}
/**
* [ B C ] [ B ]
* / -> / \
* [ A ] [ A ] [ C ]
*/
public void redistribute2() {
Ss233Node<E> rechter = new Ss233Node<>(rightValue, null);
rechter.setLeftChild(getMiddleChild());
rechter.setMiddleChild(getRightChild());
rightValue = null;
setMiddleChild(rechter);
}
/**
* [ A C ] [ B ]
* | -> / \
* [ B ] [ A ] [ C ]
*/
public void redistribute3() {
Ss233Node<E> linker = new Ss233Node<>(leftValue, null);
linker.setLeftChild(getLeftChild());
linker.setMiddleChild(getMiddleChild().getLeftChild());
Ss233Node<E> rechter = new Ss233Node<>(rightValue, null);
rechter.setLeftChild(getMiddleChild().getLeftChild());
rechter.setMiddleChild(getRightChild());
rightValue = null;
setRightChild(null);
leftValue = getMiddleChild().leftValue;
setLeftChild(linker);
setMiddleChild(rechter);
}
/**
* Gegeven een van<SUF>*/
public void setChildTo(Ss233Node<E> child, Ss233Node<E> to) {
if (getLeftChild() == child) {
setLeftChild(to);
} else if (getMiddleChild() == child) {
setMiddleChild(to);
} else if (getRightChild() == child) {
setRightChild(to);
}
}
/**
* @param e Het element waarvan we willen weten of hij een in order successor heeft
* @return of het element e een in order successor heeft
*/
public boolean hasInOrderSuccessor(E e) {
return (leftValue.compareTo(e) == 0 && getMiddleChild() != null) ||
(hasRightValue() && rightValue.compareTo(e) == 0 && getRightChild() != null);
}
public Ss233Node<E> getLeftChild() {
return leftChild;
}
public void setLeftChild(Ss233Node<E> leftChild) {
this.leftChild = leftChild;
}
public Ss233Node<E> getMiddleChild() {
return middleChild;
}
public void setMiddleChild(Ss233Node<E> middleChild) {
this.middleChild = middleChild;
}
public Ss233Node<E> getRightChild() {
return rightChild;
}
public void setRightChild(Ss233Node<E> rightChild) {
this.rightChild = rightChild;
}
}
|
11809_0 | package bibliotheek.mensen;
/**
* Representeert een bibliotheekpas.
*/
public class Pas {
public int pasNummer;
public int momenteelUitgeleend = 0;
}
| Eloise-es/java-foundations-exam-prep | 2-Basic-Java-Elements/library-project/bibliotheek/mensen/Pas.java | 51 | /**
* Representeert een bibliotheekpas.
*/ | block_comment | nl | package bibliotheek.mensen;
/**
* Representeert een bibliotheekpas.<SUF>*/
public class Pas {
public int pasNummer;
public int momenteelUitgeleend = 0;
}
|
47952_22 | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import androidx.annotation.StyleRes;
import androidx.annotation.VisibleForTesting;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import org.connectbot.bean.HostBean;
import org.connectbot.data.HostStorage;
import org.connectbot.service.OnHostStatusChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import java.util.List;
public class HostListActivity extends AppCompatListActivity implements OnHostStatusChangedListener {
public final static String TAG = "CB.HostListActivity";
public static final String DISCONNECT_ACTION = "org.connectbot.action.DISCONNECT";
public final static int REQUEST_EDIT = 1;
protected TerminalManager bound = null;
private HostStorage hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private MenuItem disconnectall;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
private boolean waitingForDisconnectAll = false;
/**
* Whether to close the activity when disconnectAll is called. True if this activity was
* only brought to the foreground via the notification button to disconnect all hosts.
*/
private boolean closeOnDisconnectAll = true;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
bound.registerOnHostStatusChangedListener(HostListActivity.this);
if (waitingForDisconnectAll) {
disconnectAll();
}
}
@Override
public void onServiceDisconnected(ComponentName className) {
bound.unregisterOnHostStatusChangedListener(HostListActivity.this);
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
hostdb = HostDatabase.get(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
hostdb = null;
closeOnDisconnectAll = true;
}
@Override
public void onResume() {
super.onResume();
// Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the
// activity open after disconnecting.
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 &&
DISCONNECT_ACTION.equals(getIntent().getAction())) {
Log.d(TAG, "Got disconnect all request");
disconnectAll();
}
// Still close on disconnect if waiting for a disconnect.
closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
setTitle(R.string.title_hosts_list);
mListView = findViewById(R.id.list);
mListView.setHasFixedSize(true);
mListView.setLayoutManager(new LinearLayoutManager(this));
mListView.addItemDecoration(new ListItemDecoration(this));
mEmptyView = findViewById(R.id.empty);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
// detect HTC Dream and apply special preferences
if (Build.MANUFACTURER.equals("HTC") && Build.DEVICE.equals("dream")) {
SharedPreferences.Editor editor = prefs.edit();
boolean doCommit = false;
if (!prefs.contains(PreferenceConstants.SHIFT_FKEYS) &&
!prefs.contains(PreferenceConstants.CTRL_FKEYS)) {
editor.putBoolean(PreferenceConstants.SHIFT_FKEYS, true);
editor.putBoolean(PreferenceConstants.CTRL_FKEYS, true);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.STICKY_MODIFIERS)) {
editor.putString(PreferenceConstants.STICKY_MODIFIERS, PreferenceConstants.YES);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.KEYMODE)) {
editor.putString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
doCommit = true;
}
if (doCommit) {
editor.apply();
}
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = HostDatabase.get(this);
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
this.registerForContextMenu(mListView);
View addHostButtonContainer = findViewById(R.id.add_host_button_container);
addHostButtonContainer.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
FloatingActionButton addHostButton = findViewById(R.id.add_host_button);
addHostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = EditHostActivity.createIntentForNewHost(HostListActivity.this);
startActivityForResult(intent, REQUEST_EDIT);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
disconnectall.setEnabled(bound != null && bound.getBridges().size() > 0);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add(R.string.title_colors);
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
disconnectall = menu.add(R.string.list_menu_disconnect);
disconnectall.setIcon(android.R.drawable.ic_menu_delete);
disconnectall.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
disconnectAll();
return false;
}
});
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
/**
* Disconnects all active connections and closes the activity if appropriate.
*/
private void disconnectAll() {
if (bound == null) {
waitingForDisconnectAll = true;
return;
}
new androidx.appcompat.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.disconnect_all_message))
.setPositiveButton(R.string.disconnect_all_pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
bound.disconnectAll(true, false);
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
if (closeOnDisconnectAll) {
finish();
}
}
})
.setNegativeButton(R.string.disconnect_all_neg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
}
}).create().show();
}
/**
* @return
*/
private boolean startConsoleActivity(Uri uri) {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.apply();
}
if (hostdb == null)
hostdb = HostDatabase.get(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.getBridges()) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
mAdapter = new HostAdapter(this, hosts, bound);
mListView.setAdapter(mAdapter);
adjustViewVisibility();
}
@Override
public void onHostStatusChanged() {
updateList();
}
@VisibleForTesting
public class HostViewHolder extends ItemViewHolder {
public final ImageView icon;
public final TextView nickname;
public final TextView caption;
public HostBean host;
public HostViewHolder(View v) {
super(v);
icon = v.findViewById(android.R.id.icon);
nickname = v.findViewById(android.R.id.text1);
caption = v.findViewById(android.R.id.text2);
}
@Override
public void onClick(View v) {
// launch off to console details
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(
HostListActivity.this, R.mipmap.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
contents.setClass(HostListActivity.this, ConsoleActivity.class);
HostListActivity.this.startActivity(contents);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle(host.getNickname());
// edit, disconnect, delete
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = (bound == null) ? null : bound.getConnectedBridge(host);
connect.setEnabled(bridge != null);
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = EditHostActivity.createIntentForExistingHost(
HostListActivity.this, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new androidx.appcompat.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if (bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
}
@VisibleForTesting
private class HostAdapter extends ItemAdapter {
private final List<HostBean> hosts;
private final TerminalManager manager;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context);
this.hosts = hosts;
this.manager = manager;
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we don't have backend service
if (this.manager == null || host == null) {
return STATE_UNKNOWN;
}
if (manager.getConnectedBridge(host) != null) {
return STATE_CONNECTED;
}
if (manager.disconnected.contains(host)) {
return STATE_DISCONNECTED;
}
return STATE_UNKNOWN;
}
@Override
public HostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_host, parent, false);
HostViewHolder vh = new HostViewHolder(v);
return vh;
}
@TargetApi(16)
private void hideFromAccessibility(View view, boolean hide) {
view.setImportantForAccessibility(hide ?
View.IMPORTANT_FOR_ACCESSIBILITY_NO : View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
HostViewHolder hostHolder = (HostViewHolder) holder;
HostBean host = hosts.get(position);
hostHolder.host = host;
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
hostHolder.nickname.setText("Error during lookup");
} else {
hostHolder.nickname.setText(host.getNickname());
}
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
hostHolder.icon.setImageState(new int[] { }, true);
hostHolder.icon.setContentDescription(null);
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, true);
}
break;
case STATE_CONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
hostHolder.icon.setContentDescription(getString(R.string.image_description_connected));
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, false);
}
break;
case STATE_DISCONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
hostHolder.icon.setContentDescription(getString(R.string.image_description_disconnected));
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, false);
}
break;
default:
Log.e("HostAdapter", "Unknown host state encountered: " + getConnectedState(host));
}
@StyleRes final int chosenStyleFirstLine;
@StyleRes final int chosenStyleSecondLine;
if (HostDatabase.COLOR_RED.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Red;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Red;
} else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Green;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Green;
} else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Blue;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Blue;
} else {
chosenStyleFirstLine = R.style.ListItemFirstLineText;
chosenStyleSecondLine = R.style.ListItemSecondLineText;
}
hostHolder.nickname.setTextAppearance(context, chosenStyleFirstLine);
hostHolder.caption.setTextAppearance(context, chosenStyleSecondLine);
CharSequence nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
nice = DateUtils.getRelativeTimeSpanString(host.getLastConnect() * 1000);
}
hostHolder.caption.setText(nice);
}
@Override
public long getItemId(int position) {
return hosts.get(position).getId();
}
@Override
public int getItemCount() {
return hosts.size();
}
}
}
| connectbot/connectbot | app/src/main/java/org/connectbot/HostListActivity.java | 5,419 | // edit, disconnect, delete | line_comment | nl | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import androidx.annotation.StyleRes;
import androidx.annotation.VisibleForTesting;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import org.connectbot.bean.HostBean;
import org.connectbot.data.HostStorage;
import org.connectbot.service.OnHostStatusChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import java.util.List;
public class HostListActivity extends AppCompatListActivity implements OnHostStatusChangedListener {
public final static String TAG = "CB.HostListActivity";
public static final String DISCONNECT_ACTION = "org.connectbot.action.DISCONNECT";
public final static int REQUEST_EDIT = 1;
protected TerminalManager bound = null;
private HostStorage hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private MenuItem disconnectall;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
private boolean waitingForDisconnectAll = false;
/**
* Whether to close the activity when disconnectAll is called. True if this activity was
* only brought to the foreground via the notification button to disconnect all hosts.
*/
private boolean closeOnDisconnectAll = true;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
bound.registerOnHostStatusChangedListener(HostListActivity.this);
if (waitingForDisconnectAll) {
disconnectAll();
}
}
@Override
public void onServiceDisconnected(ComponentName className) {
bound.unregisterOnHostStatusChangedListener(HostListActivity.this);
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
hostdb = HostDatabase.get(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
hostdb = null;
closeOnDisconnectAll = true;
}
@Override
public void onResume() {
super.onResume();
// Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the
// activity open after disconnecting.
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 &&
DISCONNECT_ACTION.equals(getIntent().getAction())) {
Log.d(TAG, "Got disconnect all request");
disconnectAll();
}
// Still close on disconnect if waiting for a disconnect.
closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
setTitle(R.string.title_hosts_list);
mListView = findViewById(R.id.list);
mListView.setHasFixedSize(true);
mListView.setLayoutManager(new LinearLayoutManager(this));
mListView.addItemDecoration(new ListItemDecoration(this));
mEmptyView = findViewById(R.id.empty);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
// detect HTC Dream and apply special preferences
if (Build.MANUFACTURER.equals("HTC") && Build.DEVICE.equals("dream")) {
SharedPreferences.Editor editor = prefs.edit();
boolean doCommit = false;
if (!prefs.contains(PreferenceConstants.SHIFT_FKEYS) &&
!prefs.contains(PreferenceConstants.CTRL_FKEYS)) {
editor.putBoolean(PreferenceConstants.SHIFT_FKEYS, true);
editor.putBoolean(PreferenceConstants.CTRL_FKEYS, true);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.STICKY_MODIFIERS)) {
editor.putString(PreferenceConstants.STICKY_MODIFIERS, PreferenceConstants.YES);
doCommit = true;
}
if (!prefs.contains(PreferenceConstants.KEYMODE)) {
editor.putString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
doCommit = true;
}
if (doCommit) {
editor.apply();
}
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = HostDatabase.get(this);
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
this.registerForContextMenu(mListView);
View addHostButtonContainer = findViewById(R.id.add_host_button_container);
addHostButtonContainer.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
FloatingActionButton addHostButton = findViewById(R.id.add_host_button);
addHostButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = EditHostActivity.createIntentForNewHost(HostListActivity.this);
startActivityForResult(intent, REQUEST_EDIT);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
disconnectall.setEnabled(bound != null && bound.getBridges().size() > 0);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add(R.string.title_colors);
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
disconnectall = menu.add(R.string.list_menu_disconnect);
disconnectall.setIcon(android.R.drawable.ic_menu_delete);
disconnectall.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
disconnectAll();
return false;
}
});
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
/**
* Disconnects all active connections and closes the activity if appropriate.
*/
private void disconnectAll() {
if (bound == null) {
waitingForDisconnectAll = true;
return;
}
new androidx.appcompat.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.disconnect_all_message))
.setPositiveButton(R.string.disconnect_all_pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
bound.disconnectAll(true, false);
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
if (closeOnDisconnectAll) {
finish();
}
}
})
.setNegativeButton(R.string.disconnect_all_neg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
waitingForDisconnectAll = false;
// Clear the intent so that the activity can be relaunched without closing.
// TODO(jlklein): Find a better way to do this.
setIntent(new Intent());
}
}).create().show();
}
/**
* @return
*/
private boolean startConsoleActivity(Uri uri) {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.apply();
}
if (hostdb == null)
hostdb = HostDatabase.get(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.getBridges()) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
mAdapter = new HostAdapter(this, hosts, bound);
mListView.setAdapter(mAdapter);
adjustViewVisibility();
}
@Override
public void onHostStatusChanged() {
updateList();
}
@VisibleForTesting
public class HostViewHolder extends ItemViewHolder {
public final ImageView icon;
public final TextView nickname;
public final TextView caption;
public HostBean host;
public HostViewHolder(View v) {
super(v);
icon = v.findViewById(android.R.id.icon);
nickname = v.findViewById(android.R.id.text1);
caption = v.findViewById(android.R.id.text2);
}
@Override
public void onClick(View v) {
// launch off to console details
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(
HostListActivity.this, R.mipmap.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
contents.setClass(HostListActivity.this, ConsoleActivity.class);
HostListActivity.this.startActivity(contents);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle(host.getNickname());
// edit, disconnect,<SUF>
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = (bound == null) ? null : bound.getConnectedBridge(host);
connect.setEnabled(bridge != null);
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = EditHostActivity.createIntentForExistingHost(
HostListActivity.this, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new androidx.appcompat.app.AlertDialog.Builder(
HostListActivity.this, R.style.AlertDialogTheme)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if (bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
}
@VisibleForTesting
private class HostAdapter extends ItemAdapter {
private final List<HostBean> hosts;
private final TerminalManager manager;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context);
this.hosts = hosts;
this.manager = manager;
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we don't have backend service
if (this.manager == null || host == null) {
return STATE_UNKNOWN;
}
if (manager.getConnectedBridge(host) != null) {
return STATE_CONNECTED;
}
if (manager.disconnected.contains(host)) {
return STATE_DISCONNECTED;
}
return STATE_UNKNOWN;
}
@Override
public HostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_host, parent, false);
HostViewHolder vh = new HostViewHolder(v);
return vh;
}
@TargetApi(16)
private void hideFromAccessibility(View view, boolean hide) {
view.setImportantForAccessibility(hide ?
View.IMPORTANT_FOR_ACCESSIBILITY_NO : View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
HostViewHolder hostHolder = (HostViewHolder) holder;
HostBean host = hosts.get(position);
hostHolder.host = host;
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
hostHolder.nickname.setText("Error during lookup");
} else {
hostHolder.nickname.setText(host.getNickname());
}
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
hostHolder.icon.setImageState(new int[] { }, true);
hostHolder.icon.setContentDescription(null);
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, true);
}
break;
case STATE_CONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
hostHolder.icon.setContentDescription(getString(R.string.image_description_connected));
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, false);
}
break;
case STATE_DISCONNECTED:
hostHolder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
hostHolder.icon.setContentDescription(getString(R.string.image_description_disconnected));
if (Build.VERSION.SDK_INT >= 16) {
hideFromAccessibility(hostHolder.icon, false);
}
break;
default:
Log.e("HostAdapter", "Unknown host state encountered: " + getConnectedState(host));
}
@StyleRes final int chosenStyleFirstLine;
@StyleRes final int chosenStyleSecondLine;
if (HostDatabase.COLOR_RED.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Red;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Red;
} else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Green;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Green;
} else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) {
chosenStyleFirstLine = R.style.ListItemFirstLineText_Blue;
chosenStyleSecondLine = R.style.ListItemSecondLineText_Blue;
} else {
chosenStyleFirstLine = R.style.ListItemFirstLineText;
chosenStyleSecondLine = R.style.ListItemSecondLineText;
}
hostHolder.nickname.setTextAppearance(context, chosenStyleFirstLine);
hostHolder.caption.setTextAppearance(context, chosenStyleSecondLine);
CharSequence nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
nice = DateUtils.getRelativeTimeSpanString(host.getLastConnect() * 1000);
}
hostHolder.caption.setText(nice);
}
@Override
public long getItemId(int position) {
return hosts.get(position).getId();
}
@Override
public int getItemCount() {
return hosts.size();
}
}
}
|
26812_24 | package org.json;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
*
* @author JSON.org
* @version 2012-10-26
*/
public class XML {
/**
* The Character '&'.
*/
public static final Character AMP = Character.valueOf('&');
/**
* The Character '''.
*/
public static final Character APOS = Character.valueOf('\'');
/**
* The Character '!'.
*/
public static final Character BANG = Character.valueOf('!');
/**
* The Character '='.
*/
public static final Character EQ = Character.valueOf('=');
/**
* The Character '>'.
*/
public static final Character GT = Character.valueOf('>');
/**
* The Character '<'.
*/
public static final Character LT = Character.valueOf('<');
/**
* The Character '?'.
*/
public static final Character QUEST = Character.valueOf('?');
/**
* The Character '"'.
*/
public static final Character QUOT = Character.valueOf('"');
/**
* The Character '/'.
*/
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x The XMLTokener containing the source string.
* @param context The JSONObject that will include the new material.
* @param name The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
JSONObject jsonobject = null;
String string;
String tagName;
Object token;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
token = x.nextToken();
// <!
if (token == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
token = x.nextToken();
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
context.accumulate("content", string);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == LT) {
i += 1;
} else if (token == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (token == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (token == SLASH) {
// Close tag </
token = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag " + token);
}
if (!token.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + token);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
tagName = (String) token;
token = null;
jsonobject = new JSONObject();
for (; ; ) {
if (token == null) {
token = x.nextToken();
}
// attribute = value
if (token instanceof String) {
string = (String) token;
token = x.nextToken();
if (token == EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
jsonobject.accumulate(string,
XML.stringToValue((String) token));
token = null;
} else {
jsonobject.accumulate(string, "");
}
// Empty tag <.../>
} else if (token == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
if (jsonobject.length() > 0) {
context.accumulate(tagName, jsonobject);
} else {
context.accumulate(tagName, "");
}
return false;
// Content, between <...> and </...>
} else if (token == GT) {
for (; ; ) {
token = x.nextContent();
if (token == null) {
if (tagName != null) {
throw x.syntaxError("Unclosed tag " + tagName);
}
return false;
} else if (token instanceof String) {
string = (String) token;
if (string.length() > 0) {
jsonobject.accumulate("content",
XML.stringToValue(string));
}
// Nested element
} else if (token == LT) {
if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) {
context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 &&
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content"));
} else {
context.accumulate(tagName, jsonobject);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points.
*
* @param string A String.
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
if ("".equals(string)) {
return string;
}
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
}
if ("0".equals(string)) {
return Integer.valueOf(0);
}
// If it might be a number, try converting it. If that doesn't work,
// return the string.
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = Long.valueOf(string);
if (myLong.longValue() == myLong.intValue()) {
return Integer.valueOf(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}
return string;
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
* because JSON is a data format and XML is a document format. XML uses
* elements, attributes, and content text, while JSON uses unordered
* collections of name/value pairs and arrays of values. JSON does not
* does not like to distinguish between elements and attributes.
* Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code><[ [ ]]></code> are ignored.
*
* @param string The source string.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, jo, null);
}
return jo;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param object A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object) throws JSONException {
return toString(object, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param object A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, String tagName)
throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
if (object instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
}
// Loop thru the keys.
jo = (JSONObject) object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
value = jo.opt(key);
if (value == null) {
value = "";
}
if (value instanceof String) {
string = (String) value;
} else {
string = null;
}
// Emit content in body
if ("content".equals(key)) {
if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
if (i > 0) {
sb.append('\n');
}
sb.append(escape(ja.get(i).toString()));
}
} else {
sb.append(escape(value.toString()));
}
// Emit an array of similar keys
} else if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
value = ja.get(i);
if (value instanceof JSONArray) {
sb.append('<');
sb.append(key);
sb.append('>');
sb.append(toString(value));
sb.append("</");
sb.append(key);
sb.append('>');
} else {
sb.append(toString(value, key));
}
}
} else if ("".equals(value)) {
sb.append('<');
sb.append(key);
sb.append("/>");
// Emit a new tag <k>
} else {
sb.append(toString(value, key));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
sb.append("</");
sb.append(tagName);
sb.append('>');
}
return sb.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} else {
if (object.getClass().isArray()) {
object = new JSONArray(object);
}
if (object instanceof JSONArray) {
ja = (JSONArray) object;
length = ja.length();
for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}
}
| foobnix/LibreraReader | Builder/src/main/java/org/json/XML.java | 3,981 | // Content, between <...> and </...> | line_comment | nl | package org.json;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
*
* @author JSON.org
* @version 2012-10-26
*/
public class XML {
/**
* The Character '&'.
*/
public static final Character AMP = Character.valueOf('&');
/**
* The Character '''.
*/
public static final Character APOS = Character.valueOf('\'');
/**
* The Character '!'.
*/
public static final Character BANG = Character.valueOf('!');
/**
* The Character '='.
*/
public static final Character EQ = Character.valueOf('=');
/**
* The Character '>'.
*/
public static final Character GT = Character.valueOf('>');
/**
* The Character '<'.
*/
public static final Character LT = Character.valueOf('<');
/**
* The Character '?'.
*/
public static final Character QUEST = Character.valueOf('?');
/**
* The Character '"'.
*/
public static final Character QUOT = Character.valueOf('"');
/**
* The Character '/'.
*/
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x The XMLTokener containing the source string.
* @param context The JSONObject that will include the new material.
* @param name The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
JSONObject jsonobject = null;
String string;
String tagName;
Object token;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
token = x.nextToken();
// <!
if (token == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
token = x.nextToken();
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
context.accumulate("content", string);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == LT) {
i += 1;
} else if (token == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (token == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (token == SLASH) {
// Close tag </
token = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag " + token);
}
if (!token.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + token);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
tagName = (String) token;
token = null;
jsonobject = new JSONObject();
for (; ; ) {
if (token == null) {
token = x.nextToken();
}
// attribute = value
if (token instanceof String) {
string = (String) token;
token = x.nextToken();
if (token == EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
jsonobject.accumulate(string,
XML.stringToValue((String) token));
token = null;
} else {
jsonobject.accumulate(string, "");
}
// Empty tag <.../>
} else if (token == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
if (jsonobject.length() > 0) {
context.accumulate(tagName, jsonobject);
} else {
context.accumulate(tagName, "");
}
return false;
// Content, between<SUF>
} else if (token == GT) {
for (; ; ) {
token = x.nextContent();
if (token == null) {
if (tagName != null) {
throw x.syntaxError("Unclosed tag " + tagName);
}
return false;
} else if (token instanceof String) {
string = (String) token;
if (string.length() > 0) {
jsonobject.accumulate("content",
XML.stringToValue(string));
}
// Nested element
} else if (token == LT) {
if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) {
context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 &&
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content"));
} else {
context.accumulate(tagName, jsonobject);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points.
*
* @param string A String.
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
if ("".equals(string)) {
return string;
}
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
}
if ("0".equals(string)) {
return Integer.valueOf(0);
}
// If it might be a number, try converting it. If that doesn't work,
// return the string.
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = Long.valueOf(string);
if (myLong.longValue() == myLong.intValue()) {
return Integer.valueOf(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}
return string;
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
* because JSON is a data format and XML is a document format. XML uses
* elements, attributes, and content text, while JSON uses unordered
* collections of name/value pairs and arrays of values. JSON does not
* does not like to distinguish between elements and attributes.
* Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code><[ [ ]]></code> are ignored.
*
* @param string The source string.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, jo, null);
}
return jo;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param object A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object) throws JSONException {
return toString(object, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param object A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, String tagName)
throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
if (object instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
}
// Loop thru the keys.
jo = (JSONObject) object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
value = jo.opt(key);
if (value == null) {
value = "";
}
if (value instanceof String) {
string = (String) value;
} else {
string = null;
}
// Emit content in body
if ("content".equals(key)) {
if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
if (i > 0) {
sb.append('\n');
}
sb.append(escape(ja.get(i).toString()));
}
} else {
sb.append(escape(value.toString()));
}
// Emit an array of similar keys
} else if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
value = ja.get(i);
if (value instanceof JSONArray) {
sb.append('<');
sb.append(key);
sb.append('>');
sb.append(toString(value));
sb.append("</");
sb.append(key);
sb.append('>');
} else {
sb.append(toString(value, key));
}
}
} else if ("".equals(value)) {
sb.append('<');
sb.append(key);
sb.append("/>");
// Emit a new tag <k>
} else {
sb.append(toString(value, key));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
sb.append("</");
sb.append(tagName);
sb.append('>');
}
return sb.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} else {
if (object.getClass().isArray()) {
object = new JSONArray(object);
}
if (object instanceof JSONArray) {
ja = (JSONArray) object;
length = ja.length();
for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}
}
|
74155_28 | package edu.arizona.biosemantics.oto.lite.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import edu.arizona.biosemantics.oto.common.io.ExecCommmand;
import edu.arizona.biosemantics.oto.lite.beans.Category;
import edu.arizona.biosemantics.oto.lite.beans.ContextBean;
import edu.arizona.biosemantics.oto.lite.beans.Group;
import edu.arizona.biosemantics.oto.lite.beans.SavedTerm;
import edu.arizona.biosemantics.oto.lite.beans.Term;
import edu.arizona.biosemantics.oto.lite.beans.Upload;
/**
* This class is for all database access pertaining to the Character Marker
*
* @author Partha, Fengqiong
*
*/
public class CategorizationDBAccess extends AbstractDBAccess {
private static final Logger LOGGER = Logger
.getLogger(CategorizationDBAccess.class);
private static CategorizationDBAccess instance;
public static CategorizationDBAccess getInstance() {
if (instance == null) {
instance = new CategorizationDBAccess();
}
return instance;
}
protected CategorizationDBAccess() {
}
/**
* remove the index when the term is a copy
*
* @param term
* @return
*/
private String removeTermIndex(String term) {
Pattern p = Pattern.compile("^(.+)_\\d+$");
Matcher m = p.matcher(term);
if (m.matches()) {
term = m.group(1);
}
return term;
}
/**
* when finish categorization, besides setting the finished flag, also
* populate tables for to_ontology and hierarchy page
*
* @param uploadID
* @return
* @throws SQLException
*/
public boolean finishCategorization(String uploadID) throws SQLException {
boolean rv = false;
Connection conn = null;
Statement stmt = null, stmt_select = null;
ResultSet rset = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt_select = conn.createStatement();
conn.setAutoCommit(false);
String sql = "update uploads set isFinalized = true where uploadID = "
+ uploadID;
stmt.executeUpdate(sql);
// populate to_ontology page: populate table
// [term_category_pair] (term, category, synonyms, uploadID, removed
// = false)
// remove copies index
sql = "select a.term, a.category, b.synonym, "
+ uploadID
+ " as uploadID, false as removed from "
+ "(select term, category from decisions where uploadID = "
+ uploadID
+ " and isMainTerm = true) a "
+ "left join "
+ "(select mainTerm, category, group_concat(synonym) as synonym from synonyms "
+ "where uploadID = " + uploadID + " group by mainTerm) b "
+ "on a.term = b.mainTerm and a.category = b.category";
rset = stmt_select.executeQuery(sql);
while (rset.next()) {
String term = removeTermIndex(rset.getString("term"));
String category = rset.getString("category");
sql = "insert into term_category_pair "
+ "(term, category, synonyms, uploadID, removed) "
+ "values " + "('" + term + "', '" + category + "', '"
+ rset.getString("synonym") + "', " + uploadID
+ ", false)";
stmt.executeUpdate(sql);
// populate table [structures] (uploadID, term, userCreated)
if (category.equals("structure")) {
sql = "insert into structures (uploadID, term, userCreated) values "
+ "(" + uploadID + ", '" + term + "', false)";
stmt.executeUpdate(sql);
}
}
conn.commit();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: finishCategorization "
+ exe);
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e) {
exe.printStackTrace();
LOGGER.error("Exception in rollback in CategorizationDBAccess: "
+ exe);
}
}
} finally {
closeConnection(stmt, conn);
}
return rv;
}
/**
*
* @param category
* @param uploadID
* @return
* @throws SQLException
*/
public boolean deleteCategory(String category, int uploadID)
throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String sql = "delete from categories where category = ? and uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, category);
pstmt.setInt(2, uploadID);
pstmt.executeUpdate();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: deleteCategory "
+ exe);
} finally {
closeConnection(pstmt, conn);
}
return rv;
}
/**
* todo
*
* @param uploadID
* @return
* @throws SQLException
*/
public boolean sentToOTO(int uploadID) throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// get prefix for OTO
// create dataset and all the tables
// validation log in
// insert data: terms, sentences, decisions
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: sentToOTO "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return rv;
}
/**
* fix typo in this upload related tables: typos, terms, decisions, synonyms
*
* @param uploadID
* @param term
* @param replacement
* @return
* @throws SQLException
*/
public boolean fixTypo(int uploadID, String term, String replacement)
throws SQLException {
String uploadID_str = Integer.toString(uploadID);
boolean returnValue = false;
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = getConnection();
stmt = conn.createStatement();
// This has to be a transaction
conn.setAutoCommit(false);
// table: terms
String sql = "update terms set term = '" + replacement
+ "' where term = '" + term + "' and uploadID = "
+ uploadID_str;
stmt.executeUpdate(sql);
ArrayList<String> termCopies = new ArrayList<String>();
sql = "select term from decisions where uploadID = " + uploadID_str
+ " and term rlike '^" + term + "(_(\\d)+)?'";
rset = stmt.executeQuery(sql);
while (rset.next()) {
termCopies.add(rset.getString(1));
}
for (String termCopy : termCopies) {
String replacementCopy = replacement;
if (termCopy.matches("^" + term + "_(\\d)+$")) {
replacementCopy = replacement
+ termCopy.substring(termCopy.lastIndexOf("_"),
termCopy.length());
}
// table: decisions
sql = "update decisions set term = '" + replacementCopy
+ "' where term = '" + termCopy + "' and uploadID = "
+ uploadID_str;
stmt.executeUpdate(sql);
// table synonyms
// mainTerm
sql = "update synonyms set mainTerm = '" + replacementCopy
+ "' where uploadID = " + uploadID_str
+ " and mainTerm = '" + termCopy + "'";
stmt.executeUpdate(sql);
// synonym
sql = "update synonyms set synonym = '" + replacementCopy
+ "' where uploadID = " + uploadID_str
+ " and synonym = '" + termCopy + "'";
stmt.executeUpdate(sql);
}
// table typos
// check if this term is already a replacement of an original term
sql = "select id, originalTerm from typos where uploadID = "
+ uploadID_str + " and replacedBy = '" + term + "'";
rset = stmt.executeQuery(sql);
if (rset.next()) {
if (rset.getString("originalTerm").equals(replacement)) {
// changed back to original state
sql = "delete from typos where id = "
+ rset.getString("id");
} else {
// changed multiple times
sql = "update typos set replacedBy = '" + replacement
+ "' where id = " + rset.getString("id");
}
} else {
sql = "insert into typos (uploadID, originalTerm, replacedBy) "
+ "values (" + uploadID_str + ", '" + term + "', '"
+ replacement + "')";
}
stmt.executeUpdate(sql);
conn.commit();
returnValue = true;
} catch (Exception exe) {
if (conn != null) {
LOGGER.error(
"Couldn't execute fixTypo in CharacterStateDBAccess: ",
exe);
exe.printStackTrace();
try {
conn.rollback();
} catch (SQLException ex1) {
LOGGER.error(
"Couldn't rollback fixTypo in CharacterStateDBAccess: ",
exe);
exe.printStackTrace();
}
}
} finally {
if (rset != null) {
rset.close();
}
closeConnection(stmt, conn);
}
return returnValue;
}
/**
* OTO lite: check if the uploads can be erased, if so delete it condition
* 1: readyToDelete = true condition 2: readyToDelete for 2 days
*
* @return
* @throws SQLException
*/
public boolean cleanUpUploads() throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
String query = "select uploadID from uploads where (not readyToDelete IS NULL) "
+ "and readyToDelete < NOW() - INTERVAL 2 DAY";
pstmt = conn.prepareStatement(query);
rset = pstmt.executeQuery();
while (rset.next()) {
deleteUpload(rset.getInt("uploadID"), conn);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: cleanUpUploads "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return rv;
}
/**
* OTO lite: delete all the data related to this upload
*
* @param uploadID
* @throws SQLException
*/
public boolean deleteUpload(int uploadID, Connection conn)
throws SQLException {
boolean rv = false;
PreparedStatement pstmt = null;
try {
// delete decisions
String sql = "delete from decisions where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete synonyms
sql = "delete from synonyms where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete category
sql = "delete from categories where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete terms
sql = "delete from terms where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete sentences
sql = "delete from sentences where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete uploads
sql = "delete from uploads where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: deleteUpload "
+ exe);
} finally {
if (pstmt != null) {
pstmt.close();
}
}
return rv;
}
/**
* For the OTO lite, get upload info to display on the page
*
* @param uploadID
* @return
* @throws SQLException
*/
public Upload getUploadInfo(int uploadID) throws SQLException {
Upload up = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// get total terms numbers
String query = "select * from uploads where uploadID = ?";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
if (rset.next()) {
up = new Upload(uploadID);
up.setSentToOTO(rset.getBoolean("sentToOTO"));
up.setUploadTime(rset.getString("uploadTime"));
up.setFinalized(rset.getBoolean("isFinalized"));
// get number of terms
query = "select count(*) from terms where uploadID = ?";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
if (rset.next()) {
up.setNumberTerms(rset.getInt(1));
}
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: getUploadInfo "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return up;
}
/**
* OTO lite: get categories to display, make sure structure is the first one
*
* @param uploadID
* @return
* @throws SQLException
*/
public ArrayList<Category> getCategories(int uploadID) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<Category> categoeies = new ArrayList<Category>();
try {
conn = getConnection();
String firstCat = "structure";
String sql = "select category, definition from categories where "
+ " category = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, firstCat);
rset = pstmt.executeQuery();
if (rset.next()) {
Category cat = new Category();
cat.setName(rset.getString("category"));
cat.setDef(rset.getString("definition"));
categoeies.add(cat);
}
// get all the other decisions
sql = "select category, definition, uploadID from categories where (uploadID = ? or uploadID IS NULL"
+ " or uploadID = 0) "
+ "and category <> ? "
+ " order by category";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, firstCat);
rset = pstmt.executeQuery();
while (rset.next()) {
Category cat = new Category();
cat.setName(rset.getString("category"));
cat.setDef(rset.getString("definition"));
if (rset.getInt("uploadID") > 0) {
cat.setUserCreated(true);
}
categoeies.add(cat);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getCategories" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return categoeies;
}
/**
* OTO lite: get types table
*
* @return
* @throws SQLException
*/
public HashMap<Integer, String> getTermTypes() throws SQLException {
HashMap<Integer, String> termTypes = new HashMap<Integer, String>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
String sql = "select typeID, typeName from types";
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while (rset.next()) {
termTypes
.put(rset.getInt("typeID"), rset.getString("typeName"));
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getTermTypes" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return termTypes;
}
/**
* OTO lite: get saved terms for all category
*
* @param uploadID
* @return
* @throws SQLException
*/
public HashMap<String, ArrayList<SavedTerm>> getSavedTerms(int uploadID)
throws SQLException {
HashMap<String, ArrayList<SavedTerm>> catTerms = new HashMap<String, ArrayList<SavedTerm>>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null, synRset = null;
try {
conn = getConnection();
// get all the decisions
String sql = "select category, term, isMainTerm from decisions where uploadID = ? order by category, term";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
String lastCatName = "";
ArrayList<SavedTerm> terms = new ArrayList<SavedTerm>();
SavedTerm st = null;
while (rset.next()) {
// separate categories
String category = rset.getString("category");
if (!lastCatName.equals(category)) {
if (!lastCatName.equals("")) {
catTerms.put(lastCatName, terms);
terms = new ArrayList<SavedTerm>();
}
}
lastCatName = category;
// get each term
st = new SavedTerm();
String termName = rset.getString("term");
st.setTermName(termName);
st.setAdditional(!rset.getBoolean("isMainTerm"));
// check synonyms
if (!st.isAdditional()) {
String synsql = "select mainTerm, synonym from synonyms where "
+ "uploadID = ? and mainTerm = ? and category = ?";
pstmt = conn.prepareStatement(synsql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, termName);
pstmt.setString(3, category);
synRset = pstmt.executeQuery();
ArrayList<String> syns = new ArrayList<String>();
while (synRset.next()) {
st.setHasSyns(true);
syns.add(synRset.getString("synonym"));
}
if (st.isHasSyns()) {
st.setSyns(syns);
}
}
terms.add(st);
}
// last group
if (!lastCatName.equals("")) {
catTerms.put(lastCatName, terms);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getSavedTerms" + exe);
} finally {
if (synRset != null) {
synRset.close();
}
closeConnection(pstmt, rset, conn);
}
return catTerms;
}
/**
* For OTO lite, get available group and terms to display in the left column
* of the page
*
* @param uploadID
* @return
* @throws SQLException
*/
public ArrayList<Group> getGroups(int uploadID) throws SQLException {
ArrayList<Group> groups = new ArrayList<Group>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// terms in terms table, but not in decision table
String sql = "select term, type from terms "
+ "where uploadID = ? and "
+ "term not in (select term from decisions where uploadID = ?) "
+ "order by type, term";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setInt(2, uploadID);
rset = pstmt.executeQuery();
int lastGroupId = -1;
Group group = null;
ArrayList<String> terms = null;
while (rset.next()) {
// separate groups
if (lastGroupId != rset.getInt("type")) {
if (group != null) {
group.setTerms(terms);
groups.add(group);
}
group = new Group();
terms = new ArrayList<String>();
group.setGroupID(rset.getInt("type"));
lastGroupId = group.getGroupID();
}
// get each term
terms.add(rset.getString("term"));
}
// last group
if (group != null) {
group.setTerms(terms);
groups.add(group);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getGroups" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return groups;
}
/**
* get context for OTO lite
*
* @param term
* @param uploadID
* @return
* @throws Exception
*/
public ArrayList<ContextBean> getContextForTerm(String term, int uploadID)
throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<ContextBean> contexts = new ArrayList<ContextBean>();
if (term != null && !term.equals("")) {
try {
conn = getConnection();
String originalTerm = term;
boolean isTypo = false;
// get the original term of the given term
String sql = "select originalTerm from typos where uploadID = ? and replacedBy = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, term);
rset = pstmt.executeQuery();
if (rset.next()) {
originalTerm = rset.getString(1);
isTypo = true;
}
sql = "SELECT source, originalsent "
+ "FROM sentences where uploadID = ? "
+ "and (originalsent rlike '^(.*[^a-zA-Z])?"
+ originalTerm + "([^a-zA-Z].*)?$' "
+ "or sentence rlike '^(.*[^a-zA-Z])?" + originalTerm
+ "([^a-zA-Z].*)?$');";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
while (rset.next()) {
String sent = rset.getString("originalsent");
if (isTypo) {
sent = "(Typo fixed: " + originalTerm + " -> " + term
+ ") " + sent;
}
ContextBean cbean = new ContextBean(
rset.getString("source"), sent);
contexts.add(cbean);
}
} catch (Exception exe) {
LOGGER.error(
"Couldn't execute db query in CharacterStateDBAccess: getContextForTerm",
exe);
exe.printStackTrace();
} finally {
closeConnection(pstmt, rset, conn);
}
}
return contexts;
}
/**
* OTO lite: save decisions
*
* @param categories
* @param uploadID
* @return
* @throws SQLException
*/
public synchronized boolean saveCategorizingDecisions(
ArrayList<Category> categories, int uploadID) throws SQLException {
String uploadID_str = Integer.toString(uploadID);
boolean returnValue = false;
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
// This has to be a transaction
conn.setAutoCommit(false);
for (int i = 0; i < categories.size(); i++) {
Category category = categories.get(i);
ArrayList<Term> terms = category.getChanged_terms();
for (Term term : terms) {
// delete existing decisions (decisions, synonyms)
String delete_sql = "delete from decisions where uploadID = "
+ uploadID_str
+ " and term = '"
+ term.getTerm()
+ "'";
stmt.executeUpdate(delete_sql);
// delete synonyms
delete_sql = "delete from synonyms where uploadID = "
+ uploadID_str + " and mainTerm = '"
+ term.getTerm() + "'";
stmt.executeUpdate(delete_sql);
// insert decisions
if (!category.getName().equals("")) {
String isMainTerm = "true";
if (term.isAdditional()) {
isMainTerm = "false";
}
String insert_sql = "insert into decisions (uploadID, term, category, isMainTerm) values ("
+ uploadID_str
+ ", '"
+ term.getTerm()
+ "', '"
+ category.getName()
+ "', "
+ isMainTerm + ")";
stmt.executeUpdate(insert_sql);
// insert synonyms
if (term.hasSyn()) {
ArrayList<String> syns = term.getSyns();
for (String syn : syns) {
insert_sql = "insert into synonyms (uploadID, mainTerm, synonym, category) "
+ "values ("
+ uploadID_str
+ ", '"
+ term.getTerm()
+ "', '"
+ syn
+ "', '" + category.getName() + "')";
stmt.executeUpdate(insert_sql);
}
}
}
}
}
conn.commit();
returnValue = true;
} catch (Exception exe) {
if (conn != null) {
LOGGER.error(
"Couldn't execute db query in CharacterStateDBAccess: saveCategorizingDecisions: ",
exe);
exe.printStackTrace();
try {
conn.rollback();
} catch (SQLException ex1) {
LOGGER.error(
"Couldn't rollback in CharacterStateDBAccess: saveCategorizingDecisions",
exe);
exe.printStackTrace();
}
}
} finally {
closeConnection(stmt, conn);
}
return returnValue;
}
/**
* for OTO light
*
* @param cats
* @param uploadID
* @return
* @throws SQLException
*/
@SuppressWarnings("finally")
public synchronized boolean addNewCategory(ArrayList<Category> cats,
int uploadID) throws SQLException {
boolean returnValue = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
String query_sql = "select * from categories where category = ? and uploadID = ?"
+ " and definition = ?";
String sql = "insert into categories "
+ "(category, definition, uploadID) values(?, ?, ?)";
for (int i = 0; i < cats.size(); i++) {
Category cat = cats.get(i);
stmt = conn.prepareStatement(query_sql);
stmt.setString(1, cat.getName());
stmt.setInt(2, uploadID);
stmt.setString(3, cat.getDef());
rs = stmt.executeQuery();
if (!rs.next()) {
stmt = conn.prepareStatement(sql);
stmt.setString(1, cat.getName());
stmt.setString(2, cat.getDef());
stmt.setInt(3, uploadID);
stmt.executeUpdate();
}
}
returnValue = true;
} catch (Exception exe) {
LOGGER.error(
"Couldn't insert new category in CharacterStateDBAccess:addNewCategory",
exe);
exe.printStackTrace();
return false;
} finally {
closeConnection(stmt, conn);
return returnValue;
}
}
public void runCommand(String comd) throws Exception {
ExecCommmand ec = new ExecCommmand();
ec.execShellCmd(comd);
}
/**
* run commands
*
* @param commands
* @throws Exception
*/
public void runCommands(ArrayList<String> commands) throws Exception {
for (String cmmd : commands) {
runCommand(cmmd);
}
}
}
| biosemantics/oto | oto-lite/src/main/java/edu/arizona/biosemantics/oto/lite/db/CategorizationDBAccess.java | 7,140 | // get each term | line_comment | nl | package edu.arizona.biosemantics.oto.lite.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import edu.arizona.biosemantics.oto.common.io.ExecCommmand;
import edu.arizona.biosemantics.oto.lite.beans.Category;
import edu.arizona.biosemantics.oto.lite.beans.ContextBean;
import edu.arizona.biosemantics.oto.lite.beans.Group;
import edu.arizona.biosemantics.oto.lite.beans.SavedTerm;
import edu.arizona.biosemantics.oto.lite.beans.Term;
import edu.arizona.biosemantics.oto.lite.beans.Upload;
/**
* This class is for all database access pertaining to the Character Marker
*
* @author Partha, Fengqiong
*
*/
public class CategorizationDBAccess extends AbstractDBAccess {
private static final Logger LOGGER = Logger
.getLogger(CategorizationDBAccess.class);
private static CategorizationDBAccess instance;
public static CategorizationDBAccess getInstance() {
if (instance == null) {
instance = new CategorizationDBAccess();
}
return instance;
}
protected CategorizationDBAccess() {
}
/**
* remove the index when the term is a copy
*
* @param term
* @return
*/
private String removeTermIndex(String term) {
Pattern p = Pattern.compile("^(.+)_\\d+$");
Matcher m = p.matcher(term);
if (m.matches()) {
term = m.group(1);
}
return term;
}
/**
* when finish categorization, besides setting the finished flag, also
* populate tables for to_ontology and hierarchy page
*
* @param uploadID
* @return
* @throws SQLException
*/
public boolean finishCategorization(String uploadID) throws SQLException {
boolean rv = false;
Connection conn = null;
Statement stmt = null, stmt_select = null;
ResultSet rset = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt_select = conn.createStatement();
conn.setAutoCommit(false);
String sql = "update uploads set isFinalized = true where uploadID = "
+ uploadID;
stmt.executeUpdate(sql);
// populate to_ontology page: populate table
// [term_category_pair] (term, category, synonyms, uploadID, removed
// = false)
// remove copies index
sql = "select a.term, a.category, b.synonym, "
+ uploadID
+ " as uploadID, false as removed from "
+ "(select term, category from decisions where uploadID = "
+ uploadID
+ " and isMainTerm = true) a "
+ "left join "
+ "(select mainTerm, category, group_concat(synonym) as synonym from synonyms "
+ "where uploadID = " + uploadID + " group by mainTerm) b "
+ "on a.term = b.mainTerm and a.category = b.category";
rset = stmt_select.executeQuery(sql);
while (rset.next()) {
String term = removeTermIndex(rset.getString("term"));
String category = rset.getString("category");
sql = "insert into term_category_pair "
+ "(term, category, synonyms, uploadID, removed) "
+ "values " + "('" + term + "', '" + category + "', '"
+ rset.getString("synonym") + "', " + uploadID
+ ", false)";
stmt.executeUpdate(sql);
// populate table [structures] (uploadID, term, userCreated)
if (category.equals("structure")) {
sql = "insert into structures (uploadID, term, userCreated) values "
+ "(" + uploadID + ", '" + term + "', false)";
stmt.executeUpdate(sql);
}
}
conn.commit();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: finishCategorization "
+ exe);
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e) {
exe.printStackTrace();
LOGGER.error("Exception in rollback in CategorizationDBAccess: "
+ exe);
}
}
} finally {
closeConnection(stmt, conn);
}
return rv;
}
/**
*
* @param category
* @param uploadID
* @return
* @throws SQLException
*/
public boolean deleteCategory(String category, int uploadID)
throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String sql = "delete from categories where category = ? and uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, category);
pstmt.setInt(2, uploadID);
pstmt.executeUpdate();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: deleteCategory "
+ exe);
} finally {
closeConnection(pstmt, conn);
}
return rv;
}
/**
* todo
*
* @param uploadID
* @return
* @throws SQLException
*/
public boolean sentToOTO(int uploadID) throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// get prefix for OTO
// create dataset and all the tables
// validation log in
// insert data: terms, sentences, decisions
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: sentToOTO "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return rv;
}
/**
* fix typo in this upload related tables: typos, terms, decisions, synonyms
*
* @param uploadID
* @param term
* @param replacement
* @return
* @throws SQLException
*/
public boolean fixTypo(int uploadID, String term, String replacement)
throws SQLException {
String uploadID_str = Integer.toString(uploadID);
boolean returnValue = false;
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = getConnection();
stmt = conn.createStatement();
// This has to be a transaction
conn.setAutoCommit(false);
// table: terms
String sql = "update terms set term = '" + replacement
+ "' where term = '" + term + "' and uploadID = "
+ uploadID_str;
stmt.executeUpdate(sql);
ArrayList<String> termCopies = new ArrayList<String>();
sql = "select term from decisions where uploadID = " + uploadID_str
+ " and term rlike '^" + term + "(_(\\d)+)?'";
rset = stmt.executeQuery(sql);
while (rset.next()) {
termCopies.add(rset.getString(1));
}
for (String termCopy : termCopies) {
String replacementCopy = replacement;
if (termCopy.matches("^" + term + "_(\\d)+$")) {
replacementCopy = replacement
+ termCopy.substring(termCopy.lastIndexOf("_"),
termCopy.length());
}
// table: decisions
sql = "update decisions set term = '" + replacementCopy
+ "' where term = '" + termCopy + "' and uploadID = "
+ uploadID_str;
stmt.executeUpdate(sql);
// table synonyms
// mainTerm
sql = "update synonyms set mainTerm = '" + replacementCopy
+ "' where uploadID = " + uploadID_str
+ " and mainTerm = '" + termCopy + "'";
stmt.executeUpdate(sql);
// synonym
sql = "update synonyms set synonym = '" + replacementCopy
+ "' where uploadID = " + uploadID_str
+ " and synonym = '" + termCopy + "'";
stmt.executeUpdate(sql);
}
// table typos
// check if this term is already a replacement of an original term
sql = "select id, originalTerm from typos where uploadID = "
+ uploadID_str + " and replacedBy = '" + term + "'";
rset = stmt.executeQuery(sql);
if (rset.next()) {
if (rset.getString("originalTerm").equals(replacement)) {
// changed back to original state
sql = "delete from typos where id = "
+ rset.getString("id");
} else {
// changed multiple times
sql = "update typos set replacedBy = '" + replacement
+ "' where id = " + rset.getString("id");
}
} else {
sql = "insert into typos (uploadID, originalTerm, replacedBy) "
+ "values (" + uploadID_str + ", '" + term + "', '"
+ replacement + "')";
}
stmt.executeUpdate(sql);
conn.commit();
returnValue = true;
} catch (Exception exe) {
if (conn != null) {
LOGGER.error(
"Couldn't execute fixTypo in CharacterStateDBAccess: ",
exe);
exe.printStackTrace();
try {
conn.rollback();
} catch (SQLException ex1) {
LOGGER.error(
"Couldn't rollback fixTypo in CharacterStateDBAccess: ",
exe);
exe.printStackTrace();
}
}
} finally {
if (rset != null) {
rset.close();
}
closeConnection(stmt, conn);
}
return returnValue;
}
/**
* OTO lite: check if the uploads can be erased, if so delete it condition
* 1: readyToDelete = true condition 2: readyToDelete for 2 days
*
* @return
* @throws SQLException
*/
public boolean cleanUpUploads() throws SQLException {
boolean rv = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
String query = "select uploadID from uploads where (not readyToDelete IS NULL) "
+ "and readyToDelete < NOW() - INTERVAL 2 DAY";
pstmt = conn.prepareStatement(query);
rset = pstmt.executeQuery();
while (rset.next()) {
deleteUpload(rset.getInt("uploadID"), conn);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: cleanUpUploads "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return rv;
}
/**
* OTO lite: delete all the data related to this upload
*
* @param uploadID
* @throws SQLException
*/
public boolean deleteUpload(int uploadID, Connection conn)
throws SQLException {
boolean rv = false;
PreparedStatement pstmt = null;
try {
// delete decisions
String sql = "delete from decisions where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete synonyms
sql = "delete from synonyms where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete category
sql = "delete from categories where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete terms
sql = "delete from terms where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete sentences
sql = "delete from sentences where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
// delete uploads
sql = "delete from uploads where uploadID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.executeUpdate();
rv = true;
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: deleteUpload "
+ exe);
} finally {
if (pstmt != null) {
pstmt.close();
}
}
return rv;
}
/**
* For the OTO lite, get upload info to display on the page
*
* @param uploadID
* @return
* @throws SQLException
*/
public Upload getUploadInfo(int uploadID) throws SQLException {
Upload up = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// get total terms numbers
String query = "select * from uploads where uploadID = ?";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
if (rset.next()) {
up = new Upload(uploadID);
up.setSentToOTO(rset.getBoolean("sentToOTO"));
up.setUploadTime(rset.getString("uploadTime"));
up.setFinalized(rset.getBoolean("isFinalized"));
// get number of terms
query = "select count(*) from terms where uploadID = ?";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
if (rset.next()) {
up.setNumberTerms(rset.getInt(1));
}
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CategorizationDBAccess: getUploadInfo "
+ exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return up;
}
/**
* OTO lite: get categories to display, make sure structure is the first one
*
* @param uploadID
* @return
* @throws SQLException
*/
public ArrayList<Category> getCategories(int uploadID) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<Category> categoeies = new ArrayList<Category>();
try {
conn = getConnection();
String firstCat = "structure";
String sql = "select category, definition from categories where "
+ " category = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, firstCat);
rset = pstmt.executeQuery();
if (rset.next()) {
Category cat = new Category();
cat.setName(rset.getString("category"));
cat.setDef(rset.getString("definition"));
categoeies.add(cat);
}
// get all the other decisions
sql = "select category, definition, uploadID from categories where (uploadID = ? or uploadID IS NULL"
+ " or uploadID = 0) "
+ "and category <> ? "
+ " order by category";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, firstCat);
rset = pstmt.executeQuery();
while (rset.next()) {
Category cat = new Category();
cat.setName(rset.getString("category"));
cat.setDef(rset.getString("definition"));
if (rset.getInt("uploadID") > 0) {
cat.setUserCreated(true);
}
categoeies.add(cat);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getCategories" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return categoeies;
}
/**
* OTO lite: get types table
*
* @return
* @throws SQLException
*/
public HashMap<Integer, String> getTermTypes() throws SQLException {
HashMap<Integer, String> termTypes = new HashMap<Integer, String>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
String sql = "select typeID, typeName from types";
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while (rset.next()) {
termTypes
.put(rset.getInt("typeID"), rset.getString("typeName"));
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getTermTypes" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return termTypes;
}
/**
* OTO lite: get saved terms for all category
*
* @param uploadID
* @return
* @throws SQLException
*/
public HashMap<String, ArrayList<SavedTerm>> getSavedTerms(int uploadID)
throws SQLException {
HashMap<String, ArrayList<SavedTerm>> catTerms = new HashMap<String, ArrayList<SavedTerm>>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null, synRset = null;
try {
conn = getConnection();
// get all the decisions
String sql = "select category, term, isMainTerm from decisions where uploadID = ? order by category, term";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
String lastCatName = "";
ArrayList<SavedTerm> terms = new ArrayList<SavedTerm>();
SavedTerm st = null;
while (rset.next()) {
// separate categories
String category = rset.getString("category");
if (!lastCatName.equals(category)) {
if (!lastCatName.equals("")) {
catTerms.put(lastCatName, terms);
terms = new ArrayList<SavedTerm>();
}
}
lastCatName = category;
// get each<SUF>
st = new SavedTerm();
String termName = rset.getString("term");
st.setTermName(termName);
st.setAdditional(!rset.getBoolean("isMainTerm"));
// check synonyms
if (!st.isAdditional()) {
String synsql = "select mainTerm, synonym from synonyms where "
+ "uploadID = ? and mainTerm = ? and category = ?";
pstmt = conn.prepareStatement(synsql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, termName);
pstmt.setString(3, category);
synRset = pstmt.executeQuery();
ArrayList<String> syns = new ArrayList<String>();
while (synRset.next()) {
st.setHasSyns(true);
syns.add(synRset.getString("synonym"));
}
if (st.isHasSyns()) {
st.setSyns(syns);
}
}
terms.add(st);
}
// last group
if (!lastCatName.equals("")) {
catTerms.put(lastCatName, terms);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getSavedTerms" + exe);
} finally {
if (synRset != null) {
synRset.close();
}
closeConnection(pstmt, rset, conn);
}
return catTerms;
}
/**
* For OTO lite, get available group and terms to display in the left column
* of the page
*
* @param uploadID
* @return
* @throws SQLException
*/
public ArrayList<Group> getGroups(int uploadID) throws SQLException {
ArrayList<Group> groups = new ArrayList<Group>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
conn = getConnection();
// terms in terms table, but not in decision table
String sql = "select term, type from terms "
+ "where uploadID = ? and "
+ "term not in (select term from decisions where uploadID = ?) "
+ "order by type, term";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setInt(2, uploadID);
rset = pstmt.executeQuery();
int lastGroupId = -1;
Group group = null;
ArrayList<String> terms = null;
while (rset.next()) {
// separate groups
if (lastGroupId != rset.getInt("type")) {
if (group != null) {
group.setTerms(terms);
groups.add(group);
}
group = new Group();
terms = new ArrayList<String>();
group.setGroupID(rset.getInt("type"));
lastGroupId = group.getGroupID();
}
// get each term
terms.add(rset.getString("term"));
}
// last group
if (group != null) {
group.setTerms(terms);
groups.add(group);
}
} catch (SQLException exe) {
exe.printStackTrace();
LOGGER.error("Exception in CharacterDBAccess: getGroups" + exe);
} finally {
closeConnection(pstmt, rset, conn);
}
return groups;
}
/**
* get context for OTO lite
*
* @param term
* @param uploadID
* @return
* @throws Exception
*/
public ArrayList<ContextBean> getContextForTerm(String term, int uploadID)
throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<ContextBean> contexts = new ArrayList<ContextBean>();
if (term != null && !term.equals("")) {
try {
conn = getConnection();
String originalTerm = term;
boolean isTypo = false;
// get the original term of the given term
String sql = "select originalTerm from typos where uploadID = ? and replacedBy = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
pstmt.setString(2, term);
rset = pstmt.executeQuery();
if (rset.next()) {
originalTerm = rset.getString(1);
isTypo = true;
}
sql = "SELECT source, originalsent "
+ "FROM sentences where uploadID = ? "
+ "and (originalsent rlike '^(.*[^a-zA-Z])?"
+ originalTerm + "([^a-zA-Z].*)?$' "
+ "or sentence rlike '^(.*[^a-zA-Z])?" + originalTerm
+ "([^a-zA-Z].*)?$');";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, uploadID);
rset = pstmt.executeQuery();
while (rset.next()) {
String sent = rset.getString("originalsent");
if (isTypo) {
sent = "(Typo fixed: " + originalTerm + " -> " + term
+ ") " + sent;
}
ContextBean cbean = new ContextBean(
rset.getString("source"), sent);
contexts.add(cbean);
}
} catch (Exception exe) {
LOGGER.error(
"Couldn't execute db query in CharacterStateDBAccess: getContextForTerm",
exe);
exe.printStackTrace();
} finally {
closeConnection(pstmt, rset, conn);
}
}
return contexts;
}
/**
* OTO lite: save decisions
*
* @param categories
* @param uploadID
* @return
* @throws SQLException
*/
public synchronized boolean saveCategorizingDecisions(
ArrayList<Category> categories, int uploadID) throws SQLException {
String uploadID_str = Integer.toString(uploadID);
boolean returnValue = false;
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
// This has to be a transaction
conn.setAutoCommit(false);
for (int i = 0; i < categories.size(); i++) {
Category category = categories.get(i);
ArrayList<Term> terms = category.getChanged_terms();
for (Term term : terms) {
// delete existing decisions (decisions, synonyms)
String delete_sql = "delete from decisions where uploadID = "
+ uploadID_str
+ " and term = '"
+ term.getTerm()
+ "'";
stmt.executeUpdate(delete_sql);
// delete synonyms
delete_sql = "delete from synonyms where uploadID = "
+ uploadID_str + " and mainTerm = '"
+ term.getTerm() + "'";
stmt.executeUpdate(delete_sql);
// insert decisions
if (!category.getName().equals("")) {
String isMainTerm = "true";
if (term.isAdditional()) {
isMainTerm = "false";
}
String insert_sql = "insert into decisions (uploadID, term, category, isMainTerm) values ("
+ uploadID_str
+ ", '"
+ term.getTerm()
+ "', '"
+ category.getName()
+ "', "
+ isMainTerm + ")";
stmt.executeUpdate(insert_sql);
// insert synonyms
if (term.hasSyn()) {
ArrayList<String> syns = term.getSyns();
for (String syn : syns) {
insert_sql = "insert into synonyms (uploadID, mainTerm, synonym, category) "
+ "values ("
+ uploadID_str
+ ", '"
+ term.getTerm()
+ "', '"
+ syn
+ "', '" + category.getName() + "')";
stmt.executeUpdate(insert_sql);
}
}
}
}
}
conn.commit();
returnValue = true;
} catch (Exception exe) {
if (conn != null) {
LOGGER.error(
"Couldn't execute db query in CharacterStateDBAccess: saveCategorizingDecisions: ",
exe);
exe.printStackTrace();
try {
conn.rollback();
} catch (SQLException ex1) {
LOGGER.error(
"Couldn't rollback in CharacterStateDBAccess: saveCategorizingDecisions",
exe);
exe.printStackTrace();
}
}
} finally {
closeConnection(stmt, conn);
}
return returnValue;
}
/**
* for OTO light
*
* @param cats
* @param uploadID
* @return
* @throws SQLException
*/
@SuppressWarnings("finally")
public synchronized boolean addNewCategory(ArrayList<Category> cats,
int uploadID) throws SQLException {
boolean returnValue = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
String query_sql = "select * from categories where category = ? and uploadID = ?"
+ " and definition = ?";
String sql = "insert into categories "
+ "(category, definition, uploadID) values(?, ?, ?)";
for (int i = 0; i < cats.size(); i++) {
Category cat = cats.get(i);
stmt = conn.prepareStatement(query_sql);
stmt.setString(1, cat.getName());
stmt.setInt(2, uploadID);
stmt.setString(3, cat.getDef());
rs = stmt.executeQuery();
if (!rs.next()) {
stmt = conn.prepareStatement(sql);
stmt.setString(1, cat.getName());
stmt.setString(2, cat.getDef());
stmt.setInt(3, uploadID);
stmt.executeUpdate();
}
}
returnValue = true;
} catch (Exception exe) {
LOGGER.error(
"Couldn't insert new category in CharacterStateDBAccess:addNewCategory",
exe);
exe.printStackTrace();
return false;
} finally {
closeConnection(stmt, conn);
return returnValue;
}
}
public void runCommand(String comd) throws Exception {
ExecCommmand ec = new ExecCommmand();
ec.execShellCmd(comd);
}
/**
* run commands
*
* @param commands
* @throws Exception
*/
public void runCommands(ArrayList<String> commands) throws Exception {
for (String cmmd : commands) {
runCommand(cmmd);
}
}
}
|
106701_8 |
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(900, 700, 1, false);
this.setBackground("startScreen.jpg");
int[][] map = {{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{28,28,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,7,7,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,14,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,6,6,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,6,6,6,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,28,28},
{6,6,6,6,6,6,28,28,28,28,28,28,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,28,28,6,6,6,7,-1,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,28,28,6,6,6,6,6,6,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,28,28,28,28,7,7,6,6,6,6,6,6,6,6,6,7,28,28,28,28,28,28,28,28,28,-1,-1,28,6,6,6,6,6,6,6,6,6,28,-1,-1,28,28,28,-1,-1,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,5,5,5,5,5,-1,-1,-1,-1,-1,28,6,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,6,6,6,6,6,6,6,6,6,6,28,11,11,28,28,28,11,11,6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,28,28,28,28,28,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
};
// 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, 300, 200);
Music music = new Music();
addObject(music,61,54);
music.getClass();
toevoegen();
// 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();
}
void toevoegen(){
//=========================//
Slime slime2 = new Slime();
addObject(slime2,1249,535);
Slime slime3 = new Slime();
addObject(slime3,3062,352);
Diamant Diamant = new Diamant();
addObject(Diamant,3425,530);
Star star = new Star();
addObject(star,2194,432);
Star star2 = new Star();
addObject(star2,4215,493);
BlauweKarakter karakter = new BlauweKarakter();
addObject(karakter,1760,433);
FlyVijand fly = new FlyVijand();
addObject(fly,2247,306);
Snail snail = new Snail();
addObject(snail,4471,530);
Deur deur2 = new Deur("door_openMid.png");
addObject(deur2,5661,384);
DeurBoven deurBoven = new DeurBoven();
addObject(deurBoven,5661,314);
Fire fire = new Fire();
addObject(fire,4756,493);
Fire fire2 = new Fire();
addObject(fire2,4933,493);
}
@Override
public void act() {
ce.update();
}
/**
* Prepare the world for the start of the program.
* That is: create the initial objects and add them to the world.
*/
private void prepare()
{
DiamantHud diamantHud = new DiamantHud();
addObject(diamantHud,166,92);
AantalSters aantalSters = new AantalSters();
addObject(aantalSters,185,58);
Hud_Ster hud_Ster = new Hud_Ster();
addObject(hud_Ster,146,55);
HartHud hartHud = new HartHud();
addObject(hartHud,59,134);
Hud_Key hud_Key = new Hud_Key();
addObject(hud_Key,58,189);
}
} | ROCMondriaanTIN/project-greenfoot-game-Shiyarjemo | Level2.java | 4,189 | // moet de klasse Mover extenden voor de camera om te werken | 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(900, 700, 1, false);
this.setBackground("startScreen.jpg");
int[][] map = {{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{28,28,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,7,7,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1},
{6,6,6,6,6,6,-1,-1,-1,-1,-1,14,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,6,6,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,6,6,6,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,28,28},
{6,6,6,6,6,6,28,28,28,28,28,28,28,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,28,28,28,28,28,28,6,6,6,7,-1,28,28,28,-1,-1,-1,-1,-1,-1,-1,-1,28,28,6,6,6,6,6,6,28,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,28,28,28,28,7,7,6,6,6,6,6,6,6,6,6,7,28,28,28,28,28,28,28,28,28,-1,-1,28,6,6,6,6,6,6,6,6,6,28,-1,-1,28,28,28,-1,-1,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,5,5,5,5,5,-1,-1,-1,-1,-1,28,6,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,6,6,6,6,6,6,6,6,6,6,28,11,11,28,28,28,11,11,6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,28,28,28,28,28,6,6,6,6,6,6,6,6},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
{6,6,6,6,6,6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10},
};
// 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<SUF>
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, 300, 200);
Music music = new Music();
addObject(music,61,54);
music.getClass();
toevoegen();
// 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();
}
void toevoegen(){
//=========================//
Slime slime2 = new Slime();
addObject(slime2,1249,535);
Slime slime3 = new Slime();
addObject(slime3,3062,352);
Diamant Diamant = new Diamant();
addObject(Diamant,3425,530);
Star star = new Star();
addObject(star,2194,432);
Star star2 = new Star();
addObject(star2,4215,493);
BlauweKarakter karakter = new BlauweKarakter();
addObject(karakter,1760,433);
FlyVijand fly = new FlyVijand();
addObject(fly,2247,306);
Snail snail = new Snail();
addObject(snail,4471,530);
Deur deur2 = new Deur("door_openMid.png");
addObject(deur2,5661,384);
DeurBoven deurBoven = new DeurBoven();
addObject(deurBoven,5661,314);
Fire fire = new Fire();
addObject(fire,4756,493);
Fire fire2 = new Fire();
addObject(fire2,4933,493);
}
@Override
public void act() {
ce.update();
}
/**
* Prepare the world for the start of the program.
* That is: create the initial objects and add them to the world.
*/
private void prepare()
{
DiamantHud diamantHud = new DiamantHud();
addObject(diamantHud,166,92);
AantalSters aantalSters = new AantalSters();
addObject(aantalSters,185,58);
Hud_Ster hud_Ster = new Hud_Ster();
addObject(hud_Ster,146,55);
HartHud hartHud = new HartHud();
addObject(hartHud,59,134);
Hud_Key hud_Key = new Hud_Key();
addObject(hud_Key,58,189);
}
} |
29556_46 | import java.util.Objects;
public class Board { // class to create the board for the game (CLI)
// private final String[][] board; // 2D array waar de board in wordt opgeslagen
private final String[][] board;
// private final int rows; // aantal rijen
private int rows = 0;
// private final int cols; // aantal kolommen
private int cols = 0;
// public Board(int rows, int cols) {
public Board(int rows, int cols) {
this.rows = rows;
this.cols = cols;
board = new String[rows][cols]; // 2D array waar de board in wordt opgeslagen
for (int i = 0; i < rows; i++) { // Loop voor elke rij
for (int j = 0; j < cols; j++) { // Loop voor elke kolom
board[i][j] = " "; // Zet de waardes van de array op een spatie
}
}
}
public String[][] getBoard() {
return board; // Returned het bord
}
public int getRows() {
return rows; // Returned het aantal rijen
}
public int getCols() {
return cols; // Returned het aantal kolommen
}
public void setBoard(int rows, int cols, String piece) {
board[rows][cols] = piece; // Veranderd de waarde van de rows en cols naar de piece
}
// zet de board opnieuw
public void setBoard(int move, String playerIcon) {
int row = move / rows; // berekent de row
int col = move % cols; // berekent de col
board[row][col] = playerIcon; // zet de waarde van de row en col naar de playerIcon
}
public Board Copy() { // Maakt een kopie van het bord en returned een nieuwe instantie
Board copy = new Board(this.rows, this.cols); // Maakt een nieuwe instantie van het bord
for (int i = 0; i < this.rows; i++) { // Loop voor elke rij
for (int j = 0; j < this.cols; j++) { // Loop voor elke kolom
copy.setBoard(i, j, this.board[i][j]); // Zet de waarde van de rij en kolom op de waarde van de rij en kolom van het originele bord
}
}
return copy;
}
// public void printBoard() {
// for (int i = 0; i < cols; i++) {
// System.out.print("----");
// }
// System.out.println("-");
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// System.out.print("| " + board[i][j] + " ");
// }
// System.out.println("|");
// for (int k = 0; k < cols; k++) {
// System.out.print("----");
// }
// System.out.println("-");
// }
// }
public boolean[][] CheckValidMoves(String playerIcon, String gameType) { // Check of de move valid is
boolean[][] validMoves = new boolean[board.length][board[0].length]; // Maakt een 2D array aan met de lengte van het bord
for (int i = 0; i < rows; i++) { // Loop voor elke rij
for (int j = 0; j < cols; j++) { // Loop voor elke kolom
if (gameType == "Reversi") { // Checkt of het spel Reversi is
validMoves[i][j] = CheckValidMoveReversi(i, j, playerIcon); // Checkt of de move valid is
} else if (gameType == "TicTacToe") { // Checkt of het spel TicTacToe is
validMoves[i][j] = CheckValidMoveTicTacToe(i, j, playerIcon); // Checkt of de move valid is
}
}
}
return validMoves; // Returned de 2D array met de valid moves
}
private boolean CheckValidMoveTicTacToe(int row, int col, String playerIcon) { // Checkt of de move valid is voor TicTacToe
return Objects.equals(board[row][col], " "); // Returned of de waarde van de row en col gelijk is aan een spatie
}
private boolean CheckValidMoveReversi(int row, int col, String playerIcon) { // Checkt of de move valid is voor Reversi
boolean validMove = false; // Zet de validMove op false
String opponentIcon = playerIcon == "⚫" ? "⚪" : "⚫"; // Checkt of de playerIcon gelijk is aan een zwarte of witte piece
// Check if the move is valid
if (board[row][col] == " " || board[row][col] == "") { // Checkt of de waarde van de row en col gelijk is aan een spatie
if (row - 1 >= 0 && board[row - 1][col] == opponentIcon) { // Checkt of de row - 1 groter of gelijk is aan 0 en of de waarde van de row - 1 en col gelijk is aan de opponentIcon
for (int i = row - 2; i >= 0; i--) { // Loop voor elke rij vanaf de row - 2
if (board[i][col] == playerIcon) { // Checkt of de waarde van de rij en col gelijk is aan de playerIcon
validMove = true; // Zet de validMove op true
break;
} else if (board[i][col] == " " || board[i][col] == "") { // Checkt of de waarde van de rij en col gelijk is aan een spatie
break;
}
}
}
// Check if the move is valid in the south direction
if (row + 1 < rows && board[row + 1][col] == opponentIcon) { // Checkt of de row + 1 kleiner is dan het aantal rijen en of de waarde van de row + 1 en col gelijk is aan de opponentIcon
for (int i = row + 2; i < rows; i++) { // Loop voor elke rij vanaf de row + 2
if (board[i][col] == playerIcon) { // Checkt of de waarde van de rij en col gelijk is aan de playerIcon
validMove = true; // Zet de validMove op true
break; // Breakt de loop
} else if (board[i][col] == " " || board[i][col] == "") { // Checkt of de waarde van de rij en col gelijk is aan een spatie
break; // Breakt de loop
}
}
}
// Check if the move is valid in the east direction
if (col + 1 < cols && board[row][col + 1] == opponentIcon) {
for (int i = col + 2; i < cols; i++) {
if (board[row][i] == playerIcon) {
validMove = true;
break;
} else if (board[row][i] == " " || board[row][i] == "") {
break;
}
}
}
// Check if the move is valid in the west direction
if (col - 1 >= 0 && board[row][col - 1] == opponentIcon) {
for (int i = col - 2; i >= 0; i--) {
if (board[row][i] == playerIcon) {
validMove = true;
break;
} else if (board[row][i] == " " || board[row][i] == "") {
break;
}
}
}
// Check if the move is valid in the north-east direction
if (row - 1 >= 0 && col + 1 < cols && board[row - 1][col + 1] == opponentIcon) {
for (int i = row - 2, j = col + 2; i >= 0 && j < cols; i--, j++) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the north-west direction
if (row - 1 >= 0 && col - 1 >= 0 && board[row - 1][col - 1] == opponentIcon) {
for (int i = row - 2, j = col - 2; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the south-east direction
if (row + 1 < rows && col + 1 < cols && board[row + 1][col + 1] == opponentIcon) {
for (int i = row + 2, j = col + 2; i < rows && j < cols; i++, j++) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the south-west direction
if (row + 1 < rows && col - 1 >= 0 && board[row + 1][col - 1] == opponentIcon) {
for (int i = row + 2, j = col - 2; i < rows && j >= 0; i++, j--) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
}
return validMove;
}
public boolean IsValidMove(int i, int j, String myPiece) { // Checkt of de move valid is
return CheckValidMoveReversi(i, j, myPiece); // Returned de CheckValidMoveReversi
}
}
| EZ-2B3/ISY | src/Board.java | 2,502 | // Checkt of de waarde van de rij en col gelijk is aan de playerIcon | line_comment | nl | import java.util.Objects;
public class Board { // class to create the board for the game (CLI)
// private final String[][] board; // 2D array waar de board in wordt opgeslagen
private final String[][] board;
// private final int rows; // aantal rijen
private int rows = 0;
// private final int cols; // aantal kolommen
private int cols = 0;
// public Board(int rows, int cols) {
public Board(int rows, int cols) {
this.rows = rows;
this.cols = cols;
board = new String[rows][cols]; // 2D array waar de board in wordt opgeslagen
for (int i = 0; i < rows; i++) { // Loop voor elke rij
for (int j = 0; j < cols; j++) { // Loop voor elke kolom
board[i][j] = " "; // Zet de waardes van de array op een spatie
}
}
}
public String[][] getBoard() {
return board; // Returned het bord
}
public int getRows() {
return rows; // Returned het aantal rijen
}
public int getCols() {
return cols; // Returned het aantal kolommen
}
public void setBoard(int rows, int cols, String piece) {
board[rows][cols] = piece; // Veranderd de waarde van de rows en cols naar de piece
}
// zet de board opnieuw
public void setBoard(int move, String playerIcon) {
int row = move / rows; // berekent de row
int col = move % cols; // berekent de col
board[row][col] = playerIcon; // zet de waarde van de row en col naar de playerIcon
}
public Board Copy() { // Maakt een kopie van het bord en returned een nieuwe instantie
Board copy = new Board(this.rows, this.cols); // Maakt een nieuwe instantie van het bord
for (int i = 0; i < this.rows; i++) { // Loop voor elke rij
for (int j = 0; j < this.cols; j++) { // Loop voor elke kolom
copy.setBoard(i, j, this.board[i][j]); // Zet de waarde van de rij en kolom op de waarde van de rij en kolom van het originele bord
}
}
return copy;
}
// public void printBoard() {
// for (int i = 0; i < cols; i++) {
// System.out.print("----");
// }
// System.out.println("-");
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// System.out.print("| " + board[i][j] + " ");
// }
// System.out.println("|");
// for (int k = 0; k < cols; k++) {
// System.out.print("----");
// }
// System.out.println("-");
// }
// }
public boolean[][] CheckValidMoves(String playerIcon, String gameType) { // Check of de move valid is
boolean[][] validMoves = new boolean[board.length][board[0].length]; // Maakt een 2D array aan met de lengte van het bord
for (int i = 0; i < rows; i++) { // Loop voor elke rij
for (int j = 0; j < cols; j++) { // Loop voor elke kolom
if (gameType == "Reversi") { // Checkt of het spel Reversi is
validMoves[i][j] = CheckValidMoveReversi(i, j, playerIcon); // Checkt of de move valid is
} else if (gameType == "TicTacToe") { // Checkt of het spel TicTacToe is
validMoves[i][j] = CheckValidMoveTicTacToe(i, j, playerIcon); // Checkt of de move valid is
}
}
}
return validMoves; // Returned de 2D array met de valid moves
}
private boolean CheckValidMoveTicTacToe(int row, int col, String playerIcon) { // Checkt of de move valid is voor TicTacToe
return Objects.equals(board[row][col], " "); // Returned of de waarde van de row en col gelijk is aan een spatie
}
private boolean CheckValidMoveReversi(int row, int col, String playerIcon) { // Checkt of de move valid is voor Reversi
boolean validMove = false; // Zet de validMove op false
String opponentIcon = playerIcon == "⚫" ? "⚪" : "⚫"; // Checkt of de playerIcon gelijk is aan een zwarte of witte piece
// Check if the move is valid
if (board[row][col] == " " || board[row][col] == "") { // Checkt of de waarde van de row en col gelijk is aan een spatie
if (row - 1 >= 0 && board[row - 1][col] == opponentIcon) { // Checkt of de row - 1 groter of gelijk is aan 0 en of de waarde van de row - 1 en col gelijk is aan de opponentIcon
for (int i = row - 2; i >= 0; i--) { // Loop voor elke rij vanaf de row - 2
if (board[i][col] == playerIcon) { // Checkt of<SUF>
validMove = true; // Zet de validMove op true
break;
} else if (board[i][col] == " " || board[i][col] == "") { // Checkt of de waarde van de rij en col gelijk is aan een spatie
break;
}
}
}
// Check if the move is valid in the south direction
if (row + 1 < rows && board[row + 1][col] == opponentIcon) { // Checkt of de row + 1 kleiner is dan het aantal rijen en of de waarde van de row + 1 en col gelijk is aan de opponentIcon
for (int i = row + 2; i < rows; i++) { // Loop voor elke rij vanaf de row + 2
if (board[i][col] == playerIcon) { // Checkt of de waarde van de rij en col gelijk is aan de playerIcon
validMove = true; // Zet de validMove op true
break; // Breakt de loop
} else if (board[i][col] == " " || board[i][col] == "") { // Checkt of de waarde van de rij en col gelijk is aan een spatie
break; // Breakt de loop
}
}
}
// Check if the move is valid in the east direction
if (col + 1 < cols && board[row][col + 1] == opponentIcon) {
for (int i = col + 2; i < cols; i++) {
if (board[row][i] == playerIcon) {
validMove = true;
break;
} else if (board[row][i] == " " || board[row][i] == "") {
break;
}
}
}
// Check if the move is valid in the west direction
if (col - 1 >= 0 && board[row][col - 1] == opponentIcon) {
for (int i = col - 2; i >= 0; i--) {
if (board[row][i] == playerIcon) {
validMove = true;
break;
} else if (board[row][i] == " " || board[row][i] == "") {
break;
}
}
}
// Check if the move is valid in the north-east direction
if (row - 1 >= 0 && col + 1 < cols && board[row - 1][col + 1] == opponentIcon) {
for (int i = row - 2, j = col + 2; i >= 0 && j < cols; i--, j++) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the north-west direction
if (row - 1 >= 0 && col - 1 >= 0 && board[row - 1][col - 1] == opponentIcon) {
for (int i = row - 2, j = col - 2; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the south-east direction
if (row + 1 < rows && col + 1 < cols && board[row + 1][col + 1] == opponentIcon) {
for (int i = row + 2, j = col + 2; i < rows && j < cols; i++, j++) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
// Check if the move is valid in the south-west direction
if (row + 1 < rows && col - 1 >= 0 && board[row + 1][col - 1] == opponentIcon) {
for (int i = row + 2, j = col - 2; i < rows && j >= 0; i++, j--) {
if (board[i][j] == playerIcon) {
validMove = true;
break;
} else if (board[i][j] == " " || board[i][j] == "") {
break;
}
}
}
}
return validMove;
}
public boolean IsValidMove(int i, int j, String myPiece) { // Checkt of de move valid is
return CheckValidMoveReversi(i, j, myPiece); // Returned de CheckValidMoveReversi
}
}
|
37577_11 | package cn.hutool.poi.excel;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.poi.excel.cell.CellLocation;
import cn.hutool.poi.excel.cell.CellUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.Closeable;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Excel基础类,用于抽象ExcelWriter和ExcelReader中共用部分的对象和方法
*
* @param <T> 子类类型,用于返回this
* @author looly
* @since 4.1.4
*/
public class ExcelBase<T extends ExcelBase<T>> implements Closeable {
/**
* 是否被关闭
*/
protected boolean isClosed;
/**
* 目标文件,如果用户读取为流或自行创建的Workbook或Sheet,此参数为{@code null}
*/
protected File destFile;
/**
* 工作簿
*/
protected Workbook workbook;
/**
* Excel中对应的Sheet
*/
protected Sheet sheet;
/**
* 标题行别名
*/
protected Map<String, String> headerAlias;
/**
* 构造
*
* @param sheet Excel中的sheet
*/
public ExcelBase(Sheet sheet) {
Assert.notNull(sheet, "No Sheet provided.");
this.sheet = sheet;
this.workbook = sheet.getWorkbook();
}
/**
* 获取Workbook
*
* @return Workbook
*/
public Workbook getWorkbook() {
return this.workbook;
}
/**
* 返回工作簿表格数
*
* @return 工作簿表格数
* @since 4.0.10
*/
public int getSheetCount() {
return this.workbook.getNumberOfSheets();
}
/**
* 获取此工作簿所有Sheet表
*
* @return sheet表列表
* @since 4.0.3
*/
public List<Sheet> getSheets() {
final int totalSheet = getSheetCount();
final List<Sheet> result = new ArrayList<>(totalSheet);
for (int i = 0; i < totalSheet; i++) {
result.add(this.workbook.getSheetAt(i));
}
return result;
}
/**
* 获取表名列表
*
* @return 表名列表
* @since 4.0.3
*/
public List<String> getSheetNames() {
final int totalSheet = workbook.getNumberOfSheets();
List<String> result = new ArrayList<>(totalSheet);
for (int i = 0; i < totalSheet; i++) {
result.add(this.workbook.getSheetAt(i).getSheetName());
}
return result;
}
/**
* 获取当前Sheet
*
* @return {@link Sheet}
*/
public Sheet getSheet() {
return this.sheet;
}
/**
* 重命名当前sheet
*
* @param newName 新名字
* @return this
* @see Workbook#setSheetName(int, String)
* @since 5.7.10
*/
@SuppressWarnings("unchecked")
public T renameSheet(String newName) {
this.workbook.setSheetName(this.workbook.getSheetIndex(this.sheet), newName);
return (T) this;
}
/**
* 自定义需要读取或写出的Sheet,如果给定的sheet不存在,创建之。<br>
* 在读取中,此方法用于切换读取的sheet,在写出时,此方法用于新建或者切换sheet。
*
* @param sheetName sheet名
* @return this
* @since 4.0.10
*/
public T setSheet(String sheetName) {
return setSheet(WorkbookUtil.getOrCreateSheet(this.workbook, sheetName));
}
/**
* 自定义需要读取或写出的Sheet,如果给定的sheet不存在,创建之(命名为默认)<br>
* 在读取中,此方法用于切换读取的sheet,在写出时,此方法用于新建或者切换sheet
*
* @param sheetIndex sheet序号,从0开始计数
* @return this
* @since 4.0.10
*/
public T setSheet(int sheetIndex) {
return setSheet(WorkbookUtil.getOrCreateSheet(this.workbook, sheetIndex));
}
/**
* 设置自定义Sheet
*
* @param sheet 自定义sheet,可以通过{@link WorkbookUtil#getOrCreateSheet(Workbook, String)} 创建
* @return this
* @since 5.2.1
*/
@SuppressWarnings("unchecked")
public T setSheet(Sheet sheet) {
this.sheet = sheet;
return (T) this;
}
/**
* 复制当前sheet为新sheet
*
* @param sheetIndex sheet位置
* @param newSheetName 新sheet名
* @param setAsCurrentSheet 是否切换为当前sheet
* @return this
* @since 5.7.10
*/
public T cloneSheet(int sheetIndex, String newSheetName, boolean setAsCurrentSheet) {
Sheet sheet;
if (this.workbook instanceof XSSFWorkbook) {
XSSFWorkbook workbook = (XSSFWorkbook) this.workbook;
sheet = workbook.cloneSheet(sheetIndex, newSheetName);
} else {
sheet = this.workbook.cloneSheet(sheetIndex);
// issue#I8QIBB,clone后的sheet的index应该重新获取
this.workbook.setSheetName(workbook.getSheetIndex(sheet), newSheetName);
}
if (setAsCurrentSheet) {
this.sheet = sheet;
}
//noinspection unchecked
return (T) this;
}
/**
* 获取指定坐标单元格,单元格不存在时返回{@code null}
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getCell(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getCell(cellLocation.getX(), cellLocation.getY());
}
/**
* 获取指定坐标单元格,单元格不存在时返回{@code null}
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link Cell}
* @since 4.0.5
*/
public Cell getCell(int x, int y) {
return getCell(x, y, false);
}
/**
* 获取或创建指定坐标单元格
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getOrCreateCell(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getOrCreateCell(cellLocation.getX(), cellLocation.getY());
}
/**
* 获取或创建指定坐标单元格
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link Cell}
* @since 4.0.6
*/
public Cell getOrCreateCell(int x, int y) {
return getCell(x, y, true);
}
/**
* 获取指定坐标单元格,如果isCreateIfNotExist为false,则在单元格不存在时返回{@code null}
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @param isCreateIfNotExist 单元格不存在时是否创建
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getCell(String locationRef, boolean isCreateIfNotExist) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getCell(cellLocation.getX(), cellLocation.getY(), isCreateIfNotExist);
}
/**
* 获取指定坐标单元格,如果isCreateIfNotExist为false,则在单元格不存在时返回{@code null}
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @param isCreateIfNotExist 单元格不存在时是否创建
* @return {@link Cell}
* @since 4.0.6
*/
public Cell getCell(int x, int y, boolean isCreateIfNotExist) {
final Row row = isCreateIfNotExist ? RowUtil.getOrCreateRow(this.sheet, y) : this.sheet.getRow(y);
if (null != row) {
return isCreateIfNotExist ? CellUtil.getOrCreateCell(row, x) : row.getCell(x);
}
return null;
}
/**
* 获取或者创建行
*
* @param y Y坐标,从0计数,即行号
* @return {@link Row}
* @since 4.1.4
*/
public Row getOrCreateRow(int y) {
return RowUtil.getOrCreateRow(this.sheet, y);
}
/**
* 为指定单元格获取或者创建样式,返回样式后可以设置样式内容
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link CellStyle}
* @since 5.1.4
*/
public CellStyle getOrCreateCellStyle(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getOrCreateCellStyle(cellLocation.getX(), cellLocation.getY());
}
/**
* 为指定单元格获取或者创建样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateCellStyle(int x, int y) {
final CellStyle cellStyle = getOrCreateCell(x, y).getCellStyle();
return StyleUtil.isNullOrDefaultStyle(this.workbook, cellStyle) ? createCellStyle(x, y) : cellStyle;
}
/**
* 为指定单元格创建样式,返回样式后可以设置样式内容
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link CellStyle}
* @since 5.1.4
*/
public CellStyle createCellStyle(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return createCellStyle(cellLocation.getX(), cellLocation.getY());
}
/**
* 为指定单元格创建样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createCellStyle(int x, int y) {
final Cell cell = getOrCreateCell(x, y);
final CellStyle cellStyle = this.workbook.createCellStyle();
cell.setCellStyle(cellStyle);
return cellStyle;
}
/**
* 创建单元格样式
*
* @return {@link CellStyle}
* @see Workbook#createCellStyle()
* @since 5.4.0
*/
public CellStyle createCellStyle() {
return StyleUtil.createCellStyle(this.workbook);
}
/**
* 获取或创建某一行的样式,返回样式后可以设置样式内容<br>
* 需要注意,此方法返回行样式,设置背景色在单元格设置值后会被覆盖,需要单独设置其单元格的样式。
*
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateRowStyle(int y) {
CellStyle rowStyle = getOrCreateRow(y).getRowStyle();
return StyleUtil.isNullOrDefaultStyle(this.workbook, rowStyle) ? createRowStyle(y) : rowStyle;
}
/**
* 创建某一行的样式,返回样式后可以设置样式内容
*
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createRowStyle(int y) {
final CellStyle rowStyle = this.workbook.createCellStyle();
getOrCreateRow(y).setRowStyle(rowStyle);
return rowStyle;
}
/**
* 获取或创建某一列的样式,返回样式后可以设置样式内容<br>
* 需要注意,此方法返回行样式,设置背景色在单元格设置值后会被覆盖,需要单独设置其单元格的样式。
*
* @param x X坐标,从0计数,即列号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateColumnStyle(int x) {
final CellStyle columnStyle = this.sheet.getColumnStyle(x);
return StyleUtil.isNullOrDefaultStyle(this.workbook, columnStyle) ? createColumnStyle(x) : columnStyle;
}
/**
* 创建某一列的样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createColumnStyle(int x) {
final CellStyle columnStyle = this.workbook.createCellStyle();
this.sheet.setDefaultColumnStyle(x, columnStyle);
return columnStyle;
}
/**
* 创建 {@link Hyperlink},默认内容(标签为链接地址本身)
* @param type 链接类型
* @param address 链接地址
* @return 链接
* @since 5.7.13
*/
public Hyperlink createHyperlink(HyperlinkType type, String address){
return createHyperlink(type, address, address);
}
/**
* 创建 {@link Hyperlink},默认内容
* @param type 链接类型
* @param address 链接地址
* @param label 标签,即单元格中显示的内容
* @return 链接
* @since 5.7.13
*/
public Hyperlink createHyperlink(HyperlinkType type, String address, String label){
final Hyperlink hyperlink = this.workbook.getCreationHelper().createHyperlink(type);
hyperlink.setAddress(address);
hyperlink.setLabel(label);
return hyperlink;
}
/**
* 获取总行数,计算方法为:
*
* <pre>
* 最后一行序号 + 1
* </pre>
*
* @return 行数
* @since 4.5.4
*/
public int getRowCount() {
return this.sheet.getLastRowNum() + 1;
}
/**
* 获取有记录的行数,计算方法为:
*
* <pre>
* 最后一行序号 - 第一行序号 + 1
* </pre>
*
* @return 行数
* @since 4.5.4
*/
public int getPhysicalRowCount() {
return this.sheet.getPhysicalNumberOfRows();
}
/**
* 获取第一行总列数,计算方法为:
*
* <pre>
* 最后一列序号 + 1
* </pre>
*
* @return 列数
*/
public int getColumnCount() {
return getColumnCount(0);
}
/**
* 获取总列数,计算方法为:
*
* <pre>
* 最后一列序号 + 1
* </pre>
*
* @param rowNum 行号
* @return 列数,-1表示获取失败
*/
public int getColumnCount(int rowNum) {
final Row row = this.sheet.getRow(rowNum);
if (null != row) {
// getLastCellNum方法返回序号+1的值
return row.getLastCellNum();
}
return -1;
}
/**
* 判断是否为xlsx格式的Excel表(Excel07格式)
*
* @return 是否为xlsx格式的Excel表(Excel07格式)
* @since 4.6.2
*/
public boolean isXlsx() {
return this.sheet instanceof XSSFSheet || this.sheet instanceof SXSSFSheet;
}
/**
* 关闭工作簿<br>
* 如果用户设定了目标文件,先写出目标文件后给关闭工作簿
*/
@Override
public void close() {
IoUtil.close(this.workbook);
this.sheet = null;
this.workbook = null;
this.isClosed = true;
}
/**
* 获得标题行的别名Map
*
* @return 别名Map
*/
public Map<String, String> getHeaderAlias() {
return headerAlias;
}
/**
* 设置标题行的别名Map
*
* @param headerAlias 别名Map
* @return this
*/
public T setHeaderAlias(Map<String, String> headerAlias) {
this.headerAlias = headerAlias;
//noinspection unchecked
return (T) this;
}
/**
* 增加标题别名
*
* @param header 标题
* @param alias 别名
* @return this
*/
public T addHeaderAlias(String header, String alias) {
Map<String, String> headerAlias = this.headerAlias;
if (null == headerAlias) {
headerAlias = new LinkedHashMap<>();
}
this.headerAlias = headerAlias;
this.headerAlias.put(header, alias);
//noinspection unchecked
return (T) this;
}
/**
* 去除标题别名
*
* @param header 标题
* @return this
*/
public T removeHeaderAlias(String header) {
this.headerAlias.remove(header);
//noinspection unchecked
return (T) this;
}
/**
* 清空标题别名,key为Map中的key,value为别名
*
* @return this
*/
public T clearHeaderAlias() {
this.headerAlias = null;
//noinspection unchecked
return (T) this;
}
}
| dromara/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelBase.java | 4,839 | /**
* 获取当前Sheet
*
* @return {@link Sheet}
*/ | block_comment | nl | package cn.hutool.poi.excel;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.poi.excel.cell.CellLocation;
import cn.hutool.poi.excel.cell.CellUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.Closeable;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Excel基础类,用于抽象ExcelWriter和ExcelReader中共用部分的对象和方法
*
* @param <T> 子类类型,用于返回this
* @author looly
* @since 4.1.4
*/
public class ExcelBase<T extends ExcelBase<T>> implements Closeable {
/**
* 是否被关闭
*/
protected boolean isClosed;
/**
* 目标文件,如果用户读取为流或自行创建的Workbook或Sheet,此参数为{@code null}
*/
protected File destFile;
/**
* 工作簿
*/
protected Workbook workbook;
/**
* Excel中对应的Sheet
*/
protected Sheet sheet;
/**
* 标题行别名
*/
protected Map<String, String> headerAlias;
/**
* 构造
*
* @param sheet Excel中的sheet
*/
public ExcelBase(Sheet sheet) {
Assert.notNull(sheet, "No Sheet provided.");
this.sheet = sheet;
this.workbook = sheet.getWorkbook();
}
/**
* 获取Workbook
*
* @return Workbook
*/
public Workbook getWorkbook() {
return this.workbook;
}
/**
* 返回工作簿表格数
*
* @return 工作簿表格数
* @since 4.0.10
*/
public int getSheetCount() {
return this.workbook.getNumberOfSheets();
}
/**
* 获取此工作簿所有Sheet表
*
* @return sheet表列表
* @since 4.0.3
*/
public List<Sheet> getSheets() {
final int totalSheet = getSheetCount();
final List<Sheet> result = new ArrayList<>(totalSheet);
for (int i = 0; i < totalSheet; i++) {
result.add(this.workbook.getSheetAt(i));
}
return result;
}
/**
* 获取表名列表
*
* @return 表名列表
* @since 4.0.3
*/
public List<String> getSheetNames() {
final int totalSheet = workbook.getNumberOfSheets();
List<String> result = new ArrayList<>(totalSheet);
for (int i = 0; i < totalSheet; i++) {
result.add(this.workbook.getSheetAt(i).getSheetName());
}
return result;
}
/**
* 获取当前Sheet
<SUF>*/
public Sheet getSheet() {
return this.sheet;
}
/**
* 重命名当前sheet
*
* @param newName 新名字
* @return this
* @see Workbook#setSheetName(int, String)
* @since 5.7.10
*/
@SuppressWarnings("unchecked")
public T renameSheet(String newName) {
this.workbook.setSheetName(this.workbook.getSheetIndex(this.sheet), newName);
return (T) this;
}
/**
* 自定义需要读取或写出的Sheet,如果给定的sheet不存在,创建之。<br>
* 在读取中,此方法用于切换读取的sheet,在写出时,此方法用于新建或者切换sheet。
*
* @param sheetName sheet名
* @return this
* @since 4.0.10
*/
public T setSheet(String sheetName) {
return setSheet(WorkbookUtil.getOrCreateSheet(this.workbook, sheetName));
}
/**
* 自定义需要读取或写出的Sheet,如果给定的sheet不存在,创建之(命名为默认)<br>
* 在读取中,此方法用于切换读取的sheet,在写出时,此方法用于新建或者切换sheet
*
* @param sheetIndex sheet序号,从0开始计数
* @return this
* @since 4.0.10
*/
public T setSheet(int sheetIndex) {
return setSheet(WorkbookUtil.getOrCreateSheet(this.workbook, sheetIndex));
}
/**
* 设置自定义Sheet
*
* @param sheet 自定义sheet,可以通过{@link WorkbookUtil#getOrCreateSheet(Workbook, String)} 创建
* @return this
* @since 5.2.1
*/
@SuppressWarnings("unchecked")
public T setSheet(Sheet sheet) {
this.sheet = sheet;
return (T) this;
}
/**
* 复制当前sheet为新sheet
*
* @param sheetIndex sheet位置
* @param newSheetName 新sheet名
* @param setAsCurrentSheet 是否切换为当前sheet
* @return this
* @since 5.7.10
*/
public T cloneSheet(int sheetIndex, String newSheetName, boolean setAsCurrentSheet) {
Sheet sheet;
if (this.workbook instanceof XSSFWorkbook) {
XSSFWorkbook workbook = (XSSFWorkbook) this.workbook;
sheet = workbook.cloneSheet(sheetIndex, newSheetName);
} else {
sheet = this.workbook.cloneSheet(sheetIndex);
// issue#I8QIBB,clone后的sheet的index应该重新获取
this.workbook.setSheetName(workbook.getSheetIndex(sheet), newSheetName);
}
if (setAsCurrentSheet) {
this.sheet = sheet;
}
//noinspection unchecked
return (T) this;
}
/**
* 获取指定坐标单元格,单元格不存在时返回{@code null}
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getCell(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getCell(cellLocation.getX(), cellLocation.getY());
}
/**
* 获取指定坐标单元格,单元格不存在时返回{@code null}
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link Cell}
* @since 4.0.5
*/
public Cell getCell(int x, int y) {
return getCell(x, y, false);
}
/**
* 获取或创建指定坐标单元格
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getOrCreateCell(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getOrCreateCell(cellLocation.getX(), cellLocation.getY());
}
/**
* 获取或创建指定坐标单元格
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link Cell}
* @since 4.0.6
*/
public Cell getOrCreateCell(int x, int y) {
return getCell(x, y, true);
}
/**
* 获取指定坐标单元格,如果isCreateIfNotExist为false,则在单元格不存在时返回{@code null}
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @param isCreateIfNotExist 单元格不存在时是否创建
* @return {@link Cell}
* @since 5.1.4
*/
public Cell getCell(String locationRef, boolean isCreateIfNotExist) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getCell(cellLocation.getX(), cellLocation.getY(), isCreateIfNotExist);
}
/**
* 获取指定坐标单元格,如果isCreateIfNotExist为false,则在单元格不存在时返回{@code null}
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @param isCreateIfNotExist 单元格不存在时是否创建
* @return {@link Cell}
* @since 4.0.6
*/
public Cell getCell(int x, int y, boolean isCreateIfNotExist) {
final Row row = isCreateIfNotExist ? RowUtil.getOrCreateRow(this.sheet, y) : this.sheet.getRow(y);
if (null != row) {
return isCreateIfNotExist ? CellUtil.getOrCreateCell(row, x) : row.getCell(x);
}
return null;
}
/**
* 获取或者创建行
*
* @param y Y坐标,从0计数,即行号
* @return {@link Row}
* @since 4.1.4
*/
public Row getOrCreateRow(int y) {
return RowUtil.getOrCreateRow(this.sheet, y);
}
/**
* 为指定单元格获取或者创建样式,返回样式后可以设置样式内容
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link CellStyle}
* @since 5.1.4
*/
public CellStyle getOrCreateCellStyle(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return getOrCreateCellStyle(cellLocation.getX(), cellLocation.getY());
}
/**
* 为指定单元格获取或者创建样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateCellStyle(int x, int y) {
final CellStyle cellStyle = getOrCreateCell(x, y).getCellStyle();
return StyleUtil.isNullOrDefaultStyle(this.workbook, cellStyle) ? createCellStyle(x, y) : cellStyle;
}
/**
* 为指定单元格创建样式,返回样式后可以设置样式内容
*
* @param locationRef 单元格地址标识符,例如A11,B5
* @return {@link CellStyle}
* @since 5.1.4
*/
public CellStyle createCellStyle(String locationRef) {
final CellLocation cellLocation = ExcelUtil.toLocation(locationRef);
return createCellStyle(cellLocation.getX(), cellLocation.getY());
}
/**
* 为指定单元格创建样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createCellStyle(int x, int y) {
final Cell cell = getOrCreateCell(x, y);
final CellStyle cellStyle = this.workbook.createCellStyle();
cell.setCellStyle(cellStyle);
return cellStyle;
}
/**
* 创建单元格样式
*
* @return {@link CellStyle}
* @see Workbook#createCellStyle()
* @since 5.4.0
*/
public CellStyle createCellStyle() {
return StyleUtil.createCellStyle(this.workbook);
}
/**
* 获取或创建某一行的样式,返回样式后可以设置样式内容<br>
* 需要注意,此方法返回行样式,设置背景色在单元格设置值后会被覆盖,需要单独设置其单元格的样式。
*
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateRowStyle(int y) {
CellStyle rowStyle = getOrCreateRow(y).getRowStyle();
return StyleUtil.isNullOrDefaultStyle(this.workbook, rowStyle) ? createRowStyle(y) : rowStyle;
}
/**
* 创建某一行的样式,返回样式后可以设置样式内容
*
* @param y Y坐标,从0计数,即行号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createRowStyle(int y) {
final CellStyle rowStyle = this.workbook.createCellStyle();
getOrCreateRow(y).setRowStyle(rowStyle);
return rowStyle;
}
/**
* 获取或创建某一列的样式,返回样式后可以设置样式内容<br>
* 需要注意,此方法返回行样式,设置背景色在单元格设置值后会被覆盖,需要单独设置其单元格的样式。
*
* @param x X坐标,从0计数,即列号
* @return {@link CellStyle}
* @since 4.1.4
*/
public CellStyle getOrCreateColumnStyle(int x) {
final CellStyle columnStyle = this.sheet.getColumnStyle(x);
return StyleUtil.isNullOrDefaultStyle(this.workbook, columnStyle) ? createColumnStyle(x) : columnStyle;
}
/**
* 创建某一列的样式,返回样式后可以设置样式内容
*
* @param x X坐标,从0计数,即列号
* @return {@link CellStyle}
* @since 4.6.3
*/
public CellStyle createColumnStyle(int x) {
final CellStyle columnStyle = this.workbook.createCellStyle();
this.sheet.setDefaultColumnStyle(x, columnStyle);
return columnStyle;
}
/**
* 创建 {@link Hyperlink},默认内容(标签为链接地址本身)
* @param type 链接类型
* @param address 链接地址
* @return 链接
* @since 5.7.13
*/
public Hyperlink createHyperlink(HyperlinkType type, String address){
return createHyperlink(type, address, address);
}
/**
* 创建 {@link Hyperlink},默认内容
* @param type 链接类型
* @param address 链接地址
* @param label 标签,即单元格中显示的内容
* @return 链接
* @since 5.7.13
*/
public Hyperlink createHyperlink(HyperlinkType type, String address, String label){
final Hyperlink hyperlink = this.workbook.getCreationHelper().createHyperlink(type);
hyperlink.setAddress(address);
hyperlink.setLabel(label);
return hyperlink;
}
/**
* 获取总行数,计算方法为:
*
* <pre>
* 最后一行序号 + 1
* </pre>
*
* @return 行数
* @since 4.5.4
*/
public int getRowCount() {
return this.sheet.getLastRowNum() + 1;
}
/**
* 获取有记录的行数,计算方法为:
*
* <pre>
* 最后一行序号 - 第一行序号 + 1
* </pre>
*
* @return 行数
* @since 4.5.4
*/
public int getPhysicalRowCount() {
return this.sheet.getPhysicalNumberOfRows();
}
/**
* 获取第一行总列数,计算方法为:
*
* <pre>
* 最后一列序号 + 1
* </pre>
*
* @return 列数
*/
public int getColumnCount() {
return getColumnCount(0);
}
/**
* 获取总列数,计算方法为:
*
* <pre>
* 最后一列序号 + 1
* </pre>
*
* @param rowNum 行号
* @return 列数,-1表示获取失败
*/
public int getColumnCount(int rowNum) {
final Row row = this.sheet.getRow(rowNum);
if (null != row) {
// getLastCellNum方法返回序号+1的值
return row.getLastCellNum();
}
return -1;
}
/**
* 判断是否为xlsx格式的Excel表(Excel07格式)
*
* @return 是否为xlsx格式的Excel表(Excel07格式)
* @since 4.6.2
*/
public boolean isXlsx() {
return this.sheet instanceof XSSFSheet || this.sheet instanceof SXSSFSheet;
}
/**
* 关闭工作簿<br>
* 如果用户设定了目标文件,先写出目标文件后给关闭工作簿
*/
@Override
public void close() {
IoUtil.close(this.workbook);
this.sheet = null;
this.workbook = null;
this.isClosed = true;
}
/**
* 获得标题行的别名Map
*
* @return 别名Map
*/
public Map<String, String> getHeaderAlias() {
return headerAlias;
}
/**
* 设置标题行的别名Map
*
* @param headerAlias 别名Map
* @return this
*/
public T setHeaderAlias(Map<String, String> headerAlias) {
this.headerAlias = headerAlias;
//noinspection unchecked
return (T) this;
}
/**
* 增加标题别名
*
* @param header 标题
* @param alias 别名
* @return this
*/
public T addHeaderAlias(String header, String alias) {
Map<String, String> headerAlias = this.headerAlias;
if (null == headerAlias) {
headerAlias = new LinkedHashMap<>();
}
this.headerAlias = headerAlias;
this.headerAlias.put(header, alias);
//noinspection unchecked
return (T) this;
}
/**
* 去除标题别名
*
* @param header 标题
* @return this
*/
public T removeHeaderAlias(String header) {
this.headerAlias.remove(header);
//noinspection unchecked
return (T) this;
}
/**
* 清空标题别名,key为Map中的key,value为别名
*
* @return this
*/
public T clearHeaderAlias() {
this.headerAlias = null;
//noinspection unchecked
return (T) this;
}
}
|
49980_8 | package domain;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Range;
@Getter @Setter
public class Price {
//private Integer percentIncrease;
//+ getter en setter
//drie @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//moet minstens 1 zijn - foutboodschap overschrijven (met sleutel)
//hoogtens 50 - foutboodschap wordt overschreven (zonder sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Min(value = 1, message = "{price.percentIncrease.Min.message}")
@Max(50)
private Integer percentIncrease;
//private Integer percentDecrease;
//twee @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//het moet liggen tussen 1 en 25 - foutboodschap overschrijven (met sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Range(min = 1, max = 25, message = "{price.percentDecrease.Range.message}")
private Integer percentDecrease;
}
| JasperLefever/EWDJOef | Spring_Boot_i18n_ProductStart/src/main/java/domain/Price.java | 335 | //het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel) | line_comment | nl | package domain;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Range;
@Getter @Setter
public class Price {
//private Integer percentIncrease;
//+ getter en setter
//drie @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//moet minstens 1 zijn - foutboodschap overschrijven (met sleutel)
//hoogtens 50 - foutboodschap wordt overschreven (zonder sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Min(value = 1, message = "{price.percentIncrease.Min.message}")
@Max(50)
private Integer percentIncrease;
//private Integer percentDecrease;
//twee @
//het moet<SUF>
//het moet liggen tussen 1 en 25 - foutboodschap overschrijven (met sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Range(min = 1, max = 25, message = "{price.percentDecrease.Range.message}")
private Integer percentDecrease;
}
|
22445_1 | package components;
/**
* PSU class. Contains all the information that a Power Supply Unit has.
* All the fields match the fields in the Neo4j Database.
* Extends {@link components.Hardware}
*
* @author Frenesius
* @since 1-1-2015
* @version 0.1
*/
public class PSU extends Hardware{
private String beoordeling;
private String typekoeling;
private String hoogte;
private String fabrieksgarantie;
private String bijzonderheden;
private String breedte;
private String product;
private String vermogenwatt; // origineel Vermogen (watt)
private String pciexpressaansluitingen;
private String aantalmolexaansluitingen;
private String aantalventilatoren;
private String diepte;
private String diameterventilator; //
private String voedingtype;
private String stroomspanningbeveiliging;
private String aantal62pinsaansluitingen; // origineel Aantal 6+2-pins aansluitingen
private String modulair;
private String rails12v; // origineel +12V Rails
private String aantalsataaansluitingen; // origineel Aantal Sata-aansluitingen
private String voedingcertificering;
private String ventilatorlocatie;
private String capaciteit12v1rail;
public String getBeoordeling() {
return beoordeling;
}
public void setBeoordeling(String beoordeling) {
this.beoordeling = beoordeling;
}
public String getTypekoeling() {
return typekoeling;
}
public void setTypekoeling(String typekoeling) {
this.typekoeling = typekoeling;
}
public String getHoogte() {
return hoogte;
}
public void setHoogte(String hoogte) {
this.hoogte = hoogte;
}
public String getFabrieksgarantie() {
return fabrieksgarantie;
}
public void setFabrieksgarantie(String fabrieksgarantie) {
this.fabrieksgarantie = fabrieksgarantie;
}
public String getBijzonderheden() {
return bijzonderheden;
}
public void setBijzonderheden(String bijzonderheden) {
this.bijzonderheden = bijzonderheden;
}
public String getBreedte() {
return breedte;
}
public void setBreedte(String breedte) {
this.breedte = breedte;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getVermogenwatt() {
return vermogenwatt;
}
public void setVermogenwatt(String vermogenwatt) {
this.vermogenwatt = vermogenwatt;
}
public String getPciexpressaansluitingen() {
return pciexpressaansluitingen;
}
public void setPciexpressaansluitingen(String pciexpressaansluitingen) {
this.pciexpressaansluitingen = pciexpressaansluitingen;
}
public String getAantalmolexaansluitingen() {
return aantalmolexaansluitingen;
}
public void setAantalmolexaansluitingen(String aantalmolexaansluitingen) {
this.aantalmolexaansluitingen = aantalmolexaansluitingen;
}
public String getAantalventilatoren() {
return aantalventilatoren;
}
public void setAantalventilatoren(String aantalventilatoren) {
this.aantalventilatoren = aantalventilatoren;
}
public String getDiepte() {
return diepte;
}
public void setDiepte(String diepte) {
this.diepte = diepte;
}
public String getDiameterventilator() {
return diameterventilator;
}
public void setDiameterventilator(String diameterventilator) {
this.diameterventilator = diameterventilator;
}
public String getVoedingtype() {
return voedingtype;
}
public void setVoedingtype(String voedingtype) {
this.voedingtype = voedingtype;
}
public String getStroomspanningbeveiliging() {
return stroomspanningbeveiliging;
}
public void setStroomspanningbeveiliging(String stroomspanningbeveiliging) {
this.stroomspanningbeveiliging = stroomspanningbeveiliging;
}
public String getAantal62pinsaansluitingen() {
return aantal62pinsaansluitingen;
}
public void setAantal62pinsaansluitingen(String aantal62pinsaansluitingen) {
this.aantal62pinsaansluitingen = aantal62pinsaansluitingen;
}
public String getModulair() {
return modulair;
}
public void setModulair(String modulair) {
this.modulair = modulair;
}
public String getRails12v() {
return rails12v;
}
public void setRails12v(String rails12v) {
this.rails12v = rails12v;
}
public String getAantalsataaansluitingen() {
return aantalsataaansluitingen;
}
public void setAantalsataaansluitingen(String aantalsataaansluitingen) {
this.aantalsataaansluitingen = aantalsataaansluitingen;
}
public String getVoedingcertificering() {
return voedingcertificering;
}
public void setVoedingcertificering(String voedingcertificering) {
this.voedingcertificering = voedingcertificering;
}
public String getVentilatorlocatie() {
return ventilatorlocatie;
}
public void setVentilatorlocatie(String ventilatorlocatie) {
this.ventilatorlocatie = ventilatorlocatie;
}
public String getCapaciteit12v1rail() {
return capaciteit12v1rail;
}
public void setCapaciteit12v1rail(String capaciteit12v1rail) {
this.capaciteit12v1rail = capaciteit12v1rail;
}
}
| Frenesius/PC-Builder-Matcher | src/components/PSU.java | 1,548 | // origineel Vermogen (watt)
| line_comment | nl | package components;
/**
* PSU class. Contains all the information that a Power Supply Unit has.
* All the fields match the fields in the Neo4j Database.
* Extends {@link components.Hardware}
*
* @author Frenesius
* @since 1-1-2015
* @version 0.1
*/
public class PSU extends Hardware{
private String beoordeling;
private String typekoeling;
private String hoogte;
private String fabrieksgarantie;
private String bijzonderheden;
private String breedte;
private String product;
private String vermogenwatt; // origineel Vermogen<SUF>
private String pciexpressaansluitingen;
private String aantalmolexaansluitingen;
private String aantalventilatoren;
private String diepte;
private String diameterventilator; //
private String voedingtype;
private String stroomspanningbeveiliging;
private String aantal62pinsaansluitingen; // origineel Aantal 6+2-pins aansluitingen
private String modulair;
private String rails12v; // origineel +12V Rails
private String aantalsataaansluitingen; // origineel Aantal Sata-aansluitingen
private String voedingcertificering;
private String ventilatorlocatie;
private String capaciteit12v1rail;
public String getBeoordeling() {
return beoordeling;
}
public void setBeoordeling(String beoordeling) {
this.beoordeling = beoordeling;
}
public String getTypekoeling() {
return typekoeling;
}
public void setTypekoeling(String typekoeling) {
this.typekoeling = typekoeling;
}
public String getHoogte() {
return hoogte;
}
public void setHoogte(String hoogte) {
this.hoogte = hoogte;
}
public String getFabrieksgarantie() {
return fabrieksgarantie;
}
public void setFabrieksgarantie(String fabrieksgarantie) {
this.fabrieksgarantie = fabrieksgarantie;
}
public String getBijzonderheden() {
return bijzonderheden;
}
public void setBijzonderheden(String bijzonderheden) {
this.bijzonderheden = bijzonderheden;
}
public String getBreedte() {
return breedte;
}
public void setBreedte(String breedte) {
this.breedte = breedte;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getVermogenwatt() {
return vermogenwatt;
}
public void setVermogenwatt(String vermogenwatt) {
this.vermogenwatt = vermogenwatt;
}
public String getPciexpressaansluitingen() {
return pciexpressaansluitingen;
}
public void setPciexpressaansluitingen(String pciexpressaansluitingen) {
this.pciexpressaansluitingen = pciexpressaansluitingen;
}
public String getAantalmolexaansluitingen() {
return aantalmolexaansluitingen;
}
public void setAantalmolexaansluitingen(String aantalmolexaansluitingen) {
this.aantalmolexaansluitingen = aantalmolexaansluitingen;
}
public String getAantalventilatoren() {
return aantalventilatoren;
}
public void setAantalventilatoren(String aantalventilatoren) {
this.aantalventilatoren = aantalventilatoren;
}
public String getDiepte() {
return diepte;
}
public void setDiepte(String diepte) {
this.diepte = diepte;
}
public String getDiameterventilator() {
return diameterventilator;
}
public void setDiameterventilator(String diameterventilator) {
this.diameterventilator = diameterventilator;
}
public String getVoedingtype() {
return voedingtype;
}
public void setVoedingtype(String voedingtype) {
this.voedingtype = voedingtype;
}
public String getStroomspanningbeveiliging() {
return stroomspanningbeveiliging;
}
public void setStroomspanningbeveiliging(String stroomspanningbeveiliging) {
this.stroomspanningbeveiliging = stroomspanningbeveiliging;
}
public String getAantal62pinsaansluitingen() {
return aantal62pinsaansluitingen;
}
public void setAantal62pinsaansluitingen(String aantal62pinsaansluitingen) {
this.aantal62pinsaansluitingen = aantal62pinsaansluitingen;
}
public String getModulair() {
return modulair;
}
public void setModulair(String modulair) {
this.modulair = modulair;
}
public String getRails12v() {
return rails12v;
}
public void setRails12v(String rails12v) {
this.rails12v = rails12v;
}
public String getAantalsataaansluitingen() {
return aantalsataaansluitingen;
}
public void setAantalsataaansluitingen(String aantalsataaansluitingen) {
this.aantalsataaansluitingen = aantalsataaansluitingen;
}
public String getVoedingcertificering() {
return voedingcertificering;
}
public void setVoedingcertificering(String voedingcertificering) {
this.voedingcertificering = voedingcertificering;
}
public String getVentilatorlocatie() {
return ventilatorlocatie;
}
public void setVentilatorlocatie(String ventilatorlocatie) {
this.ventilatorlocatie = ventilatorlocatie;
}
public String getCapaciteit12v1rail() {
return capaciteit12v1rail;
}
public void setCapaciteit12v1rail(String capaciteit12v1rail) {
this.capaciteit12v1rail = capaciteit12v1rail;
}
}
|
172271_1 | /* *****************************
* Author: Elvira van der Ven *
* Date: 01/12/2023 * *
*******************************/
package week3.les6;
public class Plastic extends Material{
private String color;
//Plastic -> smelten -> vormen naar kubus -> verven
public Plastic() {
super();
this.color = "";
this.setMeltingPoint(300);
}
public void print(){
System.out.println(this.toString());
}
@Override
public String toString() {
return "Plastic{" +
"color='" + color + '\'' +
'}';
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
} | ElviravdVen/TINPRO04-2_2324 | les_voorbeelden/src/week3/les6/Plastic.java | 204 | //Plastic -> smelten -> vormen naar kubus -> verven | line_comment | nl | /* *****************************
* Author: Elvira van der Ven *
* Date: 01/12/2023 * *
*******************************/
package week3.les6;
public class Plastic extends Material{
private String color;
//Plastic -><SUF>
public Plastic() {
super();
this.color = "";
this.setMeltingPoint(300);
}
public void print(){
System.out.println(this.toString());
}
@Override
public String toString() {
return "Plastic{" +
"color='" + color + '\'' +
'}';
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
} |
45052_5 | package be.khleuven.nieuws;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
public class KHLLoginActivity extends Activity {
/**
* De webview wat gebruikt wordt.
*/
WebView myWebView;
/**
* De url die bijgehouden wordt in de preferences wordt hier in gezet.
*/
String mFeedUrl = null;
public static final String PREFS_NAME = "MyPrefsFile";
/**
* Hierin wordt de url opgeslagen.
*/
static SharedPreferences settings;
/**
* Editor voor aanpassen van data in SharedPreferences.
*/
SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
mFeedUrl = settings.getString("feedUrl", null);
if (mFeedUrl != null) {
openRSS(mFeedUrl);
} else {
/**
* Deze klasse wordt gebruikt als interface tussen de java en
* javascriptcode die gebruikt wordt bij de webview
*
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
class MyJavaScriptInterface {
/**
* Verwerkt de html code en opent dan de KHLNieuwsActivity.
* Wordt aangeroepen vanuit de javascriptcode.
*
* @param html
* De string die de htmlcode van de pagina bevat.
*/
@SuppressWarnings("unused")
public void processHTML(String html) {
String link = fetchLink(html);
editor.putString("feedUrl", link);
editor.commit();
openRSS(link);
}
/**
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link.
*
* @param html
* De string die de htmlcode van de pagina bevat.
* @return De juiste url van de RSS-feed.
*/
private String fetchLink(String html) {
String[] temp;
temp = html.split("\n");
String link = "";
boolean stop = false;
try {
for (String t : temp) {
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {
link = t;
stop = true;
}
if (stop)
break;
}
} catch (Exception e) {
} finally {
if (link != null) {
String[] parts = link.split("\"");
link = parts[1];
}
}
return link;
}
}
// cookie bijhouden
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
// webview gebruiken voor login
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
// wat doen wanneer pagina geladen is
// checken of ingelogd door te kijken of we terug op de
// portaalsite zitten
public void onPageFinished(WebView view, String url) {
if (view.getUrl().equals("https://portaal.khleuven.be/")) {
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (url.equals("https://portaal.khleuven.be/")) {
view.setVisibility(View.INVISIBLE);
ProgressDialog.show(
KHLLoginActivity.this, "",
"Fetching RSS. Please wait...", true);
}
}
});
myWebView.getSettings().setDatabasePath("khl.news");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),
"interfaceName");
myWebView
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");
}
}
private void openRSS(String link) {
Intent intent = new Intent(getApplicationContext(),
KHLNieuwsActivity.class);
intent.putExtra("feedUrl", link);
startActivity(intent);
}
} | LaurentMouha/KHLNieuws | src/be/khleuven/nieuws/KHLLoginActivity.java | 1,323 | /**
* Deze klasse wordt gebruikt als interface tussen de java en
* javascriptcode die gebruikt wordt bij de webview
*
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/ | block_comment | nl | package be.khleuven.nieuws;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* @author Laurent Mouha, Robin Vrebos en Bram Miermans
*
*/
public class KHLLoginActivity extends Activity {
/**
* De webview wat gebruikt wordt.
*/
WebView myWebView;
/**
* De url die bijgehouden wordt in de preferences wordt hier in gezet.
*/
String mFeedUrl = null;
public static final String PREFS_NAME = "MyPrefsFile";
/**
* Hierin wordt de url opgeslagen.
*/
static SharedPreferences settings;
/**
* Editor voor aanpassen van data in SharedPreferences.
*/
SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
mFeedUrl = settings.getString("feedUrl", null);
if (mFeedUrl != null) {
openRSS(mFeedUrl);
} else {
/**
* Deze klasse wordt<SUF>*/
class MyJavaScriptInterface {
/**
* Verwerkt de html code en opent dan de KHLNieuwsActivity.
* Wordt aangeroepen vanuit de javascriptcode.
*
* @param html
* De string die de htmlcode van de pagina bevat.
*/
@SuppressWarnings("unused")
public void processHTML(String html) {
String link = fetchLink(html);
editor.putString("feedUrl", link);
editor.commit();
openRSS(link);
}
/**
* Deze functie doorzoekt de htmlcode naar een geldige RSS-link.
*
* @param html
* De string die de htmlcode van de pagina bevat.
* @return De juiste url van de RSS-feed.
*/
private String fetchLink(String html) {
String[] temp;
temp = html.split("\n");
String link = "";
boolean stop = false;
try {
for (String t : temp) {
if (t.contains("<a href=\"http://portaal.khleuven.be/rss.php")) {
link = t;
stop = true;
}
if (stop)
break;
}
} catch (Exception e) {
} finally {
if (link != null) {
String[] parts = link.split("\"");
link = parts[1];
}
}
return link;
}
}
// cookie bijhouden
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
// webview gebruiken voor login
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
// wat doen wanneer pagina geladen is
// checken of ingelogd door te kijken of we terug op de
// portaalsite zitten
public void onPageFinished(WebView view, String url) {
if (view.getUrl().equals("https://portaal.khleuven.be/")) {
view.loadUrl("javascript:window.interfaceName.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (url.equals("https://portaal.khleuven.be/")) {
view.setVisibility(View.INVISIBLE);
ProgressDialog.show(
KHLLoginActivity.this, "",
"Fetching RSS. Please wait...", true);
}
}
});
myWebView.getSettings().setDatabasePath("khl.news");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.addJavascriptInterface(new MyJavaScriptInterface(),
"interfaceName");
myWebView
.loadUrl("https://portaal.khleuven.be/Shibboleth.sso/WAYF/khleuven?target=https%3A%2F%2Fportaal.khleuven.be%2F");
}
}
private void openRSS(String link) {
Intent intent = new Intent(getApplicationContext(),
KHLNieuwsActivity.class);
intent.putExtra("feedUrl", link);
startActivity(intent);
}
} |
210591_87 | /*
* 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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
| apache/zookeeper | zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java | 6,976 | /**
* @see Code#SESSIONEXPIRED
*/ | block_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.zookeeper;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.yetus.audience.InterfaceAudience;
@InterfaceAudience.Public
public abstract class KeeperException extends Exception {
/**
* All multi-requests that result in an exception retain the results
* here so that it is possible to examine the problems in the catch
* scope. Non-multi requests will get a null if they try to access
* these results.
*/
private List<OpResult> results;
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code.
* @param path The ZooKeeper path being operated on.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code, String path) {
KeeperException r = create(code);
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code, String)}
* instead
*/
@Deprecated
public static KeeperException create(int code, String path) {
KeeperException r = create(Code.get(code));
r.path = path;
return r;
}
/**
* @deprecated deprecated in 3.1.0, use {@link #create(Code)}
* instead
*/
@Deprecated
public static KeeperException create(int code) {
return create(Code.get(code));
}
/**
* All non-specific keeper exceptions should be constructed via
* this factory method in order to guarantee consistency in error
* codes and such. If you know the error code, then you should
* construct the special purpose exception directly. That will
* allow you to have the most specific possible declarations of
* what exceptions might actually be thrown.
*
* @param code The error code of your new exception. This will
* also determine the specific type of the exception that is
* returned.
* @return The specialized exception, presumably to be thrown by
* the caller.
*/
public static KeeperException create(Code code) {
switch (code) {
case SYSTEMERROR:
return new SystemErrorException();
case RUNTIMEINCONSISTENCY:
return new RuntimeInconsistencyException();
case DATAINCONSISTENCY:
return new DataInconsistencyException();
case CONNECTIONLOSS:
return new ConnectionLossException();
case MARSHALLINGERROR:
return new MarshallingErrorException();
case UNIMPLEMENTED:
return new UnimplementedException();
case OPERATIONTIMEOUT:
return new OperationTimeoutException();
case NEWCONFIGNOQUORUM:
return new NewConfigNoQuorum();
case RECONFIGINPROGRESS:
return new ReconfigInProgress();
case BADARGUMENTS:
return new BadArgumentsException();
case APIERROR:
return new APIErrorException();
case NONODE:
return new NoNodeException();
case NOAUTH:
return new NoAuthException();
case BADVERSION:
return new BadVersionException();
case NOCHILDRENFOREPHEMERALS:
return new NoChildrenForEphemeralsException();
case NODEEXISTS:
return new NodeExistsException();
case INVALIDACL:
return new InvalidACLException();
case AUTHFAILED:
return new AuthFailedException();
case NOTEMPTY:
return new NotEmptyException();
case SESSIONEXPIRED:
return new SessionExpiredException();
case INVALIDCALLBACK:
return new InvalidCallbackException();
case SESSIONMOVED:
return new SessionMovedException();
case NOTREADONLY:
return new NotReadOnlyException();
case EPHEMERALONLOCALSESSION:
return new EphemeralOnLocalSessionException();
case NOWATCHER:
return new NoWatcherException();
case RECONFIGDISABLED:
return new ReconfigDisabledException();
case SESSIONCLOSEDREQUIRESASLAUTH:
return new SessionClosedRequireAuthException();
case REQUESTTIMEOUT:
return new RequestTimeoutException();
case QUOTAEXCEEDED:
return new QuotaExceededException();
case THROTTLEDOP:
return new ThrottledOpException();
case OK:
default:
throw new IllegalArgumentException("Invalid exception code:" + code.code);
}
}
/**
* Set the code for this exception
* @param code error code
* @deprecated deprecated in 3.1.0, exceptions should be immutable, this
* method should not be used
*/
@Deprecated
public void setCode(int code) {
this.code = Code.get(code);
}
/** This interface contains the original static final int constants
* which have now been replaced with an enumeration in Code. Do not
* reference this class directly, if necessary (legacy code) continue
* to access the constants through Code.
* Note: an interface is used here due to the fact that enums cannot
* reference constants defined within the same enum as said constants
* are considered initialized _after_ the enum itself. By using an
* interface as a super type this allows the deprecated constants to
* be initialized first and referenced when constructing the enums. I
* didn't want to have constants declared twice. This
* interface should be private, but it's declared public to enable
* javadoc to include in the user API spec.
*/
@SuppressWarnings("DeprecatedIsStillUsed") // still used in Code - kept until 4.0
@Deprecated
@InterfaceAudience.Public
public interface CodeDeprecated {
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
*/
@Deprecated
int Ok = 0;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
*/
@Deprecated
int SystemError = -1;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#RUNTIMEINCONSISTENCY} instead
*/
@Deprecated
int RuntimeInconsistency = -2;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
* instead
*/
@Deprecated
int DataInconsistency = -3;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
* instead
*/
@Deprecated
int ConnectionLoss = -4;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
* instead
*/
@Deprecated
int MarshallingError = -5;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
* instead
*/
@Deprecated
int Unimplemented = -6;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
* instead
*/
@Deprecated
int OperationTimeout = -7;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
* instead
*/
@Deprecated
int BadArguments = -8;
@Deprecated
int UnknownSession = -12;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
* instead
*/
@Deprecated
int NewConfigNoQuorum = -13;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
* instead
*/
@Deprecated
int ReconfigInProgress = -14;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
*/
@Deprecated
int APIError = -100;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
*/
@Deprecated
int NoNode = -101;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
*/
@Deprecated
int NoAuth = -102;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
*/
@Deprecated
int BadVersion = -103;
/**
* @deprecated deprecated in 3.1.0, use
* {@link Code#NOCHILDRENFOREPHEMERALS}
* instead
*/
@Deprecated
int NoChildrenForEphemerals = -108;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
*/
@Deprecated
int NodeExists = -110;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
*/
@Deprecated
int NotEmpty = -111;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
*/
@Deprecated
int SessionExpired = -112;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
* instead
*/
@Deprecated
int InvalidCallback = -113;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
*/
@Deprecated
int InvalidACL = -114;
/**
* @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
*/
@Deprecated
int AuthFailed = -115;
// This value will be used directly in {@link CODE#SESSIONMOVED}
// public static final int SessionMoved = -118;
@Deprecated
int EphemeralOnLocalSession = -120;
}
/** Codes which represent the various KeeperException
* types. This enum replaces the deprecated earlier static final int
* constants. The old, deprecated, values are in "camel case" while the new
* enum values are in all CAPS.
*/
@InterfaceAudience.Public
public enum Code implements CodeDeprecated {
/** Everything is OK */
OK(Ok),
/** System and server-side errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value, but lesser than {@link #APIERROR}, are system errors.
*/
SYSTEMERROR(SystemError),
/** A runtime inconsistency was found */
RUNTIMEINCONSISTENCY(RuntimeInconsistency),
/** A data inconsistency was found */
DATAINCONSISTENCY(DataInconsistency),
/** Connection to the server has been lost */
CONNECTIONLOSS(ConnectionLoss),
/** Error while marshalling or unmarshalling data */
MARSHALLINGERROR(MarshallingError),
/** Operation is unimplemented */
UNIMPLEMENTED(Unimplemented),
/** Operation timeout */
OPERATIONTIMEOUT(OperationTimeout),
/** Invalid arguments */
BADARGUMENTS(BadArguments),
/** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
* invoking reconfiguration after new servers are connected and synced */
NEWCONFIGNOQUORUM(NewConfigNoQuorum),
/** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
RECONFIGINPROGRESS(ReconfigInProgress),
/** Unknown session (internal server use only) */
UNKNOWNSESSION(UnknownSession),
/** API errors.
* This is never thrown by the server, it shouldn't be used other than
* to indicate a range. Specifically error codes greater than this
* value are API errors (while values less than this indicate a
* {@link #SYSTEMERROR}).
*/
APIERROR(APIError),
/** Node does not exist */
NONODE(NoNode),
/** Not authenticated */
NOAUTH(NoAuth),
/** Version conflict
In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
BADVERSION(BadVersion),
/** Ephemeral nodes may not have children */
NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
/** The node already exists */
NODEEXISTS(NodeExists),
/** The node has children */
NOTEMPTY(NotEmpty),
/** The session has been expired by the server */
SESSIONEXPIRED(SessionExpired),
/** Invalid callback specified */
INVALIDCALLBACK(InvalidCallback),
/** Invalid ACL specified */
INVALIDACL(InvalidACL),
/** Client authentication failed */
AUTHFAILED(AuthFailed),
/** Session moved to another server, so operation is ignored */
SESSIONMOVED(-118),
/** State-changing request is passed to read-only server */
NOTREADONLY(-119),
/** Attempt to create ephemeral node on a local session */
EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
/** Attempts to remove a non-existing watcher */
NOWATCHER(-121),
/** Request not completed within max allowed time.*/
REQUESTTIMEOUT(-122),
/** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
RECONFIGDISABLED(-123),
/** The session has been closed by server because server requires client to do authentication
* with configured authentication scheme at the server, but client is not configured with
* required authentication scheme or configured but authentication failed
* (i.e. wrong credential used.). */
SESSIONCLOSEDREQUIRESASLAUTH(-124),
/** Exceeded the quota that was set on the path.*/
QUOTAEXCEEDED(-125),
/** Operation was throttled and not executed at all. This error code indicates that zookeeper server
* is under heavy load and can't process incoming requests at full speed; please retry with back off.
*/
THROTTLEDOP (-127);
private static final Map<Integer, Code> lookup = new HashMap<>();
static {
for (Code c : EnumSet.allOf(Code.class)) {
lookup.put(c.code, c);
}
}
private final int code;
Code(int code) {
this.code = code;
}
/**
* Get the int value for a particular Code.
* @return error code as integer
*/
public int intValue() {
return code;
}
/**
* Get the Code value for a particular integer error code
* @param code int error code
* @return Code value corresponding to specified int code, if null throws IllegalArgumentException
*/
public static Code get(int code) {
Code codeVal = lookup.get(code);
if (codeVal == null) {
throw new IllegalArgumentException("The current client version cannot lookup this code:" + code);
}
return codeVal;
}
}
static String getCodeMessage(Code code) {
switch (code) {
case OK:
return "ok";
case SYSTEMERROR:
return "SystemError";
case RUNTIMEINCONSISTENCY:
return "RuntimeInconsistency";
case DATAINCONSISTENCY:
return "DataInconsistency";
case CONNECTIONLOSS:
return "ConnectionLoss";
case MARSHALLINGERROR:
return "MarshallingError";
case NEWCONFIGNOQUORUM:
return "NewConfigNoQuorum";
case RECONFIGINPROGRESS:
return "ReconfigInProgress";
case UNIMPLEMENTED:
return "Unimplemented";
case OPERATIONTIMEOUT:
return "OperationTimeout";
case BADARGUMENTS:
return "BadArguments";
case APIERROR:
return "APIError";
case NONODE:
return "NoNode";
case NOAUTH:
return "NoAuth";
case BADVERSION:
return "BadVersion";
case NOCHILDRENFOREPHEMERALS:
return "NoChildrenForEphemerals";
case NODEEXISTS:
return "NodeExists";
case INVALIDACL:
return "InvalidACL";
case AUTHFAILED:
return "AuthFailed";
case NOTEMPTY:
return "Directory not empty";
case SESSIONEXPIRED:
return "Session expired";
case INVALIDCALLBACK:
return "Invalid callback";
case SESSIONMOVED:
return "Session moved";
case NOTREADONLY:
return "Not a read-only call";
case EPHEMERALONLOCALSESSION:
return "Ephemeral node on local session";
case NOWATCHER:
return "No such watcher";
case RECONFIGDISABLED:
return "Reconfig is disabled";
case SESSIONCLOSEDREQUIRESASLAUTH:
return "Session closed because client failed to authenticate";
case QUOTAEXCEEDED:
return "Quota has exceeded";
case THROTTLEDOP:
return "Op throttled due to high load";
default:
return "Unknown error " + code;
}
}
private Code code;
private String path;
public KeeperException(Code code) {
this.code = code;
}
KeeperException(Code code, String path) {
this.code = code;
this.path = path;
}
/**
* Read the error code for this exception
* @return the error code for this exception
* @deprecated deprecated in 3.1.0, use {@link #code()} instead
*/
@Deprecated
public int getCode() {
return code.code;
}
/**
* Read the error Code for this exception
* @return the error Code for this exception
*/
public Code code() {
return code;
}
/**
* Read the path for this exception
* @return the path associated with this error, null if none
*/
public String getPath() {
return path;
}
@Override
public String getMessage() {
if (path == null || path.isEmpty()) {
return "KeeperErrorCode = " + getCodeMessage(code);
}
return "KeeperErrorCode = " + getCodeMessage(code) + " for " + path;
}
void setMultiResults(List<OpResult> results) {
this.results = results;
}
/**
* If this exception was thrown by a multi-request then the (partial) results
* and error codes can be retrieved using this getter.
* @return A copy of the list of results from the operations in the multi-request.
*
* @since 3.4.0
*
*/
public List<OpResult> getResults() {
return results != null ? new ArrayList<OpResult>(results) : null;
}
/**
* @see Code#APIERROR
*/
@InterfaceAudience.Public
public static class APIErrorException extends KeeperException {
public APIErrorException() {
super(Code.APIERROR);
}
}
/**
* @see Code#AUTHFAILED
*/
@InterfaceAudience.Public
public static class AuthFailedException extends KeeperException {
public AuthFailedException() {
super(Code.AUTHFAILED);
}
}
/**
* @see Code#BADARGUMENTS
*/
@InterfaceAudience.Public
public static class BadArgumentsException extends KeeperException {
public BadArgumentsException() {
super(Code.BADARGUMENTS);
}
public BadArgumentsException(String path) {
super(Code.BADARGUMENTS, path);
}
}
/**
* @see Code#BADVERSION
*/
@InterfaceAudience.Public
public static class BadVersionException extends KeeperException {
public BadVersionException() {
super(Code.BADVERSION);
}
public BadVersionException(String path) {
super(Code.BADVERSION, path);
}
}
/**
* @see Code#CONNECTIONLOSS
*/
@InterfaceAudience.Public
public static class ConnectionLossException extends KeeperException {
public ConnectionLossException() {
super(Code.CONNECTIONLOSS);
}
}
/**
* @see Code#DATAINCONSISTENCY
*/
@InterfaceAudience.Public
public static class DataInconsistencyException extends KeeperException {
public DataInconsistencyException() {
super(Code.DATAINCONSISTENCY);
}
}
/**
* @see Code#INVALIDACL
*/
@InterfaceAudience.Public
public static class InvalidACLException extends KeeperException {
public InvalidACLException() {
super(Code.INVALIDACL);
}
public InvalidACLException(String path) {
super(Code.INVALIDACL, path);
}
}
/**
* @see Code#INVALIDCALLBACK
*/
@InterfaceAudience.Public
public static class InvalidCallbackException extends KeeperException {
public InvalidCallbackException() {
super(Code.INVALIDCALLBACK);
}
}
/**
* @see Code#MARSHALLINGERROR
*/
@InterfaceAudience.Public
public static class MarshallingErrorException extends KeeperException {
public MarshallingErrorException() {
super(Code.MARSHALLINGERROR);
}
}
/**
* @see Code#NOAUTH
*/
@InterfaceAudience.Public
public static class NoAuthException extends KeeperException {
public NoAuthException() {
super(Code.NOAUTH);
}
}
/**
* @see Code#NEWCONFIGNOQUORUM
*/
@InterfaceAudience.Public
public static class NewConfigNoQuorum extends KeeperException {
public NewConfigNoQuorum() {
super(Code.NEWCONFIGNOQUORUM);
}
}
/**
* @see Code#RECONFIGINPROGRESS
*/
@InterfaceAudience.Public
public static class ReconfigInProgress extends KeeperException {
public ReconfigInProgress() {
super(Code.RECONFIGINPROGRESS);
}
}
/**
* @see Code#NOCHILDRENFOREPHEMERALS
*/
@InterfaceAudience.Public
public static class NoChildrenForEphemeralsException extends KeeperException {
public NoChildrenForEphemeralsException() {
super(Code.NOCHILDRENFOREPHEMERALS);
}
public NoChildrenForEphemeralsException(String path) {
super(Code.NOCHILDRENFOREPHEMERALS, path);
}
}
/**
* @see Code#NODEEXISTS
*/
@InterfaceAudience.Public
public static class NodeExistsException extends KeeperException {
public NodeExistsException() {
super(Code.NODEEXISTS);
}
public NodeExistsException(String path) {
super(Code.NODEEXISTS, path);
}
}
/**
* @see Code#NONODE
*/
@InterfaceAudience.Public
public static class NoNodeException extends KeeperException {
public NoNodeException() {
super(Code.NONODE);
}
public NoNodeException(String path) {
super(Code.NONODE, path);
}
}
/**
* @see Code#NOTEMPTY
*/
@InterfaceAudience.Public
public static class NotEmptyException extends KeeperException {
public NotEmptyException() {
super(Code.NOTEMPTY);
}
public NotEmptyException(String path) {
super(Code.NOTEMPTY, path);
}
}
/**
* @see Code#OPERATIONTIMEOUT
*/
@InterfaceAudience.Public
public static class OperationTimeoutException extends KeeperException {
public OperationTimeoutException() {
super(Code.OPERATIONTIMEOUT);
}
}
/**
* @see Code#RUNTIMEINCONSISTENCY
*/
@InterfaceAudience.Public
public static class RuntimeInconsistencyException extends KeeperException {
public RuntimeInconsistencyException() {
super(Code.RUNTIMEINCONSISTENCY);
}
}
/**
* @see Code#SESSIONEXPIRED
<SUF>*/
@InterfaceAudience.Public
public static class SessionExpiredException extends KeeperException {
public SessionExpiredException() {
super(Code.SESSIONEXPIRED);
}
}
/**
* @see Code#UNKNOWNSESSION
*/
@InterfaceAudience.Public
public static class UnknownSessionException extends KeeperException {
public UnknownSessionException() {
super(Code.UNKNOWNSESSION);
}
}
/**
* @see Code#SESSIONMOVED
*/
@InterfaceAudience.Public
public static class SessionMovedException extends KeeperException {
public SessionMovedException() {
super(Code.SESSIONMOVED);
}
}
/**
* @see Code#NOTREADONLY
*/
@InterfaceAudience.Public
public static class NotReadOnlyException extends KeeperException {
public NotReadOnlyException() {
super(Code.NOTREADONLY);
}
}
/**
* @see Code#EPHEMERALONLOCALSESSION
*/
@InterfaceAudience.Public
public static class EphemeralOnLocalSessionException extends KeeperException {
public EphemeralOnLocalSessionException() {
super(Code.EPHEMERALONLOCALSESSION);
}
}
/**
* @see Code#SYSTEMERROR
*/
@InterfaceAudience.Public
public static class SystemErrorException extends KeeperException {
public SystemErrorException() {
super(Code.SYSTEMERROR);
}
}
/**
* @see Code#UNIMPLEMENTED
*/
@InterfaceAudience.Public
public static class UnimplementedException extends KeeperException {
public UnimplementedException() {
super(Code.UNIMPLEMENTED);
}
}
/**
* @see Code#NOWATCHER
*/
@InterfaceAudience.Public
public static class NoWatcherException extends KeeperException {
public NoWatcherException() {
super(Code.NOWATCHER);
}
public NoWatcherException(String path) {
super(Code.NOWATCHER, path);
}
}
/**
* @see Code#RECONFIGDISABLED
*/
@InterfaceAudience.Public
public static class ReconfigDisabledException extends KeeperException {
public ReconfigDisabledException() {
super(Code.RECONFIGDISABLED);
}
public ReconfigDisabledException(String path) {
super(Code.RECONFIGDISABLED, path);
}
}
/**
* @see Code#SESSIONCLOSEDREQUIRESASLAUTH
*/
public static class SessionClosedRequireAuthException extends KeeperException {
public SessionClosedRequireAuthException() {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
}
public SessionClosedRequireAuthException(String path) {
super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
}
}
/**
* @see Code#REQUESTTIMEOUT
*/
public static class RequestTimeoutException extends KeeperException {
public RequestTimeoutException() {
super(Code.REQUESTTIMEOUT);
}
}
/**
* @see Code#QUOTAEXCEEDED
*/
@InterfaceAudience.Public
public static class QuotaExceededException extends KeeperException {
public QuotaExceededException() {
super(Code.QUOTAEXCEEDED);
}
public QuotaExceededException(String path) {
super(Code.QUOTAEXCEEDED, path);
}
}
/**
* @see Code#THROTTLEDOP
*/
public static class ThrottledOpException extends KeeperException {
public ThrottledOpException() {
super(Code.THROTTLEDOP);
}
}
}
|
88833_5 | /*
Copyright (c) 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package cern.clhep;
/**
* High Energy Physics coherent Physical Constants.
* This class is a Java port of the <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Units/PhysicalConstants_h.html">C++ version</a> found in <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep">CLHEP 1.4.0</a>, which in turn has been provided by Geant4 (a simulation toolkit for HEP).
* <p>
* For aliasing see {@link #physicalConstants}.
*
* @author [email protected]
* @version 1.0, 09/24/99
*/
public class PhysicalConstants extends Object {
/**
* Little trick to allow for "aliasing", that is, renaming this class.
* Normally you would write
* <pre>
* PhysicalConstants.twopi;
* PhysicalConstants.c_light;
* PhysicalConstants.h_Planck;
* </pre>
* Since this class has only static methods, but no instance methods
* you can also shorten the name "PhysicalConstants" to a name that better suits you, for example "P".
* <pre>
* PhysicalConstants P = PhysicalConstants.physicalConstants; // kind of "alias"
* P.twopi;
* P.c_light;
* P.h_Planck;
* </pre>
*/
public static final PhysicalConstants physicalConstants = new PhysicalConstants();
//
//
//
public static final double pi = Math.PI; //3.14159265358979323846;
public static final double twopi = 2*pi;
public static final double halfpi = pi/2;
public static final double pi2 = pi*pi;
//
//
//
public static final double Avogadro = 6.0221367e+23/Units.mole;
//
// c = 299.792458 mm/ns
// c^2 = 898.7404 (mm/ns)^2
//
public static final double c_light = 2.99792458e+8 * Units.m/Units.s;
public static final double c_squared = c_light * c_light;
//
// h = 4.13566e-12 MeV*ns
// hbar = 6.58212e-13 MeV*ns
// hbarc = 197.32705e-12 MeV*mm
//
public static final double h_Planck = 6.6260755e-34 * Units.joule*Units.s;
public static final double hbar_Planck = h_Planck/twopi;
public static final double hbarc = hbar_Planck * c_light;
public static final double hbarc_squared = hbarc * hbarc;
//
//
//
public static final double electron_charge = - Units.eplus; // see SystemOfUnits.h
public static final double e_squared = Units.eplus * Units.eplus;
//
// amu_c2 - atomic equivalent mass unit
// amu - atomic mass unit
//
public static final double electron_mass_c2 = 0.51099906 * Units.MeV;
public static final double proton_mass_c2 = 938.27231 * Units.MeV;
public static final double neutron_mass_c2 = 939.56563 * Units.MeV;
public static final double amu_c2 = 931.49432 * Units.MeV;
public static final double amu = amu_c2/c_squared;
//
// permeability of free space mu0 = 2.01334e-16 Mev*(ns*eplus)^2/mm
// permittivity of free space epsil0 = 5.52636e+10 eplus^2/(MeV*mm)
//
public static final double mu0 = 4*pi*1.e-7 * Units.henry/Units.m;
public static final double epsilon0 = 1./(c_squared*mu0);
//
// electromagnetic coupling = 1.43996e-12 MeV*mm/(eplus^2)
//
public static final double elm_coupling = e_squared/(4*pi*epsilon0);
public static final double fine_structure_const = elm_coupling/hbarc;
public static final double classic_electr_radius = elm_coupling/electron_mass_c2;
public static final double electron_Compton_length = hbarc/electron_mass_c2;
public static final double Bohr_radius = electron_Compton_length/fine_structure_const;
public static final double alpha_rcl2 = fine_structure_const
*classic_electr_radius
*classic_electr_radius;
public static final double twopi_mc2_rcl2 = twopi*electron_mass_c2
*classic_electr_radius
*classic_electr_radius;
//
//
//
public static final double k_Boltzmann = 8.617385e-11 * Units.MeV/Units.kelvin;
//
//
//
public static final double STP_Temperature = 273.15*Units.kelvin;
public static final double STP_Pressure = 1.*Units.atmosphere;
public static final double kGasThreshold = 10.*Units.mg/Units.cm3;
//
//
//
public static final double universe_mean_density = 1.e-25*Units.g/Units.cm3;
/**
* Makes this class non instantiable, but still let's others inherit from it.
*/
protected PhysicalConstants() {}
}
| wikimedia/wikidata-query-blazegraph | blazegraph-colt/src/main/java/cern/clhep/PhysicalConstants.java | 1,578 | // h = 4.13566e-12 MeV*ns
| line_comment | nl | /*
Copyright (c) 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package cern.clhep;
/**
* High Energy Physics coherent Physical Constants.
* This class is a Java port of the <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Units/PhysicalConstants_h.html">C++ version</a> found in <a href="http://wwwinfo.cern.ch/asd/lhc++/clhep">CLHEP 1.4.0</a>, which in turn has been provided by Geant4 (a simulation toolkit for HEP).
* <p>
* For aliasing see {@link #physicalConstants}.
*
* @author [email protected]
* @version 1.0, 09/24/99
*/
public class PhysicalConstants extends Object {
/**
* Little trick to allow for "aliasing", that is, renaming this class.
* Normally you would write
* <pre>
* PhysicalConstants.twopi;
* PhysicalConstants.c_light;
* PhysicalConstants.h_Planck;
* </pre>
* Since this class has only static methods, but no instance methods
* you can also shorten the name "PhysicalConstants" to a name that better suits you, for example "P".
* <pre>
* PhysicalConstants P = PhysicalConstants.physicalConstants; // kind of "alias"
* P.twopi;
* P.c_light;
* P.h_Planck;
* </pre>
*/
public static final PhysicalConstants physicalConstants = new PhysicalConstants();
//
//
//
public static final double pi = Math.PI; //3.14159265358979323846;
public static final double twopi = 2*pi;
public static final double halfpi = pi/2;
public static final double pi2 = pi*pi;
//
//
//
public static final double Avogadro = 6.0221367e+23/Units.mole;
//
// c = 299.792458 mm/ns
// c^2 = 898.7404 (mm/ns)^2
//
public static final double c_light = 2.99792458e+8 * Units.m/Units.s;
public static final double c_squared = c_light * c_light;
//
// h <SUF>
// hbar = 6.58212e-13 MeV*ns
// hbarc = 197.32705e-12 MeV*mm
//
public static final double h_Planck = 6.6260755e-34 * Units.joule*Units.s;
public static final double hbar_Planck = h_Planck/twopi;
public static final double hbarc = hbar_Planck * c_light;
public static final double hbarc_squared = hbarc * hbarc;
//
//
//
public static final double electron_charge = - Units.eplus; // see SystemOfUnits.h
public static final double e_squared = Units.eplus * Units.eplus;
//
// amu_c2 - atomic equivalent mass unit
// amu - atomic mass unit
//
public static final double electron_mass_c2 = 0.51099906 * Units.MeV;
public static final double proton_mass_c2 = 938.27231 * Units.MeV;
public static final double neutron_mass_c2 = 939.56563 * Units.MeV;
public static final double amu_c2 = 931.49432 * Units.MeV;
public static final double amu = amu_c2/c_squared;
//
// permeability of free space mu0 = 2.01334e-16 Mev*(ns*eplus)^2/mm
// permittivity of free space epsil0 = 5.52636e+10 eplus^2/(MeV*mm)
//
public static final double mu0 = 4*pi*1.e-7 * Units.henry/Units.m;
public static final double epsilon0 = 1./(c_squared*mu0);
//
// electromagnetic coupling = 1.43996e-12 MeV*mm/(eplus^2)
//
public static final double elm_coupling = e_squared/(4*pi*epsilon0);
public static final double fine_structure_const = elm_coupling/hbarc;
public static final double classic_electr_radius = elm_coupling/electron_mass_c2;
public static final double electron_Compton_length = hbarc/electron_mass_c2;
public static final double Bohr_radius = electron_Compton_length/fine_structure_const;
public static final double alpha_rcl2 = fine_structure_const
*classic_electr_radius
*classic_electr_radius;
public static final double twopi_mc2_rcl2 = twopi*electron_mass_c2
*classic_electr_radius
*classic_electr_radius;
//
//
//
public static final double k_Boltzmann = 8.617385e-11 * Units.MeV/Units.kelvin;
//
//
//
public static final double STP_Temperature = 273.15*Units.kelvin;
public static final double STP_Pressure = 1.*Units.atmosphere;
public static final double kGasThreshold = 10.*Units.mg/Units.cm3;
//
//
//
public static final double universe_mean_density = 1.e-25*Units.g/Units.cm3;
/**
* Makes this class non instantiable, but still let's others inherit from it.
*/
protected PhysicalConstants() {}
}
|
22636_6 | package hoken.checker;
import hoken.HokenException;
import hoken.ast.DeclarationNode;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.Tree;
/**
* Een symbol table om tijdens de contextuele analyse bij te houden welke
* identifiers er in welke scope gedefinieerd zijn.
*
*/
public class SymbolTable {
/** De daadwerkelijke symbol table **/
private Map<String, Stack<DeclarationNode>> symtab;
/** Stack met lijsten van op dit niveau gedefinieerde identifiers **/
private Stack<List<String>> scopeStack;
/**
* Maakt een nieuwe en lege <code>SymbolTable</code> aan.
*/
public SymbolTable() {
this.symtab = new HashMap<String, Stack<DeclarationNode>>();
this.scopeStack = new Stack<List<String>>();
}
/**
* Opent een nieuwe scope.
*/
public void openScope() {
this.scopeStack.push(new ArrayList<String>());
}
/**
* Sluit de hoogste (huidige) scope.
*/
public void closeScope() {
for (String id : this.scopeStack.pop()) {
symtab.get(id).pop();
}
}
/**
* Voegt een nieuwe identifier toe aan de symbol table.
*
* @param id
* De naam van de identifier
* @param attr
* De <code>DeclarationNode</code> waar deze identifier wordt
* gedeclareerd
* @throws HokenException
* als de identifier al bestaat op dit niveau
*/
public void enter(String id, DeclarationNode attr) throws HokenException {
if (this.scopeStack.peek().contains(id)) {
throw new HokenException(attr, "Dubbele declaratie van (" + id
+ ")!");
} else {
if (!this.symtab.containsKey(id)) {
this.symtab.put(id, new Stack<DeclarationNode>());
}
this.symtab.get(id).push(attr);
this.scopeStack.peek().add(id);
}
}
/**
* Geeft op basis van een node uit de AST de node terug waarin deze
* identifier is gedeclareerd mits deze bestaat.
*
* @param tree
* De AST node waarvoor de declaratie moet worden opgezocht
* @return De declaratie voor de gegeven AST node
* @throws RecognitionException
* als de opgegeven node verwijst naar een niet bestaande
* identifier
*/
public DeclarationNode retrieve(Tree tree) throws HokenException {
try {
return this.symtab.get(tree.getText()).peek();
} catch (EmptyStackException | NullPointerException e) {
throw new HokenException(tree, "Onbekende identifier: ("
+ tree.getText() + ")");
}
}
}
| EerdeBruining/vertalerbouw | src/hoken/checker/SymbolTable.java | 762 | /**
* Voegt een nieuwe identifier toe aan de symbol table.
*
* @param id
* De naam van de identifier
* @param attr
* De <code>DeclarationNode</code> waar deze identifier wordt
* gedeclareerd
* @throws HokenException
* als de identifier al bestaat op dit niveau
*/ | block_comment | nl | package hoken.checker;
import hoken.HokenException;
import hoken.ast.DeclarationNode;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.Tree;
/**
* Een symbol table om tijdens de contextuele analyse bij te houden welke
* identifiers er in welke scope gedefinieerd zijn.
*
*/
public class SymbolTable {
/** De daadwerkelijke symbol table **/
private Map<String, Stack<DeclarationNode>> symtab;
/** Stack met lijsten van op dit niveau gedefinieerde identifiers **/
private Stack<List<String>> scopeStack;
/**
* Maakt een nieuwe en lege <code>SymbolTable</code> aan.
*/
public SymbolTable() {
this.symtab = new HashMap<String, Stack<DeclarationNode>>();
this.scopeStack = new Stack<List<String>>();
}
/**
* Opent een nieuwe scope.
*/
public void openScope() {
this.scopeStack.push(new ArrayList<String>());
}
/**
* Sluit de hoogste (huidige) scope.
*/
public void closeScope() {
for (String id : this.scopeStack.pop()) {
symtab.get(id).pop();
}
}
/**
* Voegt een nieuwe<SUF>*/
public void enter(String id, DeclarationNode attr) throws HokenException {
if (this.scopeStack.peek().contains(id)) {
throw new HokenException(attr, "Dubbele declaratie van (" + id
+ ")!");
} else {
if (!this.symtab.containsKey(id)) {
this.symtab.put(id, new Stack<DeclarationNode>());
}
this.symtab.get(id).push(attr);
this.scopeStack.peek().add(id);
}
}
/**
* Geeft op basis van een node uit de AST de node terug waarin deze
* identifier is gedeclareerd mits deze bestaat.
*
* @param tree
* De AST node waarvoor de declaratie moet worden opgezocht
* @return De declaratie voor de gegeven AST node
* @throws RecognitionException
* als de opgegeven node verwijst naar een niet bestaande
* identifier
*/
public DeclarationNode retrieve(Tree tree) throws HokenException {
try {
return this.symtab.get(tree.getText()).peek();
} catch (EmptyStackException | NullPointerException e) {
throw new HokenException(tree, "Onbekende identifier: ("
+ tree.getText() + ")");
}
}
}
|
21871_0 | /*
XQClient.java: een minimale XQuery processor die gebruikt maakt
van de Saxon internals en bestanden ophaalt van een treebank server.
XQClient.java [-h host] [-p port] <queryfile|{query}> <--stdin|filename(s)>
Geert Kloosterman <[email protected]>
Sat Dec 2 10:30:01 2006
*/
import net.sf.saxon.*;
import net.sf.saxon.query.*;
import net.sf.saxon.trans.XPathException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Properties;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.instruct.TerminationException;
import javax.xml.transform.OutputKeys;
/*
* This will break portability, but there seems to be
* no good alternative...
* There's some documentation on these packages on
* http://forum.java.sun.com/thread.jspa?threadID=514860&messageID=2451429
*/
import sun.misc.SignalHandler;
import sun.misc.Signal;
public class XQClient
{
static String name = "xqclient";
public static void main(String args[])
{
String queryFileName;
String host = "localhost";
int port = 44444;
boolean useStdin = false;
boolean textMode = false;
boolean omitDecl = false;
boolean latin1 = false;
/*
* We use the undocumented sun.misc.Signal and
* sun.misc.SignalHandler classes to trap SIGPIPE.
*
* This will work only with Sun JVMs.
* GJK Sun Dec 3 12:18:39 2006
*/
Signal.handle(new Signal("PIPE"), SignalHandler.SIG_DFL);
int i = 0;
while (i < args.length) {
if (args[i].charAt(0) == '-') {
// -h --host
// -p --port
// -s --stdin
// --omit-xml-declaration ???
// -t --text ???
if (args[i].equals("--host") || args[i].equals("-h")) {
i++;
if (args.length < i + 1) {
badUsage(name, "No host given");
}
host = args[i++];
} else if (args[i].equals("--port") || args[i].equals("-p")) {
i++;
if (args.length < i + 1) {
badUsage(name, "No host given");
}
port = Integer.parseInt(args[i++]);
} else if (args[i].equals("--stdin") || args[i].equals("-s")) {
useStdin = true;
i++;
} else if (args[i].equals("--text") || args[i].equals("-t")) {
textMode = true;
i++;
} else if (args[i].equals("--latin1") || args[i].equals("-l")) {
latin1 = true;
i++;
} else if (args[i].equals("--omit-xml-decl")) {
omitDecl = true;
i++;
} else {
badUsage(name, "Error: unsupported option \"" + args[i] + "\"!");
}
} else {
break;
}
}
if (args.length < i + 1) {
badUsage(name, "Error: no query file given!");
}
queryFileName = args[i++];
if (args.length < i + 1 && !useStdin) {
badUsage(name, "Error: no files to process!");
}
Configuration config = new Configuration();
StaticQueryContext staticContext = new StaticQueryContext(config);
DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
XQueryExpression exp = null;
// compileer de query
try {
if (queryFileName.startsWith("{") && queryFileName.endsWith("}")) {
// query is inline on the command line
String q = queryFileName.substring(1, queryFileName.length() - 1);
exp = staticContext.compileQuery(q);
} else {
InputStream queryStream = new FileInputStream(queryFileName);
staticContext.setBaseURI(new File(queryFileName).toURI().toString());
exp = staticContext.compileQuery(queryStream, null);
}
staticContext = exp.getStaticContext(); // the original staticContext is copied
} catch (XPathException err) { // this code taken from saxons Query.java
int line = -1;
String module = null;
if (err.getLocator() != null) {
line = err.getLocator().getLineNumber();
module = err.getLocator().getSystemId();
}
if (err.hasBeenReported()) {
quit("Failed to compile query", 2);
} else {
if (line == -1) {
System.err.println("Failed to compile query: " + err.getMessage());
} else {
System.err.println("Static error at line " + line + " of " + module + ':');
System.err.println(err.getMessage());
}
}
exp = null;
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
// pas 'm ergens op toe
Properties props = new Properties();
if (omitDecl)
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
if (textMode)
props.setProperty(OutputKeys.METHOD, "text");
if (latin1)
props.setProperty(OutputKeys.ENCODING, "iso-8859-1");
TreebankClient client = null;
try {
client = new TreebankClient(host, port);
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
if (useStdin) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
String fileName = "";
try {
while ((line = reader.readLine()) != null) {
fileName = line;
processFile(client, fileName, exp, props, staticContext, dynamicContext);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
} else {
String fileName = "";
for (int arg = i; arg < args.length; arg++) {
fileName = args[arg];
processFile(client, fileName, exp, props, staticContext, dynamicContext);
}
}
client.close();
}
protected static void processFile(TreebankClient client,
String fileName,
XQueryExpression exp,
Properties props,
StaticQueryContext staticContext,
DynamicQueryContext dynamicContext) {
try {
ByteArrayInputStream bs = null;
bs = client.getByteStream( fileName );
if (bs == null) {
System.err.println("Could not get data for \"" + fileName + "\", Skipping...");
return;
}
StreamSource ss = new StreamSource(bs);
ss.setSystemId(fileName);
DocumentInfo doc = staticContext.buildDocument(ss);
dynamicContext.setContextItem(doc);
exp.run(dynamicContext, new StreamResult(System.out), props);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} catch (TerminationException err) {
quit(err.getMessage(), 1);
} catch (XPathException err) {
// warn(name, "Query processing failed, skipping file: " + err.getMessage());
// The error message is already printed at a higher level
warn(name, "Query processing failed for \"" + fileName + "\", skipping...");
}
}
protected static void warn(String programName, String message) {
System.err.println(programName + ": Warning: " + message);
}
// taken from saxon
protected static void quit(String message, int code) {
System.err.println(message);
System.exit(code);
}
protected static void badUsage(String name, String message) {
if (!"".equals(message)) {
System.err.println(name + ": " + message);
}
//System.err.println(config.getProductTitle());
System.err.println("Usage: " + name + " [options] <queryfile|{query}> [filename(s)]");
System.err.println("\nOptions: ");
System.err.println(" -h, --host hostname host name from treebankserver (default localhost)");
System.err.println(" -p, --port port port number from treebankserver (default 44444)");
System.err.println(" -s, --stdin read file ids from stdin");
System.err.println(" -t, --text output only text nodes");
System.err.println(" -l, --latin1 set output encoding to iso-8859-1");
System.err.println(" --omit-xml-decl omit the xml declaration");
if ("".equals(message)) {
System.exit(0);
} else {
System.exit(2);
}
}
}
| rug-compling/Alpino | TreebankTools/XQueryTools/xqclient/XQClient.java | 2,361 | /*
XQClient.java: een minimale XQuery processor die gebruikt maakt
van de Saxon internals en bestanden ophaalt van een treebank server.
XQClient.java [-h host] [-p port] <queryfile|{query}> <--stdin|filename(s)>
Geert Kloosterman <[email protected]>
Sat Dec 2 10:30:01 2006
*/ | block_comment | nl | /*
XQClient.java: een minimale<SUF>*/
import net.sf.saxon.*;
import net.sf.saxon.query.*;
import net.sf.saxon.trans.XPathException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Properties;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.instruct.TerminationException;
import javax.xml.transform.OutputKeys;
/*
* This will break portability, but there seems to be
* no good alternative...
* There's some documentation on these packages on
* http://forum.java.sun.com/thread.jspa?threadID=514860&messageID=2451429
*/
import sun.misc.SignalHandler;
import sun.misc.Signal;
public class XQClient
{
static String name = "xqclient";
public static void main(String args[])
{
String queryFileName;
String host = "localhost";
int port = 44444;
boolean useStdin = false;
boolean textMode = false;
boolean omitDecl = false;
boolean latin1 = false;
/*
* We use the undocumented sun.misc.Signal and
* sun.misc.SignalHandler classes to trap SIGPIPE.
*
* This will work only with Sun JVMs.
* GJK Sun Dec 3 12:18:39 2006
*/
Signal.handle(new Signal("PIPE"), SignalHandler.SIG_DFL);
int i = 0;
while (i < args.length) {
if (args[i].charAt(0) == '-') {
// -h --host
// -p --port
// -s --stdin
// --omit-xml-declaration ???
// -t --text ???
if (args[i].equals("--host") || args[i].equals("-h")) {
i++;
if (args.length < i + 1) {
badUsage(name, "No host given");
}
host = args[i++];
} else if (args[i].equals("--port") || args[i].equals("-p")) {
i++;
if (args.length < i + 1) {
badUsage(name, "No host given");
}
port = Integer.parseInt(args[i++]);
} else if (args[i].equals("--stdin") || args[i].equals("-s")) {
useStdin = true;
i++;
} else if (args[i].equals("--text") || args[i].equals("-t")) {
textMode = true;
i++;
} else if (args[i].equals("--latin1") || args[i].equals("-l")) {
latin1 = true;
i++;
} else if (args[i].equals("--omit-xml-decl")) {
omitDecl = true;
i++;
} else {
badUsage(name, "Error: unsupported option \"" + args[i] + "\"!");
}
} else {
break;
}
}
if (args.length < i + 1) {
badUsage(name, "Error: no query file given!");
}
queryFileName = args[i++];
if (args.length < i + 1 && !useStdin) {
badUsage(name, "Error: no files to process!");
}
Configuration config = new Configuration();
StaticQueryContext staticContext = new StaticQueryContext(config);
DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
XQueryExpression exp = null;
// compileer de query
try {
if (queryFileName.startsWith("{") && queryFileName.endsWith("}")) {
// query is inline on the command line
String q = queryFileName.substring(1, queryFileName.length() - 1);
exp = staticContext.compileQuery(q);
} else {
InputStream queryStream = new FileInputStream(queryFileName);
staticContext.setBaseURI(new File(queryFileName).toURI().toString());
exp = staticContext.compileQuery(queryStream, null);
}
staticContext = exp.getStaticContext(); // the original staticContext is copied
} catch (XPathException err) { // this code taken from saxons Query.java
int line = -1;
String module = null;
if (err.getLocator() != null) {
line = err.getLocator().getLineNumber();
module = err.getLocator().getSystemId();
}
if (err.hasBeenReported()) {
quit("Failed to compile query", 2);
} else {
if (line == -1) {
System.err.println("Failed to compile query: " + err.getMessage());
} else {
System.err.println("Static error at line " + line + " of " + module + ':');
System.err.println(err.getMessage());
}
}
exp = null;
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
// pas 'm ergens op toe
Properties props = new Properties();
if (omitDecl)
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
if (textMode)
props.setProperty(OutputKeys.METHOD, "text");
if (latin1)
props.setProperty(OutputKeys.ENCODING, "iso-8859-1");
TreebankClient client = null;
try {
client = new TreebankClient(host, port);
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
if (useStdin) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
String fileName = "";
try {
while ((line = reader.readLine()) != null) {
fileName = line;
processFile(client, fileName, exp, props, staticContext, dynamicContext);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
} else {
String fileName = "";
for (int arg = i; arg < args.length; arg++) {
fileName = args[arg];
processFile(client, fileName, exp, props, staticContext, dynamicContext);
}
}
client.close();
}
protected static void processFile(TreebankClient client,
String fileName,
XQueryExpression exp,
Properties props,
StaticQueryContext staticContext,
DynamicQueryContext dynamicContext) {
try {
ByteArrayInputStream bs = null;
bs = client.getByteStream( fileName );
if (bs == null) {
System.err.println("Could not get data for \"" + fileName + "\", Skipping...");
return;
}
StreamSource ss = new StreamSource(bs);
ss.setSystemId(fileName);
DocumentInfo doc = staticContext.buildDocument(ss);
dynamicContext.setContextItem(doc);
exp.run(dynamicContext, new StreamResult(System.out), props);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} catch (TerminationException err) {
quit(err.getMessage(), 1);
} catch (XPathException err) {
// warn(name, "Query processing failed, skipping file: " + err.getMessage());
// The error message is already printed at a higher level
warn(name, "Query processing failed for \"" + fileName + "\", skipping...");
}
}
protected static void warn(String programName, String message) {
System.err.println(programName + ": Warning: " + message);
}
// taken from saxon
protected static void quit(String message, int code) {
System.err.println(message);
System.exit(code);
}
protected static void badUsage(String name, String message) {
if (!"".equals(message)) {
System.err.println(name + ": " + message);
}
//System.err.println(config.getProductTitle());
System.err.println("Usage: " + name + " [options] <queryfile|{query}> [filename(s)]");
System.err.println("\nOptions: ");
System.err.println(" -h, --host hostname host name from treebankserver (default localhost)");
System.err.println(" -p, --port port port number from treebankserver (default 44444)");
System.err.println(" -s, --stdin read file ids from stdin");
System.err.println(" -t, --text output only text nodes");
System.err.println(" -l, --latin1 set output encoding to iso-8859-1");
System.err.println(" --omit-xml-decl omit the xml declaration");
if ("".equals(message)) {
System.exit(0);
} else {
System.exit(2);
}
}
}
|
4782_12 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class World4 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class World4 extends World
{
private CollisionEngine ce;
/**
* Constructor for objects of class World4.
*
*/
public World4()
{
super(1000, 800, 1,false);
this.setBackground("bg.png");
int[][] map = {
{125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125},
{125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,142,-1,41,-1,-1,-1,41,-1,142,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,142,-1,41,-1,-1,41,-1,-1,-1,25,-1,141,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,25,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,25,-1,142,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,25,-1,145,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,144,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,147,-1,-1,-1,-1,-1,-1,-1,-1,-1,146,145,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,125,125},
{125,125,-1,-1,143,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,125,125},
{125,125,138,138,138,138,138,138,138,311,311,311,311,311,311,311,311,311,311,125,311,311,311,311,311,311,311,311,311,125,311,311,311,311,311,311,311,311,311,311,311,311,311,311,311,138,138,138,125,125},
{125,125,125,125,125,125,125,125,125,312,312,312,312,312,312,312,312,312,312,125,312,312,312,312,312,312,312,312,312,125,312,312,312,312,312,312,312,312,312,312,312,312,312,312,312,125,125,125,125,125},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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, 3300, 650);
//addObject(new Enemy(), 1170, 410);
addObject(new Health(), 100, 100);
addObject(new Hud(), 100, 150);
// 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);
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-JeffreyBoone | World4.java | 2,353 | // 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 World4 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class World4 extends World
{
private CollisionEngine ce;
/**
* Constructor for objects of class World4.
*
*/
public World4()
{
super(1000, 800, 1,false);
this.setBackground("bg.png");
int[][] map = {
{125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125},
{125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,41,-1,142,-1,41,-1,-1,-1,41,-1,142,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,142,-1,41,-1,-1,41,-1,-1,-1,25,-1,141,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,25,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,25,-1,142,-1,41,-1,-1,-1,41,-1,-1,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,41,-1,-1,-1,25,-1,145,-1,41,-1,-1,-1,-1,125,125},
{125,125,-1,-1,144,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,147,-1,-1,-1,-1,-1,-1,-1,-1,-1,146,145,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,125,125},
{125,125,-1,-1,143,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,125,125},
{125,125,138,138,138,138,138,138,138,311,311,311,311,311,311,311,311,311,311,125,311,311,311,311,311,311,311,311,311,125,311,311,311,311,311,311,311,311,311,311,311,311,311,311,311,138,138,138,125,125},
{125,125,125,125,125,125,125,125,125,312,312,312,312,312,312,312,312,312,312,125,312,312,312,312,312,312,312,312,312,125,312,312,312,312,312,312,312,312,312,312,312,312,312,312,312,125,125,125,125,125},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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, 3300, 650);
//addObject(new Enemy(), 1170, 410);
addObject(new Health(), 100, 100);
addObject(new Hud(), 100, 150);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// 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();
}
}
|
7577_6 | package UI;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JPanel;
import java.lang.Integer;
import domain.Cantus;
import domain.CantusVerzameling;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.util.ShapeUtilities;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import static java.util.Collections.frequency;
import static org.jfree.util.SortOrder.DESCENDING;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Shape;
public class MainPane extends JFrame implements Observer{
private int semestercount = 1;
private int summercount = 1;
private int wintercount = 1;
private static final long serialVersionUID = -9090407129402452701L;
private boolean plaatsFlag;//true als er plaatsen in de file staan, false anders
private Controller controller;
private JPanel panel;
private JSplitPane splitPaneH;
private JScrollPane tabel;
private ChartPanel vereniggingenchartpanel;
private ChartPanel plaatsenchartpanel;
public MainPane(Controller controller)
{
System.out.println("draw mainpain");
this.controller = controller;
setTitle("Grafiekjes");
}
//teken al de charts en tabel.
public void drawCompleet(CantusVerzameling CV){
// SETUP
JPanel jpanel = new JPanel();
controller.screen.mainFrame.add(jpanel);
GridBagLayout g = new GridBagLayout();
jpanel.setLayout(g);
//Get the charts and table
this.plaatsFlag=containsNotNull(CV.getPlaatsen());
tabel = makeScrollTable(CV.getCantussen());
JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen());
vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE);
vereniggingenchart.setTitle("Verenigingen");
this.vereniggingenchartpanel = new ChartPanel(vereniggingenchart);
JFreeChart plaatsenchart = makePieChart(CV.getPlaatsen());
this.plaatsenchartpanel = new ChartPanel(plaatsenchart);
if(plaatsFlag){
plaatsenchart.setTitle("Locaties");
plaatsenchart.getPlot().setBackgroundPaint(Color.WHITE);
}
ChartPanel timechart = new ChartPanel(makeTimeLine(CV.getData()));
//Add the charts to the panel in the right column/rows met de juiste verhoudingen.
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0; c.gridwidth=2; c.weightx=0.7; c.weighty=0.8;
c.fill = GridBagConstraints.BOTH;
jpanel.add(timechart,c);
c=new GridBagConstraints();
c.gridx=0; c.gridy=1; c.gridheight=1;c.weightx=0.35; c.weighty=.2;
if(!plaatsFlag)
c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;
jpanel.add(vereniggingenchartpanel,c);
if(plaatsFlag){
c=new GridBagConstraints();
c.gridx=1; c.gridy=1; c.gridheight=1;c.weightx=.35; c.weighty=.2;
c.fill = GridBagConstraints.BOTH;
jpanel.add(plaatsenchartpanel,c);
}
c=new GridBagConstraints();
c.gridx=2; c.gridy=0; c.weightx=1; c.weighty=1; c.gridheight=2; c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;//.VERTICAL;
//tabel.setPreferredSize(new Dimension(tabel.getPreferredSize().width,this.getPreferredSize().height*100));
jpanel.add(tabel,c);
JButton plus = new JButton("+");
c=new GridBagConstraints();
c.gridx=2; c.gridy=2; c.weightx=.01; c.weighty=.01;
c.anchor= GridBagConstraints.SOUTHEAST;
jpanel.add(plus,c);
JButton minus = new JButton("-");
c=new GridBagConstraints();
c.gridx=3; c.gridy=2; c.weightx=.01; c.weighty=.01;
c.anchor= GridBagConstraints.SOUTHEAST;
jpanel.add(minus,c);
JTable t = (JTable) tabel.getViewport().getView();
//update als er iets word aangeduid in de tabel
t.getSelectionModel().addListSelectionListener(e -> {
updateRows(t.getSelectedRows(), t,timechart,vereniggingenchartpanel,plaatsenchartpanel);
});
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTable actiontabel = (JTable) tabel.getViewport().getView();
System.out.println(getRows(actiontabel.getSelectedRows(),actiontabel).toString());
CV.deleteCantussen(getRows(actiontabel.getSelectedRows(),actiontabel));
tabel.setViewport(makeScrollTable(CV.getCantussen()).getViewport());
JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen());
vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE);
vereniggingenchart.setTitle("Verenigingen");
vereniggingenchartpanel.setChart(vereniggingenchart);
}
});
controller.screen.mainFrame.setVisible(true);
}
public ArrayList<String> getRows(int[] rows, JTable t){
StringBuilder s = new StringBuilder();
ArrayList<String> a = new ArrayList<>();
for(int i: rows){
s = new StringBuilder();
for(int j = 0; j<t.getColumnCount();j++){
s.append(t.getValueAt(i,j).toString()+",");
}
a.add(s.toString());
}
return(a);
}
//update de charts aan de hand van de rijen die aangeduid zijn in de tabel
public void updateRows(int[] rows, JTable t, ChartPanel chartt,ChartPanel chartv, ChartPanel chartp){
//aanduiden in timechart
JFreeChart c = chartt.getChart();
XYPlot xyp = c.getXYPlot();
XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) xyp.getRenderer();
TimeSeriesCollection tsc = (TimeSeriesCollection) xyp.getDataset();
if(tsc.getSeries("invisible")==null){
tsc.addSeries( new TimeSeries("invisible"));
Shape shape = new java.awt.geom.Ellipse2D.Double(-2.0, -2.0, 5.0, 5.0);
r.setSeriesShape(tsc.getSeriesIndex("invisible"), shape);
r.setSeriesShapesVisible(tsc.getSeriesIndex("invisible"),true);
r.setSeriesLinesVisible(tsc.getSeriesIndex("invisible"), false);
r.setSeriesVisibleInLegend(tsc.getSeriesIndex("invisible"),false );
r.setSeriesPaint(tsc.getSeriesIndex("invisible"), Color.black);
}
TimeSeries s = tsc.getSeries("invisible");
s.clear();
HashSet<String> pset = new HashSet<>();
HashSet<String> vset = new HashSet<>();
for(int row: rows){
for(int i=0; i<tsc.getSeriesCount();i++){
TimeSeries ts = tsc.getSeries(i);
for(int j=0; j<ts.getItemCount();j++){
if(samedate(t.getValueAt(row,0).toString(), (Day) ts.getDataItem(j).getPeriod()))
s.addOrUpdate(ts.getDataItem(j).getPeriod(), ts.getDataItem(j).getValue());
}
}
//voorbereidend werk voor de piecharts te exploden
if(plaatsFlag)
pset.add(t.getValueAt(row,3).toString());
vset.add(t.getValueAt(row,2).toString());
}
//explode de piecharts
for(Object o: ((PiePlot) chartv.getChart().getPlot()).getDataset().getKeys()){
String str = o.toString();
if(vset.contains(str))
((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,.33);
else if(str!=null)
((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,0);
}
if(plaatsFlag){
for(Object o: ((PiePlot) chartp.getChart().getPlot()).getDataset().getKeys()){
String str = o.toString();
if(pset.contains(str))
((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,.33);
else if(str!=null)
((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,0);
}
}
}
//kijk na of een string die uit de tabel komt dezelfde dag voorstelt als een dag die uit de timechart is gehaald.
public boolean samedate(String s, Day d){
String[] parts = s.split("/");
Day sd = new Day(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),Integer.parseInt(parts[2]));
return(sd.equals(d));
}
//draw de cantusTable, wordt momenteel niet meer gebruikt, kan later terug nodig zijn.
public void drawCantusTable(List<Cantus> cantussen){
JScrollPane jtable = makeScrollTable(cantussen);
panel.add(jtable);
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//construeer de scrollTable met een tabel van alle cantussen
public JScrollPane makeScrollTable(List<Cantus> cantussen){
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Datum");
model.addColumn("Cantus");
model.addColumn("Vereniging");
if(plaatsFlag)
model.addColumn("plaats");
cantussen.sort(Cantus::compareTo);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
if(plaatsFlag){
for(Cantus cantus : cantussen){
Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging,cantus.plaats};
model.addRow(array);
}
} else {
for(Cantus cantus : cantussen){
Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging};
model.addRow(array);
}
}
JTable table = new JTable(model);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
return new JScrollPane(table);
}
//drawt een pieChart; wordt momenteel niet meer gebruikt, kan later terug nodig zijn.
//@Override
public void drawPieChart(List<String> dataset) {
JFreeChart chart = makePieChart(dataset);
splitPaneH.setLeftComponent(new ChartPanel(chart));
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//gaat na of een lijst een niet null element bevat. nodig om te kijken of er plaatsen zijn ingegeven.
private boolean containsNotNull(List<String> l){
for(String s: l)
if(s != null && s.length()>0)
return true;
return false;
}
//construeer een piechart van een dataset. wordt gebruikt om de verenigingen en de plaatsen in een piechart te zetten.
public JFreeChart makePieChart(List<String> dataset){
if(containsNotNull(dataset)){
dataset.sort(String::compareTo);
} else {
return null;
}
DefaultPieDataset ds = new DefaultPieDataset();
for (String s: dataset){
if(s != null && s.length()>0) {
//System.out.println("string: " + s);
if (ds.getKeys().contains(s)) {
//System.out.println(ds.getValue(s));
ds.setValue(s, ds.getValue(s).intValue() + 1);
} else
ds.setValue(s, 1);
}
}
ds.sortByValues(DESCENDING);
int count = 0;
for(Object o: ds.getKeys()){
if(ds.getValue((Comparable) o).intValue()<=dataset.size()/100){
count++;
ds.remove((Comparable) o);
}
}
if (count!=0)
ds.setValue("Overige",count);
return ChartFactory.createPieChart(
"TAAAAAART", // chart title
ds, // data
true, // include legend
true,
false);
}
//drawt de timeline; wordt momenteel niet gebruikt, kan later terug nodig zijn.
@Override
public void drawTimeline(List<Calendar> dataset){
splitPaneH.setRightComponent(new ChartPanel(makeTimeLine(dataset)));
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//construeert de timeline
public JFreeChart makeTimeLine(List<Calendar> dataset){
dataset.sort(Calendar::compareTo);
genCumul(dataset,7);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Waar-liep-het-fout-lijn", // Chart
"Date", // X-Axis Label
"cantus", // Y-Axis Label
constructTSC(dataset));
XYPlot plot = (XYPlot)chart.getPlot();
plot.setBackgroundPaint(new Color(255,255,255));
plot.setDomainGridlinePaint(new Color(155,155,155));
plot.setRangeGridlinePaint(new Color(155,155,155));
for (int i = 0; i < plot.getSeriesCount(); i++) {
plot.getRenderer().setSeriesStroke(i,new BasicStroke(2.0f));
}
plot.setDataset(1, new TimeSeriesCollection(genCumul(dataset,7)));
plot.setDataset(2, new TimeSeriesCollection(genCumul(dataset,31)));
// Renderer voor cumul7
XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(true,false);
r1.setPaint(new Color(0,0,255));
// Renderer voor cumul31
XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(true,false);
r2.setPaint(new Color(0,255,0));
plot.setRenderer(1,r1);
plot.setRenderer(2,r2);
return chart;
}
//construeer de timeseriescollection van de lijst van data.
private TimeSeriesCollection constructTSC(List<Calendar> dataset){
TimeSeriesCollection tsc = new TimeSeriesCollection();
TimeSeries series = new TimeSeries("Series1");
int i = 0;
Calendar previous,c;
while(i < dataset.size()){
c = dataset.get(i);
Period p = getPeriod(c);
if(i == 0){
series.setKey(p.name().toLowerCase() + "1");
addCount(p);
}
else {
previous = dataset.get(i-1);
if (diffPeriod(previous,c)) {
series.addOrUpdate(new Day(c.getTime()),i+1);
tsc.addSeries(series);
series = new TimeSeries(p.name().toLowerCase() + getCount(p));
addCount(p);
}
}
series.addOrUpdate(new Day(c.getTime()),i+1);
i++;
}
tsc.addSeries(series);
return tsc;
}
//genereer de cumulatieve lijn voor de laatste %i dagen.
private TimeSeries genCumul(List<Calendar> ds, int i){
TimeSeries series = new TimeSeries("Cumul" + i);
Calendar start = (Calendar) ds.get(0).clone();
Calendar end = (Calendar) ds.get(ds.size()-1).clone();
Calendar preStart= (Calendar) start.clone();
preStart.add(Calendar.DATE,-i);
int count=0;
while(start.before(end)){
if(ds.contains(preStart))
count-=frequency(ds,preStart);
if(ds.contains(start)){
count+=frequency(ds,start);
}
//System.out.println(start.getTime()+ " cumul is " + count);
series.addOrUpdate(new Day(start.getTime()),count);
start.add(Calendar.DATE,1);
preStart.add(Calendar.DATE,1);
}
return series;
}
//enum van mogelijke periodes
public enum Period {
SEMESTER, SUMMER, WINTER
}
//kijk na in welke periode een dag valt.
private Period getPeriod(Calendar c){
Calendar c2 = getStartYear(c);
Period p;
if (daysBetween(c2,c) < 89){
p = Period.SEMESTER;
}else if (daysBetween(c2,c) < 140){
p = Period.WINTER;
}else if (daysBetween(c2,c) < 243){
p = Period.SEMESTER;
}else {
p = Period.SUMMER;
}
return p;
}
/*
berekend de start van het academiejaar voor datum c
de eerste maandag na de 20ste september die c voorafgaat
*/
private Calendar getStartYear(Calendar c){
Calendar c2 = Calendar.getInstance();
c2.set(c.get(Calendar.YEAR),Calendar.SEPTEMBER,20);
//========================System.out.println(df.format(c2.getTime()));
nextMonday(c2);
if(c.before(c2)) {
c2.set(c.get(Calendar.YEAR) - 1, Calendar.SEPTEMBER, 20);
nextMonday(c2);
}
return c2;
}
//vormt een dag om naar de eerstvolgende maandag.
private void nextMonday(Calendar c){
while(c.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY)
c.add(Calendar.DATE,1);
}
//geef het aantal dagen tussen 2 dagen terug
private static long daysBetween(Calendar startDate, Calendar endDate) {
long end = endDate.getTimeInMillis();
long start = startDate.getTimeInMillis();
return (end - start)/(60*60*24*1000) +1;
}
/*
kijkt na of first en second in een verschillende periode liggen:
valt first voor de start van het academiejaar van second?
semester 1: start academiejaar .. 89 dagen later
winter: 89dagen na start .. 140 dagen na start
semester 2: 140 dagen na start .. 191 dagen na start
zomer: 191 dagen na start .. volgende academiejaar.
*/
private boolean diffPeriod(Calendar first, Calendar second){
Calendar start = getStartYear(second);
long d1 = daysBetween(start,first);
long d2 = daysBetween(start,second);
return (!first.after(start) ||
(d1<89 && d2 >= 89) ||
(d1<140 && d2 >= 140)||
(d1<243 && d2 >= 243));
}
//geef aan de hoeveelste keer dat een periode gebruikt is.
private int getCount(Period p){
if(p.equals(Period.SEMESTER))
return semestercount;
if(p.equals(Period.SUMMER))
return summercount;
return wintercount;
}
//tel 1 op bij de bijhorende periodcount van de period
private void addCount(Period p){
if(p.equals(Period.SEMESTER)) {
//System.out.println("add semester count");
semestercount++;
}
if(p.equals(Period.SUMMER))
summercount++;
if(p.equals(Period.WINTER))
wintercount++;
}
}
| DenisBlondeel/CantusCalulator | src/UI/MainPane.java | 5,586 | //update de charts aan de hand van de rijen die aangeduid zijn in de tabel
| line_comment | nl | package UI;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JPanel;
import java.lang.Integer;
import domain.Cantus;
import domain.CantusVerzameling;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.util.ShapeUtilities;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import static java.util.Collections.frequency;
import static org.jfree.util.SortOrder.DESCENDING;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Shape;
public class MainPane extends JFrame implements Observer{
private int semestercount = 1;
private int summercount = 1;
private int wintercount = 1;
private static final long serialVersionUID = -9090407129402452701L;
private boolean plaatsFlag;//true als er plaatsen in de file staan, false anders
private Controller controller;
private JPanel panel;
private JSplitPane splitPaneH;
private JScrollPane tabel;
private ChartPanel vereniggingenchartpanel;
private ChartPanel plaatsenchartpanel;
public MainPane(Controller controller)
{
System.out.println("draw mainpain");
this.controller = controller;
setTitle("Grafiekjes");
}
//teken al de charts en tabel.
public void drawCompleet(CantusVerzameling CV){
// SETUP
JPanel jpanel = new JPanel();
controller.screen.mainFrame.add(jpanel);
GridBagLayout g = new GridBagLayout();
jpanel.setLayout(g);
//Get the charts and table
this.plaatsFlag=containsNotNull(CV.getPlaatsen());
tabel = makeScrollTable(CV.getCantussen());
JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen());
vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE);
vereniggingenchart.setTitle("Verenigingen");
this.vereniggingenchartpanel = new ChartPanel(vereniggingenchart);
JFreeChart plaatsenchart = makePieChart(CV.getPlaatsen());
this.plaatsenchartpanel = new ChartPanel(plaatsenchart);
if(plaatsFlag){
plaatsenchart.setTitle("Locaties");
plaatsenchart.getPlot().setBackgroundPaint(Color.WHITE);
}
ChartPanel timechart = new ChartPanel(makeTimeLine(CV.getData()));
//Add the charts to the panel in the right column/rows met de juiste verhoudingen.
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0; c.gridwidth=2; c.weightx=0.7; c.weighty=0.8;
c.fill = GridBagConstraints.BOTH;
jpanel.add(timechart,c);
c=new GridBagConstraints();
c.gridx=0; c.gridy=1; c.gridheight=1;c.weightx=0.35; c.weighty=.2;
if(!plaatsFlag)
c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;
jpanel.add(vereniggingenchartpanel,c);
if(plaatsFlag){
c=new GridBagConstraints();
c.gridx=1; c.gridy=1; c.gridheight=1;c.weightx=.35; c.weighty=.2;
c.fill = GridBagConstraints.BOTH;
jpanel.add(plaatsenchartpanel,c);
}
c=new GridBagConstraints();
c.gridx=2; c.gridy=0; c.weightx=1; c.weighty=1; c.gridheight=2; c.gridwidth=2;
c.fill = GridBagConstraints.BOTH;//.VERTICAL;
//tabel.setPreferredSize(new Dimension(tabel.getPreferredSize().width,this.getPreferredSize().height*100));
jpanel.add(tabel,c);
JButton plus = new JButton("+");
c=new GridBagConstraints();
c.gridx=2; c.gridy=2; c.weightx=.01; c.weighty=.01;
c.anchor= GridBagConstraints.SOUTHEAST;
jpanel.add(plus,c);
JButton minus = new JButton("-");
c=new GridBagConstraints();
c.gridx=3; c.gridy=2; c.weightx=.01; c.weighty=.01;
c.anchor= GridBagConstraints.SOUTHEAST;
jpanel.add(minus,c);
JTable t = (JTable) tabel.getViewport().getView();
//update als er iets word aangeduid in de tabel
t.getSelectionModel().addListSelectionListener(e -> {
updateRows(t.getSelectedRows(), t,timechart,vereniggingenchartpanel,plaatsenchartpanel);
});
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTable actiontabel = (JTable) tabel.getViewport().getView();
System.out.println(getRows(actiontabel.getSelectedRows(),actiontabel).toString());
CV.deleteCantussen(getRows(actiontabel.getSelectedRows(),actiontabel));
tabel.setViewport(makeScrollTable(CV.getCantussen()).getViewport());
JFreeChart vereniggingenchart = makePieChart(CV.getVerenigingen());
vereniggingenchart.getPlot().setBackgroundPaint(Color.WHITE);
vereniggingenchart.setTitle("Verenigingen");
vereniggingenchartpanel.setChart(vereniggingenchart);
}
});
controller.screen.mainFrame.setVisible(true);
}
public ArrayList<String> getRows(int[] rows, JTable t){
StringBuilder s = new StringBuilder();
ArrayList<String> a = new ArrayList<>();
for(int i: rows){
s = new StringBuilder();
for(int j = 0; j<t.getColumnCount();j++){
s.append(t.getValueAt(i,j).toString()+",");
}
a.add(s.toString());
}
return(a);
}
//update de<SUF>
public void updateRows(int[] rows, JTable t, ChartPanel chartt,ChartPanel chartv, ChartPanel chartp){
//aanduiden in timechart
JFreeChart c = chartt.getChart();
XYPlot xyp = c.getXYPlot();
XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) xyp.getRenderer();
TimeSeriesCollection tsc = (TimeSeriesCollection) xyp.getDataset();
if(tsc.getSeries("invisible")==null){
tsc.addSeries( new TimeSeries("invisible"));
Shape shape = new java.awt.geom.Ellipse2D.Double(-2.0, -2.0, 5.0, 5.0);
r.setSeriesShape(tsc.getSeriesIndex("invisible"), shape);
r.setSeriesShapesVisible(tsc.getSeriesIndex("invisible"),true);
r.setSeriesLinesVisible(tsc.getSeriesIndex("invisible"), false);
r.setSeriesVisibleInLegend(tsc.getSeriesIndex("invisible"),false );
r.setSeriesPaint(tsc.getSeriesIndex("invisible"), Color.black);
}
TimeSeries s = tsc.getSeries("invisible");
s.clear();
HashSet<String> pset = new HashSet<>();
HashSet<String> vset = new HashSet<>();
for(int row: rows){
for(int i=0; i<tsc.getSeriesCount();i++){
TimeSeries ts = tsc.getSeries(i);
for(int j=0; j<ts.getItemCount();j++){
if(samedate(t.getValueAt(row,0).toString(), (Day) ts.getDataItem(j).getPeriod()))
s.addOrUpdate(ts.getDataItem(j).getPeriod(), ts.getDataItem(j).getValue());
}
}
//voorbereidend werk voor de piecharts te exploden
if(plaatsFlag)
pset.add(t.getValueAt(row,3).toString());
vset.add(t.getValueAt(row,2).toString());
}
//explode de piecharts
for(Object o: ((PiePlot) chartv.getChart().getPlot()).getDataset().getKeys()){
String str = o.toString();
if(vset.contains(str))
((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,.33);
else if(str!=null)
((PiePlot) chartv.getChart().getPlot()).setExplodePercent(str,0);
}
if(plaatsFlag){
for(Object o: ((PiePlot) chartp.getChart().getPlot()).getDataset().getKeys()){
String str = o.toString();
if(pset.contains(str))
((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,.33);
else if(str!=null)
((PiePlot) chartp.getChart().getPlot()).setExplodePercent(str,0);
}
}
}
//kijk na of een string die uit de tabel komt dezelfde dag voorstelt als een dag die uit de timechart is gehaald.
public boolean samedate(String s, Day d){
String[] parts = s.split("/");
Day sd = new Day(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]),Integer.parseInt(parts[2]));
return(sd.equals(d));
}
//draw de cantusTable, wordt momenteel niet meer gebruikt, kan later terug nodig zijn.
public void drawCantusTable(List<Cantus> cantussen){
JScrollPane jtable = makeScrollTable(cantussen);
panel.add(jtable);
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//construeer de scrollTable met een tabel van alle cantussen
public JScrollPane makeScrollTable(List<Cantus> cantussen){
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Datum");
model.addColumn("Cantus");
model.addColumn("Vereniging");
if(plaatsFlag)
model.addColumn("plaats");
cantussen.sort(Cantus::compareTo);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
if(plaatsFlag){
for(Cantus cantus : cantussen){
Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging,cantus.plaats};
model.addRow(array);
}
} else {
for(Cantus cantus : cantussen){
Object[] array = {df.format(cantus.datum.getTime()), cantus.naam, cantus.vereniging};
model.addRow(array);
}
}
JTable table = new JTable(model);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
return new JScrollPane(table);
}
//drawt een pieChart; wordt momenteel niet meer gebruikt, kan later terug nodig zijn.
//@Override
public void drawPieChart(List<String> dataset) {
JFreeChart chart = makePieChart(dataset);
splitPaneH.setLeftComponent(new ChartPanel(chart));
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//gaat na of een lijst een niet null element bevat. nodig om te kijken of er plaatsen zijn ingegeven.
private boolean containsNotNull(List<String> l){
for(String s: l)
if(s != null && s.length()>0)
return true;
return false;
}
//construeer een piechart van een dataset. wordt gebruikt om de verenigingen en de plaatsen in een piechart te zetten.
public JFreeChart makePieChart(List<String> dataset){
if(containsNotNull(dataset)){
dataset.sort(String::compareTo);
} else {
return null;
}
DefaultPieDataset ds = new DefaultPieDataset();
for (String s: dataset){
if(s != null && s.length()>0) {
//System.out.println("string: " + s);
if (ds.getKeys().contains(s)) {
//System.out.println(ds.getValue(s));
ds.setValue(s, ds.getValue(s).intValue() + 1);
} else
ds.setValue(s, 1);
}
}
ds.sortByValues(DESCENDING);
int count = 0;
for(Object o: ds.getKeys()){
if(ds.getValue((Comparable) o).intValue()<=dataset.size()/100){
count++;
ds.remove((Comparable) o);
}
}
if (count!=0)
ds.setValue("Overige",count);
return ChartFactory.createPieChart(
"TAAAAAART", // chart title
ds, // data
true, // include legend
true,
false);
}
//drawt de timeline; wordt momenteel niet gebruikt, kan later terug nodig zijn.
@Override
public void drawTimeline(List<Calendar> dataset){
splitPaneH.setRightComponent(new ChartPanel(makeTimeLine(dataset)));
panel.setVisible(true);
this.pack();
this.setVisible(true);
}
//construeert de timeline
public JFreeChart makeTimeLine(List<Calendar> dataset){
dataset.sort(Calendar::compareTo);
genCumul(dataset,7);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Waar-liep-het-fout-lijn", // Chart
"Date", // X-Axis Label
"cantus", // Y-Axis Label
constructTSC(dataset));
XYPlot plot = (XYPlot)chart.getPlot();
plot.setBackgroundPaint(new Color(255,255,255));
plot.setDomainGridlinePaint(new Color(155,155,155));
plot.setRangeGridlinePaint(new Color(155,155,155));
for (int i = 0; i < plot.getSeriesCount(); i++) {
plot.getRenderer().setSeriesStroke(i,new BasicStroke(2.0f));
}
plot.setDataset(1, new TimeSeriesCollection(genCumul(dataset,7)));
plot.setDataset(2, new TimeSeriesCollection(genCumul(dataset,31)));
// Renderer voor cumul7
XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(true,false);
r1.setPaint(new Color(0,0,255));
// Renderer voor cumul31
XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(true,false);
r2.setPaint(new Color(0,255,0));
plot.setRenderer(1,r1);
plot.setRenderer(2,r2);
return chart;
}
//construeer de timeseriescollection van de lijst van data.
private TimeSeriesCollection constructTSC(List<Calendar> dataset){
TimeSeriesCollection tsc = new TimeSeriesCollection();
TimeSeries series = new TimeSeries("Series1");
int i = 0;
Calendar previous,c;
while(i < dataset.size()){
c = dataset.get(i);
Period p = getPeriod(c);
if(i == 0){
series.setKey(p.name().toLowerCase() + "1");
addCount(p);
}
else {
previous = dataset.get(i-1);
if (diffPeriod(previous,c)) {
series.addOrUpdate(new Day(c.getTime()),i+1);
tsc.addSeries(series);
series = new TimeSeries(p.name().toLowerCase() + getCount(p));
addCount(p);
}
}
series.addOrUpdate(new Day(c.getTime()),i+1);
i++;
}
tsc.addSeries(series);
return tsc;
}
//genereer de cumulatieve lijn voor de laatste %i dagen.
private TimeSeries genCumul(List<Calendar> ds, int i){
TimeSeries series = new TimeSeries("Cumul" + i);
Calendar start = (Calendar) ds.get(0).clone();
Calendar end = (Calendar) ds.get(ds.size()-1).clone();
Calendar preStart= (Calendar) start.clone();
preStart.add(Calendar.DATE,-i);
int count=0;
while(start.before(end)){
if(ds.contains(preStart))
count-=frequency(ds,preStart);
if(ds.contains(start)){
count+=frequency(ds,start);
}
//System.out.println(start.getTime()+ " cumul is " + count);
series.addOrUpdate(new Day(start.getTime()),count);
start.add(Calendar.DATE,1);
preStart.add(Calendar.DATE,1);
}
return series;
}
//enum van mogelijke periodes
public enum Period {
SEMESTER, SUMMER, WINTER
}
//kijk na in welke periode een dag valt.
private Period getPeriod(Calendar c){
Calendar c2 = getStartYear(c);
Period p;
if (daysBetween(c2,c) < 89){
p = Period.SEMESTER;
}else if (daysBetween(c2,c) < 140){
p = Period.WINTER;
}else if (daysBetween(c2,c) < 243){
p = Period.SEMESTER;
}else {
p = Period.SUMMER;
}
return p;
}
/*
berekend de start van het academiejaar voor datum c
de eerste maandag na de 20ste september die c voorafgaat
*/
private Calendar getStartYear(Calendar c){
Calendar c2 = Calendar.getInstance();
c2.set(c.get(Calendar.YEAR),Calendar.SEPTEMBER,20);
//========================System.out.println(df.format(c2.getTime()));
nextMonday(c2);
if(c.before(c2)) {
c2.set(c.get(Calendar.YEAR) - 1, Calendar.SEPTEMBER, 20);
nextMonday(c2);
}
return c2;
}
//vormt een dag om naar de eerstvolgende maandag.
private void nextMonday(Calendar c){
while(c.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY)
c.add(Calendar.DATE,1);
}
//geef het aantal dagen tussen 2 dagen terug
private static long daysBetween(Calendar startDate, Calendar endDate) {
long end = endDate.getTimeInMillis();
long start = startDate.getTimeInMillis();
return (end - start)/(60*60*24*1000) +1;
}
/*
kijkt na of first en second in een verschillende periode liggen:
valt first voor de start van het academiejaar van second?
semester 1: start academiejaar .. 89 dagen later
winter: 89dagen na start .. 140 dagen na start
semester 2: 140 dagen na start .. 191 dagen na start
zomer: 191 dagen na start .. volgende academiejaar.
*/
private boolean diffPeriod(Calendar first, Calendar second){
Calendar start = getStartYear(second);
long d1 = daysBetween(start,first);
long d2 = daysBetween(start,second);
return (!first.after(start) ||
(d1<89 && d2 >= 89) ||
(d1<140 && d2 >= 140)||
(d1<243 && d2 >= 243));
}
//geef aan de hoeveelste keer dat een periode gebruikt is.
private int getCount(Period p){
if(p.equals(Period.SEMESTER))
return semestercount;
if(p.equals(Period.SUMMER))
return summercount;
return wintercount;
}
//tel 1 op bij de bijhorende periodcount van de period
private void addCount(Period p){
if(p.equals(Period.SEMESTER)) {
//System.out.println("add semester count");
semestercount++;
}
if(p.equals(Period.SUMMER))
summercount++;
if(p.equals(Period.WINTER))
wintercount++;
}
}
|
105155_0 | package Enigma_machine;
public class Enigma_Machine {
private static final int ASCII_VALUE_A = 65; // Test 4
private static final int ASCII_VALUE_0 = 48; // Test 1
Rotor[] rotor_blok = new Rotor[3]; // Test 1
Reflector reflector = new Reflector(); // Test 3
public void setup_rotor_blok(String volgorde_rotoren, String Start_Positie) { // Test 1
Rotor previous_rotor = null;
for (int i = 0; i <3 ; i++){
int rotor_type_volgnummer = (int)volgorde_rotoren.charAt(i) - ASCII_VALUE_0 - 1;
rotor_blok[i] = new Rotor(rotor_type_volgnummer, Start_Positie.charAt(i), previous_rotor);
previous_rotor = rotor_blok[i];
}
}
public char encode(char input_char){ // Test 4
int input_position = (int) input_char - ASCII_VALUE_A;
rotor_blok[2].rotate_rotor();
return get_output_char(reflector_to_output(reflector.reflector_result(input_to_reflector(input_position))));
}
public String string_encode(String input_string){ // Test 5
String result = "";
char character_to_encode;
for (int i=0; i < input_string.length(); i++){
character_to_encode = input_string.charAt(i);
if (character_to_encode == ' ')
result += character_to_encode;
else
result += encode(input_string.charAt(i));
}
return result;
}
public int input_to_reflector(int input_rotor){ // Test 4
for (int i = 2 ; i>=0; i--)
input_rotor = rotor_blok[i].encode_right_left(input_rotor);
return input_rotor;
// Dit kan ook geschreven worden als
// input_rotor = rotor_blok[0].encode_right_left(rotor_blok[1].encode_right_left(rotor_blok[2].encode_right_left(input_rotor)))
// maar bovenste is netter en er kunnen eventueel ook meer rotoren in het blok gezet worden.
}
public int reflector_to_output(int input_rotor){ // Test 4
for (int i =0 ; i<3; i++)
input_rotor = rotor_blok[i].encode_left_right(input_rotor);
return input_rotor;
}
public char get_output_char(int input_pos){ // Test 4
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(input_pos);
}
} | HaraldRietdijk/Enigma | Enigma/src/Enigma_machine/Enigma_Machine.java | 733 | // Dit kan ook geschreven worden als
| line_comment | nl | package Enigma_machine;
public class Enigma_Machine {
private static final int ASCII_VALUE_A = 65; // Test 4
private static final int ASCII_VALUE_0 = 48; // Test 1
Rotor[] rotor_blok = new Rotor[3]; // Test 1
Reflector reflector = new Reflector(); // Test 3
public void setup_rotor_blok(String volgorde_rotoren, String Start_Positie) { // Test 1
Rotor previous_rotor = null;
for (int i = 0; i <3 ; i++){
int rotor_type_volgnummer = (int)volgorde_rotoren.charAt(i) - ASCII_VALUE_0 - 1;
rotor_blok[i] = new Rotor(rotor_type_volgnummer, Start_Positie.charAt(i), previous_rotor);
previous_rotor = rotor_blok[i];
}
}
public char encode(char input_char){ // Test 4
int input_position = (int) input_char - ASCII_VALUE_A;
rotor_blok[2].rotate_rotor();
return get_output_char(reflector_to_output(reflector.reflector_result(input_to_reflector(input_position))));
}
public String string_encode(String input_string){ // Test 5
String result = "";
char character_to_encode;
for (int i=0; i < input_string.length(); i++){
character_to_encode = input_string.charAt(i);
if (character_to_encode == ' ')
result += character_to_encode;
else
result += encode(input_string.charAt(i));
}
return result;
}
public int input_to_reflector(int input_rotor){ // Test 4
for (int i = 2 ; i>=0; i--)
input_rotor = rotor_blok[i].encode_right_left(input_rotor);
return input_rotor;
// Dit kan<SUF>
// input_rotor = rotor_blok[0].encode_right_left(rotor_blok[1].encode_right_left(rotor_blok[2].encode_right_left(input_rotor)))
// maar bovenste is netter en er kunnen eventueel ook meer rotoren in het blok gezet worden.
}
public int reflector_to_output(int input_rotor){ // Test 4
for (int i =0 ; i<3; i++)
input_rotor = rotor_blok[i].encode_left_right(input_rotor);
return input_rotor;
}
public char get_output_char(int input_pos){ // Test 4
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(input_pos);
}
} |
111337_2 | /*
* Firebird Open Source JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* 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
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.gds.ng.jna;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import org.firebirdsql.gds.JaybirdSystemProperties;
import org.firebirdsql.gds.ng.IAttachProperties;
import org.firebirdsql.jaybird.util.Cleaners;
import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup;
import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary;
import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary;
import org.firebirdsql.jna.fbclient.FbClientLibrary;
import org.firebirdsql.jna.fbclient.WinFbClientLibrary;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the
* Firebird embedded library.
*
* @author Mark Rotteveel
* @since 3.0
*/
public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory {
private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName());
// Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12)
private static final List<String> LIBRARIES_TO_TRY =
List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT);
private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory();
private FbEmbeddedDatabaseFactory() {
// only through getInstance()
}
public static FbEmbeddedDatabaseFactory getInstance() {
return INSTANCE;
}
@Override
protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) {
T attachPropertiesCopy = attachProperties.asNewMutable();
// Clear server name
attachPropertiesCopy.setServerName(null);
return attachPropertiesCopy;
}
@Override
protected Collection<String> defaultLibraryNames() {
return LIBRARIES_TO_TRY;
}
@Override
protected FbClientLibrary createClientLibrary() {
final List<Throwable> throwables = new ArrayList<>();
final List<String> librariesToTry = findLibrariesToTry();
for (String libraryName : librariesToTry) {
try {
if (Platform.isWindows()) {
return Native.load(libraryName, WinFbClientLibrary.class);
} else {
return Native.load(libraryName, FbClientLibrary.class);
}
} catch (RuntimeException | UnsatisfiedLinkError e) {
throwables.add(e);
log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e);
// continue with next
}
}
assert throwables.size() == librariesToTry.size();
if (log.isLoggable(ERROR)) {
log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry);
for (int idx = 0; idx < librariesToTry.size(); idx++) {
log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx));
}
}
throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception",
throwables.get(0));
}
private List<String> findLibrariesToTry() {
final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient();
if (libraryPath != null) {
return Collections.singletonList(libraryPath);
}
Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded();
if (optionalFbEmbeddedInstance.isPresent()) {
FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get();
log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion());
if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) {
NativeResourceTracker.strongRegisterNativeResource(
new FirebirdEmbeddedLibraryNativeResource(disposableLibrary));
}
Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath();
List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1);
librariesToTry.add(entryPointPath.toString());
librariesToTry.addAll(LIBRARIES_TO_TRY);
return librariesToTry;
}
return LIBRARIES_TO_TRY;
}
private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource {
private final Cleaner.Cleanable cleanable;
private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) {
requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary");
cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary));
}
@Override
void dispose() {
cleanable.clean();
}
private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable {
@Override
public void run() {
firebirdEmbeddedLibrary.dispose();
}
}
}
}
| red-soft-ru/jaybird | jaybird-native/src/main/java/org/firebirdsql/gds/ng/jna/FbEmbeddedDatabaseFactory.java | 1,496 | // Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12) | line_comment | nl | /*
* Firebird Open Source JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* 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
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.gds.ng.jna;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import org.firebirdsql.gds.JaybirdSystemProperties;
import org.firebirdsql.gds.ng.IAttachProperties;
import org.firebirdsql.jaybird.util.Cleaners;
import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup;
import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary;
import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary;
import org.firebirdsql.jna.fbclient.FbClientLibrary;
import org.firebirdsql.jna.fbclient.WinFbClientLibrary;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the
* Firebird embedded library.
*
* @author Mark Rotteveel
* @since 3.0
*/
public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory {
private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName());
// Note Firebird<SUF>
private static final List<String> LIBRARIES_TO_TRY =
List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT);
private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory();
private FbEmbeddedDatabaseFactory() {
// only through getInstance()
}
public static FbEmbeddedDatabaseFactory getInstance() {
return INSTANCE;
}
@Override
protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) {
T attachPropertiesCopy = attachProperties.asNewMutable();
// Clear server name
attachPropertiesCopy.setServerName(null);
return attachPropertiesCopy;
}
@Override
protected Collection<String> defaultLibraryNames() {
return LIBRARIES_TO_TRY;
}
@Override
protected FbClientLibrary createClientLibrary() {
final List<Throwable> throwables = new ArrayList<>();
final List<String> librariesToTry = findLibrariesToTry();
for (String libraryName : librariesToTry) {
try {
if (Platform.isWindows()) {
return Native.load(libraryName, WinFbClientLibrary.class);
} else {
return Native.load(libraryName, FbClientLibrary.class);
}
} catch (RuntimeException | UnsatisfiedLinkError e) {
throwables.add(e);
log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e);
// continue with next
}
}
assert throwables.size() == librariesToTry.size();
if (log.isLoggable(ERROR)) {
log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry);
for (int idx = 0; idx < librariesToTry.size(); idx++) {
log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx));
}
}
throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception",
throwables.get(0));
}
private List<String> findLibrariesToTry() {
final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient();
if (libraryPath != null) {
return Collections.singletonList(libraryPath);
}
Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded();
if (optionalFbEmbeddedInstance.isPresent()) {
FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get();
log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion());
if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) {
NativeResourceTracker.strongRegisterNativeResource(
new FirebirdEmbeddedLibraryNativeResource(disposableLibrary));
}
Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath();
List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1);
librariesToTry.add(entryPointPath.toString());
librariesToTry.addAll(LIBRARIES_TO_TRY);
return librariesToTry;
}
return LIBRARIES_TO_TRY;
}
private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource {
private final Cleaner.Cleanable cleanable;
private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) {
requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary");
cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary));
}
@Override
void dispose() {
cleanable.clean();
}
private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable {
@Override
public void run() {
firebirdEmbeddedLibrary.dispose();
}
}
}
}
|
172239_5 | package nl.novi.techiteasy1121.controllers;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import nl.novi.techiteasy1121.dtos.IdInputDto;
import nl.novi.techiteasy1121.dtos.TelevisionDto;
import nl.novi.techiteasy1121.dtos.TelevisionInputDto;
import nl.novi.techiteasy1121.dtos.WallBracketDto;
import nl.novi.techiteasy1121.services.TelevisionService;
import nl.novi.techiteasy1121.services.TelevisionWallBracketService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static nl.novi.techiteasy1121.utilities.Utilities.getErrorString;
@RestController
@AllArgsConstructor
public class TelevisionController {
private final TelevisionService televisionService;
private final TelevisionWallBracketService televisionWallBracketService;
@GetMapping("/televisions")
public ResponseEntity<List<TelevisionDto>> getAllTelevisions(@RequestParam(value = "brand", required = false) Optional<String> brand) {
List<TelevisionDto> dtos;
if (brand.isEmpty()) {
dtos = televisionService.getAllTelevisions();
} else {
dtos = televisionService.getAllTelevisionsByBrand(brand.get());
}
return ResponseEntity.ok().body(dtos);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<TelevisionDto> getTelevision(@PathVariable("id") Long id) {
TelevisionDto television = televisionService.getTelevisionById(id);
return ResponseEntity.ok().body(television);
}
@PostMapping("/televisions")
public ResponseEntity<Object> addTelevision(@Valid @RequestBody TelevisionInputDto televisionInputDto, BindingResult br) {
if (br.hasFieldErrors()) {
String errorString = getErrorString(br);
return ResponseEntity.badRequest().body(errorString);
} else {
Long id = televisionService.addTelevision(televisionInputDto).getId();
URI uri = URI.create(ServletUriComponentsBuilder
.fromCurrentRequest().path("/" + id).toUriString());
return ResponseEntity.created(uri).body("Television added with id: " + id); // Of: body(televisionInputDto)
}
}
// Als een item niet verwijderd kan worden, in verband met relaties, geeft het alsnog een 204 No Content bericht
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable Long id) {
televisionService.deleteTelevision(id);
return ResponseEntity.noContent().build(); // Beide ResponseEntity vormen geven geen feedback na verwijderen van een item
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Object> updateTelevision(@PathVariable Long id, @Valid @RequestBody TelevisionInputDto televisionInputDto) {
TelevisionDto televisionDto = televisionService.updateTelevision(id, televisionInputDto);
return ResponseEntity.ok().body(televisionDto);
}
// Onderstaande 2 methodes zijn endpoints om andere entiteiten toe te voegen aan de Television.
// Dit is één manier om dit te doen, met één PathVariable en één RequestBody.
// Remote_controller_id wel zichtbaar in de database onder Televisions
@PutMapping("/televisions/{id}/remotecontroller")
public ResponseEntity<Object> assignRemoteControllerToTelevision(@PathVariable("id") Long id, @Valid @RequestBody IdInputDto input) {
televisionService.assignRemoteControllerToTelevision(id, input.id);
return ResponseEntity.noContent().build();
}
// Dit is een andere manier om het te doen, met twee Pathvariables, maar het kan uiteraard ook anders.
@PutMapping("/televisions/{id}/{ciModuleId}")
public ResponseEntity<Object> assignCIModuleToTelevision(@PathVariable("id") Long id, @PathVariable("ciModuleId") Long ciModuleId) {
televisionService.assignCIModuleToTelevision(id, ciModuleId);
return ResponseEntity.noContent().build();
}
// Deze methode is om alle wallbrackets op te halen die aan een bepaalde television gekoppeld zijn.
// Deze methode maakt gebruik van de televisionWallBracketService.
@GetMapping("/televisions/wallBrackets/{televisionId}")
public ResponseEntity<Collection<WallBracketDto>> getWallBracketsByTelevisionId(@PathVariable("televisionId") Long televisionId) {
return ResponseEntity.ok(televisionWallBracketService.getWallBracketsByTelevisionId(televisionId));
}
}
| Aphelion-im/Les-13-uitwerking-opdracht-tech-it-easy-relations | src/main/java/nl/novi/techiteasy1121/controllers/TelevisionController.java | 1,115 | // Dit is een andere manier om het te doen, met twee Pathvariables, maar het kan uiteraard ook anders. | line_comment | nl | package nl.novi.techiteasy1121.controllers;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import nl.novi.techiteasy1121.dtos.IdInputDto;
import nl.novi.techiteasy1121.dtos.TelevisionDto;
import nl.novi.techiteasy1121.dtos.TelevisionInputDto;
import nl.novi.techiteasy1121.dtos.WallBracketDto;
import nl.novi.techiteasy1121.services.TelevisionService;
import nl.novi.techiteasy1121.services.TelevisionWallBracketService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static nl.novi.techiteasy1121.utilities.Utilities.getErrorString;
@RestController
@AllArgsConstructor
public class TelevisionController {
private final TelevisionService televisionService;
private final TelevisionWallBracketService televisionWallBracketService;
@GetMapping("/televisions")
public ResponseEntity<List<TelevisionDto>> getAllTelevisions(@RequestParam(value = "brand", required = false) Optional<String> brand) {
List<TelevisionDto> dtos;
if (brand.isEmpty()) {
dtos = televisionService.getAllTelevisions();
} else {
dtos = televisionService.getAllTelevisionsByBrand(brand.get());
}
return ResponseEntity.ok().body(dtos);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<TelevisionDto> getTelevision(@PathVariable("id") Long id) {
TelevisionDto television = televisionService.getTelevisionById(id);
return ResponseEntity.ok().body(television);
}
@PostMapping("/televisions")
public ResponseEntity<Object> addTelevision(@Valid @RequestBody TelevisionInputDto televisionInputDto, BindingResult br) {
if (br.hasFieldErrors()) {
String errorString = getErrorString(br);
return ResponseEntity.badRequest().body(errorString);
} else {
Long id = televisionService.addTelevision(televisionInputDto).getId();
URI uri = URI.create(ServletUriComponentsBuilder
.fromCurrentRequest().path("/" + id).toUriString());
return ResponseEntity.created(uri).body("Television added with id: " + id); // Of: body(televisionInputDto)
}
}
// Als een item niet verwijderd kan worden, in verband met relaties, geeft het alsnog een 204 No Content bericht
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable Long id) {
televisionService.deleteTelevision(id);
return ResponseEntity.noContent().build(); // Beide ResponseEntity vormen geven geen feedback na verwijderen van een item
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Object> updateTelevision(@PathVariable Long id, @Valid @RequestBody TelevisionInputDto televisionInputDto) {
TelevisionDto televisionDto = televisionService.updateTelevision(id, televisionInputDto);
return ResponseEntity.ok().body(televisionDto);
}
// Onderstaande 2 methodes zijn endpoints om andere entiteiten toe te voegen aan de Television.
// Dit is één manier om dit te doen, met één PathVariable en één RequestBody.
// Remote_controller_id wel zichtbaar in de database onder Televisions
@PutMapping("/televisions/{id}/remotecontroller")
public ResponseEntity<Object> assignRemoteControllerToTelevision(@PathVariable("id") Long id, @Valid @RequestBody IdInputDto input) {
televisionService.assignRemoteControllerToTelevision(id, input.id);
return ResponseEntity.noContent().build();
}
// Dit is<SUF>
@PutMapping("/televisions/{id}/{ciModuleId}")
public ResponseEntity<Object> assignCIModuleToTelevision(@PathVariable("id") Long id, @PathVariable("ciModuleId") Long ciModuleId) {
televisionService.assignCIModuleToTelevision(id, ciModuleId);
return ResponseEntity.noContent().build();
}
// Deze methode is om alle wallbrackets op te halen die aan een bepaalde television gekoppeld zijn.
// Deze methode maakt gebruik van de televisionWallBracketService.
@GetMapping("/televisions/wallBrackets/{televisionId}")
public ResponseEntity<Collection<WallBracketDto>> getWallBracketsByTelevisionId(@PathVariable("televisionId") Long televisionId) {
return ResponseEntity.ok(televisionWallBracketService.getWallBracketsByTelevisionId(televisionId));
}
}
|
30743_80 | //package sr.unasat.facade;
//
//import sr.unasat.Helper.sr.unasat.Helper;
//import sr.unasat.entity.*;
//import sr.unasat.factory.Voertuig;
//import sr.unasat.service.*;
//
//import java.util.List;
//
//
//public class AdminFacade {
// KlantService ks = new KlantService();
// BestellingService bs = new BestellingService();
// ChauffeurService cs = new ChauffeurService();
// LeveringService ls = new LeveringService();
// ProductService ps = new ProductService();
// VoertuigService vs = new VoertuigService();
// BestellingProductService bps = new BestellingProductService();
//
//
// public void welcome() {
// System.out.println("Welcome to the logistics admin.");
// System.out.println();
// }
//
// public void menuOptions() {
// System.out.println("Menu: ");
//
// System.out.print("[Bestelling] (B)");
// System.out.print(" [Klant] (K)");
// System.out.print(" [Chauffeur] (C)");
// System.out.print(" [Product] (P)");
// System.out.print(" [Levering] (L)");
// System.out.print(" [Vrachtwagen] (V)");
// System.out.print(" (Exit)");
// }
//
// public void nieuwKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// ks.createKlant(voorNaam, achterNaam, adres, telefoon);
// System.out.println("Klant succesvol toegevoegd");
// }
//
// public void lijstKlanten() {
// for (Klant k :
// ks.getKlant()) {
// System.out.println(k);
// }
// }
//
// public void zoekOneKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println(ks.findKlantByName(voorNaam, achterNaam));
// }
//
// public void deleteKlant() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ks.deleteKlant(id);
// System.out.println("klant met ID " + id + " verwijderd");
// }
//
// public void updateKlantNaam() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
//
// ks.updateNaam(id, voorNaam, achterNaam);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantAdres() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ks.updateAdres(id, adres);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantTelefoon() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
// ks.updateAdres(id, telefoon);
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void lijstBestelling() {
// for (Bestelling b : bs.getBestelling()
// ) {
// System.out.println(b);
// }
// }
//
// public void lijstBestellingProducten() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// for (BestellingProduct bp : bs.findBestellingById(id).getProducten()
// ) {
// System.out.println(bp);
// }
// }
//
//
// public void nieuwBestelling() {
// System.out.println("Klant voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("Klant achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
//
// List<String> p = sr.unasat.Helper.scanStringList();
// List<Integer> a = sr.unasat.Helper.scanIntList();
//
// bps.createBestellingProduct(bs.createBestelling(voornaam, achternaam, jaar, maand, dag), p, a);
//
// System.out.println("Bestelling succesvol toegevoegd");
// }
//
// public void zoekOneBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(bs.findBestellingById(id));
// }
//
//// public void updateLeveringKosten() {
//// System.out.println("Bestelling ID: ");
//// int id = sr.unasat.Helper.scanInt();
//// System.out.println("leveringskosten: ");
//// double leveringskosten = sr.unasat.Helper.scandouble();
//// bs.updateLeveringskosten(id, leveringskosten);
//// System.out.println("Bestelling met ID " + id + " updated");
//// }
//
// public void updateLeveringDatum() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
// bs.updateLeveringsDatum(id, jaar, maand, dag);
// System.out.println("Bestelling met ID " + id + " updated");
// }
//
// public void deleteBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// bs.deleteBestelling(id);
// System.out.println("Bestelling met ID " + id + " verwijderd");
// }
//
// public void lijstChauffeur() {
// for (Chauffeur c :
// cs.getChauffeur()) {
// System.out.println(c);
// }
// }
//
// public void nieuwChauffeur() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.createChauffeur(voornaam, achternaam, telefoon);
// System.out.println("Chauffeur succesvol toegevoegd");
// }
//
// public void zoekChauffeurBijNaam() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// System.out.println(cs.findChauffeurByName(voornaam, achternaam));
// }
//
// public void zoekChauffeurBijId() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(cs.findChauffeurById(id));
// }
//
// public void updateChauffeurNaam() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// cs.updateNaam(id, voornaam, achternaam);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void updateChauffeurTelefoon() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.updateTelefoon(id, telefoon);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void deleteChauffeur() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// cs.deleteChauffeur(id);
// System.out.println("Chauffeur met ID " + id + " verwijderd");
// }
//
// public void nieuwLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//// System.out.println("voornaam: ");
//// String voornaam = sr.unasat.Helper.scanstring();
//// System.out.println("achternaam: ");
//// String achternaam = sr.unasat.Helper.scanstring();
//
// ls.createLevering(id);
// System.out.println("Levering succesvol toegevoegd");
// }
//
// public void lijstLevering() {
// for (Levering l :
// ls.getLevering()) {
// System.out.println(l);
// }
// }
//
// public void deleteLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.deleteLevering(id);
// System.out.println("Levering met ID " + id + " verwijderd");
// }
//
// public void zoekLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.findLeveringById(id);
// }
//
// public void updateStatus() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("nieuw status: ");
// String status = sr.unasat.Helper.scanstring();
//
// ls.updateLeveringStatus(id, status);
// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void updateLeveringChauffeur() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println("error: function not ready");
//// ls.updateLeveringChauffeur();
//// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void nieuwProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.createProduct(naam, prijs, adres);
// System.out.println("Product succesvol toegevoegd");
// }
//
// public void deleteProduct() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ps.deleteProduct(id);
// System.out.println("Product met ID " + id + " verwijderd");
// }
//
// public void lijstProduct() {
// for (Product p :
// ps.getAllProducts()) {
// System.out.println(p);
// }
// }
//
// public void updatePrijs() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
//
// ps.updatePrijs(id, prijs);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void updateAdres() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.updateAdres(id, adres);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void zoekOneProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
//
// System.out.println(ps.findProductByName(naam));
// }
//
// public void nieuwVoertuig() {
// System.out.println("type (vrachtwagen of anders): ");
// String type = sr.unasat.Helper.scanstring();
// System.out.println("merk: ");
// String merk = sr.unasat.Helper.scanstring();
// System.out.println("capaciteit: ");
// int capaciteit = sr.unasat.Helper.scanInt();
// System.out.println("kenteken nummer: ");
// String kenteken = sr.unasat.Helper.scanstring();
//
// vs.createVoertuig(type, merk, capaciteit, kenteken);
// System.out.println("Voertuig succesvol toegevoegd");
// }
//
// public void deleteVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
// vs.deleteVoertuig(id);
// System.out.println("Voertuig met ID " + id + " verwijderd");
// }
//
// public void lijstVoertuig() {
// String type = sr.unasat.Helper.scanstring();
// for (Voertuig v :
// vs.getAllVoertuig(type)) {
// System.out.println(v);
// }
// }
//
// public void zoekOneVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(vs.findVoertuigById(id));
// }
//
//// public void subMenuVoertuig() {
//// System.out.println("Functies: ");
//// System.out.print("(add)");
//// System.out.print(" (delete)");
//// System.out.print(" (lijst voertuig)");
//// System.out.print(" (zoek voertuig)");
//// System.out.println(" (back)");
////
//// String menu = sr.unasat.Helper.scanstring();
//// switch (menu.toLowerCase()) {
//// case "add" -> {
//// nieuwVoertuig();
//// subMenuVoertuig();
//// }
//// case "delete" -> {
//// deleteVoertuig();
//// subMenuVoertuig();
//// }
//// case "lijst voertuig" -> {
//// lijstVoertuig();
//// subMenuVoertuig();
//// }
//// case "zoek voertuig" -> {
//// zoekOneVoertuig();
//// subMenuVoertuig();
//// }
//// case "back" -> menu();
//// default -> {
//// System.out.println("Invalid input. Try again.");
//// subMenuVoertuig();
//// }
//// }
//// }
//
// public void subMenuProduct() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst product)");
// System.out.print(" (update prijs)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek product)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwProduct();
// subMenuProduct();
// }
// case "delete" -> {
// deleteProduct();
// subMenuProduct();
// }
// case "lijst product" -> {
// lijstProduct();
// subMenuProduct();
// }
// case "update prijs" -> {
// updatePrijs();
// subMenuKlant();
// }
// case "update adres" -> {
// updateAdres();
// subMenuProduct();
// }
// case "zoek product" -> {
// zoekOneProduct();
// subMenuProduct();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuProduct();
// }
// }
// }
//
// public void subMenuLevering() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst levering)");
// System.out.print(" (update status)");
// System.out.print(" (update chauffeur)");
// System.out.print(" (zoek levering)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwLevering();
// subMenuLevering();
// }
// case "delete" -> {
// deleteLevering();
// subMenuLevering();
// }
// case "lijst levering" -> {
// lijstLevering();
// subMenuLevering();
// }
// case "update status" -> {
// updateStatus();
// subMenuLevering();
// }
// case "update chauffeur" -> {
// updateLeveringChauffeur();
// subMenuLevering();
// }
// case "zoek levering" -> {
// zoekLevering();
// subMenuLevering();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuLevering();
// }
// }
// }
//
// public void subMenuKlant() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Klant)");
// System.out.print(" (update Telefoon)");
// System.out.print(" (update naam)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek klant)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwKlant();
// subMenuKlant();
// }
// case "delete" -> {
// deleteKlant();
// subMenuKlant();
// }
// case "lijst klant" -> {
// lijstKlanten();
// subMenuKlant();
// }
// case "update telefoon" -> {
// updateKlantTelefoon();
// subMenuKlant();
// }
// case "update naam" -> {
// updateKlantNaam();
// subMenuKlant();
// }
// case "update adres" -> {
// updateKlantAdres();
// subMenuKlant();
// }
// case "zoek klant" -> {
// zoekOneKlant();
// subMenuKlant();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuKlant();
// }
// }
// }
//
// public void subMenuBestelling() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Bestelling)");
// System.out.print(" (lijst Bestelling producten)");
// System.out.print(" (update leveringsdatum)");
// System.out.print(" (zoek Bestelling)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwBestelling();
// subMenuBestelling();
// }
// case "delete" -> {
// deleteBestelling();
// subMenuBestelling();
// }
// case "lijst bestelling" -> {
// lijstBestelling();
// subMenuBestelling();
// }
// case "update leveringsdatum" -> {
// updateLeveringDatum();
// subMenuBestelling();
// }
// case "bestelling producten" -> {
// lijstBestellingProducten();
// subMenuBestelling();
// }
// case "zoek bestelling" -> {
// zoekOneBestelling();
// subMenuBestelling();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuBestelling();
// }
// }
// }
//
// public void subMenuChauffeur() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Chauffeur)");
// System.out.print(" (update naam)");
// System.out.print(" (update telefoon)");
// System.out.print(" (zoek chauffeur bij naam)");
// System.out.print(" (zoek chauffeur bij id)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwChauffeur();
// subMenuChauffeur();
// }
// case "delete" -> {
// deleteChauffeur();
// subMenuChauffeur();
// }
// case "lijst chauffeur" -> {
// lijstChauffeur();
// subMenuChauffeur();
// }
// case "update naam" -> {
// updateChauffeurNaam();
// subMenuChauffeur();
// }
// case "update telefoon" -> {
// updateChauffeurTelefoon();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij naam" -> {
// zoekChauffeurBijNaam();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij id" -> {
// zoekChauffeurBijId();
// subMenuChauffeur();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuChauffeur();
// }
// }
// }
//
// public void menu() {
// menuOptions();
// System.out.println();
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toUpperCase()) {
// case "K" -> subMenuKlant();
// case "B" -> subMenuBestelling();
// case "C" -> subMenuChauffeur();
// case "L" -> subMenuLevering();
// case "V" -> subMenuVoertuig();
// case "P" -> subMenuProduct();
// case "EXIT" -> System.out.println("End Of Program");
// default -> {
// System.out.println("Invalid input. Try again.");
// menu();
// }
// }
// }
//
//}
| MiguelSaffier/logistiekWebApp | src/main/java/sr/unasat/facade/AdminFacade.java | 6,583 | // int jaar = sr.unasat.Helper.scanInt(); | line_comment | nl | //package sr.unasat.facade;
//
//import sr.unasat.Helper.sr.unasat.Helper;
//import sr.unasat.entity.*;
//import sr.unasat.factory.Voertuig;
//import sr.unasat.service.*;
//
//import java.util.List;
//
//
//public class AdminFacade {
// KlantService ks = new KlantService();
// BestellingService bs = new BestellingService();
// ChauffeurService cs = new ChauffeurService();
// LeveringService ls = new LeveringService();
// ProductService ps = new ProductService();
// VoertuigService vs = new VoertuigService();
// BestellingProductService bps = new BestellingProductService();
//
//
// public void welcome() {
// System.out.println("Welcome to the logistics admin.");
// System.out.println();
// }
//
// public void menuOptions() {
// System.out.println("Menu: ");
//
// System.out.print("[Bestelling] (B)");
// System.out.print(" [Klant] (K)");
// System.out.print(" [Chauffeur] (C)");
// System.out.print(" [Product] (P)");
// System.out.print(" [Levering] (L)");
// System.out.print(" [Vrachtwagen] (V)");
// System.out.print(" (Exit)");
// }
//
// public void nieuwKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// ks.createKlant(voorNaam, achterNaam, adres, telefoon);
// System.out.println("Klant succesvol toegevoegd");
// }
//
// public void lijstKlanten() {
// for (Klant k :
// ks.getKlant()) {
// System.out.println(k);
// }
// }
//
// public void zoekOneKlant() {
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
// System.out.println(ks.findKlantByName(voorNaam, achterNaam));
// }
//
// public void deleteKlant() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ks.deleteKlant(id);
// System.out.println("klant met ID " + id + " verwijderd");
// }
//
// public void updateKlantNaam() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voorNaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achterNaam = sr.unasat.Helper.scanstring();
//
// ks.updateNaam(id, voorNaam, achterNaam);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantAdres() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ks.updateAdres(id, adres);
//
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void updateKlantTelefoon() {
// System.out.println("klant ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
// ks.updateAdres(id, telefoon);
// System.out.println("klant met ID " + id + " updated");
// }
//
// public void lijstBestelling() {
// for (Bestelling b : bs.getBestelling()
// ) {
// System.out.println(b);
// }
// }
//
// public void lijstBestellingProducten() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// for (BestellingProduct bp : bs.findBestellingById(id).getProducten()
// ) {
// System.out.println(bp);
// }
// }
//
//
// public void nieuwBestelling() {
// System.out.println("Klant voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("Klant achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("jaar: ");
// int jaar = sr.unasat.Helper.scanInt();
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
//
// List<String> p = sr.unasat.Helper.scanStringList();
// List<Integer> a = sr.unasat.Helper.scanIntList();
//
// bps.createBestellingProduct(bs.createBestelling(voornaam, achternaam, jaar, maand, dag), p, a);
//
// System.out.println("Bestelling succesvol toegevoegd");
// }
//
// public void zoekOneBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(bs.findBestellingById(id));
// }
//
//// public void updateLeveringKosten() {
//// System.out.println("Bestelling ID: ");
//// int id = sr.unasat.Helper.scanInt();
//// System.out.println("leveringskosten: ");
//// double leveringskosten = sr.unasat.Helper.scandouble();
//// bs.updateLeveringskosten(id, leveringskosten);
//// System.out.println("Bestelling met ID " + id + " updated");
//// }
//
// public void updateLeveringDatum() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("jaar: ");
// int jaar<SUF>
// System.out.println("maand: ");
// int maand = sr.unasat.Helper.scanInt();
// System.out.println("dag: ");
// int dag = sr.unasat.Helper.scanInt();
// bs.updateLeveringsDatum(id, jaar, maand, dag);
// System.out.println("Bestelling met ID " + id + " updated");
// }
//
// public void deleteBestelling() {
// System.out.println("Bestelling ID: ");
// int id = sr.unasat.Helper.scanInt();
// bs.deleteBestelling(id);
// System.out.println("Bestelling met ID " + id + " verwijderd");
// }
//
// public void lijstChauffeur() {
// for (Chauffeur c :
// cs.getChauffeur()) {
// System.out.println(c);
// }
// }
//
// public void nieuwChauffeur() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.createChauffeur(voornaam, achternaam, telefoon);
// System.out.println("Chauffeur succesvol toegevoegd");
// }
//
// public void zoekChauffeurBijNaam() {
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// System.out.println(cs.findChauffeurByName(voornaam, achternaam));
// }
//
// public void zoekChauffeurBijId() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(cs.findChauffeurById(id));
// }
//
// public void updateChauffeurNaam() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("voornaam: ");
// String voornaam = sr.unasat.Helper.scanstring();
// System.out.println("achternaam: ");
// String achternaam = sr.unasat.Helper.scanstring();
//
// cs.updateNaam(id, voornaam, achternaam);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void updateChauffeurTelefoon() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("telefoon nummer: ");
// String telefoon = sr.unasat.Helper.scanstring();
//
// cs.updateTelefoon(id, telefoon);
// System.out.println("Chauffeur met ID " + id + " updated");
// }
//
// public void deleteChauffeur() {
// System.out.println("chauffeur ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// cs.deleteChauffeur(id);
// System.out.println("Chauffeur met ID " + id + " verwijderd");
// }
//
// public void nieuwLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//// System.out.println("voornaam: ");
//// String voornaam = sr.unasat.Helper.scanstring();
//// System.out.println("achternaam: ");
//// String achternaam = sr.unasat.Helper.scanstring();
//
// ls.createLevering(id);
// System.out.println("Levering succesvol toegevoegd");
// }
//
// public void lijstLevering() {
// for (Levering l :
// ls.getLevering()) {
// System.out.println(l);
// }
// }
//
// public void deleteLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.deleteLevering(id);
// System.out.println("Levering met ID " + id + " verwijderd");
// }
//
// public void zoekLevering() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ls.findLeveringById(id);
// }
//
// public void updateStatus() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("nieuw status: ");
// String status = sr.unasat.Helper.scanstring();
//
// ls.updateLeveringStatus(id, status);
// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void updateLeveringChauffeur() {
// System.out.println("levering ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println("error: function not ready");
//// ls.updateLeveringChauffeur();
//// System.out.println("Levering met ID " + id + " updated");
// }
//
// public void nieuwProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.createProduct(naam, prijs, adres);
// System.out.println("Product succesvol toegevoegd");
// }
//
// public void deleteProduct() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// ps.deleteProduct(id);
// System.out.println("Product met ID " + id + " verwijderd");
// }
//
// public void lijstProduct() {
// for (Product p :
// ps.getAllProducts()) {
// System.out.println(p);
// }
// }
//
// public void updatePrijs() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("prijs: ");
// double prijs = sr.unasat.Helper.scandouble();
//
// ps.updatePrijs(id, prijs);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void updateAdres() {
// System.out.println("product ID: ");
// int id = sr.unasat.Helper.scanInt();
// System.out.println("adres: ");
// String adres = sr.unasat.Helper.scanstring();
//
// ps.updateAdres(id, adres);
// System.out.println("Product met ID " + id + " updated");
// }
//
// public void zoekOneProduct() {
// System.out.println("product naam: ");
// String naam = sr.unasat.Helper.scanstring();
//
// System.out.println(ps.findProductByName(naam));
// }
//
// public void nieuwVoertuig() {
// System.out.println("type (vrachtwagen of anders): ");
// String type = sr.unasat.Helper.scanstring();
// System.out.println("merk: ");
// String merk = sr.unasat.Helper.scanstring();
// System.out.println("capaciteit: ");
// int capaciteit = sr.unasat.Helper.scanInt();
// System.out.println("kenteken nummer: ");
// String kenteken = sr.unasat.Helper.scanstring();
//
// vs.createVoertuig(type, merk, capaciteit, kenteken);
// System.out.println("Voertuig succesvol toegevoegd");
// }
//
// public void deleteVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
// vs.deleteVoertuig(id);
// System.out.println("Voertuig met ID " + id + " verwijderd");
// }
//
// public void lijstVoertuig() {
// String type = sr.unasat.Helper.scanstring();
// for (Voertuig v :
// vs.getAllVoertuig(type)) {
// System.out.println(v);
// }
// }
//
// public void zoekOneVoertuig() {
// System.out.println("voertuig ID: ");
// int id = sr.unasat.Helper.scanInt();
//
// System.out.println(vs.findVoertuigById(id));
// }
//
//// public void subMenuVoertuig() {
//// System.out.println("Functies: ");
//// System.out.print("(add)");
//// System.out.print(" (delete)");
//// System.out.print(" (lijst voertuig)");
//// System.out.print(" (zoek voertuig)");
//// System.out.println(" (back)");
////
//// String menu = sr.unasat.Helper.scanstring();
//// switch (menu.toLowerCase()) {
//// case "add" -> {
//// nieuwVoertuig();
//// subMenuVoertuig();
//// }
//// case "delete" -> {
//// deleteVoertuig();
//// subMenuVoertuig();
//// }
//// case "lijst voertuig" -> {
//// lijstVoertuig();
//// subMenuVoertuig();
//// }
//// case "zoek voertuig" -> {
//// zoekOneVoertuig();
//// subMenuVoertuig();
//// }
//// case "back" -> menu();
//// default -> {
//// System.out.println("Invalid input. Try again.");
//// subMenuVoertuig();
//// }
//// }
//// }
//
// public void subMenuProduct() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst product)");
// System.out.print(" (update prijs)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek product)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwProduct();
// subMenuProduct();
// }
// case "delete" -> {
// deleteProduct();
// subMenuProduct();
// }
// case "lijst product" -> {
// lijstProduct();
// subMenuProduct();
// }
// case "update prijs" -> {
// updatePrijs();
// subMenuKlant();
// }
// case "update adres" -> {
// updateAdres();
// subMenuProduct();
// }
// case "zoek product" -> {
// zoekOneProduct();
// subMenuProduct();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuProduct();
// }
// }
// }
//
// public void subMenuLevering() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst levering)");
// System.out.print(" (update status)");
// System.out.print(" (update chauffeur)");
// System.out.print(" (zoek levering)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwLevering();
// subMenuLevering();
// }
// case "delete" -> {
// deleteLevering();
// subMenuLevering();
// }
// case "lijst levering" -> {
// lijstLevering();
// subMenuLevering();
// }
// case "update status" -> {
// updateStatus();
// subMenuLevering();
// }
// case "update chauffeur" -> {
// updateLeveringChauffeur();
// subMenuLevering();
// }
// case "zoek levering" -> {
// zoekLevering();
// subMenuLevering();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuLevering();
// }
// }
// }
//
// public void subMenuKlant() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Klant)");
// System.out.print(" (update Telefoon)");
// System.out.print(" (update naam)");
// System.out.print(" (update adres)");
// System.out.print(" (zoek klant)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwKlant();
// subMenuKlant();
// }
// case "delete" -> {
// deleteKlant();
// subMenuKlant();
// }
// case "lijst klant" -> {
// lijstKlanten();
// subMenuKlant();
// }
// case "update telefoon" -> {
// updateKlantTelefoon();
// subMenuKlant();
// }
// case "update naam" -> {
// updateKlantNaam();
// subMenuKlant();
// }
// case "update adres" -> {
// updateKlantAdres();
// subMenuKlant();
// }
// case "zoek klant" -> {
// zoekOneKlant();
// subMenuKlant();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuKlant();
// }
// }
// }
//
// public void subMenuBestelling() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Bestelling)");
// System.out.print(" (lijst Bestelling producten)");
// System.out.print(" (update leveringsdatum)");
// System.out.print(" (zoek Bestelling)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwBestelling();
// subMenuBestelling();
// }
// case "delete" -> {
// deleteBestelling();
// subMenuBestelling();
// }
// case "lijst bestelling" -> {
// lijstBestelling();
// subMenuBestelling();
// }
// case "update leveringsdatum" -> {
// updateLeveringDatum();
// subMenuBestelling();
// }
// case "bestelling producten" -> {
// lijstBestellingProducten();
// subMenuBestelling();
// }
// case "zoek bestelling" -> {
// zoekOneBestelling();
// subMenuBestelling();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuBestelling();
// }
// }
// }
//
// public void subMenuChauffeur() {
// System.out.println("Functies: ");
// System.out.print("(add)");
// System.out.print(" (delete)");
// System.out.print(" (lijst Chauffeur)");
// System.out.print(" (update naam)");
// System.out.print(" (update telefoon)");
// System.out.print(" (zoek chauffeur bij naam)");
// System.out.print(" (zoek chauffeur bij id)");
// System.out.println(" (back)");
//
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toLowerCase()) {
// case "add" -> {
// nieuwChauffeur();
// subMenuChauffeur();
// }
// case "delete" -> {
// deleteChauffeur();
// subMenuChauffeur();
// }
// case "lijst chauffeur" -> {
// lijstChauffeur();
// subMenuChauffeur();
// }
// case "update naam" -> {
// updateChauffeurNaam();
// subMenuChauffeur();
// }
// case "update telefoon" -> {
// updateChauffeurTelefoon();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij naam" -> {
// zoekChauffeurBijNaam();
// subMenuChauffeur();
// }
// case "zoek chauffeur bij id" -> {
// zoekChauffeurBijId();
// subMenuChauffeur();
// }
// case "back" -> menu();
// default -> {
// System.out.println("Invalid input. Try again.");
// subMenuChauffeur();
// }
// }
// }
//
// public void menu() {
// menuOptions();
// System.out.println();
// String menu = sr.unasat.Helper.scanstring();
// switch (menu.toUpperCase()) {
// case "K" -> subMenuKlant();
// case "B" -> subMenuBestelling();
// case "C" -> subMenuChauffeur();
// case "L" -> subMenuLevering();
// case "V" -> subMenuVoertuig();
// case "P" -> subMenuProduct();
// case "EXIT" -> System.out.println("End Of Program");
// default -> {
// System.out.println("Invalid input. Try again.");
// menu();
// }
// }
// }
//
//}
|
95543_34 | // jDownloader - Downloadmanager
// Copyright (C) 2009 JD-Team [email protected]
//
// 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 jd.captcha.specials;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
import jd.captcha.JAntiCaptcha;
import jd.captcha.LetterComperator;
import jd.captcha.pixelgrid.Captcha;
import jd.captcha.pixelgrid.Letter;
import jd.captcha.pixelgrid.PixelGrid;
import jd.captcha.pixelobject.PixelObject;
/**
* das ist krank bitte nicht anschauen
*
* @author dwd
*
*/
public class ThreeDlTv {
/**
* prüft ob das objekt an der stelle x y höher ist als 14px
*
* @param captcha
* @param x
* @param y
* @return
*/
private static boolean checkAt(final Captcha captcha, final int x, final int y) {
final int yMax = Math.min(captcha.getHeight(), y + 7);
final int yMin = Math.max(0, y - 7);
for (int i = yMin; i < yMax; i++) {
if (captcha.getPixelValue(x, i) == 0xffffff) { return true; }
}
return false;
}
/**
* löscht alle objekte die höher sind als 14px
*
* @param captcha
*/
private static void clear(final Captcha captcha) {
for (int x = 0; x < captcha.getWidth(); x++) {
for (int y = 0; y < captcha.getHeight(); y++) {
if (captcha.getPixelValue(x, y) != 0xffffff && !checkAt(captcha, x, y)) {
clearAt(captcha, x, y);
}
}
}
}
/**
* löscht ein objekt an der position x y
*
* @param captcha
* @param x
* @param y
*/
private static void clearAt(final Captcha captcha, final int x, final int y) {
if (captcha.getHeight() >= y && captcha.getWidth() >= x && x > 0 && y > 0 && captcha.getPixelValue(x, y) != 0xffffff) {
captcha.grid[x][y] = 0xffffff;
clearAt(captcha, x + 1, y + 1);
clearAt(captcha, x, y + 1);
clearAt(captcha, x + 1, y);
clearAt(captcha, x - 1, y - 1);
clearAt(captcha, x - 1, y);
clearAt(captcha, x, y - 1);
clearAt(captcha, x + 1, y - 1);
clearAt(captcha, x - 1, y + 1);
}
}
/**
* schneidet ein 30px breites und 25px hohes objekt an der position int[] {x,y} aus
*
* @param captcha
* @param header1
* @return
*/
private static Letter createLetter(final Captcha captcha, final int[] header1) {
captcha.crop(Math.max(0, header1[0] - 15), header1[1], Math.max(0, captcha.getWidth() - header1[0] - 15), Math.max(0, captcha.getHeight() - header1[1] - 25));
final Letter l = captcha.createLetter();
captcha.toBlackAndWhite();
l.setLocation(header1);
l.setGrid(captcha.getGrid());
captcha.reset();
return l;
}
/**
* gibt die position aus wo im oberen Teil des Bildes ein objekt anfängt
*
* @param captcha
* @param xMin
* @param xMax
* @return
*/
private static int[] getHeader(final Captcha captcha, final int xMin, final int xMax) {
for (int y = 0; y < captcha.getHeight() / 8; y++) {
for (int x = xMin; x < xMax; x++) {
if (captcha.getPixelValue(x, y) != 0xffffff) { return new int[] { x, y }; }
}
}
return null;
}
public static Letter[] getLetters(final Captcha captcha) throws Exception {
captcha.owner.loadMTHFile(captcha.owner.getResourceFile("lettersheads.mth"));
// es wird der Buchstabe M bzw F von unten ausgeschnitten
captcha.crop(206, 150, 236, 0);
Vector<PixelObject> obj = captcha.getObjects(0.7, 0.7);
// es gibt nur ein objekt M oder F
Letter let = obj.get(0).toLetter();
// invertieren macht den vergleich schneller
let.invert();
let.normalize();
let = let.toPixelObject(0.7).toLetter();
final LetterComperator r = captcha.owner.getLetter(let);
let.detected = r;
let.setDecodedValue(r.getDecodedValue());
captcha.reset();
final int xMax = captcha.getWidth() / 3;
// holt die drei Köpfe
final Letter head1 = createLetter(captcha, getHeader(captcha, 0, xMax));
final Letter head2 = createLetter(captcha, getHeader(captcha, xMax, xMax * 2));
final Letter head3 = createLetter(captcha, getHeader(captcha, xMax * 2, xMax * 3));
int pos = 0;
final LetterComperator rc1 = captcha.owner.getLetter(head1);
head1.detected = rc1;
head1.setDecodedValue(rc1.getDecodedValue());
// schaut welcher der 3 köpfe Mann bzw Frau ist
if (head1.getDecodedValue().equals(let.getDecodedValue())) {
pos = 0;
} else {
final LetterComperator rc2 = captcha.owner.getLetter(head2);
head2.detected = rc2;
head2.setDecodedValue(rc2.getDecodedValue());
if (head2.getDecodedValue().equals(let.getDecodedValue())) {
pos = 1;
} else {
final LetterComperator rc3 = captcha.owner.getLetter(head3);
head3.detected = rc3;
head3.setDecodedValue(rc3.getDecodedValue());
if (head3.getDecodedValue().equals(let.getDecodedValue())) {
pos = 2;
} else {// wenn keines der 3 letters zutrifft ist es bestimmt
// das
// welches am schlechtesten erkannt wurde
if (head1.detected.getValityPercent() > head2.detected.getValityPercent()) {
if (head1.detected.getValityPercent() > head3.detected.getValityPercent()) {
pos = 0;
} else {
pos = 2;
}
} else {
if (head2.detected.getValityPercent() > head3.detected.getValityPercent()) {
pos = 1;
} else {
pos = 2;
}
}
}
}
}
// lösche die untere zeile
captcha.crop(0, 0, 0, 20);
// entferne alle männchen
clear(captcha);
// captcha.removeSmallObjects(0.7, 0.7, 6);
captcha.toBlackAndWhite(0.8);
// BasicWindow.showImage(captcha.getImage());
// holt die 3 buchstabenpackete
obj = getObjects(captcha, 3);
Collections.sort(obj);
if (obj.size() > 3) {
for (final Iterator<PixelObject> iterator = obj.iterator(); iterator.hasNext();) {
final PixelObject pixelObject = iterator.next();
if (pixelObject.getArea() < 80) {
iterator.remove();
}
}
}
captcha.owner.loadMTHFile();
captcha.owner.getJas().set("minimumObjectArea", 1);
captcha.owner.getJas().set("minimumLetterWidth", 1);
captcha.grid = obj.get(pos).toLetter().grid;
obj = captcha.getObjects(0.7, 0.7);
// die objekte die kleiner sind als 4 pixel können gemerged werden
int merge = 0;
for (final PixelObject pixelObject : obj) {
if (pixelObject.getArea() < 3) {
merge++;
}
}
captcha.owner.setLetterNum(obj.size() - merge);
EasyCaptcha.mergeObjectsBasic(obj, captcha, 2);
Collections.sort(obj);
final java.util.List<Letter> ret = new ArrayList<Letter>();
for (final ListIterator<PixelObject> iterator = obj.listIterator(); iterator.hasNext();) {
final PixelObject pixelObject = iterator.next();
ret.addAll(getSplitted(pixelObject, captcha, 0));
}
replaceLetters(ret);
return ret.toArray(new Letter[] {});
}
/**
* hiermit lassen sich große objekte schnell heraus suchen
*
* @param grid
* @param neighbourradius
* @return
*/
static Vector<PixelObject> getObjects(final PixelGrid grid, final int neighbourradius) {
final Vector<PixelObject> ret = new Vector<PixelObject>();
Vector<PixelObject> merge;
for (int x = 0; x < grid.getWidth(); x++) {
for (int y = 0; y < grid.getHeight(); y++) {
if (grid.getGrid()[x][y] < 0 || grid.getGrid()[x][y] != 0x000000) {
continue;
}
final PixelObject n = new PixelObject(grid);
n.add(x, y, grid.getGrid()[x][y]);
merge = new Vector<PixelObject>();
for (final PixelObject o : ret) {
if (o.isTouching(x, y, true, neighbourradius, neighbourradius)) {
merge.add(o);
}
}
if (merge.size() == 0) {
ret.add(n);
} else if (merge.size() == 1) {
merge.get(0).add(n);
} else {
for (final PixelObject po : merge) {
ret.remove(po);
n.add(po);
}
ret.add(n);
}
}
}
return ret;
}
/**
* teilt recht zuverlässig ist aber auch ressourcen lastig sollte nur bei kleinen Letters bentzt werden
*
* @author bismarck
* @param pixelObject
* @param captcha
* @param index
* @return
* @throws InterruptedException
*/
private static java.util.List<Letter> getSplitted(PixelObject pixelObject, final Captcha captcha, int index) throws InterruptedException {
final java.util.List<Letter> ret = new ArrayList<Letter>();
if (pixelObject.getArea() < 4) { return ret; }
// durchschnittliche breite vom char
final int lWith = 5;
// wenn pixelobject aus nur einem Character besteht
final Letter let1 = pixelObject.toLetter();
let1.toBlackAndWhite();
final LetterComperator r1 = captcha.owner.getLetter(let1);
let1.detected = r1;
if (r1.getValityPercent() < 3 || pixelObject.getArea() < 15) {
ret.add(let1);
return ret;
}
// hier werden komplette Worte gesplittet
final java.util.List<Integer> splitMap = new ArrayList<Integer>();
final Hashtable<String, Vector<Integer>> testMap = new Hashtable<String, Vector<Integer>>();
final Vector<Integer> one = new Vector<Integer>();
final Vector<Integer> two = new Vector<Integer>();
final Vector<Integer> three = new Vector<Integer>();
int eins = 0, zwei = 0, drei = 0;
for (int x = pixelObject.getWidth() - 1; x > 0; x--) {
int black = 0;
for (int y = 0; y < pixelObject.getHeight(); y++) {
if (pixelObject.getGrid()[x][y] < 0 || pixelObject.getGrid()[x][y] != 0x000000) {
continue;
}
black++;
}
if (black == index) {
if (splitMap != null && splitMap.size() > 0) {
final int p = splitMap.get(splitMap.size() - 1);
if (p == x + 1 || p == x + 2 || x == 0) {
continue;
}
}
splitMap.add(x);
}
if (black == 1) {
eins++;
one.add(x);
} else if (black == 2) {
zwei++;
two.add(x);
} else if (black == 3) {
drei++;
three.add(x);
}
// System.out.println("X:" + x + " black: " + black);
Collections.sort(one);
Collections.sort(two);
Collections.sort(three);
testMap.put("eins", one);
testMap.put("zwei", two);
testMap.put("drei", three);
}
Collections.reverse(splitMap);
if (splitMap != null && splitMap.size() > 0 && splitMap.get(0) >= lWith * 2) {
splitMap.add((splitMap.get(0) - splitMap.get(0) % 2) / 2);
Collections.sort(splitMap);
}
// wenn splits vorhanden sind aber einige chars zusammenkleben
final int CharAnzahl = (pixelObject.getWidth() - pixelObject.getWidth() % lWith) / lWith - 1;
if (CharAnzahl > splitMap.size()) {
// mögliche Position suchen
int sPos = 0, xPos = 0, maxPos = 0;
for (final ListIterator<Integer> i = splitMap.listIterator(); i.hasNext();) {
if (i.hasPrevious()) {
xPos = i.previous();
i.next();
sPos = i.next() - xPos;
} else {
i.next();
}
maxPos = sPos > maxPos ? sPos : maxPos;
}
if (maxPos > 0) {
for (int i = 1; i <= (maxPos - maxPos % lWith) / lWith; i++) {
final long min = 56847819l;
final long b = Math.min(min, pixelObject.getMassValue(6, 0));
if (b != min) {
splitMap.add(xPos + i * lWith);
}
}
Collections.sort(splitMap);
}
if (CharAnzahl > splitMap.size()) {
for (final int c : testMap.get("eins")) {
for (final int let : new ArrayList<Integer>(splitMap)) {
if (c - lWith < let || splitMap.contains(c - 3) || splitMap.contains(c - 2) || splitMap.contains(c - 1) || splitMap.contains(c) || splitMap.contains(c + 1) || splitMap.contains(c + 2) || splitMap.contains(c + 3)) {
continue;
}
splitMap.add(c);
Collections.sort(splitMap);
}
}
}
}
int xm = 0;
PixelObject[] bArray = null;
LetterComperator r2;
Letter splittedLetter;
// wenn kein weissraum vorhanden, splitte bei 1,2 oder 3 Pixeln
if (splitMap == null || splitMap.size() == 0) {
if (eins == 0 && zwei == 0 && drei == 0) { return ret; }
index = eins == 0 && zwei >= drei ? 3 : 2;
index = eins > 0 ? 1 : index;
if (index == 0) { return ret; }
return getSplitted(pixelObject, captcha, index);
}
for (final int let : splitMap) {
bArray = pixelObject.splitAt(let - xm);
pixelObject = bArray[1];
splittedLetter = bArray[0].toLetter();
splittedLetter.toBlackAndWhite();
r2 = captcha.owner.getLetter(splittedLetter);
splittedLetter.detected = r2;
ret.add(splittedLetter);
xm = let + 1;
}
splittedLetter = bArray[1].toLetter();
splittedLetter.toBlackAndWhite();
r2 = captcha.owner.getLetter(splittedLetter);
splittedLetter.detected = r2;
ret.add(splittedLetter);
return ret;
}
public static Letter[] letterFilter(final Letter[] org, final JAntiCaptcha jac) {
return org;
}
/**
* es wird z.B. letter 1 mit letter r erstetzt und ein letter i hinzugefügt
*
* @param lets
*/
private static void replaceLetters(final java.util.List<Letter> lets) {
int i = 0;
String add = null;
for (final Letter letter : lets) {
if (letter.detected.getDecodedValue().equals("1")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "i";
break;
} else if (letter.detected.getDecodedValue().equals("2")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "l";
break;
} else if (letter.detected.getDecodedValue().equals("3")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "t";
break;
} else if (letter.detected.getDecodedValue().equals("4")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "n";
break;
}
i++;
}
if (add != null) {
final Letter re = new Letter();
re.setDecodedValue(add);
final LetterComperator let1 = new LetterComperator(re, re);
let1.setValityPercent(0);
re.detected = let1;
lets.add(i + 1, re);
replaceLetters(lets);
}
}
}
| svn2github/jdownloader | src/jd/captcha/specials/ThreeDlTv.java | 5,032 | // hier werden komplette Worte gesplittet
| line_comment | nl | // jDownloader - Downloadmanager
// Copyright (C) 2009 JD-Team [email protected]
//
// 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 jd.captcha.specials;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
import jd.captcha.JAntiCaptcha;
import jd.captcha.LetterComperator;
import jd.captcha.pixelgrid.Captcha;
import jd.captcha.pixelgrid.Letter;
import jd.captcha.pixelgrid.PixelGrid;
import jd.captcha.pixelobject.PixelObject;
/**
* das ist krank bitte nicht anschauen
*
* @author dwd
*
*/
public class ThreeDlTv {
/**
* prüft ob das objekt an der stelle x y höher ist als 14px
*
* @param captcha
* @param x
* @param y
* @return
*/
private static boolean checkAt(final Captcha captcha, final int x, final int y) {
final int yMax = Math.min(captcha.getHeight(), y + 7);
final int yMin = Math.max(0, y - 7);
for (int i = yMin; i < yMax; i++) {
if (captcha.getPixelValue(x, i) == 0xffffff) { return true; }
}
return false;
}
/**
* löscht alle objekte die höher sind als 14px
*
* @param captcha
*/
private static void clear(final Captcha captcha) {
for (int x = 0; x < captcha.getWidth(); x++) {
for (int y = 0; y < captcha.getHeight(); y++) {
if (captcha.getPixelValue(x, y) != 0xffffff && !checkAt(captcha, x, y)) {
clearAt(captcha, x, y);
}
}
}
}
/**
* löscht ein objekt an der position x y
*
* @param captcha
* @param x
* @param y
*/
private static void clearAt(final Captcha captcha, final int x, final int y) {
if (captcha.getHeight() >= y && captcha.getWidth() >= x && x > 0 && y > 0 && captcha.getPixelValue(x, y) != 0xffffff) {
captcha.grid[x][y] = 0xffffff;
clearAt(captcha, x + 1, y + 1);
clearAt(captcha, x, y + 1);
clearAt(captcha, x + 1, y);
clearAt(captcha, x - 1, y - 1);
clearAt(captcha, x - 1, y);
clearAt(captcha, x, y - 1);
clearAt(captcha, x + 1, y - 1);
clearAt(captcha, x - 1, y + 1);
}
}
/**
* schneidet ein 30px breites und 25px hohes objekt an der position int[] {x,y} aus
*
* @param captcha
* @param header1
* @return
*/
private static Letter createLetter(final Captcha captcha, final int[] header1) {
captcha.crop(Math.max(0, header1[0] - 15), header1[1], Math.max(0, captcha.getWidth() - header1[0] - 15), Math.max(0, captcha.getHeight() - header1[1] - 25));
final Letter l = captcha.createLetter();
captcha.toBlackAndWhite();
l.setLocation(header1);
l.setGrid(captcha.getGrid());
captcha.reset();
return l;
}
/**
* gibt die position aus wo im oberen Teil des Bildes ein objekt anfängt
*
* @param captcha
* @param xMin
* @param xMax
* @return
*/
private static int[] getHeader(final Captcha captcha, final int xMin, final int xMax) {
for (int y = 0; y < captcha.getHeight() / 8; y++) {
for (int x = xMin; x < xMax; x++) {
if (captcha.getPixelValue(x, y) != 0xffffff) { return new int[] { x, y }; }
}
}
return null;
}
public static Letter[] getLetters(final Captcha captcha) throws Exception {
captcha.owner.loadMTHFile(captcha.owner.getResourceFile("lettersheads.mth"));
// es wird der Buchstabe M bzw F von unten ausgeschnitten
captcha.crop(206, 150, 236, 0);
Vector<PixelObject> obj = captcha.getObjects(0.7, 0.7);
// es gibt nur ein objekt M oder F
Letter let = obj.get(0).toLetter();
// invertieren macht den vergleich schneller
let.invert();
let.normalize();
let = let.toPixelObject(0.7).toLetter();
final LetterComperator r = captcha.owner.getLetter(let);
let.detected = r;
let.setDecodedValue(r.getDecodedValue());
captcha.reset();
final int xMax = captcha.getWidth() / 3;
// holt die drei Köpfe
final Letter head1 = createLetter(captcha, getHeader(captcha, 0, xMax));
final Letter head2 = createLetter(captcha, getHeader(captcha, xMax, xMax * 2));
final Letter head3 = createLetter(captcha, getHeader(captcha, xMax * 2, xMax * 3));
int pos = 0;
final LetterComperator rc1 = captcha.owner.getLetter(head1);
head1.detected = rc1;
head1.setDecodedValue(rc1.getDecodedValue());
// schaut welcher der 3 köpfe Mann bzw Frau ist
if (head1.getDecodedValue().equals(let.getDecodedValue())) {
pos = 0;
} else {
final LetterComperator rc2 = captcha.owner.getLetter(head2);
head2.detected = rc2;
head2.setDecodedValue(rc2.getDecodedValue());
if (head2.getDecodedValue().equals(let.getDecodedValue())) {
pos = 1;
} else {
final LetterComperator rc3 = captcha.owner.getLetter(head3);
head3.detected = rc3;
head3.setDecodedValue(rc3.getDecodedValue());
if (head3.getDecodedValue().equals(let.getDecodedValue())) {
pos = 2;
} else {// wenn keines der 3 letters zutrifft ist es bestimmt
// das
// welches am schlechtesten erkannt wurde
if (head1.detected.getValityPercent() > head2.detected.getValityPercent()) {
if (head1.detected.getValityPercent() > head3.detected.getValityPercent()) {
pos = 0;
} else {
pos = 2;
}
} else {
if (head2.detected.getValityPercent() > head3.detected.getValityPercent()) {
pos = 1;
} else {
pos = 2;
}
}
}
}
}
// lösche die untere zeile
captcha.crop(0, 0, 0, 20);
// entferne alle männchen
clear(captcha);
// captcha.removeSmallObjects(0.7, 0.7, 6);
captcha.toBlackAndWhite(0.8);
// BasicWindow.showImage(captcha.getImage());
// holt die 3 buchstabenpackete
obj = getObjects(captcha, 3);
Collections.sort(obj);
if (obj.size() > 3) {
for (final Iterator<PixelObject> iterator = obj.iterator(); iterator.hasNext();) {
final PixelObject pixelObject = iterator.next();
if (pixelObject.getArea() < 80) {
iterator.remove();
}
}
}
captcha.owner.loadMTHFile();
captcha.owner.getJas().set("minimumObjectArea", 1);
captcha.owner.getJas().set("minimumLetterWidth", 1);
captcha.grid = obj.get(pos).toLetter().grid;
obj = captcha.getObjects(0.7, 0.7);
// die objekte die kleiner sind als 4 pixel können gemerged werden
int merge = 0;
for (final PixelObject pixelObject : obj) {
if (pixelObject.getArea() < 3) {
merge++;
}
}
captcha.owner.setLetterNum(obj.size() - merge);
EasyCaptcha.mergeObjectsBasic(obj, captcha, 2);
Collections.sort(obj);
final java.util.List<Letter> ret = new ArrayList<Letter>();
for (final ListIterator<PixelObject> iterator = obj.listIterator(); iterator.hasNext();) {
final PixelObject pixelObject = iterator.next();
ret.addAll(getSplitted(pixelObject, captcha, 0));
}
replaceLetters(ret);
return ret.toArray(new Letter[] {});
}
/**
* hiermit lassen sich große objekte schnell heraus suchen
*
* @param grid
* @param neighbourradius
* @return
*/
static Vector<PixelObject> getObjects(final PixelGrid grid, final int neighbourradius) {
final Vector<PixelObject> ret = new Vector<PixelObject>();
Vector<PixelObject> merge;
for (int x = 0; x < grid.getWidth(); x++) {
for (int y = 0; y < grid.getHeight(); y++) {
if (grid.getGrid()[x][y] < 0 || grid.getGrid()[x][y] != 0x000000) {
continue;
}
final PixelObject n = new PixelObject(grid);
n.add(x, y, grid.getGrid()[x][y]);
merge = new Vector<PixelObject>();
for (final PixelObject o : ret) {
if (o.isTouching(x, y, true, neighbourradius, neighbourradius)) {
merge.add(o);
}
}
if (merge.size() == 0) {
ret.add(n);
} else if (merge.size() == 1) {
merge.get(0).add(n);
} else {
for (final PixelObject po : merge) {
ret.remove(po);
n.add(po);
}
ret.add(n);
}
}
}
return ret;
}
/**
* teilt recht zuverlässig ist aber auch ressourcen lastig sollte nur bei kleinen Letters bentzt werden
*
* @author bismarck
* @param pixelObject
* @param captcha
* @param index
* @return
* @throws InterruptedException
*/
private static java.util.List<Letter> getSplitted(PixelObject pixelObject, final Captcha captcha, int index) throws InterruptedException {
final java.util.List<Letter> ret = new ArrayList<Letter>();
if (pixelObject.getArea() < 4) { return ret; }
// durchschnittliche breite vom char
final int lWith = 5;
// wenn pixelobject aus nur einem Character besteht
final Letter let1 = pixelObject.toLetter();
let1.toBlackAndWhite();
final LetterComperator r1 = captcha.owner.getLetter(let1);
let1.detected = r1;
if (r1.getValityPercent() < 3 || pixelObject.getArea() < 15) {
ret.add(let1);
return ret;
}
// hier werden<SUF>
final java.util.List<Integer> splitMap = new ArrayList<Integer>();
final Hashtable<String, Vector<Integer>> testMap = new Hashtable<String, Vector<Integer>>();
final Vector<Integer> one = new Vector<Integer>();
final Vector<Integer> two = new Vector<Integer>();
final Vector<Integer> three = new Vector<Integer>();
int eins = 0, zwei = 0, drei = 0;
for (int x = pixelObject.getWidth() - 1; x > 0; x--) {
int black = 0;
for (int y = 0; y < pixelObject.getHeight(); y++) {
if (pixelObject.getGrid()[x][y] < 0 || pixelObject.getGrid()[x][y] != 0x000000) {
continue;
}
black++;
}
if (black == index) {
if (splitMap != null && splitMap.size() > 0) {
final int p = splitMap.get(splitMap.size() - 1);
if (p == x + 1 || p == x + 2 || x == 0) {
continue;
}
}
splitMap.add(x);
}
if (black == 1) {
eins++;
one.add(x);
} else if (black == 2) {
zwei++;
two.add(x);
} else if (black == 3) {
drei++;
three.add(x);
}
// System.out.println("X:" + x + " black: " + black);
Collections.sort(one);
Collections.sort(two);
Collections.sort(three);
testMap.put("eins", one);
testMap.put("zwei", two);
testMap.put("drei", three);
}
Collections.reverse(splitMap);
if (splitMap != null && splitMap.size() > 0 && splitMap.get(0) >= lWith * 2) {
splitMap.add((splitMap.get(0) - splitMap.get(0) % 2) / 2);
Collections.sort(splitMap);
}
// wenn splits vorhanden sind aber einige chars zusammenkleben
final int CharAnzahl = (pixelObject.getWidth() - pixelObject.getWidth() % lWith) / lWith - 1;
if (CharAnzahl > splitMap.size()) {
// mögliche Position suchen
int sPos = 0, xPos = 0, maxPos = 0;
for (final ListIterator<Integer> i = splitMap.listIterator(); i.hasNext();) {
if (i.hasPrevious()) {
xPos = i.previous();
i.next();
sPos = i.next() - xPos;
} else {
i.next();
}
maxPos = sPos > maxPos ? sPos : maxPos;
}
if (maxPos > 0) {
for (int i = 1; i <= (maxPos - maxPos % lWith) / lWith; i++) {
final long min = 56847819l;
final long b = Math.min(min, pixelObject.getMassValue(6, 0));
if (b != min) {
splitMap.add(xPos + i * lWith);
}
}
Collections.sort(splitMap);
}
if (CharAnzahl > splitMap.size()) {
for (final int c : testMap.get("eins")) {
for (final int let : new ArrayList<Integer>(splitMap)) {
if (c - lWith < let || splitMap.contains(c - 3) || splitMap.contains(c - 2) || splitMap.contains(c - 1) || splitMap.contains(c) || splitMap.contains(c + 1) || splitMap.contains(c + 2) || splitMap.contains(c + 3)) {
continue;
}
splitMap.add(c);
Collections.sort(splitMap);
}
}
}
}
int xm = 0;
PixelObject[] bArray = null;
LetterComperator r2;
Letter splittedLetter;
// wenn kein weissraum vorhanden, splitte bei 1,2 oder 3 Pixeln
if (splitMap == null || splitMap.size() == 0) {
if (eins == 0 && zwei == 0 && drei == 0) { return ret; }
index = eins == 0 && zwei >= drei ? 3 : 2;
index = eins > 0 ? 1 : index;
if (index == 0) { return ret; }
return getSplitted(pixelObject, captcha, index);
}
for (final int let : splitMap) {
bArray = pixelObject.splitAt(let - xm);
pixelObject = bArray[1];
splittedLetter = bArray[0].toLetter();
splittedLetter.toBlackAndWhite();
r2 = captcha.owner.getLetter(splittedLetter);
splittedLetter.detected = r2;
ret.add(splittedLetter);
xm = let + 1;
}
splittedLetter = bArray[1].toLetter();
splittedLetter.toBlackAndWhite();
r2 = captcha.owner.getLetter(splittedLetter);
splittedLetter.detected = r2;
ret.add(splittedLetter);
return ret;
}
public static Letter[] letterFilter(final Letter[] org, final JAntiCaptcha jac) {
return org;
}
/**
* es wird z.B. letter 1 mit letter r erstetzt und ein letter i hinzugefügt
*
* @param lets
*/
private static void replaceLetters(final java.util.List<Letter> lets) {
int i = 0;
String add = null;
for (final Letter letter : lets) {
if (letter.detected.getDecodedValue().equals("1")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "i";
break;
} else if (letter.detected.getDecodedValue().equals("2")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "l";
break;
} else if (letter.detected.getDecodedValue().equals("3")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "t";
break;
} else if (letter.detected.getDecodedValue().equals("4")) {
letter.detected.getB().setDecodedValue("r");
letter.setDecodedValue("r");
add = "n";
break;
}
i++;
}
if (add != null) {
final Letter re = new Letter();
re.setDecodedValue(add);
final LetterComperator let1 = new LetterComperator(re, re);
let1.setValityPercent(0);
re.detected = let1;
lets.add(i + 1, re);
replaceLetters(lets);
}
}
}
|
33833_8 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package connectors;
/**
*
* @author oaz
*/
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.io.*;
public class CsvConnector extends Thread{
//tijdelijk
BufferedWriter writer;
private String path;
private String OutPutCsvS;
private JTextField infoField;
private JTextField dataField;
private JTextArea outputFieldArea;
private String filterText;
private int indexNr;
/**
* Basic constructor
*/
public CsvConnector() {
// Do nothing
}
//TODO: Tijdelijk zeeland drenthe
public CsvConnector(String path, String OutPutCsv, String filterText, int indexNr, JTextField infoField, JTextField dataField, JTextArea outputFieldArea){
this.path = path;
this.OutPutCsvS = OutPutCsv;
this.infoField = infoField;
this.dataField = dataField;
this.outputFieldArea = outputFieldArea;
this.filterText = filterText;
this.indexNr = indexNr;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OutPutCsvS), "ISO-8859-1"));
} catch (Exception e) {
}
}
@Override
public void run(){
try {
long timeExpand = 0;
long begintime = System.currentTimeMillis();
int teller = 0;
int hits = 0;
int mil = 1000;
String RawLine;
//java.io.BufferedReader reader = new BufferedReader(new java.io.FileReader(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "ISO-8859-1" ));
// first read and write header
String header = reader.readLine();
appendText(header);
while ((RawLine = reader.readLine())!= null ) {
// Teller
if (teller == mil) {
infoField.setText(teller + " lines - HITS: " + hits);
mil += 1000;
}
// nextLine[] is an array of values from the line
String[] serperatedLine = RawLine.split(",");
// filtering
if ( (serperatedLine.length > indexNr) && (serperatedLine[indexNr].contains(filterText) )) {
String lineToAppend = "";
hits++;
for (int i = 0; i < serperatedLine.length; i++) {
lineToAppend += serperatedLine[i] + ",";
}
lineToAppend = lineToAppend.substring(0, lineToAppend.length()-1);
appendText(lineToAppend);
}
teller++;
}
// Close reader and writer
reader.close();
writer.close();
// TODO: Werkelijke aantallen er bij zetten
//tijd berekenen
timeExpand = System.currentTimeMillis() - begintime;
int iTimeEx = (int)(timeExpand / 1000);
dataField.setText("DONE IN " + general.Functions.stopWatch(iTimeEx));
//krijgt 2 sec om daarna hardhandig gestopt te worden
this.stop();
}
catch (Exception e) {
//do nothing a.t.m.
}
}
public String[] importHeader(String CsvPath) {
try {
externalModules.openCsv.CSVReader cr = new externalModules.openCsv.CSVReader(new FileReader(CsvPath));
return cr.readNext();
} catch (Exception e) {
// do nothing
}
return null;
}
/**
*
* @param CsvPath contains the
* @param serperator contains the serperator char, is it is not a comma
* @return
*/
public String[] importHeader(String CsvPath, char serperator) {
try {
externalModules.openCsv.CSVReader cr = new externalModules.openCsv.CSVReader(new FileReader(CsvPath),serperator);
return cr.readNext();
} catch (Exception e) {
// do nothing
}
return null;
}
// Append text to file
private void appendText(String text){
try {
writer.write(text);
writer.newLine();
} catch (Exception e) {
}
}
} | IISH/links | LinksProject/src/main/java/connectors/CsvConnector.java | 1,091 | // TODO: Werkelijke aantallen er bij zetten | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package connectors;
/**
*
* @author oaz
*/
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.io.*;
public class CsvConnector extends Thread{
//tijdelijk
BufferedWriter writer;
private String path;
private String OutPutCsvS;
private JTextField infoField;
private JTextField dataField;
private JTextArea outputFieldArea;
private String filterText;
private int indexNr;
/**
* Basic constructor
*/
public CsvConnector() {
// Do nothing
}
//TODO: Tijdelijk zeeland drenthe
public CsvConnector(String path, String OutPutCsv, String filterText, int indexNr, JTextField infoField, JTextField dataField, JTextArea outputFieldArea){
this.path = path;
this.OutPutCsvS = OutPutCsv;
this.infoField = infoField;
this.dataField = dataField;
this.outputFieldArea = outputFieldArea;
this.filterText = filterText;
this.indexNr = indexNr;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OutPutCsvS), "ISO-8859-1"));
} catch (Exception e) {
}
}
@Override
public void run(){
try {
long timeExpand = 0;
long begintime = System.currentTimeMillis();
int teller = 0;
int hits = 0;
int mil = 1000;
String RawLine;
//java.io.BufferedReader reader = new BufferedReader(new java.io.FileReader(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "ISO-8859-1" ));
// first read and write header
String header = reader.readLine();
appendText(header);
while ((RawLine = reader.readLine())!= null ) {
// Teller
if (teller == mil) {
infoField.setText(teller + " lines - HITS: " + hits);
mil += 1000;
}
// nextLine[] is an array of values from the line
String[] serperatedLine = RawLine.split(",");
// filtering
if ( (serperatedLine.length > indexNr) && (serperatedLine[indexNr].contains(filterText) )) {
String lineToAppend = "";
hits++;
for (int i = 0; i < serperatedLine.length; i++) {
lineToAppend += serperatedLine[i] + ",";
}
lineToAppend = lineToAppend.substring(0, lineToAppend.length()-1);
appendText(lineToAppend);
}
teller++;
}
// Close reader and writer
reader.close();
writer.close();
// TODO: Werkelijke<SUF>
//tijd berekenen
timeExpand = System.currentTimeMillis() - begintime;
int iTimeEx = (int)(timeExpand / 1000);
dataField.setText("DONE IN " + general.Functions.stopWatch(iTimeEx));
//krijgt 2 sec om daarna hardhandig gestopt te worden
this.stop();
}
catch (Exception e) {
//do nothing a.t.m.
}
}
public String[] importHeader(String CsvPath) {
try {
externalModules.openCsv.CSVReader cr = new externalModules.openCsv.CSVReader(new FileReader(CsvPath));
return cr.readNext();
} catch (Exception e) {
// do nothing
}
return null;
}
/**
*
* @param CsvPath contains the
* @param serperator contains the serperator char, is it is not a comma
* @return
*/
public String[] importHeader(String CsvPath, char serperator) {
try {
externalModules.openCsv.CSVReader cr = new externalModules.openCsv.CSVReader(new FileReader(CsvPath),serperator);
return cr.readNext();
} catch (Exception e) {
// do nothing
}
return null;
}
// Append text to file
private void appendText(String text){
try {
writer.write(text);
writer.newLine();
} catch (Exception e) {
}
}
} |
172734_19 | import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.awt.Robot;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.AWTException;
import com.onformative.leap.*;
import com.leapmotion.leap.*;
import com.leapmotion.leap.Gesture.Type;
import java.util.*;
import controlP5.*;
import http.requests.*;
import ddf.minim.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class pong extends PApplet {
int x_ball, y_ball, x_direction, y_direction, x_paddle, y_paddle;
boolean pauze, gameOver, canPost, b_showScore, b_showHowTo, b_showSetting, playMusic;
int x_leap, y_leap;
int score;
int lives, mode, combo;
int level;
String name;
PImage img;
PImage bg;
JSONArray json;
Minim minim;
AudioPlayer backgroundsong;
AudioPlayer bounce;
AudioPlayer dead;
LeapMotionP5 leap;
ControlP5 cp5;
Robot robot = null;
int rows = 7; //Number of bricks per row
int columns = 7; //Number of columns
int total = rows * columns; //Total number of bricks
Brick[] box = new Brick[total];
public void setup()
{
size(800,500);
background(255);
playMusic = false;
minim = new Minim(this);
bounce = minim.loadFile("sound/bounce.mp3");
dead = minim.loadFile("sound/dead.wav");
backgroundsong = minim.loadFile("sound/backgroundsong.mp3");
PFont pong = createFont("Arial", 20);
leap = new LeapMotionP5(this);
leap.enableGesture(Type.TYPE_SCREEN_TAP);
try {
robot = new Robot();
}catch(AWTException awt){
println("failed to load robot");
}
for (int i = 0; i < rows; i++){
for (int j = 0; j< columns; j++){
box[i*rows + j] = new Brick((i+1) *width/(rows + 2), 20 + (j+1) * 30); //places all the bricks into the array, properly labelled.
}
}
cp5 = new ControlP5(this);
cp5.setAutoDraw(false);
cp5.setColorBackground(color(255,255,255));
cp5.addTextfield("Name")
.setPosition(width/2 - 100, height/2 - 50)
.setSize(200,40)
.setFont(pong)
.setFocus(true)
.setVisible(false)
.setColor(color(255,0,0))
;
cp5.addButton("KeyboardPress")
.setValue(0)
.setCaptionLabel("Keyboard")
.setPosition(width/2 - 100,150)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("MusicOnOff")
.setValue(0)
.setImages(loadImage("images/play.png"),loadImage("images/play.png"),loadImage("images/play.png"))
.setPosition(width - 55,50)
.updateSize();
;
cp5.addButton("MousePress")
.setValue(0)
.setCaptionLabel("Mouse")
.setPosition(width/2 - 100,230)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("PostHighscore")
.setValue(0)
.setCaptionLabel("Post highscore and continue")
.setPosition(width/2 - 100, height/2 + 20)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("LeapPress")
.setValue(0)
.setCaptionLabel("Leap Motion")
.setPosition(width/2 - 100,310)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Settings")
.setValue(0)
.setCaptionLabel("Choose Gamemode")
.setPosition(width/2 - 100,150)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Highscore")
.setValue(0)
.setPosition(width/2 - 100,230)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("HowToPlay")
.setValue(0)
.setCaptionLabel("How to play")
.setPosition(width/2 - 100,310)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Return")
.setValue(0)
.setPosition(15,50)
.setSize(80,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.getController("Return")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("KeyboardPress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("MousePress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("LeapPress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("Settings")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("Highscore")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("HowToPlay")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("PostHighscore")
.getCaptionLabel()
.setFont(createFont("Arial", 10))
.setColor(0)
;
//position of paddle
x_paddle = 60;
y_paddle = height-15;
//direction of ball
x_direction = -3;
y_direction = -6;
//position of ball
x_ball = width/2;
y_ball = height - 100;
//score
score = 0;
//mode keyboard, mouse, leap motion
mode = 0;
//# lives
lives = 3;
level = 1;
//combo streak
combo = 0;
canPost = true;
img = loadImage("images/heart.png");
bg = loadImage("images/bg.jpg");
gameOver = false;
pauze = true;
b_showScore = false;
b_showHowTo = false;
b_showSetting = false;
}
public void draw()
{
image(bg, 0,0, 800, 500);
if (score == level * total) {
for(int i = 0; i < total; i ++){
box[i].reset();
}
level++;
}
if (pauze) {
cp5.getController("MusicOnOff").setVisible(true);
if (b_showScore){
showHighscore();
}else if(b_showHowTo){
showHowToPlay();
}else if(b_showSetting){
showSettings();
}else{
showPauze();
}
cp5.draw();
PVector vingerPos = leap.getTip(leap.getFinger(0));
fill(color(255, 0, 0));
x_leap = (int)vingerPos.x;
y_leap = (int)vingerPos.y;
ellipse(x_leap, y_leap, 5, 5);
}else{
disableAllControls();
cp5.getController("MusicOnOff").setVisible(false);
if (gameOver==false) {
canPost = true;
play(mode);
}
if (gameOver==true) {
showGameOver();
}
cp5.draw();
}
}
public void showGameOver(){
textAlign(CENTER);
textSize(40);
text("Game Over", width/2, height/4);
textSize(20);
text("Enter name to continue!", width/2, height/4 + 40);
cp5.getController("Name").setVisible(true);
cp5.getController("PostHighscore").setVisible(true);
}
public void showSettings(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(true);
cp5.getController("MousePress").setVisible(true);
cp5.getController("LeapPress").setVisible(true);
cp5.getController("Return").setVisible(true);
}
public void showHighscore(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(true);
fill(255);
rect(width/2 - 200, 60, 400, 396);
textAlign(CENTER);
textSize(25);
fill(0);
text("Highscore", width/2, 100);
for (int i = 0; i < json.size(); i++){
if (i%2 == 1) {
fill(244);
rect(width/2-200, 80+34*i, 400, 34);
}
}
for (int i = 0; i < json.size(); i++) {
JSONObject item = json.getJSONObject(i);
String name = item.getString("Name");
Integer score = item.getInt("Score");
fill(0);
textSize(20);
textAlign(LEFT);
text(name + ":", width/2 - 180, 140+34*i);
textAlign(RIGHT);
text(score, width/2 + 180, 140+34*i);
}
}
public void showPauze(){
stats();
cp5.getController("Settings").setVisible(true);
cp5.getController("Highscore").setVisible(true);
cp5.getController("HowToPlay").setVisible(true);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(false);
}
public void showHowToPlay() {
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(true);
fill(255);
rect(width/2 - 200, 60, 400, 396);
fill(0);
textSize(25);
text("How To Play", width/2, 100);
textSize(15);
textAlign(LEFT);
text("Open and close menu by pressing spacebar", width/2 - 180, 150);
text("You can choose out of 3 gamemodes:", width/2 - 180, 180);
text("Control with Mouse", width/2 - 160, 200);
text("Control with Keyboard", width/2 - 160, 220);
text("Control with Leap Motion", width/2 - 160, 240);
text("'Leap Motion mode' requires actual Leap", width/2 - 180, 270);
text("Motion device", width/2 - 180, 290);
text("After combo score of 20, you receive", width/2 - 180, 310);
text("an extra life", width/2 - 180, 330);
text("Break all the bricks to get to the", width/2 - 180, 370);
text("next level", width/2 - 180, 390);
}
public void disableAllControls(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(false);
}
public void changeMode(){
fill(255);
textAlign(CENTER);
textSize(30);
text("Please select Game Mode", width/2, 100);
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(true);
cp5.getController("MousePress").setVisible(true);
cp5.getController("LeapPress").setVisible(true);
}
public void reset() {
x_direction = -3;
y_direction = -6;
x_ball = width/2;
y_ball = height - 100;
score = 0;
combo = 0;
lives = 3;
level = 1;
gameOver = false;
for(int i = 0; i < total; i ++){
box[i].reset();
}
}
public void drawContent()
{
smooth();
fill(13,51,102);
//draw the paddle
rect(x_paddle,y_paddle,80,5);
//draw the ball
ellipse(x_ball,y_ball,10,10);
}
public void moveWithKeyboard()
{
if(keyPressed) {
if(keyCode == LEFT && x_paddle > 0) {
x_paddle -= 10;
}
if(keyCode == RIGHT && x_paddle < (width - 80)) {
x_paddle+= 10;
}
}
}
public void moveWithMouse()
{
x_paddle = mouseX - 40;
if(x_paddle < 0) {
x_paddle = 0;
}
if(x_paddle > (width - 80)) {
x_paddle = (width - 80);
}
}
public void moveWithLeapMotion(){
PVector vingerPos = leap.getTip(leap.getFinger(0));
x_paddle = (int)vingerPos.x - 40;
if(x_paddle < 0) {
x_paddle = 0;
}
if(x_paddle > (width - 80)) {
x_paddle = (width - 80);
}
}
public void bounceBall()
{
// bounce right wall
if (x_ball >= (width-5))
{
x_direction = -x_direction;
}
//bounce left wall
if (x_ball <= 5)
{
x_direction = -x_direction;
}
//bounce on paddle top
//if y collides and x is between paddle left and right
if (y_ball>=(y_paddle-5) && y_ball<=(y_paddle+5) && x_ball >= x_paddle && x_ball<=(x_paddle+85) && y_direction > 0)
{
int i = x_ball - (x_paddle + 42);
int temp = i/5;
if(temp != 0){
x_direction = temp * level;
}
if(playMusic){
bounce.play();
bounce.rewind();
}
y_direction = -y_direction;
combo++;
}
//bounce roof
if (y_ball <= 35)
{
y_direction = -y_direction;
}
//bounce floor
if (y_ball >= (height - 10))
{
if(playMusic){
dead.play();
dead.rewind();
}
if(lives > 0)
{
fill(color(255,0,0));
rect(0, 497, width, 3);
y_direction = -y_direction;
lives--;
combo = 0;
}
if(lives == 0)
{
gameOver = true;
}
}
for (int i = 0; i < total; i ++)
{
//If ball hits bottom of brick, ball moves down, increment score
if (y_ball - 5 <= box[i].y + box[i].h && y_ball - 5 >= box[i].y && x_ball >= box[i].x && x_ball <= box[i].x + box[i].w && box[i].hit == false )
{
y_direction = -y_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//If ball hits top of brick ball moves up, increment score
if (y_ball + 5 >= box[i].y && y_ball - 5 <= box[i].y + box[i].h/2 && x_ball >= box[i].x && x_ball <= box[i].x + box[i].w && box[i].hit == false )
{
y_direction = -y_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//if ball hits the left of the brick, ball switches to the right, and moves in same direction, increment score
if (x_ball + 5 >= box[i].x && x_ball + 5 <= box[i].x + box[i].w / 2 && y_ball >= box[i].y && y_ball <= box[i].y + box[i].h && box[i].hit == false)
{
x_direction = - x_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//if ball hits the right of the brick, ball switches to the left, and moves in same direction, increment score
if (x_ball - 5 <= box[i].x + box[i].w && x_ball + 5 >= box[i].x + box[i].w / 2 && y_ball >= box[i].y && y_ball <= box[i].y + box[i].h && box[i].hit == false)
{
x_direction = - x_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
}
}
public void play(int mode)
{
for (int i = 0; i<total; i++){
box[i].update();
}
//move ball
x_ball = x_ball + x_direction;
y_ball = y_ball + y_direction;
switch (mode) {
case 1:
moveWithLeapMotion();
break;
case 2:
moveWithKeyboard();
break;
case 3:
moveWithMouse();
break;
}
bounceBall();
drawContent();
//regain live with 20 score
if(combo == 20) {
lives++;
if (lives > 3) {
lives = 3;
}
combo = 0;
}
fill(0, 128, 255);
stats();
}
public void stats() {
//white rect
fill(255);
noStroke();
rect(0,0,width, 35);
fill(13,51,102);
textAlign(LEFT);
textSize(10);
text("Combo : ",10,15);
text(combo,95,15);
text("Level : ",10,28);
text(level,95,28);
textAlign(CENTER);
textSize(30);
text(score, width/2, 30);
textSize(20);
//toon hartjes ipv getal
for (int i = 0; i < lives; i++) {
image(img, (width - 30 - 30*i), 10, 20, 20);
}
}
public void keyPressed()
{
//pauze
if(keyCode == 32 && gameOver == false && mode != 0)
{
if (b_showScore == true) {
b_showScore = false;
}
if (b_showSetting == true) {
b_showSetting = false;
}
if (b_showHowTo == true) {
b_showHowTo = false;
}
pauze = !pauze;
}
}
public void screenTapGestureRecognized(ScreenTapGesture gesture){
/*if(gameOver == false && mode != 0)
{
if (b_showScore == true) {
b_showScore = false;
}
if (b_showSetting == true) {
b_showSetting = false;
}
if (b_showHowTo == true) {
b_showHowTo = false;
}
pauze = !pauze;
} */
if (robot != null) {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int)b.getX();
int y = (int)b.getY();
robot.mouseMove(frame.getLocation().x + x_leap,frame.getLocation().y + y_leap);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mouseMove(x,y);
}
}
public void KeyboardPress(int theValue) {
mode = 2;
pauze = false;
b_showSetting = false;
}
public void PostHighscore(int theValue) {
if(cp5.get(Textfield.class,"Name").getText() != "" & score != 0){
GetRequest get = new GetRequest("http://student.howest.be/arn.vanhoutte/newmedia/post.php?name=" + cp5.get(Textfield.class,"Name").getText() + "&score=" + score);
get.send();
}
cp5.getController("Name").setVisible(false);
cp5.getController("PostHighscore").setVisible(false);
reset();
}
public void MousePress(int theValue) {
mode = 3;
pauze = false;
b_showSetting = false;
}
public void LeapPress(int theValue) {
mode = 1;
pauze = false;
b_showSetting = false;
}
public void Settings(int theValue) {
b_showSetting = true;
}
public void Highscore(int theValue) {
b_showScore = true;
json = loadJSONArray("http://student.howest.be/arn.vanhoutte/newmedia/get.php");
}
public void MusicOnOff(int theValue) {
playMusic = !playMusic;
if(playMusic){
cp5.getController("MusicOnOff").setImages(loadImage("images/play.png"),loadImage("images/play.png"),loadImage("images/play.png"));
backgroundsong.loop();
}else{
cp5.getController("MusicOnOff").setImages(loadImage("images/mute.png"),loadImage("images/mute.png"),loadImage("images/mute.png"));
backgroundsong.pause();
}
}
public void HowToPlay() {
b_showHowTo = true;
}
public void Return() {
b_showScore = false;
b_showSetting = false;
b_showHowTo = false;
}
class Brick
{
float x; //brick x
float y; //brick y
float w; //brick width
float h; //brich height
float r; //brick red val
float g; //grick green val
float b; //brick blue val
boolean hit; //whether or not the brick has been hit
Brick(float x0, float y0)
{
x = x0;
y = y0;
//pastel colors
r = random(128, 255);
g = random(128, 255);
b = random(128, 255);
w = 50; //brick width
h = 15; //brick height
hit = false; //brick is initially not hit
}
//Draws the brick
public void update()
{
if (hit) {
}else{
noStroke();
fill(r, g, b);
rect(x, y, w, h);
}
}
//What happens to the brick once it gets hit
public void gotHit()
{
hit = true;
}
public void reset(){
hit = false;
r = random(128, 255);
g = random(128, 255);
b = random(128, 255);
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "pong" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
| justijndepover/New-Media-Project | pong/build-tmp/source/pong.java | 7,223 | //toon hartjes ipv getal | line_comment | nl | import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.awt.Robot;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.AWTException;
import com.onformative.leap.*;
import com.leapmotion.leap.*;
import com.leapmotion.leap.Gesture.Type;
import java.util.*;
import controlP5.*;
import http.requests.*;
import ddf.minim.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class pong extends PApplet {
int x_ball, y_ball, x_direction, y_direction, x_paddle, y_paddle;
boolean pauze, gameOver, canPost, b_showScore, b_showHowTo, b_showSetting, playMusic;
int x_leap, y_leap;
int score;
int lives, mode, combo;
int level;
String name;
PImage img;
PImage bg;
JSONArray json;
Minim minim;
AudioPlayer backgroundsong;
AudioPlayer bounce;
AudioPlayer dead;
LeapMotionP5 leap;
ControlP5 cp5;
Robot robot = null;
int rows = 7; //Number of bricks per row
int columns = 7; //Number of columns
int total = rows * columns; //Total number of bricks
Brick[] box = new Brick[total];
public void setup()
{
size(800,500);
background(255);
playMusic = false;
minim = new Minim(this);
bounce = minim.loadFile("sound/bounce.mp3");
dead = minim.loadFile("sound/dead.wav");
backgroundsong = minim.loadFile("sound/backgroundsong.mp3");
PFont pong = createFont("Arial", 20);
leap = new LeapMotionP5(this);
leap.enableGesture(Type.TYPE_SCREEN_TAP);
try {
robot = new Robot();
}catch(AWTException awt){
println("failed to load robot");
}
for (int i = 0; i < rows; i++){
for (int j = 0; j< columns; j++){
box[i*rows + j] = new Brick((i+1) *width/(rows + 2), 20 + (j+1) * 30); //places all the bricks into the array, properly labelled.
}
}
cp5 = new ControlP5(this);
cp5.setAutoDraw(false);
cp5.setColorBackground(color(255,255,255));
cp5.addTextfield("Name")
.setPosition(width/2 - 100, height/2 - 50)
.setSize(200,40)
.setFont(pong)
.setFocus(true)
.setVisible(false)
.setColor(color(255,0,0))
;
cp5.addButton("KeyboardPress")
.setValue(0)
.setCaptionLabel("Keyboard")
.setPosition(width/2 - 100,150)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("MusicOnOff")
.setValue(0)
.setImages(loadImage("images/play.png"),loadImage("images/play.png"),loadImage("images/play.png"))
.setPosition(width - 55,50)
.updateSize();
;
cp5.addButton("MousePress")
.setValue(0)
.setCaptionLabel("Mouse")
.setPosition(width/2 - 100,230)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("PostHighscore")
.setValue(0)
.setCaptionLabel("Post highscore and continue")
.setPosition(width/2 - 100, height/2 + 20)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("LeapPress")
.setValue(0)
.setCaptionLabel("Leap Motion")
.setPosition(width/2 - 100,310)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Settings")
.setValue(0)
.setCaptionLabel("Choose Gamemode")
.setPosition(width/2 - 100,150)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Highscore")
.setValue(0)
.setPosition(width/2 - 100,230)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("HowToPlay")
.setValue(0)
.setCaptionLabel("How to play")
.setPosition(width/2 - 100,310)
.setSize(200,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Return")
.setValue(0)
.setPosition(15,50)
.setSize(80,40)
.setVisible(false)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.getController("Return")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("KeyboardPress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("MousePress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("LeapPress")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("Settings")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("Highscore")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("HowToPlay")
.getCaptionLabel()
.setFont(createFont("Arial", 15))
.setColor(0)
;
cp5.getController("PostHighscore")
.getCaptionLabel()
.setFont(createFont("Arial", 10))
.setColor(0)
;
//position of paddle
x_paddle = 60;
y_paddle = height-15;
//direction of ball
x_direction = -3;
y_direction = -6;
//position of ball
x_ball = width/2;
y_ball = height - 100;
//score
score = 0;
//mode keyboard, mouse, leap motion
mode = 0;
//# lives
lives = 3;
level = 1;
//combo streak
combo = 0;
canPost = true;
img = loadImage("images/heart.png");
bg = loadImage("images/bg.jpg");
gameOver = false;
pauze = true;
b_showScore = false;
b_showHowTo = false;
b_showSetting = false;
}
public void draw()
{
image(bg, 0,0, 800, 500);
if (score == level * total) {
for(int i = 0; i < total; i ++){
box[i].reset();
}
level++;
}
if (pauze) {
cp5.getController("MusicOnOff").setVisible(true);
if (b_showScore){
showHighscore();
}else if(b_showHowTo){
showHowToPlay();
}else if(b_showSetting){
showSettings();
}else{
showPauze();
}
cp5.draw();
PVector vingerPos = leap.getTip(leap.getFinger(0));
fill(color(255, 0, 0));
x_leap = (int)vingerPos.x;
y_leap = (int)vingerPos.y;
ellipse(x_leap, y_leap, 5, 5);
}else{
disableAllControls();
cp5.getController("MusicOnOff").setVisible(false);
if (gameOver==false) {
canPost = true;
play(mode);
}
if (gameOver==true) {
showGameOver();
}
cp5.draw();
}
}
public void showGameOver(){
textAlign(CENTER);
textSize(40);
text("Game Over", width/2, height/4);
textSize(20);
text("Enter name to continue!", width/2, height/4 + 40);
cp5.getController("Name").setVisible(true);
cp5.getController("PostHighscore").setVisible(true);
}
public void showSettings(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(true);
cp5.getController("MousePress").setVisible(true);
cp5.getController("LeapPress").setVisible(true);
cp5.getController("Return").setVisible(true);
}
public void showHighscore(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(true);
fill(255);
rect(width/2 - 200, 60, 400, 396);
textAlign(CENTER);
textSize(25);
fill(0);
text("Highscore", width/2, 100);
for (int i = 0; i < json.size(); i++){
if (i%2 == 1) {
fill(244);
rect(width/2-200, 80+34*i, 400, 34);
}
}
for (int i = 0; i < json.size(); i++) {
JSONObject item = json.getJSONObject(i);
String name = item.getString("Name");
Integer score = item.getInt("Score");
fill(0);
textSize(20);
textAlign(LEFT);
text(name + ":", width/2 - 180, 140+34*i);
textAlign(RIGHT);
text(score, width/2 + 180, 140+34*i);
}
}
public void showPauze(){
stats();
cp5.getController("Settings").setVisible(true);
cp5.getController("Highscore").setVisible(true);
cp5.getController("HowToPlay").setVisible(true);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(false);
}
public void showHowToPlay() {
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(true);
fill(255);
rect(width/2 - 200, 60, 400, 396);
fill(0);
textSize(25);
text("How To Play", width/2, 100);
textSize(15);
textAlign(LEFT);
text("Open and close menu by pressing spacebar", width/2 - 180, 150);
text("You can choose out of 3 gamemodes:", width/2 - 180, 180);
text("Control with Mouse", width/2 - 160, 200);
text("Control with Keyboard", width/2 - 160, 220);
text("Control with Leap Motion", width/2 - 160, 240);
text("'Leap Motion mode' requires actual Leap", width/2 - 180, 270);
text("Motion device", width/2 - 180, 290);
text("After combo score of 20, you receive", width/2 - 180, 310);
text("an extra life", width/2 - 180, 330);
text("Break all the bricks to get to the", width/2 - 180, 370);
text("next level", width/2 - 180, 390);
}
public void disableAllControls(){
stats();
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(false);
cp5.getController("MousePress").setVisible(false);
cp5.getController("LeapPress").setVisible(false);
cp5.getController("Return").setVisible(false);
}
public void changeMode(){
fill(255);
textAlign(CENTER);
textSize(30);
text("Please select Game Mode", width/2, 100);
cp5.getController("Settings").setVisible(false);
cp5.getController("Highscore").setVisible(false);
cp5.getController("HowToPlay").setVisible(false);
cp5.getController("KeyboardPress").setVisible(true);
cp5.getController("MousePress").setVisible(true);
cp5.getController("LeapPress").setVisible(true);
}
public void reset() {
x_direction = -3;
y_direction = -6;
x_ball = width/2;
y_ball = height - 100;
score = 0;
combo = 0;
lives = 3;
level = 1;
gameOver = false;
for(int i = 0; i < total; i ++){
box[i].reset();
}
}
public void drawContent()
{
smooth();
fill(13,51,102);
//draw the paddle
rect(x_paddle,y_paddle,80,5);
//draw the ball
ellipse(x_ball,y_ball,10,10);
}
public void moveWithKeyboard()
{
if(keyPressed) {
if(keyCode == LEFT && x_paddle > 0) {
x_paddle -= 10;
}
if(keyCode == RIGHT && x_paddle < (width - 80)) {
x_paddle+= 10;
}
}
}
public void moveWithMouse()
{
x_paddle = mouseX - 40;
if(x_paddle < 0) {
x_paddle = 0;
}
if(x_paddle > (width - 80)) {
x_paddle = (width - 80);
}
}
public void moveWithLeapMotion(){
PVector vingerPos = leap.getTip(leap.getFinger(0));
x_paddle = (int)vingerPos.x - 40;
if(x_paddle < 0) {
x_paddle = 0;
}
if(x_paddle > (width - 80)) {
x_paddle = (width - 80);
}
}
public void bounceBall()
{
// bounce right wall
if (x_ball >= (width-5))
{
x_direction = -x_direction;
}
//bounce left wall
if (x_ball <= 5)
{
x_direction = -x_direction;
}
//bounce on paddle top
//if y collides and x is between paddle left and right
if (y_ball>=(y_paddle-5) && y_ball<=(y_paddle+5) && x_ball >= x_paddle && x_ball<=(x_paddle+85) && y_direction > 0)
{
int i = x_ball - (x_paddle + 42);
int temp = i/5;
if(temp != 0){
x_direction = temp * level;
}
if(playMusic){
bounce.play();
bounce.rewind();
}
y_direction = -y_direction;
combo++;
}
//bounce roof
if (y_ball <= 35)
{
y_direction = -y_direction;
}
//bounce floor
if (y_ball >= (height - 10))
{
if(playMusic){
dead.play();
dead.rewind();
}
if(lives > 0)
{
fill(color(255,0,0));
rect(0, 497, width, 3);
y_direction = -y_direction;
lives--;
combo = 0;
}
if(lives == 0)
{
gameOver = true;
}
}
for (int i = 0; i < total; i ++)
{
//If ball hits bottom of brick, ball moves down, increment score
if (y_ball - 5 <= box[i].y + box[i].h && y_ball - 5 >= box[i].y && x_ball >= box[i].x && x_ball <= box[i].x + box[i].w && box[i].hit == false )
{
y_direction = -y_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//If ball hits top of brick ball moves up, increment score
if (y_ball + 5 >= box[i].y && y_ball - 5 <= box[i].y + box[i].h/2 && x_ball >= box[i].x && x_ball <= box[i].x + box[i].w && box[i].hit == false )
{
y_direction = -y_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//if ball hits the left of the brick, ball switches to the right, and moves in same direction, increment score
if (x_ball + 5 >= box[i].x && x_ball + 5 <= box[i].x + box[i].w / 2 && y_ball >= box[i].y && y_ball <= box[i].y + box[i].h && box[i].hit == false)
{
x_direction = - x_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
//if ball hits the right of the brick, ball switches to the left, and moves in same direction, increment score
if (x_ball - 5 <= box[i].x + box[i].w && x_ball + 5 >= box[i].x + box[i].w / 2 && y_ball >= box[i].y && y_ball <= box[i].y + box[i].h && box[i].hit == false)
{
x_direction = - x_direction;
box[i].gotHit();
score ++;
if(playMusic){
bounce.play();
bounce.rewind();
}
}
}
}
public void play(int mode)
{
for (int i = 0; i<total; i++){
box[i].update();
}
//move ball
x_ball = x_ball + x_direction;
y_ball = y_ball + y_direction;
switch (mode) {
case 1:
moveWithLeapMotion();
break;
case 2:
moveWithKeyboard();
break;
case 3:
moveWithMouse();
break;
}
bounceBall();
drawContent();
//regain live with 20 score
if(combo == 20) {
lives++;
if (lives > 3) {
lives = 3;
}
combo = 0;
}
fill(0, 128, 255);
stats();
}
public void stats() {
//white rect
fill(255);
noStroke();
rect(0,0,width, 35);
fill(13,51,102);
textAlign(LEFT);
textSize(10);
text("Combo : ",10,15);
text(combo,95,15);
text("Level : ",10,28);
text(level,95,28);
textAlign(CENTER);
textSize(30);
text(score, width/2, 30);
textSize(20);
//toon hartjes<SUF>
for (int i = 0; i < lives; i++) {
image(img, (width - 30 - 30*i), 10, 20, 20);
}
}
public void keyPressed()
{
//pauze
if(keyCode == 32 && gameOver == false && mode != 0)
{
if (b_showScore == true) {
b_showScore = false;
}
if (b_showSetting == true) {
b_showSetting = false;
}
if (b_showHowTo == true) {
b_showHowTo = false;
}
pauze = !pauze;
}
}
public void screenTapGestureRecognized(ScreenTapGesture gesture){
/*if(gameOver == false && mode != 0)
{
if (b_showScore == true) {
b_showScore = false;
}
if (b_showSetting == true) {
b_showSetting = false;
}
if (b_showHowTo == true) {
b_showHowTo = false;
}
pauze = !pauze;
} */
if (robot != null) {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int)b.getX();
int y = (int)b.getY();
robot.mouseMove(frame.getLocation().x + x_leap,frame.getLocation().y + y_leap);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mouseMove(x,y);
}
}
public void KeyboardPress(int theValue) {
mode = 2;
pauze = false;
b_showSetting = false;
}
public void PostHighscore(int theValue) {
if(cp5.get(Textfield.class,"Name").getText() != "" & score != 0){
GetRequest get = new GetRequest("http://student.howest.be/arn.vanhoutte/newmedia/post.php?name=" + cp5.get(Textfield.class,"Name").getText() + "&score=" + score);
get.send();
}
cp5.getController("Name").setVisible(false);
cp5.getController("PostHighscore").setVisible(false);
reset();
}
public void MousePress(int theValue) {
mode = 3;
pauze = false;
b_showSetting = false;
}
public void LeapPress(int theValue) {
mode = 1;
pauze = false;
b_showSetting = false;
}
public void Settings(int theValue) {
b_showSetting = true;
}
public void Highscore(int theValue) {
b_showScore = true;
json = loadJSONArray("http://student.howest.be/arn.vanhoutte/newmedia/get.php");
}
public void MusicOnOff(int theValue) {
playMusic = !playMusic;
if(playMusic){
cp5.getController("MusicOnOff").setImages(loadImage("images/play.png"),loadImage("images/play.png"),loadImage("images/play.png"));
backgroundsong.loop();
}else{
cp5.getController("MusicOnOff").setImages(loadImage("images/mute.png"),loadImage("images/mute.png"),loadImage("images/mute.png"));
backgroundsong.pause();
}
}
public void HowToPlay() {
b_showHowTo = true;
}
public void Return() {
b_showScore = false;
b_showSetting = false;
b_showHowTo = false;
}
class Brick
{
float x; //brick x
float y; //brick y
float w; //brick width
float h; //brich height
float r; //brick red val
float g; //grick green val
float b; //brick blue val
boolean hit; //whether or not the brick has been hit
Brick(float x0, float y0)
{
x = x0;
y = y0;
//pastel colors
r = random(128, 255);
g = random(128, 255);
b = random(128, 255);
w = 50; //brick width
h = 15; //brick height
hit = false; //brick is initially not hit
}
//Draws the brick
public void update()
{
if (hit) {
}else{
noStroke();
fill(r, g, b);
rect(x, y, w, h);
}
}
//What happens to the brick once it gets hit
public void gotHit()
{
hit = true;
}
public void reset(){
hit = false;
r = random(128, 255);
g = random(128, 255);
b = random(128, 255);
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "pong" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
33032_16 | package org.openstreetmap.josm.plugins.ods.bag.modifiers;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_Address;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_HouseNumber;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_HouseNumberImpl;
import org.openstreetmap.josm.plugins.ods.entities.EntityModifier;
/**
* <p>
* The BAG database was built on the assumption that all house numbers in the Netherlands consisted of a numeric value,
* followed by an optional letter, followed by an optional alphanumeric extension. This assumption was wrong. A number
* of localities have house numbers that follow these conventions with one notable exception: they start with a letter.
* </p>
* <p>
* Because the BAG encodes the required house number field as an integer, a leading letter is not possible. To work
* around this limitation, the BAG engineers conceived of a hack that appended that letter to the street name instead.
* On a printed address label, this doesn't matter too much (house number <u>underlined</u> for emphasis):
* </p>
* <dl>
* <dt>Local usage (signage etc.)</dt>
* <dd>Dominee Sicco Tjadenstraat <u>C52</u></dd>
* <dt>BAG-hack</dt>
* <dd>Dominee Sicco Tjadenstraat C <u>52</u></dd>
* </dl>
* <p>
* The downside of this hack is that consumers of BAG data now have streets named "Dominee Sicco Tjadenstraat
* C", where in reality the street sign says "Dominee Sicco Tjadenstraat"; and house numbers that lack
* their leading letter, whereas on the houses themselves the sign includes it.
* </p>
* <p>
* OpenStreetMap has no such limitation, so this class reverses this hack for known postcodes. The list of postcodes
* can be extended, but care should be taken to include only those postcodes that contain addresses on streets that are
* applicable. It is fine to include postcodes that contain addresses on streets that do not end with a letter as
* well as those that do, but bear in mind that not every street that ends in a letter should be passed to this class
* (e.g., "Hoofdstraat W" in Winsum is literally called this on local signage).
* </p>
*
* <p>
* @author Jeroen Hoek
* @author gertjan
*
*/
public class NL_PrefixedHouseNumberAddressModifier implements EntityModifier<NL_Address> {
static final Set<String> applicablePostcodes4;
static final Set<String> applicablePostcodes6;
static {
// Add larger postcode areas by leading number here.
applicablePostcodes4 = new HashSet<>(Arrays.asList(
// Pekela; het Pekelder ABC.
"9663"
));
// More localised postcode areas can be added here.
applicablePostcodes6 = new HashSet<>(Arrays.asList(
// Zinkweg, Nieuw-Beijerland. Drie adressen in Zinkweg liggen net in een andere
// gemeente. Zij hebben de voorloopletter 'N' (voor Nieuw-Beijerland). Het bedrijf dat
// op Zinkweg N4 zit gebruikt de voorloopletter ook letterlijk zo op bebording en website.
"3264LK",
// Langbroekerdijk, Langbroek. Voorloopletter (A of B) staat op de
// huisnummerbordjes.
"3947BA",
"3947BB",
"3947BC",
"3947BD",
"3947BE",
"3947BG",
"3947BH",
"3947BJ",
"3947BK",
// Graafjansdijk, Westdorpe (Terneuzen). Voorloopletter (A of B) staat op de
// huisnummerbordjes.
"4554AE",
"4554AG",
"4554AH",
"4554AJ",
"4554AK",
"4554AL",
"4554AM",
"4554CA",
"4554CB",
"4554CC",
"4554CD",
"4554LA",
"4554LB",
"4554LC",
"4554LD",
"4554LE",
"4554LG",
// Deken van Erpstraat en Meierij, Sint-Oedenrode. Flats uit 2007 in bestaande straten.
// Voorloopletters zijn gebruikt om adresruimte te creëren in
"5492DE",
"5492DG",
"5492DH",
"5492DJ",
"5492DK",
"5492DL",
// Adelbert van Scharnlaan, Maastricht. Een lange straat met flats met voorloopletter.
// (A t/m S). Boven de portieken van de flats staan de huisnummers die daar bij horen,
// met voorloopletter. Straatnaamborden spreken ook enkel van Adelbert van Scharnlaan
// (geen letter erachter).
"6226EC",
"6226ED",
"6226EE",
"6226EG",
"6226EH",
"6226EJ",
"6226EK",
"6226EL",
"6226EM",
"6226EN",
"6226EP",
"6226ER",
"6226ES",
"6226ET",
"6226EV",
"6226EW",
"6226EX",
"6226EZ",
"6226HT",
"6226HV",
"6226HW",
"6227CE",
"6227CG",
"6227CH",
"6227VE",
"6227VG",
"6227VH",
// Wethouder Vrankenstraat, Maastricht. Deze straat heeft naast gewone huisnummers
// één flat met voorloopletters aan het begin van de straat.
"6227CE",
"6227CG",
"6227CH",
// Burgemeester Kessensingel, Maastricht. Deze straat heeft naast gewone huisnummers
// drie flats ('A', 'B', 'C') met voorloopletters. Op de straatnaamborden bestaat
// alleen de Burgemeester Kessensingel zonder toevoeging.
"6227VE",
"6227VG",
"6227VH",
// Averbergen, Olst. Dit zijn (verzorgings)flats waar de vleugels een eigen letter
// hebben. De straat heet gewoon Averbergen.
"8121CD",
"8121CE",
"8121CG",
"8121CH",
"8121CJ",
// Recreatiewoningen aan de Beukenlaan in Oudemirdum.
// Huisnummers beginnen allen met 'Z' (valt op de huisnummerplaatjes te zien).
"8567HE",
"8567HG",
// Nieuwebildtzijl. Adressen hebben gehuchtnaam als 'straatnaam', maar een paar adressen
// (deze postcode) liggen net in een andere gemeente (Nieuwebildtzijl ligt in de Waadhoeke).
// Nu is dat Noardeast-Frsylân, maar dat was Ferwerderadiel. Vandaar de 'F' die deze
// huisnummers als voorloopletter hebben (valt op de huisnummerplaatjes te zien).
"9074PA",
// Bartlehiem. Adressen hebben gehuchtnaam als 'straatnaam', maar een paar adressen
// (deze postcode) liggen net in een andere gemeente (de rest van Bartlehiem ligt in
// Tytsjerksteradiel). Nu is dat Noardeast-Frsylân, maar dat was Ferwerderadiel. Vandaar
// de 'F' die deze huisnummers als voorloopletter hebben (valt op de huisnummerplaatjes te zien).
"9178GH",
// Recreatiepark Oosterduinen in Norg.
// Alle adressen hebben Oosterduinen (het terrein) als 'straatnaam'. Paden tussen de huisjes hebben
// eigen namen die niet in de adressen terugkeren.
// Zie ook: http://oosterduinen.nl/
"9331WB",
"9331WC",
"9331WD",
"9331WE",
"9331WG",
"9331WH",
"9331WK",
// Amerika, Een (Drenthe). Recreatiewoningen met een voorloopletter om binnen de adresruimte
// te passen.
"9342TN",
// Fivelkade Appingedam. De woonboten aan de kade hebben een voorloopletter 'W'. De huizen
// aan dezelfde straat niet. Zonder voorloopletter botsen de nummers.
"9901GE"
));
// False positives: these streets look like they might be used to hide a voorloopletter, but
// are in fact valid street names. They are documented here to prevent contributors from wasting
// time hunting down these streets ending in a letter.
/*
2064KA
Zijkanaal C, Spaarndam. Vernoemd naar naastgelegen kanaal dat zo heet.
5521E*
Lindehof N, M, B, Z in Eersel. Letter hoort bij straatnaam.
6225CH
In de O, Maastricht. Straat heet gewoon zo.
7739PX
Kolonieweg O. Staat zo op straatnaambordjes. Vroeger zal deze weg in de naastgelegen gemeente
verder hebben gelopen, maar die lijkt hem hernoemd te hebben naar 'De Kolonie'.
8011VS
Kleine A, Zwolle. Letter hoort bij straatnaam.
9951A*
Winsum, Hoofdstraat O en Hoofdstraat W. O en W staan voor Obergum en Winsum, respectievelijk.
9711HV
Kleine der A, Groningen, de A is een gracht in Groningen.
9712A*
Hoge der A, Groningen, de A is een gracht in Groningen.
9718B*
Lage der A, Groningen, de A is een gracht in Groningen.
*/ }
@Override
public Class<NL_Address> getTargetType() {
return NL_Address.class;
}
@Override
public void modify(NL_Address address) {
String street = address.getStreetName();
String prefix = street.substring(street.length() -1);
address.setStreetName(street.substring(0, street.length() - 2));
modifyHouseNumber(address, prefix);
}
private void modifyHouseNumber(NL_Address address, String prefix) {
NL_HouseNumber hnr = address.getHouseNumber();
address.setHouseNumber(new NL_HouseNumberImpl(
prefix, hnr.getHouseNumber(), hnr.getHouseLetter(),
hnr.getHouseNumberExtra()));
}
@Override
public boolean isApplicable(NL_Address address) {
String postcode6 = address.getPostcode();
if (postcode6 == null) return false;
// The 1234 part of 1234AB.
String postcode4 = postcode6.substring(0, 4);
if (applicablePostcodes4.contains(postcode4) || applicablePostcodes6.contains(postcode6)) {
return address.getStreetName() != null &&
// Ignore addresses on streets that do not end in a single capital letter.
address.getStreetName().matches(".+ [A-Z]") &&
address.getHouseNumber() != null;
}
return false;
}
}
| SanderH/josm-ods-bag | src/main/java/org/openstreetmap/josm/plugins/ods/bag/modifiers/NL_PrefixedHouseNumberAddressModifier.java | 3,025 | // één flat met voorloopletters aan het begin van de straat. | line_comment | nl | package org.openstreetmap.josm.plugins.ods.bag.modifiers;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_Address;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_HouseNumber;
import org.openstreetmap.josm.plugins.ods.bag.entity.NL_HouseNumberImpl;
import org.openstreetmap.josm.plugins.ods.entities.EntityModifier;
/**
* <p>
* The BAG database was built on the assumption that all house numbers in the Netherlands consisted of a numeric value,
* followed by an optional letter, followed by an optional alphanumeric extension. This assumption was wrong. A number
* of localities have house numbers that follow these conventions with one notable exception: they start with a letter.
* </p>
* <p>
* Because the BAG encodes the required house number field as an integer, a leading letter is not possible. To work
* around this limitation, the BAG engineers conceived of a hack that appended that letter to the street name instead.
* On a printed address label, this doesn't matter too much (house number <u>underlined</u> for emphasis):
* </p>
* <dl>
* <dt>Local usage (signage etc.)</dt>
* <dd>Dominee Sicco Tjadenstraat <u>C52</u></dd>
* <dt>BAG-hack</dt>
* <dd>Dominee Sicco Tjadenstraat C <u>52</u></dd>
* </dl>
* <p>
* The downside of this hack is that consumers of BAG data now have streets named "Dominee Sicco Tjadenstraat
* C", where in reality the street sign says "Dominee Sicco Tjadenstraat"; and house numbers that lack
* their leading letter, whereas on the houses themselves the sign includes it.
* </p>
* <p>
* OpenStreetMap has no such limitation, so this class reverses this hack for known postcodes. The list of postcodes
* can be extended, but care should be taken to include only those postcodes that contain addresses on streets that are
* applicable. It is fine to include postcodes that contain addresses on streets that do not end with a letter as
* well as those that do, but bear in mind that not every street that ends in a letter should be passed to this class
* (e.g., "Hoofdstraat W" in Winsum is literally called this on local signage).
* </p>
*
* <p>
* @author Jeroen Hoek
* @author gertjan
*
*/
public class NL_PrefixedHouseNumberAddressModifier implements EntityModifier<NL_Address> {
static final Set<String> applicablePostcodes4;
static final Set<String> applicablePostcodes6;
static {
// Add larger postcode areas by leading number here.
applicablePostcodes4 = new HashSet<>(Arrays.asList(
// Pekela; het Pekelder ABC.
"9663"
));
// More localised postcode areas can be added here.
applicablePostcodes6 = new HashSet<>(Arrays.asList(
// Zinkweg, Nieuw-Beijerland. Drie adressen in Zinkweg liggen net in een andere
// gemeente. Zij hebben de voorloopletter 'N' (voor Nieuw-Beijerland). Het bedrijf dat
// op Zinkweg N4 zit gebruikt de voorloopletter ook letterlijk zo op bebording en website.
"3264LK",
// Langbroekerdijk, Langbroek. Voorloopletter (A of B) staat op de
// huisnummerbordjes.
"3947BA",
"3947BB",
"3947BC",
"3947BD",
"3947BE",
"3947BG",
"3947BH",
"3947BJ",
"3947BK",
// Graafjansdijk, Westdorpe (Terneuzen). Voorloopletter (A of B) staat op de
// huisnummerbordjes.
"4554AE",
"4554AG",
"4554AH",
"4554AJ",
"4554AK",
"4554AL",
"4554AM",
"4554CA",
"4554CB",
"4554CC",
"4554CD",
"4554LA",
"4554LB",
"4554LC",
"4554LD",
"4554LE",
"4554LG",
// Deken van Erpstraat en Meierij, Sint-Oedenrode. Flats uit 2007 in bestaande straten.
// Voorloopletters zijn gebruikt om adresruimte te creëren in
"5492DE",
"5492DG",
"5492DH",
"5492DJ",
"5492DK",
"5492DL",
// Adelbert van Scharnlaan, Maastricht. Een lange straat met flats met voorloopletter.
// (A t/m S). Boven de portieken van de flats staan de huisnummers die daar bij horen,
// met voorloopletter. Straatnaamborden spreken ook enkel van Adelbert van Scharnlaan
// (geen letter erachter).
"6226EC",
"6226ED",
"6226EE",
"6226EG",
"6226EH",
"6226EJ",
"6226EK",
"6226EL",
"6226EM",
"6226EN",
"6226EP",
"6226ER",
"6226ES",
"6226ET",
"6226EV",
"6226EW",
"6226EX",
"6226EZ",
"6226HT",
"6226HV",
"6226HW",
"6227CE",
"6227CG",
"6227CH",
"6227VE",
"6227VG",
"6227VH",
// Wethouder Vrankenstraat, Maastricht. Deze straat heeft naast gewone huisnummers
// één flat<SUF>
"6227CE",
"6227CG",
"6227CH",
// Burgemeester Kessensingel, Maastricht. Deze straat heeft naast gewone huisnummers
// drie flats ('A', 'B', 'C') met voorloopletters. Op de straatnaamborden bestaat
// alleen de Burgemeester Kessensingel zonder toevoeging.
"6227VE",
"6227VG",
"6227VH",
// Averbergen, Olst. Dit zijn (verzorgings)flats waar de vleugels een eigen letter
// hebben. De straat heet gewoon Averbergen.
"8121CD",
"8121CE",
"8121CG",
"8121CH",
"8121CJ",
// Recreatiewoningen aan de Beukenlaan in Oudemirdum.
// Huisnummers beginnen allen met 'Z' (valt op de huisnummerplaatjes te zien).
"8567HE",
"8567HG",
// Nieuwebildtzijl. Adressen hebben gehuchtnaam als 'straatnaam', maar een paar adressen
// (deze postcode) liggen net in een andere gemeente (Nieuwebildtzijl ligt in de Waadhoeke).
// Nu is dat Noardeast-Frsylân, maar dat was Ferwerderadiel. Vandaar de 'F' die deze
// huisnummers als voorloopletter hebben (valt op de huisnummerplaatjes te zien).
"9074PA",
// Bartlehiem. Adressen hebben gehuchtnaam als 'straatnaam', maar een paar adressen
// (deze postcode) liggen net in een andere gemeente (de rest van Bartlehiem ligt in
// Tytsjerksteradiel). Nu is dat Noardeast-Frsylân, maar dat was Ferwerderadiel. Vandaar
// de 'F' die deze huisnummers als voorloopletter hebben (valt op de huisnummerplaatjes te zien).
"9178GH",
// Recreatiepark Oosterduinen in Norg.
// Alle adressen hebben Oosterduinen (het terrein) als 'straatnaam'. Paden tussen de huisjes hebben
// eigen namen die niet in de adressen terugkeren.
// Zie ook: http://oosterduinen.nl/
"9331WB",
"9331WC",
"9331WD",
"9331WE",
"9331WG",
"9331WH",
"9331WK",
// Amerika, Een (Drenthe). Recreatiewoningen met een voorloopletter om binnen de adresruimte
// te passen.
"9342TN",
// Fivelkade Appingedam. De woonboten aan de kade hebben een voorloopletter 'W'. De huizen
// aan dezelfde straat niet. Zonder voorloopletter botsen de nummers.
"9901GE"
));
// False positives: these streets look like they might be used to hide a voorloopletter, but
// are in fact valid street names. They are documented here to prevent contributors from wasting
// time hunting down these streets ending in a letter.
/*
2064KA
Zijkanaal C, Spaarndam. Vernoemd naar naastgelegen kanaal dat zo heet.
5521E*
Lindehof N, M, B, Z in Eersel. Letter hoort bij straatnaam.
6225CH
In de O, Maastricht. Straat heet gewoon zo.
7739PX
Kolonieweg O. Staat zo op straatnaambordjes. Vroeger zal deze weg in de naastgelegen gemeente
verder hebben gelopen, maar die lijkt hem hernoemd te hebben naar 'De Kolonie'.
8011VS
Kleine A, Zwolle. Letter hoort bij straatnaam.
9951A*
Winsum, Hoofdstraat O en Hoofdstraat W. O en W staan voor Obergum en Winsum, respectievelijk.
9711HV
Kleine der A, Groningen, de A is een gracht in Groningen.
9712A*
Hoge der A, Groningen, de A is een gracht in Groningen.
9718B*
Lage der A, Groningen, de A is een gracht in Groningen.
*/ }
@Override
public Class<NL_Address> getTargetType() {
return NL_Address.class;
}
@Override
public void modify(NL_Address address) {
String street = address.getStreetName();
String prefix = street.substring(street.length() -1);
address.setStreetName(street.substring(0, street.length() - 2));
modifyHouseNumber(address, prefix);
}
private void modifyHouseNumber(NL_Address address, String prefix) {
NL_HouseNumber hnr = address.getHouseNumber();
address.setHouseNumber(new NL_HouseNumberImpl(
prefix, hnr.getHouseNumber(), hnr.getHouseLetter(),
hnr.getHouseNumberExtra()));
}
@Override
public boolean isApplicable(NL_Address address) {
String postcode6 = address.getPostcode();
if (postcode6 == null) return false;
// The 1234 part of 1234AB.
String postcode4 = postcode6.substring(0, 4);
if (applicablePostcodes4.contains(postcode4) || applicablePostcodes6.contains(postcode6)) {
return address.getStreetName() != null &&
// Ignore addresses on streets that do not end in a single capital letter.
address.getStreetName().matches(".+ [A-Z]") &&
address.getHouseNumber() != null;
}
return false;
}
}
|
34540_7 | /**
* AODA - Aspect Oriented Debugging Architecture
* Copyright (C) 2007-2009 Wouter De Borger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser 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 ajdi;
import java.util.List;
import com.sun.jdi.IncompatibleThreadStateException;
public interface Aspect extends ClassType, Shadow{
public static final int PER_SINGLETON = 0x01;
public static final int PER_OBJECT = 0x02;
public static final int PER_CLASS = 0x04;
/**
* per object per joinpoint
*/
public static final int PER_JOINPOINT = 0x08;
public static final int PER_VM_JOINPOINT = PER_JOINPOINT + PER_SINGLETON;
public static final int PER_OBJECT_JOINPOINT = PER_JOINPOINT + PER_OBJECT;
public static final int PER_CLASS_JOINPOINT = PER_JOINPOINT + PER_CLASS;
/**
* @return all advises defined in this aspect and all of it's ancestors
*/
public List<Advice> allAdvices();
/**
* @return all advises defined directly in this aspect
*/
public List<Advice> advices();
/**
* @param sig the advice signature of the advice, no regex
* @return a list of advises having this signature
*/
public List<Advice> advicesBySignature(String sig);
/**
* @param sig the advice signature of the advice
* @return the concrete version of the advice having this signature
*/
//TODO onnozele semantiek
//denk aan de binding,....
public Advice concreteAdviceBySignature(String sig);
public boolean isPerSingleton();
public boolean isPerObject();
public int getPer();
// /**
// * @return
// */
// public List<AspectInstance> allInstances();
//geen singleton: error
/**
* if this aspect is not a singleton, an is thrown,
* otherwise the worker thread is used to invoke the needed commands to retrieve the instance
*
* this call may use jdi.classType.invokeMethod, causing VM resumption
*
* @param worker
* @throws IncompatibleThreadStateException if the specified thread has not been suspended by an event.
* @throws IncompatibleAspectTypeException if this aspect is not a singleton
* @throws AspectInitialisationException an exception occurred in the target VM
*/
public AspectInstance getInstance(ThreadReference worker) throws IncompatibleAspectTypeException,IncompatibleThreadStateException, AspectInitialisationException;
// //singleton: werkt
// //CFLOW: werkt
// //Obj: error
// public AspectInstance getInstanceFor(ThreadReference thread);
//singleton: werkt
//CFLOW: error
//Obj: werkt
/**
* @param worker
* @param object the object the instance is bound to
* @return
* @throws IncompatibleThreadStateException if the specified thread has not been suspended by an event.
* @throws IncompatibleAspectTypeException if this aspect is not a singleton or a per object aspect
* @throws AspectInitialisationException an exception occurred in the target VM
* @throws IllegalArgumentException this object can not be linked to an instance
*/
public AspectInstance getInstanceFor(ThreadReference worker,ObjectReference object) throws IncompatibleThreadStateException, AspectInitialisationException,IncompatibleAspectTypeException;
/* (non-Javadoc)
* kan wel eens problemen gaan geven
* @see com.sun.jdi.ReferenceType#classObject()
*/
//public ClassObjectReference classObject();
public List<Aspect> subAspects();
public String mechanismName();
}
| OpenUniversity/AOP-Awesome-Legacy | awesome.ajdi/ajdi/Aspect.java | 1,046 | //denk aan de binding,.... | line_comment | nl | /**
* AODA - Aspect Oriented Debugging Architecture
* Copyright (C) 2007-2009 Wouter De Borger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser 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 ajdi;
import java.util.List;
import com.sun.jdi.IncompatibleThreadStateException;
public interface Aspect extends ClassType, Shadow{
public static final int PER_SINGLETON = 0x01;
public static final int PER_OBJECT = 0x02;
public static final int PER_CLASS = 0x04;
/**
* per object per joinpoint
*/
public static final int PER_JOINPOINT = 0x08;
public static final int PER_VM_JOINPOINT = PER_JOINPOINT + PER_SINGLETON;
public static final int PER_OBJECT_JOINPOINT = PER_JOINPOINT + PER_OBJECT;
public static final int PER_CLASS_JOINPOINT = PER_JOINPOINT + PER_CLASS;
/**
* @return all advises defined in this aspect and all of it's ancestors
*/
public List<Advice> allAdvices();
/**
* @return all advises defined directly in this aspect
*/
public List<Advice> advices();
/**
* @param sig the advice signature of the advice, no regex
* @return a list of advises having this signature
*/
public List<Advice> advicesBySignature(String sig);
/**
* @param sig the advice signature of the advice
* @return the concrete version of the advice having this signature
*/
//TODO onnozele semantiek
//denk aan<SUF>
public Advice concreteAdviceBySignature(String sig);
public boolean isPerSingleton();
public boolean isPerObject();
public int getPer();
// /**
// * @return
// */
// public List<AspectInstance> allInstances();
//geen singleton: error
/**
* if this aspect is not a singleton, an is thrown,
* otherwise the worker thread is used to invoke the needed commands to retrieve the instance
*
* this call may use jdi.classType.invokeMethod, causing VM resumption
*
* @param worker
* @throws IncompatibleThreadStateException if the specified thread has not been suspended by an event.
* @throws IncompatibleAspectTypeException if this aspect is not a singleton
* @throws AspectInitialisationException an exception occurred in the target VM
*/
public AspectInstance getInstance(ThreadReference worker) throws IncompatibleAspectTypeException,IncompatibleThreadStateException, AspectInitialisationException;
// //singleton: werkt
// //CFLOW: werkt
// //Obj: error
// public AspectInstance getInstanceFor(ThreadReference thread);
//singleton: werkt
//CFLOW: error
//Obj: werkt
/**
* @param worker
* @param object the object the instance is bound to
* @return
* @throws IncompatibleThreadStateException if the specified thread has not been suspended by an event.
* @throws IncompatibleAspectTypeException if this aspect is not a singleton or a per object aspect
* @throws AspectInitialisationException an exception occurred in the target VM
* @throws IllegalArgumentException this object can not be linked to an instance
*/
public AspectInstance getInstanceFor(ThreadReference worker,ObjectReference object) throws IncompatibleThreadStateException, AspectInitialisationException,IncompatibleAspectTypeException;
/* (non-Javadoc)
* kan wel eens problemen gaan geven
* @see com.sun.jdi.ReferenceType#classObject()
*/
//public ClassObjectReference classObject();
public List<Aspect> subAspects();
public String mechanismName();
}
|
206506_1 | package com.DigitaleFactuur.db;
import com.google.common.base.Optional;
import com.DigitaleFactuur.models.Car;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import java.sql.*;
import java.util.ArrayList;
public class CarDAO extends AbstractDAO<Car> {
Connection con;
public CarDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
//GETCAR BY LICENCE
private String SQLgetCarByLicence(String licence){
return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'";
}
private String SQLgetCarsByOwnerID(int ownerID){
return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'";
}
public String SQLdeleteCarByLicence(String licence){
return "DELETE FROM car WHERE licencePlate='" + licence + "';";
}
public Optional<Car> findByID(long id) {
return Optional.fromNullable(get(id));
}
public Car save(Car car) {
return persist(car);
}
/**
* Delete car uit de database aan de hand van een
* prepared SQl Statement waarin de auto zijn
* licenceplate meegegeven wordt.
* @param licence
* @author Tom
*/
public void deleteCarByLicence(String licence) {
try {
con = DatabaseConnector.getConnection();
PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence));
deleteCarByLicence.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get car d.m.v. het kentekenplaat op te zoeken.
* @param licencePlate - kentekenplaat
* @return auto
* @author Ole
*/
public Car getCarByLicence(String licencePlate){
Car requestedCar = new Car("a", "a", "a", "a", "a", "a");
try{
con = DatabaseConnector.getConnection();
String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate);
PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate);
ResultSet rs = getCarByLicencePlate.executeQuery();
if (rs.next()){
requestedCar = new Car(
rs.getString("licencePlate"),
rs.getString("carName"),
rs.getString("carBrand"),
rs.getString("carType"),
rs.getString("carColor"),
rs.getString("fuelType"));
}
}catch(SQLException e){
}
return requestedCar;
}
/**
* Get alle auto's die gelinkt zijn aan een owner via ownerID.
* @param ownerID owner van de auto
* @return ArrayList met daarin alle auto's
* @author Ole
*/
public ArrayList<Car> getCarsByOwnerID(int ownerID){
ArrayList<Car> autos = new ArrayList<>();
try{
con = DatabaseConnector.getConnection();
String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID);
PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID);
ResultSet rs = CarsByOwnerID.executeQuery();
while (rs.next()){
Car reqeuestedCar = new Car(
rs.getString("licencePlate"),
rs.getString("carName"),
rs.getString("carBrand"),
rs.getString("carType"),
rs.getString("carColor"),
rs.getString("fuelType"));
autos.add(reqeuestedCar);
}
}catch(SQLException e){
}
return autos;
}
} | RobinUit/hsleiden-ikrefact | KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/CarDAO.java | 898 | /**
* Delete car uit de database aan de hand van een
* prepared SQl Statement waarin de auto zijn
* licenceplate meegegeven wordt.
* @param licence
* @author Tom
*/ | block_comment | nl | package com.DigitaleFactuur.db;
import com.google.common.base.Optional;
import com.DigitaleFactuur.models.Car;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import java.sql.*;
import java.util.ArrayList;
public class CarDAO extends AbstractDAO<Car> {
Connection con;
public CarDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
//GETCAR BY LICENCE
private String SQLgetCarByLicence(String licence){
return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'";
}
private String SQLgetCarsByOwnerID(int ownerID){
return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'";
}
public String SQLdeleteCarByLicence(String licence){
return "DELETE FROM car WHERE licencePlate='" + licence + "';";
}
public Optional<Car> findByID(long id) {
return Optional.fromNullable(get(id));
}
public Car save(Car car) {
return persist(car);
}
/**
* Delete car uit<SUF>*/
public void deleteCarByLicence(String licence) {
try {
con = DatabaseConnector.getConnection();
PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence));
deleteCarByLicence.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Get car d.m.v. het kentekenplaat op te zoeken.
* @param licencePlate - kentekenplaat
* @return auto
* @author Ole
*/
public Car getCarByLicence(String licencePlate){
Car requestedCar = new Car("a", "a", "a", "a", "a", "a");
try{
con = DatabaseConnector.getConnection();
String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate);
PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate);
ResultSet rs = getCarByLicencePlate.executeQuery();
if (rs.next()){
requestedCar = new Car(
rs.getString("licencePlate"),
rs.getString("carName"),
rs.getString("carBrand"),
rs.getString("carType"),
rs.getString("carColor"),
rs.getString("fuelType"));
}
}catch(SQLException e){
}
return requestedCar;
}
/**
* Get alle auto's die gelinkt zijn aan een owner via ownerID.
* @param ownerID owner van de auto
* @return ArrayList met daarin alle auto's
* @author Ole
*/
public ArrayList<Car> getCarsByOwnerID(int ownerID){
ArrayList<Car> autos = new ArrayList<>();
try{
con = DatabaseConnector.getConnection();
String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID);
PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID);
ResultSet rs = CarsByOwnerID.executeQuery();
while (rs.next()){
Car reqeuestedCar = new Car(
rs.getString("licencePlate"),
rs.getString("carName"),
rs.getString("carBrand"),
rs.getString("carType"),
rs.getString("carColor"),
rs.getString("fuelType"));
autos.add(reqeuestedCar);
}
}catch(SQLException e){
}
return autos;
}
} |
182793_1 | package nl.saxion.client.communication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetworkCommunicator {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private final String serverAddress;
private final int serverPort;
private static final int RECONNECT_ATTEMPTS = 5;
private static final int RECONNECT_INTERVAL_MS = 5000; // 5 seconden
public NetworkCommunicator(String serverAddress, int serverPort) {
this.serverAddress = serverAddress;
this.serverPort = serverPort;
connectToServer();
}
private void connectToServer() {
for (int attempt = 1; attempt <= RECONNECT_ATTEMPTS; attempt++) {
try {
socket = new Socket(serverAddress, serverPort);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Logger.getGlobal().log(Level.INFO, "Connected to server on port " + socket.getLocalPort());
return; // Succesvol verbonden, dus break uit de loop
} catch (IOException e) {
Logger.getGlobal().log(Level.WARNING, "Connection attempt " + attempt + " failed, retrying...");
try {
Thread.sleep(RECONNECT_INTERVAL_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
}
}
Logger.getGlobal().log(Level.SEVERE, "Unable to connect to server after " + RECONNECT_ATTEMPTS + " attempts.");
try {
close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void sendRequest(String request) {
out.println(request);
Logger.getGlobal().log(Level.INFO, "--> SERVER: " + request);
}
public String readResponse() throws IOException {
return in.readLine(); // Of gebruik een andere manier om te bepalen hoe je wilt lezen
}
public void close() throws IOException {
in.close();
out.close();
socket.close();
}
public boolean isConnected() {
return socket != null && socket.isConnected() && !socket.isClosed();
}
// Mogelijk meer methoden voor specifieke soorten requests
}
| ThijsvDorp/IT-3 | 10-Level3-Thijs/10-Level3-Thijs/src/nl/saxion/client/communication/NetworkCommunicator.java | 610 | // Of gebruik een andere manier om te bepalen hoe je wilt lezen | line_comment | nl | package nl.saxion.client.communication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetworkCommunicator {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private final String serverAddress;
private final int serverPort;
private static final int RECONNECT_ATTEMPTS = 5;
private static final int RECONNECT_INTERVAL_MS = 5000; // 5 seconden
public NetworkCommunicator(String serverAddress, int serverPort) {
this.serverAddress = serverAddress;
this.serverPort = serverPort;
connectToServer();
}
private void connectToServer() {
for (int attempt = 1; attempt <= RECONNECT_ATTEMPTS; attempt++) {
try {
socket = new Socket(serverAddress, serverPort);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Logger.getGlobal().log(Level.INFO, "Connected to server on port " + socket.getLocalPort());
return; // Succesvol verbonden, dus break uit de loop
} catch (IOException e) {
Logger.getGlobal().log(Level.WARNING, "Connection attempt " + attempt + " failed, retrying...");
try {
Thread.sleep(RECONNECT_INTERVAL_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
}
}
Logger.getGlobal().log(Level.SEVERE, "Unable to connect to server after " + RECONNECT_ATTEMPTS + " attempts.");
try {
close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void sendRequest(String request) {
out.println(request);
Logger.getGlobal().log(Level.INFO, "--> SERVER: " + request);
}
public String readResponse() throws IOException {
return in.readLine(); // Of gebruik<SUF>
}
public void close() throws IOException {
in.close();
out.close();
socket.close();
}
public boolean isConnected() {
return socket != null && socket.isConnected() && !socket.isClosed();
}
// Mogelijk meer methoden voor specifieke soorten requests
}
|
19620_2 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be.hogent.team10.catan.client.view.viewComponents;
import be.hogent.team10.catan.client.view.GuiController;
import be.hogent.team10.catan_businesslogic.model.ResourceSet;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Joachim
*/
public class ResourceTradePanel extends JPanel {
private GuiController guiC;
private Image plus, min;
private ImageIcon lumber, ore, wool, brick, grain;
private JLabel lumberAmount, oreAmount, woolAmount, brickAmount, grainAmount, plusBrick, minBrick, plusLumber, minLumber, plusOre, minOre, plusGrain, minGrain, plusWool, minWool;
private PlusHandler plusHandler;
private MinHandler minHandler;
private String receive;
private int woolQuantity, grainQuantity, brickQuantity, oreQuantity, lumberQuantity;
private Map<String,Integer> trade;
private ResourceSet resources;
public ResourceTradePanel() {
try {
guiC = GuiController.getInstance();
GridLayout grid = new GridLayout(5, 4);
grid.setHgap(-10);
setLayout(grid);
//Resources ophalen van de speler.
resources = guiC.getClient().getResources();
//Images ophalen
Image img1 = ImageIO.read(getClass().getResource("/LUMBERicon.png"));
img1 = img1.getScaledInstance(42, 42, 1);
Image img2 = ImageIO.read(getClass().getResource("/GRAINicon.png"));
img2 = img2.getScaledInstance(42, 42, 1);
Image img3 = ImageIO.read(getClass().getResource("/BRICKicon.png"));
img3 = img3.getScaledInstance(42, 42, 1);
Image img4 = ImageIO.read(getClass().getResource("/WOOLicon.png"));
img4 = img4.getScaledInstance(42, 42, 1);
Image img5 = ImageIO.read(getClass().getResource("/OREicon.png"));
img5 = img5.getScaledInstance(42, 42, 1);
lumber = new ImageIcon(img1);
grain = new ImageIcon(img2);
brick = new ImageIcon(img3);
wool = new ImageIcon(img4);
ore = new ImageIcon(img5);
plus = ImageIO.read(getClass().getResource("/plus.gif"));
min = ImageIO.read(getClass().getResource("/min.gif"));
plusHandler=new ResourceTradePanel.PlusHandler();
minHandler=new ResourceTradePanel.MinHandler();
//Startwaarden van de labels nog instellen.
//Brick
minBrick = new JLabel(new ImageIcon(min));
minBrick.addMouseListener(minHandler);
add(minBrick);
add(new JLabel(brick));
plusBrick = new JLabel(new ImageIcon(plus));
plusBrick.addMouseListener(plusHandler);
add(plusBrick);
brickAmount = new JLabel(brickQuantity+"");
brickAmount.setForeground(Color.BLACK);
brickAmount.setHorizontalAlignment(JLabel.CENTER);
add(brickAmount);
//Lumber
minLumber = new JLabel(new ImageIcon(min));
minLumber.addMouseListener(minHandler);
add(minLumber);
add(new JLabel(lumber));
plusLumber = new JLabel(new ImageIcon(plus));
plusLumber.addMouseListener(plusHandler);
add(plusLumber);
lumberAmount = new JLabel(lumberQuantity+"");
lumberAmount.setForeground(Color.BLACK);
lumberAmount.setHorizontalAlignment(JLabel.CENTER);
add(lumberAmount);
//Wool
minWool = new JLabel(new ImageIcon(min));
minWool.addMouseListener(minHandler);
add(minWool);
add(new JLabel(wool));
plusWool = new JLabel(new ImageIcon(plus));
plusWool.addMouseListener(plusHandler);
add(plusWool);
woolAmount = new JLabel(woolQuantity+"");
woolAmount.setForeground(Color.BLACK);
woolAmount.setHorizontalAlignment(JLabel.CENTER);
add(woolAmount);
//Grain
minGrain = new JLabel(new ImageIcon(min));
minGrain.addMouseListener(minHandler);
add(minGrain);
add(new JLabel(grain));
plusGrain = new JLabel(new ImageIcon(plus));
plusGrain.addMouseListener(plusHandler);
add(plusGrain);
grainAmount = new JLabel(grainQuantity+"");
grainAmount.setForeground(Color.BLACK);
grainAmount.setHorizontalAlignment(JLabel.CENTER);
add(grainAmount);
//Ore
minOre = new JLabel(new ImageIcon(min));
minOre.addMouseListener(minHandler);
add(minOre);
add(new JLabel(ore));
plusOre = new JLabel(new ImageIcon(plus));
plusOre.addMouseListener(plusHandler);
add(plusOre);
oreAmount = new JLabel(oreQuantity+"");
oreAmount.setForeground(Color.BLACK);
oreAmount.setHorizontalAlignment(JLabel.CENTER);
add(oreAmount);
} catch (IOException ex) {
Logger.getLogger(ResourceTradePanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getWoolQuantity() {
return woolQuantity;
}
public int getGrainQuantity() {
return grainQuantity;
}
public int getBrickQuantity() {
return brickQuantity;
}
public int getOreQuantity() {
return oreQuantity;
}
public int getLumberQuantity() {
return lumberQuantity;
}
private class PlusHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JLabel source = (JLabel) e.getSource();
if (source == plusLumber) {
receive = "LUMBER";
int get = Integer.parseInt(lumberAmount.getText());
get++;
lumberAmount.setText("" + get);
lumberQuantity = get;
} else if (source == plusOre) {
receive = "ORE";
int get = Integer.parseInt(oreAmount.getText());
get++;
oreAmount.setText("" + get);
oreQuantity = get;
} else if (source == plusBrick) {
receive = "BRICK";
int get = Integer.parseInt(brickAmount.getText());
get++;
brickAmount.setText("" + get);
brickQuantity = get;
} else if (source == plusWool) {
receive = "WOOL";
int get = Integer.parseInt(woolAmount.getText());
get++;
woolAmount.setText("" + get);
woolQuantity = get;
} else if (source == plusGrain) {
receive = "GRAIN";
int get = Integer.parseInt(grainAmount.getText());
get++;
grainAmount.setText("" + get);
grainQuantity = get;
}
}
}
private class MinHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JLabel source = (JLabel) e.getSource();
if (source == minLumber) {
int get = Integer.parseInt(lumberAmount.getText());
get--;
if(get+resources.getAmount("LUMBER")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("LUMBER")>=0){
lumberAmount.setText("" + get);
lumberQuantity = get;
}
} else if (source == minOre) {
int get = Integer.parseInt(oreAmount.getText());
get--;
if(get+resources.getAmount("ORE")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("ORE")>=0){
oreAmount.setText("" + get);
oreQuantity = get;
}
} else if (source == minBrick) {
int get = Integer.parseInt(brickAmount.getText());
get--;
if(get+resources.getAmount("BRICK")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("BRICK")>=0){
brickAmount.setText("" + get);
brickQuantity = get;
}
} else if (source == minWool) {
int get = Integer.parseInt(woolAmount.getText());
get--;
if(get+resources.getAmount("WOOL")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("WOOL")>=0){
woolAmount.setText("" + get);
woolQuantity = get;
}
} else if (source == minGrain) {
int get = Integer.parseInt(grainAmount.getText());
get--;
if(get+resources.getAmount("GRAIN")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("GRAIN")>=0){
grainAmount.setText("" + get);
grainQuantity = get;
}
}
}
}
}
| janseeuw/Settlers-of-Catan | catan_client/src/main/java/be/hogent/team10/catan/client/view/viewComponents/ResourceTradePanel.java | 2,441 | //Resources ophalen van de speler.
| line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be.hogent.team10.catan.client.view.viewComponents;
import be.hogent.team10.catan.client.view.GuiController;
import be.hogent.team10.catan_businesslogic.model.ResourceSet;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Joachim
*/
public class ResourceTradePanel extends JPanel {
private GuiController guiC;
private Image plus, min;
private ImageIcon lumber, ore, wool, brick, grain;
private JLabel lumberAmount, oreAmount, woolAmount, brickAmount, grainAmount, plusBrick, minBrick, plusLumber, minLumber, plusOre, minOre, plusGrain, minGrain, plusWool, minWool;
private PlusHandler plusHandler;
private MinHandler minHandler;
private String receive;
private int woolQuantity, grainQuantity, brickQuantity, oreQuantity, lumberQuantity;
private Map<String,Integer> trade;
private ResourceSet resources;
public ResourceTradePanel() {
try {
guiC = GuiController.getInstance();
GridLayout grid = new GridLayout(5, 4);
grid.setHgap(-10);
setLayout(grid);
//Resources ophalen<SUF>
resources = guiC.getClient().getResources();
//Images ophalen
Image img1 = ImageIO.read(getClass().getResource("/LUMBERicon.png"));
img1 = img1.getScaledInstance(42, 42, 1);
Image img2 = ImageIO.read(getClass().getResource("/GRAINicon.png"));
img2 = img2.getScaledInstance(42, 42, 1);
Image img3 = ImageIO.read(getClass().getResource("/BRICKicon.png"));
img3 = img3.getScaledInstance(42, 42, 1);
Image img4 = ImageIO.read(getClass().getResource("/WOOLicon.png"));
img4 = img4.getScaledInstance(42, 42, 1);
Image img5 = ImageIO.read(getClass().getResource("/OREicon.png"));
img5 = img5.getScaledInstance(42, 42, 1);
lumber = new ImageIcon(img1);
grain = new ImageIcon(img2);
brick = new ImageIcon(img3);
wool = new ImageIcon(img4);
ore = new ImageIcon(img5);
plus = ImageIO.read(getClass().getResource("/plus.gif"));
min = ImageIO.read(getClass().getResource("/min.gif"));
plusHandler=new ResourceTradePanel.PlusHandler();
minHandler=new ResourceTradePanel.MinHandler();
//Startwaarden van de labels nog instellen.
//Brick
minBrick = new JLabel(new ImageIcon(min));
minBrick.addMouseListener(minHandler);
add(minBrick);
add(new JLabel(brick));
plusBrick = new JLabel(new ImageIcon(plus));
plusBrick.addMouseListener(plusHandler);
add(plusBrick);
brickAmount = new JLabel(brickQuantity+"");
brickAmount.setForeground(Color.BLACK);
brickAmount.setHorizontalAlignment(JLabel.CENTER);
add(brickAmount);
//Lumber
minLumber = new JLabel(new ImageIcon(min));
minLumber.addMouseListener(minHandler);
add(minLumber);
add(new JLabel(lumber));
plusLumber = new JLabel(new ImageIcon(plus));
plusLumber.addMouseListener(plusHandler);
add(plusLumber);
lumberAmount = new JLabel(lumberQuantity+"");
lumberAmount.setForeground(Color.BLACK);
lumberAmount.setHorizontalAlignment(JLabel.CENTER);
add(lumberAmount);
//Wool
minWool = new JLabel(new ImageIcon(min));
minWool.addMouseListener(minHandler);
add(minWool);
add(new JLabel(wool));
plusWool = new JLabel(new ImageIcon(plus));
plusWool.addMouseListener(plusHandler);
add(plusWool);
woolAmount = new JLabel(woolQuantity+"");
woolAmount.setForeground(Color.BLACK);
woolAmount.setHorizontalAlignment(JLabel.CENTER);
add(woolAmount);
//Grain
minGrain = new JLabel(new ImageIcon(min));
minGrain.addMouseListener(minHandler);
add(minGrain);
add(new JLabel(grain));
plusGrain = new JLabel(new ImageIcon(plus));
plusGrain.addMouseListener(plusHandler);
add(plusGrain);
grainAmount = new JLabel(grainQuantity+"");
grainAmount.setForeground(Color.BLACK);
grainAmount.setHorizontalAlignment(JLabel.CENTER);
add(grainAmount);
//Ore
minOre = new JLabel(new ImageIcon(min));
minOre.addMouseListener(minHandler);
add(minOre);
add(new JLabel(ore));
plusOre = new JLabel(new ImageIcon(plus));
plusOre.addMouseListener(plusHandler);
add(plusOre);
oreAmount = new JLabel(oreQuantity+"");
oreAmount.setForeground(Color.BLACK);
oreAmount.setHorizontalAlignment(JLabel.CENTER);
add(oreAmount);
} catch (IOException ex) {
Logger.getLogger(ResourceTradePanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getWoolQuantity() {
return woolQuantity;
}
public int getGrainQuantity() {
return grainQuantity;
}
public int getBrickQuantity() {
return brickQuantity;
}
public int getOreQuantity() {
return oreQuantity;
}
public int getLumberQuantity() {
return lumberQuantity;
}
private class PlusHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JLabel source = (JLabel) e.getSource();
if (source == plusLumber) {
receive = "LUMBER";
int get = Integer.parseInt(lumberAmount.getText());
get++;
lumberAmount.setText("" + get);
lumberQuantity = get;
} else if (source == plusOre) {
receive = "ORE";
int get = Integer.parseInt(oreAmount.getText());
get++;
oreAmount.setText("" + get);
oreQuantity = get;
} else if (source == plusBrick) {
receive = "BRICK";
int get = Integer.parseInt(brickAmount.getText());
get++;
brickAmount.setText("" + get);
brickQuantity = get;
} else if (source == plusWool) {
receive = "WOOL";
int get = Integer.parseInt(woolAmount.getText());
get++;
woolAmount.setText("" + get);
woolQuantity = get;
} else if (source == plusGrain) {
receive = "GRAIN";
int get = Integer.parseInt(grainAmount.getText());
get++;
grainAmount.setText("" + get);
grainQuantity = get;
}
}
}
private class MinHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JLabel source = (JLabel) e.getSource();
if (source == minLumber) {
int get = Integer.parseInt(lumberAmount.getText());
get--;
if(get+resources.getAmount("LUMBER")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("LUMBER")>=0){
lumberAmount.setText("" + get);
lumberQuantity = get;
}
} else if (source == minOre) {
int get = Integer.parseInt(oreAmount.getText());
get--;
if(get+resources.getAmount("ORE")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("ORE")>=0){
oreAmount.setText("" + get);
oreQuantity = get;
}
} else if (source == minBrick) {
int get = Integer.parseInt(brickAmount.getText());
get--;
if(get+resources.getAmount("BRICK")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("BRICK")>=0){
brickAmount.setText("" + get);
brickQuantity = get;
}
} else if (source == minWool) {
int get = Integer.parseInt(woolAmount.getText());
get--;
if(get+resources.getAmount("WOOL")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("WOOL")>=0){
woolAmount.setText("" + get);
woolQuantity = get;
}
} else if (source == minGrain) {
int get = Integer.parseInt(grainAmount.getText());
get--;
if(get+resources.getAmount("GRAIN")<0){
ErrorPanel.getInstance().setError("U hebt niet genoeg grondstoffen om te ruilen.");
} else if(get+resources.getAmount("GRAIN")>=0){
grainAmount.setText("" + get);
grainQuantity = get;
}
}
}
}
}
|
66475_1 | package Controller.Tile_Controllers;
import Controller.Player_Controllers.PlayerController;
import Model.Bord.Onderdeel;
import Model.Tiles.*;
import Model.data.StaticData;
import Model.equipment.*;
import Model.player.Player;
import Model.storm.Stappen;
import View.ViewManager;
import View.bord_views.SpeelbordView;
import javafx.application.Platform;
import observers.BordObserver;
import observers.OnderdeelObserver;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
/**
* Deze klasse wordt gebruikt om tile behaviour uit te voeren zoals het verplaatsen van tiles.
*
* @author ryan
* @author Daniël
* @author Tim
*/
public class TileController {
Random random = new Random();
public static TileController tileController;
public static TileController cheatController;
private static EquipmentController equipmentController = EquipmentController.getInstance();
ArrayList<Tile> tiles = new ArrayList<>();
ArrayList<Tile> randomTiles = new ArrayList<>();
ArrayList<Onderdeel> onderdelen = new ArrayList<>();
PlayerController playerController;
public int counter = 0;
public TileController(){
makeTiles();
randomizeTiles(tiles);
randomTiles.add(12, new Storm());
beginZand();
setTileLocations();
maakOnderdelen();
}
private TileController(Object roominfo){
Map<String, Object> tilesMap = (Map)((Map) roominfo).get("tiles");
makeTilesFormFB(tilesMap);
}
public static TileController getCheatInstance(){
if (cheatController == null){
cheatController = new TileController();
}
return cheatController;
}
public static TileController getInstance(){
if (tileController == null){
StaticData staticData = StaticData.getInstance();
Object roominfo = staticData.getRoomInfo();
tileController = new TileController(roominfo);
}
return tileController;
}
public void tileClicked(int x, int y) {
Tile tile = getTileByLocation(y,x);
tile.discoverTile();
tile.removeZandTegel();
}
/**
* Deze functie initialiseert alle tiles.
* Volgens de spel regels zijn er in totaal 24 tiles, dus loopt de for loop tot 24.
*
* @author ryan
*/
private void makeTiles(){
for (int i = 0; i < 24; i++){
if (i < 1){
tiles.add(new Finish());
}else if (i < 2){
tiles.add(new FataMorgana());
}else if (i < 4){
tiles.add(new Waterput());
}else if (i < 7){
tiles.add(new Tunnel(equipmentController.getEquipment()));
}else if (i < 8){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.KOMPAS));
}else if (i < 9){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.PROPELOR));
}else if (i < 10){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.MOTOR));
}else if (i < 11){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.OBELISK));
}else if (i < 12){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.KOMPAS));
}else if (i < 13){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.PROPELOR));
}else if (i < 14){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.MOTOR));
}else if (i < 15) {
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.OBELISK));
}else if (i < 16) {
tiles.add(new StartTile(equipmentController.getEquipment()));
}else{
tiles.add(new EquipmentTile(equipmentController.getEquipment()));
}
}
EquipmentTile.resetTeller();
}
/**
* Deze functie randomized een ArrayList die hij mee krijgt.
* Het is een recursive method.
*
* @param tiles Een ArrayList van het type Tile.
* @author ryan
*/
private void randomizeTiles(ArrayList<Tile> tiles){
if (tiles.isEmpty()){
return;
}
int randomInt = random.nextInt(tiles.size());
randomTiles.add(tiles.get(randomInt));
tiles.remove(randomInt);
randomizeTiles(tiles);
}
/**
* Deze functie geeft de tiles die zijn gerandomized een x en y waarde.
*
* @author ryan
*/
private void setTileLocations(){
int counter = 0;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
randomTiles.get(counter).setLocation(i, j);
counter++;
}
}
}
public void maakOnderdelen(){
onderdelen.add(new Onderdeel(PartTile.Soorten.OBELISK));
onderdelen.add(new Onderdeel(PartTile.Soorten.MOTOR));
onderdelen.add(new Onderdeel(PartTile.Soorten.KOMPAS));
onderdelen.add(new Onderdeel(PartTile.Soorten.PROPELOR));
}
public void moveTileNoord(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY,0,1);
}
public void moveTileOost(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, -1, 0);
}
public void moveTileZuid(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, 0, -1);
}
public void moveTileWest(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, 1, 0);
}
/**
* Deze functie draait de locaties van 2 tiles om in een bepaalde richting voor een x aantal stappen.
*
* @param stappen Het aantal stappen dat de storm heeft genomen.
* @param stormX De x locatie van de storm.
* @param stormY De y locatie van de storm.
* @param moveStormX De x locatie waar de storm naartoe beweegt.
* @param moveStormY De y locatie waar de storm naartoe beweegt.
* @author ryan
*/
private void moveTile(Stappen stappen, int stormX, int stormY, int moveStormX, int moveStormY){
playerController = PlayerController.getInstance();
for (int i = 0; i < stappen.getNumber(); i++){
if (stormY+moveStormY <= 4 && stormX+moveStormX >= 0 && stormY+moveStormY >= 0 && stormX+moveStormX <= 4){
Tile stormTile = getTileByLocation(stormY, stormX);
Tile tmp = getTileByLocation(stormY+moveStormY, stormX+moveStormX);
stormTile.setLocation(stormX+moveStormX, stormY+moveStormY);
tmp.setLocation(stormX, stormY);
tmp.addZandTegel();
tmp.notifyAllObservers();
stormTile.notifyAllObservers();
SpeelbordView.getInstance().updateSpelBord(tmp, stormTile);
for (Player speler : tmp.getSpelers()){
speler.setLocatie(stormX, stormY);
}
stormY = stormY + moveStormY;
stormX = stormX + moveStormX;
}
}
}
/**
* Deze functie voegt zand toe aan een paar tiles in het begin, dit is volgens de spelregels.
*
* @author ryan
*/
private void beginZand(){
randomTiles.get(2).addZandTegel();
randomTiles.get(6).addZandTegel();
randomTiles.get(8).addZandTegel();
randomTiles.get(10).addZandTegel();
randomTiles.get(14).addZandTegel();
randomTiles.get(16).addZandTegel();
randomTiles.get(18).addZandTegel();
randomTiles.get(22).addZandTegel();
}
public Tile getTileByLocation(int y, int x){
for (Tile tile : randomTiles){
if (tile.getX() == x && tile.getY() == y){
return tile;
}
}
return null;
}
public void registerObserver(BordObserver bo, int counter){
randomTiles.get(counter).register(bo);
this.counter++;
}
public void registerOnderdeelObserver(OnderdeelObserver ob){
for(int i = 0; i < 4; i++){
onderdelen.get(i).register(ob); }
}
public void useTileDiscoveredAction(int x, int y){
Tile tile = (getTileByLocation(y, x));
playerController = PlayerController.getInstance();
Player player = playerController.getPlayer();
if(tile.getClass().equals(EquipmentTile.class) || tile.getClass().equals(StartTile.class)){
EquipmentTile eTile = (EquipmentTile) tile;
//geef equipment
player.addEquipment(eTile.getEquipment());
}
else if (tile.getClass().equals(Waterput.class)){
Waterput wTile = (Waterput) tile;
for (Player speler : wTile.getSpelers()){
speler.addWater(2);
}
//geef water
}
else if (tile.getClass().equals(Tunnel.class)){
Tunnel tTile = (Tunnel) tile;
player.addEquipment(tTile.getEquipment());
//geen zon brand
}
else if (tile.getClass().equals(PartTile.class)){
PartTile pTile = (PartTile) tile;
geefHint(pTile);
//ontdek hint
}
else if (tile.getClass().equals(Finish.class)){
Finish fTile = (Finish) tile;
fTile.isSpelKlaar();
//ga ff checken of je hebt gewonnen
}
else{
//System.out.println("Dit gaat fout (Tilecontroller)");
}
}
public void geefHint(PartTile tile){
for(Onderdeel onderdeel:onderdelen){
if(tile.getSoort().equals(onderdeel.getSoort())){
if (tile.getRichting() == PartTile.Richtingen.OPZIJ){
onderdeel.setY((tile.getY()));
checkOnderdeelSpawned(onderdeel);
}
else if(tile.getRichting() == PartTile.Richtingen.OMHOOG){
onderdeel.setX((tile.getX()));
checkOnderdeelSpawned(onderdeel);
}
else{
//System.out.println("gaat fout lol (tilecontroller)");
}
}
}
}
public void checkOnderdeelSpawned(Onderdeel onderdeel){
if(!(onderdeel.getY() == -1) && !(onderdeel.getX() == -1) && !onderdeel.isOpgepakt()) {
Tile onderdeelSpawn = getTileByLocation(onderdeel.getY(), onderdeel.getX());
onderdeelSpawn.setOnderdeel(onderdeel);
}
}
/**
* Deze functie checkt voor alle onderdelen of ze al zijn gespawned.
*
* @author ryan
*/
private void checkOnderdelenSpawned(){
for (Onderdeel onderdeel : onderdelen){
if(!(onderdeel.getY() == -1) && !(onderdeel.getX() == -1) && !onderdeel.isOpgepakt()) {
Tile onderdeelSpawn = getTileByLocation(onderdeel.getY(), onderdeel.getX());
if (!onderdeelSpawn.getOnderdelen().contains(onderdeel)){
onderdeelSpawn.setOnderdeel(onderdeel);
}
}
}
}
/**
* Deze functie verwijdert alle onderdelen van de tile waarop hij lag die zijn opgepakt.
*
* @author ryan
*/
private void despawnOnderdelen(){
for (Onderdeel onderdeel : onderdelen){
if (onderdeel.isOpgepakt()){
for(Tile tile:randomTiles){
for(Onderdeel oD : tile.getOnderdelen()){
if(oD.equals(onderdeel)){
tile.removeOnderdeelSoort(onderdeel);
}
}
}
//Tile onderdeelTile = getTileByLocation(onderdeel.getY(), onderdeel.getX());
//onderdeelTile.removeOnderdeelSoort(onderdeel);
}
}
}
private Tile getFinsihTile(){
for (Tile tile : randomTiles){
if (tile.getVariant() == Tile.Varianten.FINISH){
return tile;
}
}
return null;
}
private boolean checkAlleOnderdelen(){
int opgepaktCounter = 0;
for (Onderdeel onderdeel : onderdelen){
if (onderdeel.isOpgepakt()){
opgepaktCounter++;
}
}
return opgepaktCounter == 4;
}
public boolean checkFinish(){
return getFinsihTile().getSpelers().size() == 4 && checkAlleOnderdelen();
}
public void checkZandCounter() {
int zandCounter = 0;
//int zandMax = 48;
int zandMax = 9;
for (Tile tile : randomTiles) {
zandCounter += tile.getZand();
}
if (zandCounter > zandMax) {
ViewManager.getInstance().loadEndGame(ViewManager.endConditions.SUFFOCATION);
}
}
public ArrayList<Tile> getTiles(){
return this.randomTiles;
}
/**
* Deze functie update alle data waarover deze klasse gaat met de data uit FireBase.
*
* @author ryan
*/
public void updateData(){
StaticData staticData = StaticData.getInstance();
Object roominfo = staticData.getRoomInfo();
Map<String, Object> tilesMap = (Map)((Map) roominfo).get("tiles");
updateTilesFromFB(tilesMap);
Map<String, Object> onderdelenMap = (Map)((Map) roominfo).get("onderdelen");
Platform.runLater(() -> {
updateOnderdelenFromFB(onderdelenMap);
//despawnOnderdelen();
//checkOnderdelenSpawned();
});
//updateOnderdelenFromFB(onderdelenMap);
checkOnderdelenSpawned();
despawnOnderdelen();
}
/**
* Deze functie update de onderdelen met data vanuit FireBase.
*
* @param onderdelenMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void updateOnderdelenFromFB(Map<String, Object> onderdelenMap){
for (int i = 0; i <onderdelen.size(); i++){
Map<String, Object> onderdeelFB = (Map)onderdelenMap.get(Integer.toString(i));
Onderdeel onderdeel = onderdelen.get(i);
int x = Integer.valueOf(onderdeelFB.get("x").toString());
int y = Integer.valueOf(onderdeelFB.get("y").toString());
if((onderdeelFB.get("opgepakt").toString()).equals("true")){
onderdeel.pakOp();
}
onderdeel.setX(x);
onderdeel.setY(y);
}
}
/**
* Deze functie update de tiles met data vanuit FireBase.
*
* @param tilesMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void updateTilesFromFB(Map<String, Object> tilesMap){
for (int i = 0; i < 25; i++){
Map<String, Object> tileFB = (Map)tilesMap.get(Integer.toString(i));
Tile tile = randomTiles.get(i);
int x = Integer.valueOf(tileFB.get("x").toString());
int y = Integer.valueOf(tileFB.get("y").toString());
boolean discovered = false;
if((tileFB.get("discovered").toString()).equals("true")){
discovered = true;
}
boolean hasZonneSchild = tileFB.get("hasZonneSchild").toString().equals("true");
int aantalZand = Integer.valueOf(tileFB.get("aantalZandTegels").toString());
tile.emptyPlayers();
String s = tileFB.get("Players").toString();
if(s.contains("Archeoloog")){
tile.addPlayer("Archeoloog");
}
if(s.contains("Klimmer")){
tile.addPlayer("Klimmer");
}
if(s.contains("Verkenner")){
tile.addPlayer("Verkenner");
}
if(s.contains("Waterdrager")){
tile.addPlayer("Waterdrager");
}
tile.setLocation(x, y);
tile.setDiscovered(discovered);
if (hasZonneSchild){
tile.setZonneSchild();
}
tile.setAantalZandTegels(aantalZand);
}
}
/**
* Deze functie maakt tiles aan, aan de hand van info uit FireBase
*
* @param tilesMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void makeTilesFormFB(Map<String, Object> tilesMap){
ArrayList<Tile> fbTiles = new ArrayList<>();
for (int i = 0; i < 25; i++){
Map<String, Object> tileFB = (Map)tilesMap.get(Integer.toString(i));
Tile tile = null;
String variant = tileFB.get("naam").toString();
int x = Integer.valueOf(tileFB.get("x").toString());
int y = Integer.valueOf(tileFB.get("y").toString());
boolean discovered = false;
if((tileFB.get("discovered").toString()).equals("true")){
discovered = true;
}
boolean hasZonneSchild = Boolean.getBoolean(tileFB.get("hasZonneSchild").toString());
int aantalZand = Integer.valueOf(tileFB.get("aantalZandTegels").toString());
switch (variant){
case "PART":
tile = new PartTile(stringToRichting(tileFB.get("richting").toString()), stringToSoort(tileFB.get("soort").toString()));
break;
case "FATAMORGANA":
tile = new FataMorgana();
break;
case "EQUIPMENT":
tile = new EquipmentTile(stringToEquipment(tileFB.get("equipment").toString()));
break;
case "TUNNEL":
tile = new Tunnel(stringToEquipment(tileFB.get("equipment").toString()));
break;
case "WATERPUT":
tile = new Waterput();
break;
case "FINISH":
tile = new Finish();
break;
case "STORM":
tile = new Storm();
break;
case "START":
tile = new StartTile(stringToEquipment(tileFB.get("equipment").toString()));
break;
}
String s = tileFB.get("Players").toString();
if(s.contains("Archeoloog")){
tile.addPlayer("Archeoloog");
}
if(s.contains("Klimmer")){
tile.addPlayer("Klimmer");
}
if(s.contains("Verkenner")){
tile.addPlayer("Verkenner");
}
if(s.contains("Waterdrager")){
tile.addPlayer("Waterdrager");
}
tile.setLocation(x, y);
tile.setDiscovered(discovered);
tile.setHasZonneSchild(hasZonneSchild);
tile.setAantalZandTegels(aantalZand);
fbTiles.add(tile);
}
randomTiles = fbTiles;
maakOnderdelen();
}
public Equipment stringToEquipment(String eq){
switch (eq){
case "JETPACK":
return new Jetpack();
case "AARDEKIJKER":
return new Aardekijker();
case "DUINKANON":
return new Duinkanon();
case "TIJDSCHAKELAAR":
return new Tijdschakelaar();
case "ZONNESCHILD":
return new Zonneschild();
case "WATERRESERVE":
return new Waterreserve();
}
return null;
}
public PartTile.Richtingen stringToRichting(String richting){
if (richting.equals("OPZIJ")){
return PartTile.Richtingen.OPZIJ;
}
return PartTile.Richtingen.OMHOOG;
}
public PartTile.Soorten stringToSoort(String soort){
switch (soort){
case "OBELISK":
return PartTile.Soorten.OBELISK;
case "MOTOR":
return PartTile.Soorten.MOTOR;
case "KOMPAS":
return PartTile.Soorten.KOMPAS;
case "PROPELOR":
return PartTile.Soorten.PROPELOR;
}
return null;
}
public ArrayList<Onderdeel> getOnderdelen() {
return onderdelen;
}
public void update(){
for (Tile tile : randomTiles){
tile.notifyAllObservers();
}
}
}
| danields317/de-vergeten-stad | src/main/java/Controller/Tile_Controllers/TileController.java | 5,371 | /**
* Deze functie initialiseert alle tiles.
* Volgens de spel regels zijn er in totaal 24 tiles, dus loopt de for loop tot 24.
*
* @author ryan
*/ | block_comment | nl | package Controller.Tile_Controllers;
import Controller.Player_Controllers.PlayerController;
import Model.Bord.Onderdeel;
import Model.Tiles.*;
import Model.data.StaticData;
import Model.equipment.*;
import Model.player.Player;
import Model.storm.Stappen;
import View.ViewManager;
import View.bord_views.SpeelbordView;
import javafx.application.Platform;
import observers.BordObserver;
import observers.OnderdeelObserver;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
/**
* Deze klasse wordt gebruikt om tile behaviour uit te voeren zoals het verplaatsen van tiles.
*
* @author ryan
* @author Daniël
* @author Tim
*/
public class TileController {
Random random = new Random();
public static TileController tileController;
public static TileController cheatController;
private static EquipmentController equipmentController = EquipmentController.getInstance();
ArrayList<Tile> tiles = new ArrayList<>();
ArrayList<Tile> randomTiles = new ArrayList<>();
ArrayList<Onderdeel> onderdelen = new ArrayList<>();
PlayerController playerController;
public int counter = 0;
public TileController(){
makeTiles();
randomizeTiles(tiles);
randomTiles.add(12, new Storm());
beginZand();
setTileLocations();
maakOnderdelen();
}
private TileController(Object roominfo){
Map<String, Object> tilesMap = (Map)((Map) roominfo).get("tiles");
makeTilesFormFB(tilesMap);
}
public static TileController getCheatInstance(){
if (cheatController == null){
cheatController = new TileController();
}
return cheatController;
}
public static TileController getInstance(){
if (tileController == null){
StaticData staticData = StaticData.getInstance();
Object roominfo = staticData.getRoomInfo();
tileController = new TileController(roominfo);
}
return tileController;
}
public void tileClicked(int x, int y) {
Tile tile = getTileByLocation(y,x);
tile.discoverTile();
tile.removeZandTegel();
}
/**
* Deze functie initialiseert<SUF>*/
private void makeTiles(){
for (int i = 0; i < 24; i++){
if (i < 1){
tiles.add(new Finish());
}else if (i < 2){
tiles.add(new FataMorgana());
}else if (i < 4){
tiles.add(new Waterput());
}else if (i < 7){
tiles.add(new Tunnel(equipmentController.getEquipment()));
}else if (i < 8){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.KOMPAS));
}else if (i < 9){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.PROPELOR));
}else if (i < 10){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.MOTOR));
}else if (i < 11){
tiles.add(new PartTile(PartTile.Richtingen.OMHOOG, PartTile.Soorten.OBELISK));
}else if (i < 12){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.KOMPAS));
}else if (i < 13){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.PROPELOR));
}else if (i < 14){
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.MOTOR));
}else if (i < 15) {
tiles.add(new PartTile(PartTile.Richtingen.OPZIJ, PartTile.Soorten.OBELISK));
}else if (i < 16) {
tiles.add(new StartTile(equipmentController.getEquipment()));
}else{
tiles.add(new EquipmentTile(equipmentController.getEquipment()));
}
}
EquipmentTile.resetTeller();
}
/**
* Deze functie randomized een ArrayList die hij mee krijgt.
* Het is een recursive method.
*
* @param tiles Een ArrayList van het type Tile.
* @author ryan
*/
private void randomizeTiles(ArrayList<Tile> tiles){
if (tiles.isEmpty()){
return;
}
int randomInt = random.nextInt(tiles.size());
randomTiles.add(tiles.get(randomInt));
tiles.remove(randomInt);
randomizeTiles(tiles);
}
/**
* Deze functie geeft de tiles die zijn gerandomized een x en y waarde.
*
* @author ryan
*/
private void setTileLocations(){
int counter = 0;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
randomTiles.get(counter).setLocation(i, j);
counter++;
}
}
}
public void maakOnderdelen(){
onderdelen.add(new Onderdeel(PartTile.Soorten.OBELISK));
onderdelen.add(new Onderdeel(PartTile.Soorten.MOTOR));
onderdelen.add(new Onderdeel(PartTile.Soorten.KOMPAS));
onderdelen.add(new Onderdeel(PartTile.Soorten.PROPELOR));
}
public void moveTileNoord(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY,0,1);
}
public void moveTileOost(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, -1, 0);
}
public void moveTileZuid(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, 0, -1);
}
public void moveTileWest(Stappen stappen, int stormX, int stormY){
moveTile(stappen, stormX, stormY, 1, 0);
}
/**
* Deze functie draait de locaties van 2 tiles om in een bepaalde richting voor een x aantal stappen.
*
* @param stappen Het aantal stappen dat de storm heeft genomen.
* @param stormX De x locatie van de storm.
* @param stormY De y locatie van de storm.
* @param moveStormX De x locatie waar de storm naartoe beweegt.
* @param moveStormY De y locatie waar de storm naartoe beweegt.
* @author ryan
*/
private void moveTile(Stappen stappen, int stormX, int stormY, int moveStormX, int moveStormY){
playerController = PlayerController.getInstance();
for (int i = 0; i < stappen.getNumber(); i++){
if (stormY+moveStormY <= 4 && stormX+moveStormX >= 0 && stormY+moveStormY >= 0 && stormX+moveStormX <= 4){
Tile stormTile = getTileByLocation(stormY, stormX);
Tile tmp = getTileByLocation(stormY+moveStormY, stormX+moveStormX);
stormTile.setLocation(stormX+moveStormX, stormY+moveStormY);
tmp.setLocation(stormX, stormY);
tmp.addZandTegel();
tmp.notifyAllObservers();
stormTile.notifyAllObservers();
SpeelbordView.getInstance().updateSpelBord(tmp, stormTile);
for (Player speler : tmp.getSpelers()){
speler.setLocatie(stormX, stormY);
}
stormY = stormY + moveStormY;
stormX = stormX + moveStormX;
}
}
}
/**
* Deze functie voegt zand toe aan een paar tiles in het begin, dit is volgens de spelregels.
*
* @author ryan
*/
private void beginZand(){
randomTiles.get(2).addZandTegel();
randomTiles.get(6).addZandTegel();
randomTiles.get(8).addZandTegel();
randomTiles.get(10).addZandTegel();
randomTiles.get(14).addZandTegel();
randomTiles.get(16).addZandTegel();
randomTiles.get(18).addZandTegel();
randomTiles.get(22).addZandTegel();
}
public Tile getTileByLocation(int y, int x){
for (Tile tile : randomTiles){
if (tile.getX() == x && tile.getY() == y){
return tile;
}
}
return null;
}
public void registerObserver(BordObserver bo, int counter){
randomTiles.get(counter).register(bo);
this.counter++;
}
public void registerOnderdeelObserver(OnderdeelObserver ob){
for(int i = 0; i < 4; i++){
onderdelen.get(i).register(ob); }
}
public void useTileDiscoveredAction(int x, int y){
Tile tile = (getTileByLocation(y, x));
playerController = PlayerController.getInstance();
Player player = playerController.getPlayer();
if(tile.getClass().equals(EquipmentTile.class) || tile.getClass().equals(StartTile.class)){
EquipmentTile eTile = (EquipmentTile) tile;
//geef equipment
player.addEquipment(eTile.getEquipment());
}
else if (tile.getClass().equals(Waterput.class)){
Waterput wTile = (Waterput) tile;
for (Player speler : wTile.getSpelers()){
speler.addWater(2);
}
//geef water
}
else if (tile.getClass().equals(Tunnel.class)){
Tunnel tTile = (Tunnel) tile;
player.addEquipment(tTile.getEquipment());
//geen zon brand
}
else if (tile.getClass().equals(PartTile.class)){
PartTile pTile = (PartTile) tile;
geefHint(pTile);
//ontdek hint
}
else if (tile.getClass().equals(Finish.class)){
Finish fTile = (Finish) tile;
fTile.isSpelKlaar();
//ga ff checken of je hebt gewonnen
}
else{
//System.out.println("Dit gaat fout (Tilecontroller)");
}
}
public void geefHint(PartTile tile){
for(Onderdeel onderdeel:onderdelen){
if(tile.getSoort().equals(onderdeel.getSoort())){
if (tile.getRichting() == PartTile.Richtingen.OPZIJ){
onderdeel.setY((tile.getY()));
checkOnderdeelSpawned(onderdeel);
}
else if(tile.getRichting() == PartTile.Richtingen.OMHOOG){
onderdeel.setX((tile.getX()));
checkOnderdeelSpawned(onderdeel);
}
else{
//System.out.println("gaat fout lol (tilecontroller)");
}
}
}
}
public void checkOnderdeelSpawned(Onderdeel onderdeel){
if(!(onderdeel.getY() == -1) && !(onderdeel.getX() == -1) && !onderdeel.isOpgepakt()) {
Tile onderdeelSpawn = getTileByLocation(onderdeel.getY(), onderdeel.getX());
onderdeelSpawn.setOnderdeel(onderdeel);
}
}
/**
* Deze functie checkt voor alle onderdelen of ze al zijn gespawned.
*
* @author ryan
*/
private void checkOnderdelenSpawned(){
for (Onderdeel onderdeel : onderdelen){
if(!(onderdeel.getY() == -1) && !(onderdeel.getX() == -1) && !onderdeel.isOpgepakt()) {
Tile onderdeelSpawn = getTileByLocation(onderdeel.getY(), onderdeel.getX());
if (!onderdeelSpawn.getOnderdelen().contains(onderdeel)){
onderdeelSpawn.setOnderdeel(onderdeel);
}
}
}
}
/**
* Deze functie verwijdert alle onderdelen van de tile waarop hij lag die zijn opgepakt.
*
* @author ryan
*/
private void despawnOnderdelen(){
for (Onderdeel onderdeel : onderdelen){
if (onderdeel.isOpgepakt()){
for(Tile tile:randomTiles){
for(Onderdeel oD : tile.getOnderdelen()){
if(oD.equals(onderdeel)){
tile.removeOnderdeelSoort(onderdeel);
}
}
}
//Tile onderdeelTile = getTileByLocation(onderdeel.getY(), onderdeel.getX());
//onderdeelTile.removeOnderdeelSoort(onderdeel);
}
}
}
private Tile getFinsihTile(){
for (Tile tile : randomTiles){
if (tile.getVariant() == Tile.Varianten.FINISH){
return tile;
}
}
return null;
}
private boolean checkAlleOnderdelen(){
int opgepaktCounter = 0;
for (Onderdeel onderdeel : onderdelen){
if (onderdeel.isOpgepakt()){
opgepaktCounter++;
}
}
return opgepaktCounter == 4;
}
public boolean checkFinish(){
return getFinsihTile().getSpelers().size() == 4 && checkAlleOnderdelen();
}
public void checkZandCounter() {
int zandCounter = 0;
//int zandMax = 48;
int zandMax = 9;
for (Tile tile : randomTiles) {
zandCounter += tile.getZand();
}
if (zandCounter > zandMax) {
ViewManager.getInstance().loadEndGame(ViewManager.endConditions.SUFFOCATION);
}
}
public ArrayList<Tile> getTiles(){
return this.randomTiles;
}
/**
* Deze functie update alle data waarover deze klasse gaat met de data uit FireBase.
*
* @author ryan
*/
public void updateData(){
StaticData staticData = StaticData.getInstance();
Object roominfo = staticData.getRoomInfo();
Map<String, Object> tilesMap = (Map)((Map) roominfo).get("tiles");
updateTilesFromFB(tilesMap);
Map<String, Object> onderdelenMap = (Map)((Map) roominfo).get("onderdelen");
Platform.runLater(() -> {
updateOnderdelenFromFB(onderdelenMap);
//despawnOnderdelen();
//checkOnderdelenSpawned();
});
//updateOnderdelenFromFB(onderdelenMap);
checkOnderdelenSpawned();
despawnOnderdelen();
}
/**
* Deze functie update de onderdelen met data vanuit FireBase.
*
* @param onderdelenMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void updateOnderdelenFromFB(Map<String, Object> onderdelenMap){
for (int i = 0; i <onderdelen.size(); i++){
Map<String, Object> onderdeelFB = (Map)onderdelenMap.get(Integer.toString(i));
Onderdeel onderdeel = onderdelen.get(i);
int x = Integer.valueOf(onderdeelFB.get("x").toString());
int y = Integer.valueOf(onderdeelFB.get("y").toString());
if((onderdeelFB.get("opgepakt").toString()).equals("true")){
onderdeel.pakOp();
}
onderdeel.setX(x);
onderdeel.setY(y);
}
}
/**
* Deze functie update de tiles met data vanuit FireBase.
*
* @param tilesMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void updateTilesFromFB(Map<String, Object> tilesMap){
for (int i = 0; i < 25; i++){
Map<String, Object> tileFB = (Map)tilesMap.get(Integer.toString(i));
Tile tile = randomTiles.get(i);
int x = Integer.valueOf(tileFB.get("x").toString());
int y = Integer.valueOf(tileFB.get("y").toString());
boolean discovered = false;
if((tileFB.get("discovered").toString()).equals("true")){
discovered = true;
}
boolean hasZonneSchild = tileFB.get("hasZonneSchild").toString().equals("true");
int aantalZand = Integer.valueOf(tileFB.get("aantalZandTegels").toString());
tile.emptyPlayers();
String s = tileFB.get("Players").toString();
if(s.contains("Archeoloog")){
tile.addPlayer("Archeoloog");
}
if(s.contains("Klimmer")){
tile.addPlayer("Klimmer");
}
if(s.contains("Verkenner")){
tile.addPlayer("Verkenner");
}
if(s.contains("Waterdrager")){
tile.addPlayer("Waterdrager");
}
tile.setLocation(x, y);
tile.setDiscovered(discovered);
if (hasZonneSchild){
tile.setZonneSchild();
}
tile.setAantalZandTegels(aantalZand);
}
}
/**
* Deze functie maakt tiles aan, aan de hand van info uit FireBase
*
* @param tilesMap Een Map met informatie over de onderdelen
* @author ryan
*/
private void makeTilesFormFB(Map<String, Object> tilesMap){
ArrayList<Tile> fbTiles = new ArrayList<>();
for (int i = 0; i < 25; i++){
Map<String, Object> tileFB = (Map)tilesMap.get(Integer.toString(i));
Tile tile = null;
String variant = tileFB.get("naam").toString();
int x = Integer.valueOf(tileFB.get("x").toString());
int y = Integer.valueOf(tileFB.get("y").toString());
boolean discovered = false;
if((tileFB.get("discovered").toString()).equals("true")){
discovered = true;
}
boolean hasZonneSchild = Boolean.getBoolean(tileFB.get("hasZonneSchild").toString());
int aantalZand = Integer.valueOf(tileFB.get("aantalZandTegels").toString());
switch (variant){
case "PART":
tile = new PartTile(stringToRichting(tileFB.get("richting").toString()), stringToSoort(tileFB.get("soort").toString()));
break;
case "FATAMORGANA":
tile = new FataMorgana();
break;
case "EQUIPMENT":
tile = new EquipmentTile(stringToEquipment(tileFB.get("equipment").toString()));
break;
case "TUNNEL":
tile = new Tunnel(stringToEquipment(tileFB.get("equipment").toString()));
break;
case "WATERPUT":
tile = new Waterput();
break;
case "FINISH":
tile = new Finish();
break;
case "STORM":
tile = new Storm();
break;
case "START":
tile = new StartTile(stringToEquipment(tileFB.get("equipment").toString()));
break;
}
String s = tileFB.get("Players").toString();
if(s.contains("Archeoloog")){
tile.addPlayer("Archeoloog");
}
if(s.contains("Klimmer")){
tile.addPlayer("Klimmer");
}
if(s.contains("Verkenner")){
tile.addPlayer("Verkenner");
}
if(s.contains("Waterdrager")){
tile.addPlayer("Waterdrager");
}
tile.setLocation(x, y);
tile.setDiscovered(discovered);
tile.setHasZonneSchild(hasZonneSchild);
tile.setAantalZandTegels(aantalZand);
fbTiles.add(tile);
}
randomTiles = fbTiles;
maakOnderdelen();
}
public Equipment stringToEquipment(String eq){
switch (eq){
case "JETPACK":
return new Jetpack();
case "AARDEKIJKER":
return new Aardekijker();
case "DUINKANON":
return new Duinkanon();
case "TIJDSCHAKELAAR":
return new Tijdschakelaar();
case "ZONNESCHILD":
return new Zonneschild();
case "WATERRESERVE":
return new Waterreserve();
}
return null;
}
public PartTile.Richtingen stringToRichting(String richting){
if (richting.equals("OPZIJ")){
return PartTile.Richtingen.OPZIJ;
}
return PartTile.Richtingen.OMHOOG;
}
public PartTile.Soorten stringToSoort(String soort){
switch (soort){
case "OBELISK":
return PartTile.Soorten.OBELISK;
case "MOTOR":
return PartTile.Soorten.MOTOR;
case "KOMPAS":
return PartTile.Soorten.KOMPAS;
case "PROPELOR":
return PartTile.Soorten.PROPELOR;
}
return null;
}
public ArrayList<Onderdeel> getOnderdelen() {
return onderdelen;
}
public void update(){
for (Tile tile : randomTiles){
tile.notifyAllObservers();
}
}
}
|
23586_2 | package application;
import model.datum.Datum;
public class Registration {
// wie
String voornaam;
String familienaam;
// waar / wat
int huisnummer; // rijnummer + volgnummer
// wanneer
Datum startDatum;
int aantalVerblijfNachten;
public Registration(String voornaam, String familienaam, int huisnummer, Datum startDatum,
int aantalVerblijfNachten) throws Exception
{
// Eerst wat validatie. De datum wordt in de Datum klasse gevalideerd, hier wordt datum > nu gecheckt.
if (voornaam == null || !voornaam.chars().allMatch(letter -> Character.isLetter(letter)))
{
throw new Exception("De voornaam mag enkel letters bevatten");
}
else if (familienaam == null || !familienaam.chars().allMatch(letter -> Character.isLetter(letter)))
{
throw new Exception("De familienaam mag enkel letters bevatten");
}
else if (huisnummer < 1 || huisnummer > 107)
{
throw new Exception("De huisnummer moet een getal tussen 1 en 107 zijn");
}
else if (((new Datum()).kleinerDan(startDatum)))
{
throw new Exception("De datum mag niet kleiner dan de huidige datum zijn silly!");
}
else if (aantalVerblijfNachten < 1)
{
throw new Exception("Minder dan 1 nacht verblijven? Dat gaat toch niet!!!");
}
this.voornaam = voornaam;
this.familienaam = familienaam;
this.huisnummer = huisnummer;
this.startDatum = startDatum;
this.aantalVerblijfNachten = aantalVerblijfNachten;
}
/**
*
* @return
*/
public String formaatVoorBestandLijn()
{
return huisnummer + "," + startDatum.getDatumInEuropeesFormaat() + "," + aantalVerblijfNachten + ">" + familienaam + "," + voornaam;
}
@Override
public String toString() {
return "Voornaam: " + voornaam + ", Naam: " + familienaam + ", HN: " + huisnummer + ", Vanaf: " + startDatum.toString() +
", Nachten: " + aantalVerblijfNachten;
}
}
| thunder-tw/JavaPractOpdrachten | Opdracht 1/src/application/Registration.java | 574 | // Eerst wat validatie. De datum wordt in de Datum klasse gevalideerd, hier wordt datum > nu gecheckt. | line_comment | nl | package application;
import model.datum.Datum;
public class Registration {
// wie
String voornaam;
String familienaam;
// waar / wat
int huisnummer; // rijnummer + volgnummer
// wanneer
Datum startDatum;
int aantalVerblijfNachten;
public Registration(String voornaam, String familienaam, int huisnummer, Datum startDatum,
int aantalVerblijfNachten) throws Exception
{
// Eerst wat<SUF>
if (voornaam == null || !voornaam.chars().allMatch(letter -> Character.isLetter(letter)))
{
throw new Exception("De voornaam mag enkel letters bevatten");
}
else if (familienaam == null || !familienaam.chars().allMatch(letter -> Character.isLetter(letter)))
{
throw new Exception("De familienaam mag enkel letters bevatten");
}
else if (huisnummer < 1 || huisnummer > 107)
{
throw new Exception("De huisnummer moet een getal tussen 1 en 107 zijn");
}
else if (((new Datum()).kleinerDan(startDatum)))
{
throw new Exception("De datum mag niet kleiner dan de huidige datum zijn silly!");
}
else if (aantalVerblijfNachten < 1)
{
throw new Exception("Minder dan 1 nacht verblijven? Dat gaat toch niet!!!");
}
this.voornaam = voornaam;
this.familienaam = familienaam;
this.huisnummer = huisnummer;
this.startDatum = startDatum;
this.aantalVerblijfNachten = aantalVerblijfNachten;
}
/**
*
* @return
*/
public String formaatVoorBestandLijn()
{
return huisnummer + "," + startDatum.getDatumInEuropeesFormaat() + "," + aantalVerblijfNachten + ">" + familienaam + "," + voornaam;
}
@Override
public String toString() {
return "Voornaam: " + voornaam + ", Naam: " + familienaam + ", HN: " + huisnummer + ", Vanaf: " + startDatum.toString() +
", Nachten: " + aantalVerblijfNachten;
}
}
|
32238_1 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.monitor.jvm;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.ReferenceDocs;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.ChunkedLoggingStream;
import org.elasticsearch.common.time.DateFormatter;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.Maps;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.transport.Transports;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.ToLongFunction;
public class HotThreads {
private static final Object mutex = new Object();
private static final StackTraceElement[] EMPTY = new StackTraceElement[0];
private static final DateFormatter DATE_TIME_FORMATTER = DateFormatter.forPattern("date_optional_time");
private static final long INVALID_TIMING = -1L;
private int busiestThreads = 3;
private TimeValue interval = new TimeValue(500, TimeUnit.MILLISECONDS);
private TimeValue threadElementsSnapshotDelay = new TimeValue(10, TimeUnit.MILLISECONDS);
private int threadElementsSnapshotCount = 10;
private ReportType type = ReportType.CPU;
private SortOrder sortOrder = SortOrder.TOTAL;
private boolean ignoreIdleThreads = true;
private static final List<String[]> knownIdleStackFrames = Arrays.asList(
new String[] { "java.util.concurrent.ThreadPoolExecutor", "getTask" },
new String[] { "sun.nio.ch.SelectorImpl", "select" },
new String[] { "org.elasticsearch.threadpool.ThreadPool$CachedTimeThread", "run" },
new String[] { "org.elasticsearch.indices.ttl.IndicesTTLService$Notifier", "await" },
new String[] { "java.util.concurrent.LinkedTransferQueue", "poll" },
new String[] { "com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout", "run" }
);
// NOTE: these are JVM dependent and JVM version dependent
private static final List<String> knownJDKInternalThreads = Arrays.asList(
"Signal Dispatcher",
"Finalizer",
"Reference Handler",
"Notification Thread",
"Common-Cleaner",
"process reaper",
"DestroyJavaVM"
);
/**
* Capture and log the hot threads on the local node. Useful for capturing stack traces for unexpectedly-slow operations in production.
* The resulting log message may be large, and contains significant whitespace, so it is compressed and base64-encoded using {@link
* ChunkedLoggingStream}.
*
* @param logger The logger to use for the logging
* @param level The log level to use for the logging.
* @param prefix The prefix to emit on each chunk of the logging.
* @param referenceDocs A link to the docs describing how to decode the logging.
*/
public static void logLocalHotThreads(Logger logger, Level level, String prefix, ReferenceDocs referenceDocs) {
if (logger.isEnabled(level) == false) {
return;
}
try (
var stream = ChunkedLoggingStream.create(logger, level, prefix, referenceDocs);
var writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8)
) {
new HotThreads().busiestThreads(500).ignoreIdleThreads(false).detect(writer);
} catch (Exception e) {
logger.error(() -> org.elasticsearch.common.Strings.format("failed to write local hot threads with prefix [%s]", prefix), e);
}
}
public enum ReportType {
CPU("cpu"),
WAIT("wait"),
BLOCK("block"),
MEM("mem");
private final String type;
ReportType(String type) {
this.type = type;
}
public String getTypeValue() {
return type;
}
// Custom enum from string because of legacy support. The standard Enum.valueOf is static
// and cannot be overriden to show a nice error message in case the enum value isn't found
public static ReportType of(String type) {
for (var report : values()) {
if (report.type.equals(type)) {
return report;
}
}
throw new IllegalArgumentException("type not supported [" + type + "]");
}
}
public enum SortOrder {
TOTAL("total"),
CPU("cpu");
private final String order;
SortOrder(String order) {
this.order = order;
}
public String getOrderValue() {
return order;
}
// Custom enum from string because of legacy support. The standard Enum.valueOf is static
// and cannot be overriden to show a nice error message in case the enum value isn't found
public static SortOrder of(String order) {
for (var sortOrder : values()) {
if (sortOrder.order.equals(order)) {
return sortOrder;
}
}
throw new IllegalArgumentException("sort order not supported [" + order + "]");
}
}
public HotThreads interval(TimeValue interval) {
this.interval = interval;
return this;
}
public HotThreads busiestThreads(int busiestThreads) {
this.busiestThreads = busiestThreads;
return this;
}
public HotThreads ignoreIdleThreads(boolean ignoreIdleThreads) {
this.ignoreIdleThreads = ignoreIdleThreads;
return this;
}
public HotThreads threadElementsSnapshotCount(int threadElementsSnapshotCount) {
this.threadElementsSnapshotCount = threadElementsSnapshotCount;
return this;
}
public HotThreads type(ReportType type) {
this.type = type;
return this;
}
public HotThreads sortOrder(SortOrder order) {
this.sortOrder = order;
return this;
}
public void detect(Writer writer) throws Exception {
synchronized (mutex) {
innerDetect(ManagementFactory.getThreadMXBean(), SunThreadInfo.INSTANCE, Thread.currentThread().getId(), (interval) -> {
Thread.sleep(interval);
return null;
}, writer);
}
}
static boolean isKnownJDKThread(ThreadInfo threadInfo) {
return (knownJDKInternalThreads.stream()
.anyMatch(jvmThread -> threadInfo.getThreadName() != null && threadInfo.getThreadName().equals(jvmThread)));
}
static boolean isKnownIdleStackFrame(String className, String methodName) {
return (knownIdleStackFrames.stream().anyMatch(pair -> pair[0].equals(className) && pair[1].equals(methodName)));
}
static boolean isIdleThread(ThreadInfo threadInfo) {
if (isKnownJDKThread(threadInfo)) {
return true;
}
for (StackTraceElement frame : threadInfo.getStackTrace()) {
if (isKnownIdleStackFrame(frame.getClassName(), frame.getMethodName())) {
return true;
}
}
return false;
}
Map<Long, ThreadTimeAccumulator> getAllValidThreadInfos(ThreadMXBean threadBean, SunThreadInfo sunThreadInfo, long currentThreadId) {
long[] threadIds = threadBean.getAllThreadIds();
ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadIds);
Map<Long, ThreadTimeAccumulator> result = Maps.newMapWithExpectedSize(threadIds.length);
for (int i = 0; i < threadIds.length; i++) {
if (threadInfos[i] == null || threadIds[i] == currentThreadId) {
continue;
}
long cpuTime = threadBean.getThreadCpuTime(threadIds[i]);
if (cpuTime == INVALID_TIMING) {
continue;
}
long allocatedBytes = type == ReportType.MEM ? sunThreadInfo.getThreadAllocatedBytes(threadIds[i]) : 0;
result.put(threadIds[i], new ThreadTimeAccumulator(threadInfos[i], interval, cpuTime, allocatedBytes));
}
return result;
}
ThreadInfo[][] captureThreadStacks(ThreadMXBean threadBean, long[] threadIds) throws InterruptedException {
ThreadInfo[][] result = new ThreadInfo[threadElementsSnapshotCount][];
for (int j = 0; j < threadElementsSnapshotCount; j++) {
// NOTE, javadoc of getThreadInfo says: If a thread of the given ID is not alive or does not exist,
// null will be set in the corresponding element in the returned array. A thread is alive if it has
// been started and has not yet died.
result[j] = threadBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
Thread.sleep(threadElementsSnapshotDelay.millis());
}
return result;
}
private static boolean isThreadWaitBlockTimeMonitoringEnabled(ThreadMXBean threadBean) {
if (threadBean.isThreadContentionMonitoringSupported()) {
return threadBean.isThreadContentionMonitoringEnabled();
}
return false;
}
private double getTimeSharePercentage(long time) {
return (((double) time) / interval.nanos()) * 100;
}
void innerDetect(
ThreadMXBean threadBean,
SunThreadInfo sunThreadInfo,
long currentThreadId,
SleepFunction<Long, Void> threadSleep,
Writer writer
) throws Exception {
if (threadBean.isThreadCpuTimeSupported() == false) {
throw new ElasticsearchException("thread CPU time is not supported on this JDK");
}
if (type == ReportType.MEM && sunThreadInfo.isThreadAllocatedMemorySupported() == false) {
throw new ElasticsearchException("thread allocated memory is not supported on this JDK");
}
// Enabling thread contention monitoring is required for capturing JVM thread wait/blocked times. If we weren't
// able to enable this functionality during bootstrap, we should not produce HotThreads reports.
if (isThreadWaitBlockTimeMonitoringEnabled(threadBean) == false) {
throw new ElasticsearchException("thread wait/blocked time accounting is not supported on this JDK");
}
writer.append("Hot threads at ")
.append(DATE_TIME_FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
.append(", interval=")
.append(interval.toString())
.append(", busiestThreads=")
.append(Integer.toString(busiestThreads))
.append(", ignoreIdleThreads=")
.append(Boolean.toString(ignoreIdleThreads))
.append(":\n");
// Capture before and after thread state with timings
Map<Long, ThreadTimeAccumulator> previousThreadInfos = getAllValidThreadInfos(threadBean, sunThreadInfo, currentThreadId);
threadSleep.apply(interval.millis());
Map<Long, ThreadTimeAccumulator> latestThreadInfos = getAllValidThreadInfos(threadBean, sunThreadInfo, currentThreadId);
latestThreadInfos.forEach((threadId, accumulator) -> accumulator.subtractPrevious(previousThreadInfos.get(threadId)));
// Sort by delta CPU time on thread.
List<ThreadTimeAccumulator> topThreads = new ArrayList<>(latestThreadInfos.values());
// Special comparator for CPU mode with TOTAL sort type only. Otherwise, we simply use the value.
if (type == ReportType.CPU && sortOrder == SortOrder.TOTAL) {
CollectionUtil.introSort(
topThreads,
Comparator.comparingLong(ThreadTimeAccumulator::getRunnableTime)
.thenComparingLong(ThreadTimeAccumulator::getCpuTime)
.reversed()
);
} else {
CollectionUtil.introSort(topThreads, Comparator.comparingLong(ThreadTimeAccumulator.valueGetterForReportType(type)).reversed());
}
topThreads = topThreads.subList(0, Math.min(busiestThreads, topThreads.size()));
long[] topThreadIds = topThreads.stream().mapToLong(t -> t.threadId).toArray();
// analyse N stack traces for the top threads
ThreadInfo[][] allInfos = captureThreadStacks(threadBean, topThreadIds);
for (int t = 0; t < topThreads.size(); t++) {
String threadName = null;
for (ThreadInfo[] info : allInfos) {
if (info != null && info[t] != null) {
if (ignoreIdleThreads && isIdleThread(info[t])) {
info[t] = null;
continue;
}
threadName = info[t].getThreadName();
break;
}
}
if (threadName == null) {
continue; // thread is not alive yet or died before the first snapshot - ignore it!
}
ThreadTimeAccumulator topThread = topThreads.get(t);
switch (type) {
case MEM -> writer.append(
Strings.format(
"%n%s memory allocated by thread '%s'%n",
ByteSizeValue.ofBytes(topThread.getAllocatedBytes()),
threadName
)
);
case CPU -> {
double percentCpu = getTimeSharePercentage(topThread.getCpuTime());
double percentOther = Transports.isTransportThread(threadName) && topThread.getCpuTime() == 0L
? 100.0
: getTimeSharePercentage(topThread.getOtherTime());
double percentTotal = (Transports.isTransportThread(threadName)) ? percentCpu : percentOther + percentCpu;
String otherLabel = (Transports.isTransportThread(threadName)) ? "idle" : "other";
writer.append(
Strings.format(
"%n%4.1f%% [cpu=%1.1f%%, %s=%1.1f%%] (%s out of %s) %s usage by thread '%s'%n",
percentTotal,
percentCpu,
otherLabel,
percentOther,
TimeValue.timeValueNanos(topThread.getCpuTime() + topThread.getOtherTime()),
interval,
type.getTypeValue(),
threadName
)
);
}
default -> {
long time = ThreadTimeAccumulator.valueGetterForReportType(type).applyAsLong(topThread);
double percent = getTimeSharePercentage(time);
writer.append(
Strings.format(
"%n%4.1f%% (%s out of %s) %s usage by thread '%s'%n",
percent,
TimeValue.timeValueNanos(time),
interval,
type.getTypeValue(),
threadName
)
);
}
}
// for each snapshot (2nd array index) find later snapshot for same thread with max number of
// identical StackTraceElements (starting from end of each)
boolean[] done = new boolean[threadElementsSnapshotCount];
for (int i = 0; i < threadElementsSnapshotCount; i++) {
if (done[i]) continue;
int maxSim = 1;
boolean[] similars = new boolean[threadElementsSnapshotCount];
for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
if (done[j]) continue;
int similarity = similarity(allInfos[i][t], allInfos[j][t]);
if (similarity > maxSim) {
maxSim = similarity;
similars = new boolean[threadElementsSnapshotCount];
}
if (similarity == maxSim) similars[j] = true;
}
// print out trace maxSim levels of i, and mark similar ones as done
int count = 1;
for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
if (similars[j]) {
done[j] = true;
count++;
}
}
if (allInfos[i][t] != null) {
final StackTraceElement[] show = allInfos[i][t].getStackTrace();
if (count == 1) {
writer.append(Strings.format(" unique snapshot%n"));
for (StackTraceElement frame : show) {
writer.append(Strings.format(" %s%n", frame));
}
} else {
writer.append(
Strings.format(" %d/%d snapshots sharing following %d elements%n", count, threadElementsSnapshotCount, maxSim)
);
for (int l = show.length - maxSim; l < show.length; l++) {
writer.append(Strings.format(" %s%n", show[l]));
}
}
}
}
}
}
static int similarity(ThreadInfo threadInfo, ThreadInfo threadInfo0) {
StackTraceElement[] s1 = threadInfo == null ? EMPTY : threadInfo.getStackTrace();
StackTraceElement[] s2 = threadInfo0 == null ? EMPTY : threadInfo0.getStackTrace();
int i = s1.length - 1;
int j = s2.length - 1;
int rslt = 0;
while (i >= 0 && j >= 0 && s1[i].equals(s2[j])) {
rslt++;
i--;
j--;
}
return rslt;
}
static class ThreadTimeAccumulator {
private final long threadId;
private final String threadName;
private final TimeValue interval;
private long cpuTime;
private long blockedTime;
private long waitedTime;
private long allocatedBytes;
ThreadTimeAccumulator(ThreadInfo info, TimeValue interval, long cpuTime, long allocatedBytes) {
this.blockedTime = millisecondsToNanos(info.getBlockedTime()); // Convert to nanos to standardize
this.waitedTime = millisecondsToNanos(info.getWaitedTime()); // Convert to nanos to standardize
this.cpuTime = cpuTime;
this.allocatedBytes = allocatedBytes;
this.threadId = info.getThreadId();
this.threadName = info.getThreadName();
this.interval = interval;
}
private static long millisecondsToNanos(long millis) {
return millis * 1_000_000;
}
void subtractPrevious(ThreadTimeAccumulator previous) {
// Previous can be null for threads that had started while we were sleeping.
// In that case the absolute thread timings are the delta.
if (previous != null) {
if (previous.getThreadId() != getThreadId()) {
throw new IllegalStateException("Thread timing accumulation must be done on the same thread");
}
this.blockedTime -= previous.blockedTime;
this.waitedTime -= previous.waitedTime;
this.cpuTime -= previous.cpuTime;
this.allocatedBytes -= previous.allocatedBytes;
}
}
// A thread can migrate a CPU while executing, in which case, on certain processors, the
// reported timings will be bogus (and likely negative). We cap the reported timings to >= 0 values only.
public long getCpuTime() {
return Math.max(cpuTime, 0);
}
public long getRunnableTime() {
// If the thread didn't have any CPU movement, we can't really tell if it's
// not running, or it has been asleep forever.
if (getCpuTime() == 0) {
return 0;
} else if (Transports.isTransportThread(threadName)) {
return getCpuTime();
}
return Math.max(interval.nanos() - getWaitedTime() - getBlockedTime(), 0);
}
public long getOtherTime() {
// If the thread didn't have any CPU movement, we can't really tell if it's
// not running, or it has been asleep forever.
if (getCpuTime() == 0) {
return 0;
}
return Math.max(interval.nanos() - getWaitedTime() - getBlockedTime() - getCpuTime(), 0);
}
public long getBlockedTime() {
return Math.max(blockedTime, 0);
}
public long getWaitedTime() {
return Math.max(waitedTime, 0);
}
public long getAllocatedBytes() {
return Math.max(allocatedBytes, 0);
}
public long getThreadId() {
return threadId;
}
static ToLongFunction<ThreadTimeAccumulator> valueGetterForReportType(ReportType type) {
return switch (type) {
case CPU -> ThreadTimeAccumulator::getCpuTime;
case WAIT -> ThreadTimeAccumulator::getWaitedTime;
case BLOCK -> ThreadTimeAccumulator::getBlockedTime;
case MEM -> ThreadTimeAccumulator::getAllocatedBytes;
};
}
}
@FunctionalInterface
public interface SleepFunction<T, R> {
R apply(T t) throws InterruptedException;
}
public static void initializeRuntimeMonitoring() {
// We'll let the JVM boot without this functionality, however certain APIs like HotThreads will not
// function and report an error.
if (ManagementFactory.getThreadMXBean().isThreadContentionMonitoringSupported() == false) {
LogManager.getLogger(HotThreads.class).info("Thread wait/blocked time accounting not supported.");
} else {
try {
ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
} catch (UnsupportedOperationException monitoringUnavailable) {
LogManager.getLogger(HotThreads.class).warn("Thread wait/blocked time accounting cannot be enabled.");
}
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/monitor/jvm/HotThreads.java | 5,403 | // NOTE: these are JVM dependent and JVM version dependent | line_comment | nl | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.monitor.jvm;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.ReferenceDocs;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.ChunkedLoggingStream;
import org.elasticsearch.common.time.DateFormatter;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.Maps;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.transport.Transports;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.ToLongFunction;
public class HotThreads {
private static final Object mutex = new Object();
private static final StackTraceElement[] EMPTY = new StackTraceElement[0];
private static final DateFormatter DATE_TIME_FORMATTER = DateFormatter.forPattern("date_optional_time");
private static final long INVALID_TIMING = -1L;
private int busiestThreads = 3;
private TimeValue interval = new TimeValue(500, TimeUnit.MILLISECONDS);
private TimeValue threadElementsSnapshotDelay = new TimeValue(10, TimeUnit.MILLISECONDS);
private int threadElementsSnapshotCount = 10;
private ReportType type = ReportType.CPU;
private SortOrder sortOrder = SortOrder.TOTAL;
private boolean ignoreIdleThreads = true;
private static final List<String[]> knownIdleStackFrames = Arrays.asList(
new String[] { "java.util.concurrent.ThreadPoolExecutor", "getTask" },
new String[] { "sun.nio.ch.SelectorImpl", "select" },
new String[] { "org.elasticsearch.threadpool.ThreadPool$CachedTimeThread", "run" },
new String[] { "org.elasticsearch.indices.ttl.IndicesTTLService$Notifier", "await" },
new String[] { "java.util.concurrent.LinkedTransferQueue", "poll" },
new String[] { "com.sun.jmx.remote.internal.ServerCommunicatorAdmin$Timeout", "run" }
);
// NOTE: these<SUF>
private static final List<String> knownJDKInternalThreads = Arrays.asList(
"Signal Dispatcher",
"Finalizer",
"Reference Handler",
"Notification Thread",
"Common-Cleaner",
"process reaper",
"DestroyJavaVM"
);
/**
* Capture and log the hot threads on the local node. Useful for capturing stack traces for unexpectedly-slow operations in production.
* The resulting log message may be large, and contains significant whitespace, so it is compressed and base64-encoded using {@link
* ChunkedLoggingStream}.
*
* @param logger The logger to use for the logging
* @param level The log level to use for the logging.
* @param prefix The prefix to emit on each chunk of the logging.
* @param referenceDocs A link to the docs describing how to decode the logging.
*/
public static void logLocalHotThreads(Logger logger, Level level, String prefix, ReferenceDocs referenceDocs) {
if (logger.isEnabled(level) == false) {
return;
}
try (
var stream = ChunkedLoggingStream.create(logger, level, prefix, referenceDocs);
var writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8)
) {
new HotThreads().busiestThreads(500).ignoreIdleThreads(false).detect(writer);
} catch (Exception e) {
logger.error(() -> org.elasticsearch.common.Strings.format("failed to write local hot threads with prefix [%s]", prefix), e);
}
}
public enum ReportType {
CPU("cpu"),
WAIT("wait"),
BLOCK("block"),
MEM("mem");
private final String type;
ReportType(String type) {
this.type = type;
}
public String getTypeValue() {
return type;
}
// Custom enum from string because of legacy support. The standard Enum.valueOf is static
// and cannot be overriden to show a nice error message in case the enum value isn't found
public static ReportType of(String type) {
for (var report : values()) {
if (report.type.equals(type)) {
return report;
}
}
throw new IllegalArgumentException("type not supported [" + type + "]");
}
}
public enum SortOrder {
TOTAL("total"),
CPU("cpu");
private final String order;
SortOrder(String order) {
this.order = order;
}
public String getOrderValue() {
return order;
}
// Custom enum from string because of legacy support. The standard Enum.valueOf is static
// and cannot be overriden to show a nice error message in case the enum value isn't found
public static SortOrder of(String order) {
for (var sortOrder : values()) {
if (sortOrder.order.equals(order)) {
return sortOrder;
}
}
throw new IllegalArgumentException("sort order not supported [" + order + "]");
}
}
public HotThreads interval(TimeValue interval) {
this.interval = interval;
return this;
}
public HotThreads busiestThreads(int busiestThreads) {
this.busiestThreads = busiestThreads;
return this;
}
public HotThreads ignoreIdleThreads(boolean ignoreIdleThreads) {
this.ignoreIdleThreads = ignoreIdleThreads;
return this;
}
public HotThreads threadElementsSnapshotCount(int threadElementsSnapshotCount) {
this.threadElementsSnapshotCount = threadElementsSnapshotCount;
return this;
}
public HotThreads type(ReportType type) {
this.type = type;
return this;
}
public HotThreads sortOrder(SortOrder order) {
this.sortOrder = order;
return this;
}
public void detect(Writer writer) throws Exception {
synchronized (mutex) {
innerDetect(ManagementFactory.getThreadMXBean(), SunThreadInfo.INSTANCE, Thread.currentThread().getId(), (interval) -> {
Thread.sleep(interval);
return null;
}, writer);
}
}
static boolean isKnownJDKThread(ThreadInfo threadInfo) {
return (knownJDKInternalThreads.stream()
.anyMatch(jvmThread -> threadInfo.getThreadName() != null && threadInfo.getThreadName().equals(jvmThread)));
}
static boolean isKnownIdleStackFrame(String className, String methodName) {
return (knownIdleStackFrames.stream().anyMatch(pair -> pair[0].equals(className) && pair[1].equals(methodName)));
}
static boolean isIdleThread(ThreadInfo threadInfo) {
if (isKnownJDKThread(threadInfo)) {
return true;
}
for (StackTraceElement frame : threadInfo.getStackTrace()) {
if (isKnownIdleStackFrame(frame.getClassName(), frame.getMethodName())) {
return true;
}
}
return false;
}
Map<Long, ThreadTimeAccumulator> getAllValidThreadInfos(ThreadMXBean threadBean, SunThreadInfo sunThreadInfo, long currentThreadId) {
long[] threadIds = threadBean.getAllThreadIds();
ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadIds);
Map<Long, ThreadTimeAccumulator> result = Maps.newMapWithExpectedSize(threadIds.length);
for (int i = 0; i < threadIds.length; i++) {
if (threadInfos[i] == null || threadIds[i] == currentThreadId) {
continue;
}
long cpuTime = threadBean.getThreadCpuTime(threadIds[i]);
if (cpuTime == INVALID_TIMING) {
continue;
}
long allocatedBytes = type == ReportType.MEM ? sunThreadInfo.getThreadAllocatedBytes(threadIds[i]) : 0;
result.put(threadIds[i], new ThreadTimeAccumulator(threadInfos[i], interval, cpuTime, allocatedBytes));
}
return result;
}
ThreadInfo[][] captureThreadStacks(ThreadMXBean threadBean, long[] threadIds) throws InterruptedException {
ThreadInfo[][] result = new ThreadInfo[threadElementsSnapshotCount][];
for (int j = 0; j < threadElementsSnapshotCount; j++) {
// NOTE, javadoc of getThreadInfo says: If a thread of the given ID is not alive or does not exist,
// null will be set in the corresponding element in the returned array. A thread is alive if it has
// been started and has not yet died.
result[j] = threadBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
Thread.sleep(threadElementsSnapshotDelay.millis());
}
return result;
}
private static boolean isThreadWaitBlockTimeMonitoringEnabled(ThreadMXBean threadBean) {
if (threadBean.isThreadContentionMonitoringSupported()) {
return threadBean.isThreadContentionMonitoringEnabled();
}
return false;
}
private double getTimeSharePercentage(long time) {
return (((double) time) / interval.nanos()) * 100;
}
void innerDetect(
ThreadMXBean threadBean,
SunThreadInfo sunThreadInfo,
long currentThreadId,
SleepFunction<Long, Void> threadSleep,
Writer writer
) throws Exception {
if (threadBean.isThreadCpuTimeSupported() == false) {
throw new ElasticsearchException("thread CPU time is not supported on this JDK");
}
if (type == ReportType.MEM && sunThreadInfo.isThreadAllocatedMemorySupported() == false) {
throw new ElasticsearchException("thread allocated memory is not supported on this JDK");
}
// Enabling thread contention monitoring is required for capturing JVM thread wait/blocked times. If we weren't
// able to enable this functionality during bootstrap, we should not produce HotThreads reports.
if (isThreadWaitBlockTimeMonitoringEnabled(threadBean) == false) {
throw new ElasticsearchException("thread wait/blocked time accounting is not supported on this JDK");
}
writer.append("Hot threads at ")
.append(DATE_TIME_FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
.append(", interval=")
.append(interval.toString())
.append(", busiestThreads=")
.append(Integer.toString(busiestThreads))
.append(", ignoreIdleThreads=")
.append(Boolean.toString(ignoreIdleThreads))
.append(":\n");
// Capture before and after thread state with timings
Map<Long, ThreadTimeAccumulator> previousThreadInfos = getAllValidThreadInfos(threadBean, sunThreadInfo, currentThreadId);
threadSleep.apply(interval.millis());
Map<Long, ThreadTimeAccumulator> latestThreadInfos = getAllValidThreadInfos(threadBean, sunThreadInfo, currentThreadId);
latestThreadInfos.forEach((threadId, accumulator) -> accumulator.subtractPrevious(previousThreadInfos.get(threadId)));
// Sort by delta CPU time on thread.
List<ThreadTimeAccumulator> topThreads = new ArrayList<>(latestThreadInfos.values());
// Special comparator for CPU mode with TOTAL sort type only. Otherwise, we simply use the value.
if (type == ReportType.CPU && sortOrder == SortOrder.TOTAL) {
CollectionUtil.introSort(
topThreads,
Comparator.comparingLong(ThreadTimeAccumulator::getRunnableTime)
.thenComparingLong(ThreadTimeAccumulator::getCpuTime)
.reversed()
);
} else {
CollectionUtil.introSort(topThreads, Comparator.comparingLong(ThreadTimeAccumulator.valueGetterForReportType(type)).reversed());
}
topThreads = topThreads.subList(0, Math.min(busiestThreads, topThreads.size()));
long[] topThreadIds = topThreads.stream().mapToLong(t -> t.threadId).toArray();
// analyse N stack traces for the top threads
ThreadInfo[][] allInfos = captureThreadStacks(threadBean, topThreadIds);
for (int t = 0; t < topThreads.size(); t++) {
String threadName = null;
for (ThreadInfo[] info : allInfos) {
if (info != null && info[t] != null) {
if (ignoreIdleThreads && isIdleThread(info[t])) {
info[t] = null;
continue;
}
threadName = info[t].getThreadName();
break;
}
}
if (threadName == null) {
continue; // thread is not alive yet or died before the first snapshot - ignore it!
}
ThreadTimeAccumulator topThread = topThreads.get(t);
switch (type) {
case MEM -> writer.append(
Strings.format(
"%n%s memory allocated by thread '%s'%n",
ByteSizeValue.ofBytes(topThread.getAllocatedBytes()),
threadName
)
);
case CPU -> {
double percentCpu = getTimeSharePercentage(topThread.getCpuTime());
double percentOther = Transports.isTransportThread(threadName) && topThread.getCpuTime() == 0L
? 100.0
: getTimeSharePercentage(topThread.getOtherTime());
double percentTotal = (Transports.isTransportThread(threadName)) ? percentCpu : percentOther + percentCpu;
String otherLabel = (Transports.isTransportThread(threadName)) ? "idle" : "other";
writer.append(
Strings.format(
"%n%4.1f%% [cpu=%1.1f%%, %s=%1.1f%%] (%s out of %s) %s usage by thread '%s'%n",
percentTotal,
percentCpu,
otherLabel,
percentOther,
TimeValue.timeValueNanos(topThread.getCpuTime() + topThread.getOtherTime()),
interval,
type.getTypeValue(),
threadName
)
);
}
default -> {
long time = ThreadTimeAccumulator.valueGetterForReportType(type).applyAsLong(topThread);
double percent = getTimeSharePercentage(time);
writer.append(
Strings.format(
"%n%4.1f%% (%s out of %s) %s usage by thread '%s'%n",
percent,
TimeValue.timeValueNanos(time),
interval,
type.getTypeValue(),
threadName
)
);
}
}
// for each snapshot (2nd array index) find later snapshot for same thread with max number of
// identical StackTraceElements (starting from end of each)
boolean[] done = new boolean[threadElementsSnapshotCount];
for (int i = 0; i < threadElementsSnapshotCount; i++) {
if (done[i]) continue;
int maxSim = 1;
boolean[] similars = new boolean[threadElementsSnapshotCount];
for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
if (done[j]) continue;
int similarity = similarity(allInfos[i][t], allInfos[j][t]);
if (similarity > maxSim) {
maxSim = similarity;
similars = new boolean[threadElementsSnapshotCount];
}
if (similarity == maxSim) similars[j] = true;
}
// print out trace maxSim levels of i, and mark similar ones as done
int count = 1;
for (int j = i + 1; j < threadElementsSnapshotCount; j++) {
if (similars[j]) {
done[j] = true;
count++;
}
}
if (allInfos[i][t] != null) {
final StackTraceElement[] show = allInfos[i][t].getStackTrace();
if (count == 1) {
writer.append(Strings.format(" unique snapshot%n"));
for (StackTraceElement frame : show) {
writer.append(Strings.format(" %s%n", frame));
}
} else {
writer.append(
Strings.format(" %d/%d snapshots sharing following %d elements%n", count, threadElementsSnapshotCount, maxSim)
);
for (int l = show.length - maxSim; l < show.length; l++) {
writer.append(Strings.format(" %s%n", show[l]));
}
}
}
}
}
}
static int similarity(ThreadInfo threadInfo, ThreadInfo threadInfo0) {
StackTraceElement[] s1 = threadInfo == null ? EMPTY : threadInfo.getStackTrace();
StackTraceElement[] s2 = threadInfo0 == null ? EMPTY : threadInfo0.getStackTrace();
int i = s1.length - 1;
int j = s2.length - 1;
int rslt = 0;
while (i >= 0 && j >= 0 && s1[i].equals(s2[j])) {
rslt++;
i--;
j--;
}
return rslt;
}
static class ThreadTimeAccumulator {
private final long threadId;
private final String threadName;
private final TimeValue interval;
private long cpuTime;
private long blockedTime;
private long waitedTime;
private long allocatedBytes;
ThreadTimeAccumulator(ThreadInfo info, TimeValue interval, long cpuTime, long allocatedBytes) {
this.blockedTime = millisecondsToNanos(info.getBlockedTime()); // Convert to nanos to standardize
this.waitedTime = millisecondsToNanos(info.getWaitedTime()); // Convert to nanos to standardize
this.cpuTime = cpuTime;
this.allocatedBytes = allocatedBytes;
this.threadId = info.getThreadId();
this.threadName = info.getThreadName();
this.interval = interval;
}
private static long millisecondsToNanos(long millis) {
return millis * 1_000_000;
}
void subtractPrevious(ThreadTimeAccumulator previous) {
// Previous can be null for threads that had started while we were sleeping.
// In that case the absolute thread timings are the delta.
if (previous != null) {
if (previous.getThreadId() != getThreadId()) {
throw new IllegalStateException("Thread timing accumulation must be done on the same thread");
}
this.blockedTime -= previous.blockedTime;
this.waitedTime -= previous.waitedTime;
this.cpuTime -= previous.cpuTime;
this.allocatedBytes -= previous.allocatedBytes;
}
}
// A thread can migrate a CPU while executing, in which case, on certain processors, the
// reported timings will be bogus (and likely negative). We cap the reported timings to >= 0 values only.
public long getCpuTime() {
return Math.max(cpuTime, 0);
}
public long getRunnableTime() {
// If the thread didn't have any CPU movement, we can't really tell if it's
// not running, or it has been asleep forever.
if (getCpuTime() == 0) {
return 0;
} else if (Transports.isTransportThread(threadName)) {
return getCpuTime();
}
return Math.max(interval.nanos() - getWaitedTime() - getBlockedTime(), 0);
}
public long getOtherTime() {
// If the thread didn't have any CPU movement, we can't really tell if it's
// not running, or it has been asleep forever.
if (getCpuTime() == 0) {
return 0;
}
return Math.max(interval.nanos() - getWaitedTime() - getBlockedTime() - getCpuTime(), 0);
}
public long getBlockedTime() {
return Math.max(blockedTime, 0);
}
public long getWaitedTime() {
return Math.max(waitedTime, 0);
}
public long getAllocatedBytes() {
return Math.max(allocatedBytes, 0);
}
public long getThreadId() {
return threadId;
}
static ToLongFunction<ThreadTimeAccumulator> valueGetterForReportType(ReportType type) {
return switch (type) {
case CPU -> ThreadTimeAccumulator::getCpuTime;
case WAIT -> ThreadTimeAccumulator::getWaitedTime;
case BLOCK -> ThreadTimeAccumulator::getBlockedTime;
case MEM -> ThreadTimeAccumulator::getAllocatedBytes;
};
}
}
@FunctionalInterface
public interface SleepFunction<T, R> {
R apply(T t) throws InterruptedException;
}
public static void initializeRuntimeMonitoring() {
// We'll let the JVM boot without this functionality, however certain APIs like HotThreads will not
// function and report an error.
if (ManagementFactory.getThreadMXBean().isThreadContentionMonitoringSupported() == false) {
LogManager.getLogger(HotThreads.class).info("Thread wait/blocked time accounting not supported.");
} else {
try {
ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
} catch (UnsupportedOperationException monitoringUnavailable) {
LogManager.getLogger(HotThreads.class).warn("Thread wait/blocked time accounting cannot be enabled.");
}
}
}
}
|
207231_5 | package net.sf.regadb.io.db.ghb.lis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import net.sf.regadb.db.Attribute;
import net.sf.regadb.db.Dataset;
import net.sf.regadb.db.Patient;
import net.sf.regadb.db.PatientAttributeValue;
import net.sf.regadb.db.TestNominalValue;
import net.sf.regadb.db.TestResult;
import net.sf.regadb.db.TestType;
import net.sf.regadb.db.login.DisabledUserException;
import net.sf.regadb.db.login.WrongPasswordException;
import net.sf.regadb.db.login.WrongUidException;
import net.sf.regadb.db.session.Login;
import net.sf.regadb.io.db.ghb.GhbUtils;
import net.sf.regadb.io.db.util.Utils;
import net.sf.regadb.io.db.util.mapping.DbObjectStore;
import net.sf.regadb.io.db.util.mapping.ObjectMapper;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.InvalidValueException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.MappingDoesNotExistException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.MappingException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.ObjectDoesNotExistException;
import net.sf.regadb.io.db.util.mapping.ObjectStore;
import net.sf.regadb.io.util.StandardObjects;
import net.sf.regadb.util.args.Arguments;
import net.sf.regadb.util.args.Arguments.ArgumentException;
import net.sf.regadb.util.args.PositionalArgument;
import net.sf.regadb.util.args.ValueArgument;
import net.sf.regadb.util.mapper.XmlMapper;
import net.sf.regadb.util.mapper.XmlMapper.MapperParseException;
import net.sf.regadb.util.settings.RegaDBSettings;
public class AutoImport {
private class FileLogger{
private PrintStream out;
public FileLogger(File file) throws FileNotFoundException{
out = new PrintStream(new FileOutputStream(file));
}
public void println(String msg){
out.println(msg);
}
public void close(){
out.close();
}
}
private class ErrorTypes{
public boolean mapping = false;
public boolean object = false;
public boolean value = false;
public String toString(){
String s = "";
if(mapping)
s = "not mapped, ";
if(object)
s += "wrong mapping, ";
if(value)
s += "invalid value";
return s.length() == 0 ? "ok":s;
}
}
private FileLogger errLog, importLog, infoLog;
public Date firstCd4 = new Date();
public Date firstCd8 = new Date();
public Date firstViralLoad = new Date();
public Date firstSeroStatus = new Date();
Map<String, ErrorTypes> lisTests = new TreeMap<String, ErrorTypes>();
private ObjectMapper objectMapper;
private XmlMapper xmlMapper;
private ObjectStore objectStore;
private String datasetDescription = null;
private Set<String> patientsNotFound = new HashSet<String>();
public static void main(String [] args) {
Arguments as = new Arguments();
ValueArgument conf = as.addValueArgument("conf-dir", "configuration directory", false);
PositionalArgument user = as.addPositionalArgument("regadb user", true);
PositionalArgument pass = as.addPositionalArgument("regadb password", true);
PositionalArgument dataset = as.addPositionalArgument("regadb dataset", true);
PositionalArgument mapfile = as.addPositionalArgument("lis mapping xml file", true);
PositionalArgument lisdir = as.addPositionalArgument("lis export directory", true);
try {
as.parse(args);
} catch (ArgumentException e1) {
System.err.println(e1);
}
if(as.isValid()){
if(conf.isSet())
RegaDBSettings.createInstance(conf.getValue());
else
RegaDBSettings.createInstance();
as.printValues(System.out);
try{
AutoImport ai = new AutoImport(user.getValue(), pass.getValue(), new File(mapfile.getValue()), dataset.getValue());
ai.run(new File(lisdir.getValue()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (WrongUidException e) {
e.printStackTrace();
} catch (WrongPasswordException e) {
e.printStackTrace();
} catch (DisabledUserException e) {
e.printStackTrace();
} catch (MapperParseException e) {
e.printStackTrace();
}
}
else
as.printUsage(System.err);
}
public AutoImport(){
}
public AutoImport(File mappingFile, File nationMappingFile, ObjectStore objectStore, String datasetDescription) throws MapperParseException{
init(mappingFile, objectStore);
this.datasetDescription = datasetDescription;
}
public AutoImport(String user, String pass, File mappingFile, String datasetDescription) throws WrongUidException, WrongPasswordException, DisabledUserException, MapperParseException {
Login login;
login = Login.authenticate(user, pass);
init(mappingFile, new DbObjectStore(login));
this.datasetDescription = datasetDescription;
}
private void init(File mappingFile, ObjectStore objectStore) throws MapperParseException{
xmlMapper = new XmlMapper(mappingFile);
objectMapper = new ObjectMapper(objectStore, xmlMapper);
this.objectStore = objectStore;
}
public TestNominalValue getNominalValue(TestType tt, String str){
for(TestNominalValue tnv : tt.getTestNominalValues()){
if(tnv.getTestType().equals(tt) && tnv.getValue().equals(str)){
return tnv;
}
}
return null;
}
public void run(File path) throws FileNotFoundException{
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String logFile = File.separatorChar + date + ".log";
if(!path.exists())
throw new FileNotFoundException(path.getAbsolutePath());
if(path.isFile()){
infoLog = new FileLogger(new File(path.getParent() + logFile));
process(path);
}
else if(path.isDirectory()){
infoLog = new FileLogger(new File(path.getAbsolutePath() + logFile));
batchProcess(path);
}
logInfo("Tests summary ------");
for(Map.Entry<String, ErrorTypes> me : lisTests.entrySet())
logInfo(me.getKey() +": \t"+ me.getValue());
logInfo("------");
infoLog.close();
}
public void batchProcess(File dir) throws FileNotFoundException {
File[] files = dir.listFiles();
for(final File f : files) {
if(f.getAbsolutePath().toLowerCase().endsWith(".xls") && f.getName().toLowerCase().startsWith("regadb")){
process(f);
}
}
}
public void process(File file) throws FileNotFoundException{
File logDir = RegaDBSettings.getInstance().getInstituteConfig().getLogDir();
errLog = new FileLogger(new File(logDir.getAbsolutePath() + File.separatorChar + file.getName() +".errors.txt"));
importLog = new FileLogger(new File(logDir.getAbsolutePath() + File.separatorChar + file.getName() +".not-imported.txt"));
logInfo("\nProcessing file: "+ file.getAbsolutePath());
try {
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
if(line != null){
Map<String, Integer> headers = new HashMap<String, Integer>();
int i=0;
String[] fields = tokenizeTab(line);
logNotImported(line);
for(String s : fields)
headers.put(s, i++);
int n = 2;
while((line = br.readLine()) != null) {
fields = tokenizeTab(line);
if(fields.length > 0 && headers.get(fields[0]) == null){
Patient p = handlePatient(headers, fields, n);
if(p != null)
handleTest(p, headers, fields, n);
objectStore.commit();
}
++n;
}
}
br.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importLog.close();
errLog.close();
}
private Patient handlePatient(Map<String,Integer> headers, String[] line, int lineNumber) {
String ead = line[headers.get("EADnr")];
if(ead == null || ead.length() == 0)
return null;
String emd = line[headers.get("EMDnr")];
Date birthDate = null;
try {
birthDate = GhbUtils.LISDateFormat.parse(line[headers.get("geboortedatum")]);
} catch (ParseException e) {
e.printStackTrace();
}
Patient p = getPatient(ead);
if(p==null){
if(patientsNotFound.add(ead)){
logError(lineNumber, "Patient not found: '"+ ead +"'");
}
logNotImported(toString(line));
return null;
}
Attribute emdAttribute = objectStore.getAttribute("EMD Number", StandardObjects.getClinicalAttributeGroup().getGroupName());
if(emdAttribute == null){
emdAttribute = objectStore.createAttribute( objectStore.getAttributeGroup(StandardObjects.getClinicalAttributeGroup().getGroupName()),
objectStore.getValueType(StandardObjects.getStringValueType().getDescription()),
"EMD Number");
}
Attribute birthDateAttribute = objectStore.getAttribute("Birth date","Personal");
if(!containsAttribute(emdAttribute, p))
p.createPatientAttributeValue(emdAttribute).setValue(emd);
if(!containsAttribute(birthDateAttribute, p))
p.createPatientAttributeValue(birthDateAttribute).setValue(birthDate.getTime()+"");
return p;
}
public boolean containsAttribute(Attribute a, Patient p) {
String name = a.getName();
for(PatientAttributeValue pav : p.getPatientAttributeValues()) {
if(pav.getAttribute().getName().equals(name)) {
return true;
}
}
return false;
}
private void handleTest(Patient p, Map<String,Integer> headers, String[] line, int lineNumber) {
Date sampleDate = null;
String testId = line[headers.get("aanvraagTestNaam")] +", "+ line[headers.get("elementNaam")];
try {
sampleDate = GhbUtils.LISDateFormat.parse(line[headers.get("afname")]);
if(!GhbUtils.isValidDate(sampleDate))
throw new Exception("invalid test date: "+ sampleDate);
if(!lisTests.containsKey(testId))
lisTests.put(testId,new ErrorTypes());
String reeel = line[headers.get("reeel")];
String resultaat = line[headers.get("resultaat")];
//work with a mapping file
if((reeel != null && reeel.length() > 0)
|| (resultaat != null && resultaat.length() > 0)) {
String correctId = getCorrectSampleId(headers, line);
Map<String,String> variables = new HashMap<String,String>();
for(Map.Entry<String, Integer> header : headers.entrySet()){
variables.put(header.getKey(),line[header.getValue()].trim());
}
variables.put("relatie+reeel", line[headers.get("relatie")]+reeel);
long ul = 0;
long geheel = 0;
try{
double dreeel = Double.parseDouble(reeel);
ul = Math.round(dreeel * 1000);
geheel = Math.round(dreeel);
}
catch(Exception e){
}
variables.put("reeel*1000", ""+ul);
variables.put("geheel", ""+ geheel);
variables.put("relatie+geheel", line[headers.get("relatie")]+geheel);
TestResult tr = null;
tr = objectMapper.getTestResult(variables);
tr.setSampleId(correctId);
tr.setTestDate(sampleDate);
if(duplicateTestResult(p, tr) != null){
logError(lineNumber, "Duplicate test result ignored");
return;
}
setFirstTestDate(tr);
p.addTestResult(tr);
}
else{
logError(lineNumber, "No result");
}
}
catch(MappingDoesNotExistException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).mapping = true;
logNotImported(toString(line));
}
catch(ObjectDoesNotExistException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).object = true;
logNotImported(toString(line));
}
catch(InvalidValueException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).value = true;
logNotImported(toString(line));
}
catch (MappingException e) {
logError(lineNumber, "MappingException: "+ e.getMessage());
logNotImported(toString(line));
}
catch (ParseException e) {
logNotImported(toString(line));
logError("ParseException at line "+ lineNumber +": "+ e.getMessage());
}
catch (Exception e){
logError(lineNumber, "Exception: "+ e.getMessage());
e.printStackTrace();
logNotImported(toString(line));
}
}
// private void handleHiv1ViralLoad(
// Patient p, Date sampleDate, String sampleId, String aanvraagTestNaam, String labotestNaam,
// String berekeningNaam, String listestNaam, String elementNaam,String eenheden, String relatie,
// String reeel, String resultaat) throws Exception {
//
// if(!elementNaam.endsWith("sym") && reeel.length() != 0){
// String description;
// Test t;
// if(elementNaam.equals("HIV-1 VL")){
// if(labotestNaam.startsWith("Abbott"))
// description = "Abbott Realtime";
// else
// description = StandardObjects.getGenericHiv1ViralLoadTest().getDescription();
//
// t = objectStore.getTest(description,
// StandardObjects.getHiv1ViralLoadTestType().getDescription(),
// StandardObjects.getHiv1Genome().getOrganismName());
// }
// else if(elementNaam.equals("HIV-1 VL log")){
// if(labotestNaam.startsWith("Abbott"))
// description = "Abbott Realtime (log10)";
// else
// description = StandardObjects.getGenericHiv1ViralLoadLog10Test().getDescription();
//
// t = objectStore.getTest(description,
// StandardObjects.getHiv1ViralLoadTestType().getDescription(),
// StandardObjects.getHiv1Genome().getOrganismName());
//
// }
// else{
// throw new Exception("Unknown viral load element name.");
// }
//
// TestResult tr = new TestResult(t);
// tr.setSampleId(sampleId);
// tr.setTestDate(sampleDate);
// tr.setValue(relatie + reeel);
//
// if(duplicateTestResult(p, tr) == null){
// p.addTestResult(tr);
// }
// else{
// throw new Exception("Duplicate viral load.");
// }
// }
// else{
// String copies=null,log=null;
// if(resultaat.contains("<40") || resultaat.contains("< 40")){
// copies="<40";
// log="<1.6";
// }
// else if(resultaat.contains("<50")){
// copies="<50";
// log="<1.7";
// }
// else if(resultaat.contains("> 10000000")){
// copies=">10000000";
// log=">7";
// }
//
// for(TestResult tr : p.getTestResults()){
// if(tr.getTestDate().equals(sampleDate)){
// if(Equals.isSameTestType(tr.getTest().getTestType(), StandardObjects.getHiv1ViralLoadTestType())){
// tr.setValue(copies);
// }
// else if(Equals.isSameTestType(tr.getTest().getTestType(), StandardObjects.getHiv1ViralLoadLog10TestType())){
// tr.setValue(log);
// }
// }
// }
// }
// }
private void setFirstTestDate(TestResult tr) {
String description = tr.getTest().getTestType().getDescription();
if(description.equals(StandardObjects.getCd4TestType().getDescription()) && tr.getTestDate().before(firstCd4))
firstCd4 = tr.getTestDate();
else if(description.equals(StandardObjects.getCd8TestType().getDescription()) && tr.getTestDate().before(firstCd8))
firstCd8 = tr.getTestDate();
else if(description.equals(StandardObjects.getViralLoadDescription()) && tr.getTestDate().before(firstViralLoad))
firstViralLoad = tr.getTestDate();
else if(description.equals(StandardObjects.getSeroStatusDescription()) && tr.getTestDate().before(firstSeroStatus))
firstSeroStatus = tr.getTestDate();
}
private String getCorrectSampleId(Map<String,Integer> headers, String[] line) {
String id = line[headers.get("otheeknr")];
if(id.equals("")) {
id = line[headers.get("staalId")];
}
if(id.equals("")) {
id = line[headers.get("metingId")];
}
if(id.equals("")) {
id = line[headers.get("berekeningId")];
}
id = id.trim();
return id.length() == 0 ? null : id;
}
// private void handleNominalAttributeValue(Patient p, String name, String nominalValue) throws MappingException {
// try {
// Map<String,String> variables = new HashMap<String,String>();
// variables.put("name", name);
// variables.put("value", nominalValue);
// PatientAttributeValue pav = objectMapper.getAttributeValue(variables);
// p.addPatientAttributeValue(pav);
//
// } catch (ObjectDoesNotExistException e) {
// ConsoleLogger.getInstance().logWarning("Unsupported attribute value" + name + ": "+nominalValue);
// } catch (MatcherException e) {
// e.printStackTrace();
// }
// }
private String[] tokenizeTab(String line) {
return line.split("\t",-1);
}
private TestResult duplicateTestResult(Patient p, TestResult result) {
return Utils.getDuplicateTestResult(p, result);
}
// private TestResult dublicateTestTypeResult(Patient p, TestResult result) {
// for(TestResult tr : p.getTestResults()) {
// if(Equals.isSameTestType(tr.getTest().getTestType(),result.getTest().getTestType()) &&
// DateUtils.equals(tr.getTestDate(),result.getTestDate()) &&
// equals(tr.getSampleId(),result.getSampleId())) {
// return tr;
// }
// }
// return null;
// }
private boolean equals(String s1, String s2){
if(s1 == s2)
return true;
if(s1 != null)
return s1.equals(s2);
return false;
}
private Patient getPatient(String ead){
Dataset dataset = objectStore.getDataset(datasetDescription);
return objectStore.getPatient(dataset, ead);
}
// private Patient createPatient(String ead){
// Dataset dataset = objectStore.getDataset(datasetDescription);
// return objectStore.createPatient(dataset, ead);
// }
private void logNotImported(String msg){
importLog.println(msg);
}
private void logError(String msg){
errLog.println(msg);
}
private void logError(int lineNumber, String msg){
logError(lineNumber +": "+ msg);
}
private void logInfo(String msg){
System.out.println(msg);
logError(msg);
}
private String toString(String[] line){
StringBuilder sb = new StringBuilder();
for(String s : line){
sb.append(s);
sb.append('\t');
}
return sb.toString();
}
public void close(){
objectStore.close();
}
}
| hivdb/regadb | regadb-io-db/src/net/sf/regadb/io/db/ghb/lis/AutoImport.java | 5,636 | // if(!elementNaam.endsWith("sym") && reeel.length() != 0){ | line_comment | nl | package net.sf.regadb.io.db.ghb.lis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import net.sf.regadb.db.Attribute;
import net.sf.regadb.db.Dataset;
import net.sf.regadb.db.Patient;
import net.sf.regadb.db.PatientAttributeValue;
import net.sf.regadb.db.TestNominalValue;
import net.sf.regadb.db.TestResult;
import net.sf.regadb.db.TestType;
import net.sf.regadb.db.login.DisabledUserException;
import net.sf.regadb.db.login.WrongPasswordException;
import net.sf.regadb.db.login.WrongUidException;
import net.sf.regadb.db.session.Login;
import net.sf.regadb.io.db.ghb.GhbUtils;
import net.sf.regadb.io.db.util.Utils;
import net.sf.regadb.io.db.util.mapping.DbObjectStore;
import net.sf.regadb.io.db.util.mapping.ObjectMapper;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.InvalidValueException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.MappingDoesNotExistException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.MappingException;
import net.sf.regadb.io.db.util.mapping.ObjectMapper.ObjectDoesNotExistException;
import net.sf.regadb.io.db.util.mapping.ObjectStore;
import net.sf.regadb.io.util.StandardObjects;
import net.sf.regadb.util.args.Arguments;
import net.sf.regadb.util.args.Arguments.ArgumentException;
import net.sf.regadb.util.args.PositionalArgument;
import net.sf.regadb.util.args.ValueArgument;
import net.sf.regadb.util.mapper.XmlMapper;
import net.sf.regadb.util.mapper.XmlMapper.MapperParseException;
import net.sf.regadb.util.settings.RegaDBSettings;
public class AutoImport {
private class FileLogger{
private PrintStream out;
public FileLogger(File file) throws FileNotFoundException{
out = new PrintStream(new FileOutputStream(file));
}
public void println(String msg){
out.println(msg);
}
public void close(){
out.close();
}
}
private class ErrorTypes{
public boolean mapping = false;
public boolean object = false;
public boolean value = false;
public String toString(){
String s = "";
if(mapping)
s = "not mapped, ";
if(object)
s += "wrong mapping, ";
if(value)
s += "invalid value";
return s.length() == 0 ? "ok":s;
}
}
private FileLogger errLog, importLog, infoLog;
public Date firstCd4 = new Date();
public Date firstCd8 = new Date();
public Date firstViralLoad = new Date();
public Date firstSeroStatus = new Date();
Map<String, ErrorTypes> lisTests = new TreeMap<String, ErrorTypes>();
private ObjectMapper objectMapper;
private XmlMapper xmlMapper;
private ObjectStore objectStore;
private String datasetDescription = null;
private Set<String> patientsNotFound = new HashSet<String>();
public static void main(String [] args) {
Arguments as = new Arguments();
ValueArgument conf = as.addValueArgument("conf-dir", "configuration directory", false);
PositionalArgument user = as.addPositionalArgument("regadb user", true);
PositionalArgument pass = as.addPositionalArgument("regadb password", true);
PositionalArgument dataset = as.addPositionalArgument("regadb dataset", true);
PositionalArgument mapfile = as.addPositionalArgument("lis mapping xml file", true);
PositionalArgument lisdir = as.addPositionalArgument("lis export directory", true);
try {
as.parse(args);
} catch (ArgumentException e1) {
System.err.println(e1);
}
if(as.isValid()){
if(conf.isSet())
RegaDBSettings.createInstance(conf.getValue());
else
RegaDBSettings.createInstance();
as.printValues(System.out);
try{
AutoImport ai = new AutoImport(user.getValue(), pass.getValue(), new File(mapfile.getValue()), dataset.getValue());
ai.run(new File(lisdir.getValue()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (WrongUidException e) {
e.printStackTrace();
} catch (WrongPasswordException e) {
e.printStackTrace();
} catch (DisabledUserException e) {
e.printStackTrace();
} catch (MapperParseException e) {
e.printStackTrace();
}
}
else
as.printUsage(System.err);
}
public AutoImport(){
}
public AutoImport(File mappingFile, File nationMappingFile, ObjectStore objectStore, String datasetDescription) throws MapperParseException{
init(mappingFile, objectStore);
this.datasetDescription = datasetDescription;
}
public AutoImport(String user, String pass, File mappingFile, String datasetDescription) throws WrongUidException, WrongPasswordException, DisabledUserException, MapperParseException {
Login login;
login = Login.authenticate(user, pass);
init(mappingFile, new DbObjectStore(login));
this.datasetDescription = datasetDescription;
}
private void init(File mappingFile, ObjectStore objectStore) throws MapperParseException{
xmlMapper = new XmlMapper(mappingFile);
objectMapper = new ObjectMapper(objectStore, xmlMapper);
this.objectStore = objectStore;
}
public TestNominalValue getNominalValue(TestType tt, String str){
for(TestNominalValue tnv : tt.getTestNominalValues()){
if(tnv.getTestType().equals(tt) && tnv.getValue().equals(str)){
return tnv;
}
}
return null;
}
public void run(File path) throws FileNotFoundException{
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String logFile = File.separatorChar + date + ".log";
if(!path.exists())
throw new FileNotFoundException(path.getAbsolutePath());
if(path.isFile()){
infoLog = new FileLogger(new File(path.getParent() + logFile));
process(path);
}
else if(path.isDirectory()){
infoLog = new FileLogger(new File(path.getAbsolutePath() + logFile));
batchProcess(path);
}
logInfo("Tests summary ------");
for(Map.Entry<String, ErrorTypes> me : lisTests.entrySet())
logInfo(me.getKey() +": \t"+ me.getValue());
logInfo("------");
infoLog.close();
}
public void batchProcess(File dir) throws FileNotFoundException {
File[] files = dir.listFiles();
for(final File f : files) {
if(f.getAbsolutePath().toLowerCase().endsWith(".xls") && f.getName().toLowerCase().startsWith("regadb")){
process(f);
}
}
}
public void process(File file) throws FileNotFoundException{
File logDir = RegaDBSettings.getInstance().getInstituteConfig().getLogDir();
errLog = new FileLogger(new File(logDir.getAbsolutePath() + File.separatorChar + file.getName() +".errors.txt"));
importLog = new FileLogger(new File(logDir.getAbsolutePath() + File.separatorChar + file.getName() +".not-imported.txt"));
logInfo("\nProcessing file: "+ file.getAbsolutePath());
try {
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
if(line != null){
Map<String, Integer> headers = new HashMap<String, Integer>();
int i=0;
String[] fields = tokenizeTab(line);
logNotImported(line);
for(String s : fields)
headers.put(s, i++);
int n = 2;
while((line = br.readLine()) != null) {
fields = tokenizeTab(line);
if(fields.length > 0 && headers.get(fields[0]) == null){
Patient p = handlePatient(headers, fields, n);
if(p != null)
handleTest(p, headers, fields, n);
objectStore.commit();
}
++n;
}
}
br.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importLog.close();
errLog.close();
}
private Patient handlePatient(Map<String,Integer> headers, String[] line, int lineNumber) {
String ead = line[headers.get("EADnr")];
if(ead == null || ead.length() == 0)
return null;
String emd = line[headers.get("EMDnr")];
Date birthDate = null;
try {
birthDate = GhbUtils.LISDateFormat.parse(line[headers.get("geboortedatum")]);
} catch (ParseException e) {
e.printStackTrace();
}
Patient p = getPatient(ead);
if(p==null){
if(patientsNotFound.add(ead)){
logError(lineNumber, "Patient not found: '"+ ead +"'");
}
logNotImported(toString(line));
return null;
}
Attribute emdAttribute = objectStore.getAttribute("EMD Number", StandardObjects.getClinicalAttributeGroup().getGroupName());
if(emdAttribute == null){
emdAttribute = objectStore.createAttribute( objectStore.getAttributeGroup(StandardObjects.getClinicalAttributeGroup().getGroupName()),
objectStore.getValueType(StandardObjects.getStringValueType().getDescription()),
"EMD Number");
}
Attribute birthDateAttribute = objectStore.getAttribute("Birth date","Personal");
if(!containsAttribute(emdAttribute, p))
p.createPatientAttributeValue(emdAttribute).setValue(emd);
if(!containsAttribute(birthDateAttribute, p))
p.createPatientAttributeValue(birthDateAttribute).setValue(birthDate.getTime()+"");
return p;
}
public boolean containsAttribute(Attribute a, Patient p) {
String name = a.getName();
for(PatientAttributeValue pav : p.getPatientAttributeValues()) {
if(pav.getAttribute().getName().equals(name)) {
return true;
}
}
return false;
}
private void handleTest(Patient p, Map<String,Integer> headers, String[] line, int lineNumber) {
Date sampleDate = null;
String testId = line[headers.get("aanvraagTestNaam")] +", "+ line[headers.get("elementNaam")];
try {
sampleDate = GhbUtils.LISDateFormat.parse(line[headers.get("afname")]);
if(!GhbUtils.isValidDate(sampleDate))
throw new Exception("invalid test date: "+ sampleDate);
if(!lisTests.containsKey(testId))
lisTests.put(testId,new ErrorTypes());
String reeel = line[headers.get("reeel")];
String resultaat = line[headers.get("resultaat")];
//work with a mapping file
if((reeel != null && reeel.length() > 0)
|| (resultaat != null && resultaat.length() > 0)) {
String correctId = getCorrectSampleId(headers, line);
Map<String,String> variables = new HashMap<String,String>();
for(Map.Entry<String, Integer> header : headers.entrySet()){
variables.put(header.getKey(),line[header.getValue()].trim());
}
variables.put("relatie+reeel", line[headers.get("relatie")]+reeel);
long ul = 0;
long geheel = 0;
try{
double dreeel = Double.parseDouble(reeel);
ul = Math.round(dreeel * 1000);
geheel = Math.round(dreeel);
}
catch(Exception e){
}
variables.put("reeel*1000", ""+ul);
variables.put("geheel", ""+ geheel);
variables.put("relatie+geheel", line[headers.get("relatie")]+geheel);
TestResult tr = null;
tr = objectMapper.getTestResult(variables);
tr.setSampleId(correctId);
tr.setTestDate(sampleDate);
if(duplicateTestResult(p, tr) != null){
logError(lineNumber, "Duplicate test result ignored");
return;
}
setFirstTestDate(tr);
p.addTestResult(tr);
}
else{
logError(lineNumber, "No result");
}
}
catch(MappingDoesNotExistException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).mapping = true;
logNotImported(toString(line));
}
catch(ObjectDoesNotExistException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).object = true;
logNotImported(toString(line));
}
catch(InvalidValueException e){
logError(lineNumber, e.getMessage());
lisTests.get(testId).value = true;
logNotImported(toString(line));
}
catch (MappingException e) {
logError(lineNumber, "MappingException: "+ e.getMessage());
logNotImported(toString(line));
}
catch (ParseException e) {
logNotImported(toString(line));
logError("ParseException at line "+ lineNumber +": "+ e.getMessage());
}
catch (Exception e){
logError(lineNumber, "Exception: "+ e.getMessage());
e.printStackTrace();
logNotImported(toString(line));
}
}
// private void handleHiv1ViralLoad(
// Patient p, Date sampleDate, String sampleId, String aanvraagTestNaam, String labotestNaam,
// String berekeningNaam, String listestNaam, String elementNaam,String eenheden, String relatie,
// String reeel, String resultaat) throws Exception {
//
// if(!elementNaam.endsWith("sym") &&<SUF>
// String description;
// Test t;
// if(elementNaam.equals("HIV-1 VL")){
// if(labotestNaam.startsWith("Abbott"))
// description = "Abbott Realtime";
// else
// description = StandardObjects.getGenericHiv1ViralLoadTest().getDescription();
//
// t = objectStore.getTest(description,
// StandardObjects.getHiv1ViralLoadTestType().getDescription(),
// StandardObjects.getHiv1Genome().getOrganismName());
// }
// else if(elementNaam.equals("HIV-1 VL log")){
// if(labotestNaam.startsWith("Abbott"))
// description = "Abbott Realtime (log10)";
// else
// description = StandardObjects.getGenericHiv1ViralLoadLog10Test().getDescription();
//
// t = objectStore.getTest(description,
// StandardObjects.getHiv1ViralLoadTestType().getDescription(),
// StandardObjects.getHiv1Genome().getOrganismName());
//
// }
// else{
// throw new Exception("Unknown viral load element name.");
// }
//
// TestResult tr = new TestResult(t);
// tr.setSampleId(sampleId);
// tr.setTestDate(sampleDate);
// tr.setValue(relatie + reeel);
//
// if(duplicateTestResult(p, tr) == null){
// p.addTestResult(tr);
// }
// else{
// throw new Exception("Duplicate viral load.");
// }
// }
// else{
// String copies=null,log=null;
// if(resultaat.contains("<40") || resultaat.contains("< 40")){
// copies="<40";
// log="<1.6";
// }
// else if(resultaat.contains("<50")){
// copies="<50";
// log="<1.7";
// }
// else if(resultaat.contains("> 10000000")){
// copies=">10000000";
// log=">7";
// }
//
// for(TestResult tr : p.getTestResults()){
// if(tr.getTestDate().equals(sampleDate)){
// if(Equals.isSameTestType(tr.getTest().getTestType(), StandardObjects.getHiv1ViralLoadTestType())){
// tr.setValue(copies);
// }
// else if(Equals.isSameTestType(tr.getTest().getTestType(), StandardObjects.getHiv1ViralLoadLog10TestType())){
// tr.setValue(log);
// }
// }
// }
// }
// }
private void setFirstTestDate(TestResult tr) {
String description = tr.getTest().getTestType().getDescription();
if(description.equals(StandardObjects.getCd4TestType().getDescription()) && tr.getTestDate().before(firstCd4))
firstCd4 = tr.getTestDate();
else if(description.equals(StandardObjects.getCd8TestType().getDescription()) && tr.getTestDate().before(firstCd8))
firstCd8 = tr.getTestDate();
else if(description.equals(StandardObjects.getViralLoadDescription()) && tr.getTestDate().before(firstViralLoad))
firstViralLoad = tr.getTestDate();
else if(description.equals(StandardObjects.getSeroStatusDescription()) && tr.getTestDate().before(firstSeroStatus))
firstSeroStatus = tr.getTestDate();
}
private String getCorrectSampleId(Map<String,Integer> headers, String[] line) {
String id = line[headers.get("otheeknr")];
if(id.equals("")) {
id = line[headers.get("staalId")];
}
if(id.equals("")) {
id = line[headers.get("metingId")];
}
if(id.equals("")) {
id = line[headers.get("berekeningId")];
}
id = id.trim();
return id.length() == 0 ? null : id;
}
// private void handleNominalAttributeValue(Patient p, String name, String nominalValue) throws MappingException {
// try {
// Map<String,String> variables = new HashMap<String,String>();
// variables.put("name", name);
// variables.put("value", nominalValue);
// PatientAttributeValue pav = objectMapper.getAttributeValue(variables);
// p.addPatientAttributeValue(pav);
//
// } catch (ObjectDoesNotExistException e) {
// ConsoleLogger.getInstance().logWarning("Unsupported attribute value" + name + ": "+nominalValue);
// } catch (MatcherException e) {
// e.printStackTrace();
// }
// }
private String[] tokenizeTab(String line) {
return line.split("\t",-1);
}
private TestResult duplicateTestResult(Patient p, TestResult result) {
return Utils.getDuplicateTestResult(p, result);
}
// private TestResult dublicateTestTypeResult(Patient p, TestResult result) {
// for(TestResult tr : p.getTestResults()) {
// if(Equals.isSameTestType(tr.getTest().getTestType(),result.getTest().getTestType()) &&
// DateUtils.equals(tr.getTestDate(),result.getTestDate()) &&
// equals(tr.getSampleId(),result.getSampleId())) {
// return tr;
// }
// }
// return null;
// }
private boolean equals(String s1, String s2){
if(s1 == s2)
return true;
if(s1 != null)
return s1.equals(s2);
return false;
}
private Patient getPatient(String ead){
Dataset dataset = objectStore.getDataset(datasetDescription);
return objectStore.getPatient(dataset, ead);
}
// private Patient createPatient(String ead){
// Dataset dataset = objectStore.getDataset(datasetDescription);
// return objectStore.createPatient(dataset, ead);
// }
private void logNotImported(String msg){
importLog.println(msg);
}
private void logError(String msg){
errLog.println(msg);
}
private void logError(int lineNumber, String msg){
logError(lineNumber +": "+ msg);
}
private void logInfo(String msg){
System.out.println(msg);
logError(msg);
}
private String toString(String[] line){
StringBuilder sb = new StringBuilder();
for(String s : line){
sb.append(s);
sb.append('\t');
}
return sb.toString();
}
public void close(){
objectStore.close();
}
}
|
109977_5 | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import husacct.validate.domain.validation.violationtype.ViolationTypes;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<ViolationTypes> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define)
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} | HUSACCT/HUSACCT | src/husacct/validate/domain/factory/violationtype/AbstractViolationType.java | 2,040 | //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define)
| line_comment | nl | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import husacct.validate.domain.validation.violationtype.ViolationTypes;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<ViolationTypes> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige<SUF>
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} |
121811_4 | package org.example.exceptionsfun;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionExamples {
// unchecked exceptions voorbeeld, op te lossen met beter coderen
// in dit geval if statement
public static void ohNoUnchecked() {
String[] strings = null; //{ "!" };
int i = 1;
if(strings != null && strings.length > i) {
System.out.println(strings[i]);
}
}
// checked exception, handling voorbeeld 1
public static void ohNoChecked1() throws IOException {
String fileName = "blabla.txt";
FileReader fr = new FileReader(fileName);
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
// checked exception, handling voorbeeld 2
public static void ohNoChecked2() {
String fileName = "blabla.txt";
FileReader fr = null;
try {
fr = new FileReader(fileName);
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// checked exception, handling voorbeeld 3
public static void ohNoChecked3() {
String fileName = "blabla.txt";
try(FileReader fr = new FileReader(fileName)) {
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
} catch(IOException e) {
e.printStackTrace();
}
}
// zelf exception gooien
public static void ohNoThrowException() {
throw new IllegalArgumentException("blablabla");
}
// zelf eigen exception gooien
public static void ohNoThrowMyOwnException() {
throw new VerkeerdeNaamException("dit klopt niet");
}
public static void main(String[] args) {
ohNoUnchecked();
ohNoChecked2();
ohNoChecked3();
try {
ohNoChecked1();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Lalalalal");
}
}
| BrightBoost/java9april | src/main/java/org/example/exceptionsfun/ExceptionExamples.java | 616 | // checked exception, handling voorbeeld 2 | line_comment | nl | package org.example.exceptionsfun;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionExamples {
// unchecked exceptions voorbeeld, op te lossen met beter coderen
// in dit geval if statement
public static void ohNoUnchecked() {
String[] strings = null; //{ "!" };
int i = 1;
if(strings != null && strings.length > i) {
System.out.println(strings[i]);
}
}
// checked exception, handling voorbeeld 1
public static void ohNoChecked1() throws IOException {
String fileName = "blabla.txt";
FileReader fr = new FileReader(fileName);
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
// checked exception,<SUF>
public static void ohNoChecked2() {
String fileName = "blabla.txt";
FileReader fr = null;
try {
fr = new FileReader(fileName);
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// checked exception, handling voorbeeld 3
public static void ohNoChecked3() {
String fileName = "blabla.txt";
try(FileReader fr = new FileReader(fileName)) {
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
} catch(IOException e) {
e.printStackTrace();
}
}
// zelf exception gooien
public static void ohNoThrowException() {
throw new IllegalArgumentException("blablabla");
}
// zelf eigen exception gooien
public static void ohNoThrowMyOwnException() {
throw new VerkeerdeNaamException("dit klopt niet");
}
public static void main(String[] args) {
ohNoUnchecked();
ohNoChecked2();
ohNoChecked3();
try {
ohNoChecked1();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Lalalalal");
}
}
|
26602_0 | package nl.computerhuys.tabnavui;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class VraagBanenDialogFragment extends DialogFragment {
private View v;
private EditText editText1;
private EditText editText2;
//private ArrayList<Baan> banen;
private int[] oldBanen;
private int[] currentBanen;
private SharedPreferences prefs;
private int baan1;
private int baan2;
private int aantalParallel;
/* public VraagBanenDialogFragment(ArrayList<Baan> banen) {
this.baanNummers = banen;
}
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Restore preferences
// Dit zou ook kunnen:
// prefs = InitSpel.prefsBanen;
// en dan verderop InitSpel.addPreference(prefs, "BAAN_01", baan1); om te bewaren
prefs = getActivity().getSharedPreferences("numberPicker.preferences", 0);
baan1 = prefs.getInt( "BAAN_01", 0 );
baan2 = prefs.getInt( "BAAN_02", 0 );
//aantalParallel = InitSpel.prefs.getInt( "AANTAL_PARALLEL", 0 );
aantalParallel = prefs.getInt( "AANTAL_PARALLEL", 0 );
//oldBanen = new int[InitSpel.aantalParallel];
oldBanen = new int[aantalParallel];
oldBanen[0] = baan1;
oldBanen[1] = baan2;
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
v = inflater.inflate(R.layout.vraag_banen, null);
// velden vullen met opgeslagen waarden
editText1 = (EditText) v.findViewById(R.id.editText1);
editText2 = (EditText) v.findViewById(R.id.editText2);
editText1.setText(String.valueOf(baan1));
editText2.setText(String.valueOf(baan2));
//editText1.setText(String.valueOf(banen.get(0).getBaanNummer()));
//editText2.setText(String.valueOf(banen.get(1).getBaanNummer()));
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
baan1 = Integer.valueOf(editText1.getText().toString());
baan2 = Integer.valueOf(editText2.getText().toString());
InitSpel.setBaanNummer(0, baan1);
InitSpel.setBaanNummer(1, baan2);
// en banen nog bij de preferences op schijf opslaan.
prefs.edit()
.putInt("BAAN_01", baan1)
.putInt("BAAN_02", baan2)
.commit();
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO cancel;
}
});
return builder.create();
}
}
| ruud00000/KegelApp | TabNavUI/src/nl/computerhuys/tabnavui/VraagBanenDialogFragment.java | 1,021 | //private ArrayList<Baan> banen;
| line_comment | nl | package nl.computerhuys.tabnavui;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class VraagBanenDialogFragment extends DialogFragment {
private View v;
private EditText editText1;
private EditText editText2;
//private ArrayList<Baan><SUF>
private int[] oldBanen;
private int[] currentBanen;
private SharedPreferences prefs;
private int baan1;
private int baan2;
private int aantalParallel;
/* public VraagBanenDialogFragment(ArrayList<Baan> banen) {
this.baanNummers = banen;
}
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Restore preferences
// Dit zou ook kunnen:
// prefs = InitSpel.prefsBanen;
// en dan verderop InitSpel.addPreference(prefs, "BAAN_01", baan1); om te bewaren
prefs = getActivity().getSharedPreferences("numberPicker.preferences", 0);
baan1 = prefs.getInt( "BAAN_01", 0 );
baan2 = prefs.getInt( "BAAN_02", 0 );
//aantalParallel = InitSpel.prefs.getInt( "AANTAL_PARALLEL", 0 );
aantalParallel = prefs.getInt( "AANTAL_PARALLEL", 0 );
//oldBanen = new int[InitSpel.aantalParallel];
oldBanen = new int[aantalParallel];
oldBanen[0] = baan1;
oldBanen[1] = baan2;
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
v = inflater.inflate(R.layout.vraag_banen, null);
// velden vullen met opgeslagen waarden
editText1 = (EditText) v.findViewById(R.id.editText1);
editText2 = (EditText) v.findViewById(R.id.editText2);
editText1.setText(String.valueOf(baan1));
editText2.setText(String.valueOf(baan2));
//editText1.setText(String.valueOf(banen.get(0).getBaanNummer()));
//editText2.setText(String.valueOf(banen.get(1).getBaanNummer()));
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
baan1 = Integer.valueOf(editText1.getText().toString());
baan2 = Integer.valueOf(editText2.getText().toString());
InitSpel.setBaanNummer(0, baan1);
InitSpel.setBaanNummer(1, baan2);
// en banen nog bij de preferences op schijf opslaan.
prefs.edit()
.putInt("BAAN_01", baan1)
.putInt("BAAN_02", baan2)
.commit();
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO cancel;
}
});
return builder.create();
}
}
|
57800_1 | package org.minima.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import org.minima.objects.base.MiniString;
public class RPCClient {
public static String USER_AGENT = "Minima/1.0";
public static String sendGET(String zHost) throws IOException {
if(zHost.startsWith("https")) {
return sendGETHTTPS(zHost);
}else {
return sendGETBasicAuth(zHost, "", "");
}
}
public static String sendGETBasicAuth(String zHost, String zUser, String zPassword) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Create the Authorisation header
if(!zPassword.equals("")) {
String userpass = zUser + ":" + zPassword;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
}
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendGETHTTPS(String zHost) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpsURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendGETSSL(String zHost) throws IOException {
return sendGETBasicAuthSSL(zHost, "", "", null);
}
public static String sendGETBasicAuthSSL(String zHost, String zUser, String zPassword, SSLContext zSSLContext) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
con.setSSLSocketFactory(zSSLContext.getSocketFactory());
//Create the Authorisation header
if(!zPassword.equals("")) {
String userpass = zUser + ":" + zPassword;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
}
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendPUT(String zHost) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("PUT");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("PUT request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendPOST(String zHost, String zParams) throws IOException {
if(zHost.startsWith("https")) {
return sendPOSTHTTPS(zHost, zParams, null);
}else {
return sendPOST(zHost, zParams, null);
}
}
public static String sendPOST(String zHost, String zParams, String zType) throws IOException {
URL obj = new URL(zHost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setInstanceFollowRedirects(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Type specified..
if(zType != null) {
con.setRequestProperty("Content-Type", zType);
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(zParams.getBytes(MiniString.MINIMA_CHARSET));
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),MiniString.MINIMA_CHARSET));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
throw new IOException("POST request not HTTP_OK resp:"+responseCode+" @ "+zHost+" params "+zParams);
}
public static String sendPOSTHTTPS(String zHost, String zParams, String zType) throws IOException {
URL obj = new URL(zHost);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setInstanceFollowRedirects(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Type specified..
if(zType != null) {
con.setRequestProperty("Content-Type", zType);
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(zParams.getBytes(MiniString.MINIMA_CHARSET));
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),MiniString.MINIMA_CHARSET));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
throw new IOException("POST request not HTTP_OK resp:"+responseCode+" @ "+zHost+" params "+zParams);
}
}
| minima-global/Minima | src/org/minima/utils/RPCClient.java | 2,392 | //Open her up
| line_comment | nl | package org.minima.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import org.minima.objects.base.MiniString;
public class RPCClient {
public static String USER_AGENT = "Minima/1.0";
public static String sendGET(String zHost) throws IOException {
if(zHost.startsWith("https")) {
return sendGETHTTPS(zHost);
}else {
return sendGETBasicAuth(zHost, "", "");
}
}
public static String sendGETBasicAuth(String zHost, String zUser, String zPassword) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her<SUF>
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Create the Authorisation header
if(!zPassword.equals("")) {
String userpass = zUser + ":" + zPassword;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
}
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendGETHTTPS(String zHost) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpsURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendGETSSL(String zHost) throws IOException {
return sendGETBasicAuthSSL(zHost, "", "", null);
}
public static String sendGETBasicAuthSSL(String zHost, String zUser, String zPassword, SSLContext zSSLContext) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
con.setSSLSocketFactory(zSSLContext.getSocketFactory());
//Create the Authorisation header
if(!zPassword.equals("")) {
String userpass = zUser + ":" + zPassword;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
}
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("GET request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendPUT(String zHost) throws IOException {
//Create the URL
URL obj = new URL(zHost);
//Open her up
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setRequestMethod("PUT");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
int responseCode = con.getResponseCode();
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
is.close();
} else {
System.out.println("PUT request not HTTP_OK resp:"+responseCode+" @ "+zHost);
}
return response.toString();
}
public static String sendPOST(String zHost, String zParams) throws IOException {
if(zHost.startsWith("https")) {
return sendPOSTHTTPS(zHost, zParams, null);
}else {
return sendPOST(zHost, zParams, null);
}
}
public static String sendPOST(String zHost, String zParams, String zType) throws IOException {
URL obj = new URL(zHost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setInstanceFollowRedirects(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Type specified..
if(zType != null) {
con.setRequestProperty("Content-Type", zType);
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(zParams.getBytes(MiniString.MINIMA_CHARSET));
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),MiniString.MINIMA_CHARSET));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
throw new IOException("POST request not HTTP_OK resp:"+responseCode+" @ "+zHost+" params "+zParams);
}
public static String sendPOSTHTTPS(String zHost, String zParams, String zType) throws IOException {
URL obj = new URL(zHost);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setConnectTimeout(10000);
con.setInstanceFollowRedirects(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Connection", "close");
//Type specified..
if(zType != null) {
con.setRequestProperty("Content-Type", zType);
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(zParams.getBytes(MiniString.MINIMA_CHARSET));
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),MiniString.MINIMA_CHARSET));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
throw new IOException("POST request not HTTP_OK resp:"+responseCode+" @ "+zHost+" params "+zParams);
}
}
|
56929_7 | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
* Copyright (C) 2018-2024 e-Contract.be BV.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
* @see Identity
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf
*/
FOREIGNER_A("11", "33"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12", "34"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van
* inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17", "35"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18", "36"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19"),
/**
* I. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_I("20"),
/**
* J. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_J("21"),
FOREIGNER_M("22"),
FOREIGNER_N("23"),
/**
* ETABLISSEMENT
*/
FOREIGNER_K("27"),
/**
* RESIDENT DE LONGUE DUREE – UE
*/
FOREIGNER_L("28"),
FOREIGNER_EU("31"),
FOREIGNER_EU_PLUS("32"),
FOREIGNER_KIDS_EU("61"),
FOREIGNER_KIDS_EU_PLUS("62"),
FOREIGNER_KIDS_A("63"),
FOREIGNER_KIDS_B("64"),
FOREIGNER_KIDS_K("65"),
FOREIGNER_KIDS_L("66"),
FOREIGNER_KIDS_F("67"),
FOREIGNER_KIDS_F_PLUS("68"),
FOREIGNER_KIDS_M("69");
private final Set<Integer> keys;
DocumentType(final String... valueList) {
this.keys = new HashSet<>();
for (String value : valueList) {
this.keys.add(toKey(value));
}
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<>();
for (DocumentType documentType : DocumentType.values()) {
for (Integer key : documentType.keys) {
if (documentTypes.containsKey(key)) {
throw new RuntimeException("duplicate document type enum: " + key);
}
documentTypes.put(key, documentType);
}
}
DocumentType.documentTypes = documentTypes;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
/*
* If the key is unknown, we simply return null.
*/
return DocumentType.documentTypes.get(key);
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
| e-Contract/commons-eid | commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java | 1,449 | /**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/ | block_comment | nl | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
* Copyright (C) 2018-2024 e-Contract.be BV.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
* @see Identity
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf
*/
FOREIGNER_A("11", "33"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12", "34"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van
* inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving<SUF>*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17", "35"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18", "36"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19"),
/**
* I. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_I("20"),
/**
* J. New types of foreigner cards (I and J cards) will be issued for employees
* that are transferred within their company (EU directive 2014/66/EU)
*/
FOREIGNER_J("21"),
FOREIGNER_M("22"),
FOREIGNER_N("23"),
/**
* ETABLISSEMENT
*/
FOREIGNER_K("27"),
/**
* RESIDENT DE LONGUE DUREE – UE
*/
FOREIGNER_L("28"),
FOREIGNER_EU("31"),
FOREIGNER_EU_PLUS("32"),
FOREIGNER_KIDS_EU("61"),
FOREIGNER_KIDS_EU_PLUS("62"),
FOREIGNER_KIDS_A("63"),
FOREIGNER_KIDS_B("64"),
FOREIGNER_KIDS_K("65"),
FOREIGNER_KIDS_L("66"),
FOREIGNER_KIDS_F("67"),
FOREIGNER_KIDS_F_PLUS("68"),
FOREIGNER_KIDS_M("69");
private final Set<Integer> keys;
DocumentType(final String... valueList) {
this.keys = new HashSet<>();
for (String value : valueList) {
this.keys.add(toKey(value));
}
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<>();
for (DocumentType documentType : DocumentType.values()) {
for (Integer key : documentType.keys) {
if (documentTypes.containsKey(key)) {
throw new RuntimeException("duplicate document type enum: " + key);
}
documentTypes.put(key, documentType);
}
}
DocumentType.documentTypes = documentTypes;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
/*
* If the key is unknown, we simply return null.
*/
return DocumentType.documentTypes.get(key);
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
|
104271_0 |
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Simulator implements ActionListener {
private ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
private JSONObject jsonObject;
private JSONArray layers;
private ArrayList<BufferedImage> tileArray;
private JSONObject layer;
private int visitorAmount;
private Timer timer = new Timer(1000 * 30, this);
private int indexTimer;
private ArrayList<Point> spawnPoints = new ArrayList<Point>();
private ArrayList<Visitor> visitors = new ArrayList<Visitor>();
ArrayList<Pathfinding> pathFinding = new ArrayList<Pathfinding>();
@SuppressWarnings("unchecked")
public Simulator(int visitorAmount) {
this.visitorAmount = visitorAmount;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/podiums.json"));
jsonObject = (JSONObject) obj;
layers = new JSONArray();
layers = (JSONArray) jsonObject.get("layers");
for (int i = 0; i < layers.size(); i++) {
layer = (JSONObject) layers.get(i);
}
tileArray = new ArrayList<>();
JSONArray jsonTilesets = (JSONArray) jsonObject.get("tilesets");
for (int i = 0; i < jsonTilesets.size(); i++) {
JSONObject tileset = (JSONObject) jsonTilesets.get(i);
String imageFile = (String) tileset.get("image");
BufferedImage img = ImageIO.read(new File(imageFile));
int index = ((Long) tileset.get("firstgid")).intValue();
while (tileArray.size() < 22000)
tileArray.add(null);
for (int y = 0; y < img.getHeight(); y = y + 16) {
for (int x = 0; x < img.getWidth(); x = x + 16) {
BufferedImage tile = img.getSubimage(x, y, 16, 16);
tileArray.set(index, tile);
index++;
}
}
}
spawnPoints.add(new Point(42, 5));
spawnPoints.add(new Point(54, 13));
spawnPoints.add(new Point(54, 48));
pathFinding.add(new Pathfinding(this, new Point(16, 18)));
pathFinding.add(new Pathfinding(this, new Point(43, 24)));
pathFinding.add(new Pathfinding(this, new Point(15, 48)));
pathFinding.add(new Pathfinding(this, new Point(42, 2)));
pathFinding.add(new Pathfinding(this, new Point(57, 13)));
pathFinding.add(new Pathfinding(this, new Point(57, 48)));
timer.start();
// nieuwe bezoekers aanmaken
for (int i = 0; i < visitorAmount; i++) {
int spawn = (int) Math.floor(Math.random() * 3);
Pathfinding path = pathFinding.get((int) Math.floor(Math.random() * 3));
Point2D spawnPoint = null;
switch (spawn) {
case 0:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 1:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 2:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
}
Point2D location = new Point2D.Double(spawnPoint.getX(), spawnPoint.getY());
Visitor v = new Visitor(location, this, path);
visitors.add(v);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
// public boolean isSpawnable(ArrayList<Visitor> visitors) {
// boolean spawnable = true;
//
// for (Visitor v : visitors) {
// if (v.getLocation().distance(v.getStartLocation()) < 7)
// spawnable = false;
// }
//
// return spawnable;
// }
public void makeGUI(int visitorAmount) {
JFrame frame = new JFrame("SIM");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.visitorAmount = visitorAmount;
JPanel panel = new TestPanel(visitorAmount);
frame.getContentPane().add(panel);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public ArrayList<BufferedImage> getTileArray() {
return tileArray;
}
public JSONArray getLayer() {
return layers;
}
public ArrayList<Visitor> getVisitors() {
return visitors;
}
public ArrayList<Pathfinding> getPathfinding() {
return pathFinding;
}
@Override
public void actionPerformed(ActionEvent arg0) {
indexTimer++;
if (indexTimer % 3 == 0 && indexTimer != 0) {
for (Visitor v : visitors) {
v.setPath(pathFinding.get((int) Math.floor(Math.random() * 3) + 3));
}
timer.restart();
System.out.println(visitorAmount + " " + visitors.size() + " " + indexTimer);
} else {
makeVisitors();
for (Visitor v : visitors) {
v.setPath(pathFinding.get((int) Math.floor(Math.random() * 3)));
}
timer.restart();
System.out.println(visitorAmount + " " + visitors.size() + " " + indexTimer);
}
}
private void makeVisitors() {
for (int i = 0; visitors.size() <= visitorAmount; i++) {
int spawn = (int) Math.floor(Math.random() * 3);
Pathfinding path = pathFinding.get((int) Math.floor(Math.random() * 3));
Point2D spawnPoint = null;
switch (spawn) {
case 0:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 1:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 2:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
}
Point2D location = new Point2D.Double(spawnPoint.getX(), spawnPoint.getY());
Visitor v = new Visitor(location, this, path);
visitors.add(v);
}
}
}
class TestPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Simulator tiled;
private TiledLayer layer;
private Point mouseP;
private int newCX;
private int visitorAmount;
private int newCY;
private float cameraZoom = 1;
float rotation = 0;
Timer timer;
GUI gui;
public TestPanel(int visitorAmount) {
timer = new Timer((1000 / 60), this);
timer.start();
this.visitorAmount = visitorAmount;
tiled = new Simulator(visitorAmount);
setPreferredSize(new Dimension((60 * 16), (60 * 16)));
camera();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AffineTransform camera = getCamera();
g2.setTransform(camera);
int a = 0;
for (int i = 0; i < (tiled.getLayer().size() - 1); i++) {
layer = new TiledLayer((JSONObject) tiled.getLayer().get(i));
for (int x = 0; x <= (layer.getHeight() * 16 - 16); x = x + 16) {
for (int y = 0; y <= (layer.getWidth() * 16 - 16); y = y + 16) {
Long b = layer.getData().get(a);
int c = b.intValue();
g2.drawImage(tiled.getTileArray().get(c), y, x, 16, 16, null);
if (a >= (60 * 60 - 1)) {
a = 0;
} else {
a++;
}
}
}
}
for (Visitor v : tiled.getVisitors()) {
v.draw(g2);
}
Iterator<Visitor> iterator = tiled.getVisitors().iterator();
while (iterator.hasNext()) {// for (Visitor v : tiled.getVisitors()) {
Visitor v = iterator.next();
v.update(tiled.getVisitors());
if (v.atTarget() && (v.getPath() == tiled.getPathfinding().get(3)
|| v.getPath() == tiled.getPathfinding().get(4) || v.getPath() == tiled.getPathfinding().get(5))) {
iterator.remove();
}
}
}
public void camera() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
mouseP = me.getPoint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me)) {
newCX -= (int) (mouseP.getX() - me.getX());
newCY -= (int) (mouseP.getY() - me.getY());
}
mouseP = me.getPoint();
repaint();
}
});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent me) {
if (me.isControlDown())
rotation += me.getWheelRotation() / 10.0f;
else {
try {
Point2D mousePD = getCamera().inverseTransform(me.getPoint(), null);
cameraZoom *= 1 - me.getWheelRotation() * 0.05f;
Point2D mousePD2 = getCamera().inverseTransform(me.getPoint(), null);
newCX -= (mousePD.getX() - mousePD2.getX()) * cameraZoom;
newCY -= (mousePD.getY() - mousePD2.getY()) * cameraZoom;
} catch (NoninvertibleTransformException e) {
e.printStackTrace();
}
}
repaint();
}
});
}
public AffineTransform getCamera() {
AffineTransform camera = new AffineTransform();
camera.translate(getWidth() / 2, getHeight() / 2);
camera.rotate(rotation);
camera.translate(newCX, newCY);
camera.scale(cameraZoom, cameraZoom);
return camera;
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
| jbwwboom/FestivalPlanner | FestivalPlannerBeta/src/Simulator.java | 3,158 | // nieuwe bezoekers aanmaken | line_comment | nl |
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Simulator implements ActionListener {
private ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
private JSONObject jsonObject;
private JSONArray layers;
private ArrayList<BufferedImage> tileArray;
private JSONObject layer;
private int visitorAmount;
private Timer timer = new Timer(1000 * 30, this);
private int indexTimer;
private ArrayList<Point> spawnPoints = new ArrayList<Point>();
private ArrayList<Visitor> visitors = new ArrayList<Visitor>();
ArrayList<Pathfinding> pathFinding = new ArrayList<Pathfinding>();
@SuppressWarnings("unchecked")
public Simulator(int visitorAmount) {
this.visitorAmount = visitorAmount;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/podiums.json"));
jsonObject = (JSONObject) obj;
layers = new JSONArray();
layers = (JSONArray) jsonObject.get("layers");
for (int i = 0; i < layers.size(); i++) {
layer = (JSONObject) layers.get(i);
}
tileArray = new ArrayList<>();
JSONArray jsonTilesets = (JSONArray) jsonObject.get("tilesets");
for (int i = 0; i < jsonTilesets.size(); i++) {
JSONObject tileset = (JSONObject) jsonTilesets.get(i);
String imageFile = (String) tileset.get("image");
BufferedImage img = ImageIO.read(new File(imageFile));
int index = ((Long) tileset.get("firstgid")).intValue();
while (tileArray.size() < 22000)
tileArray.add(null);
for (int y = 0; y < img.getHeight(); y = y + 16) {
for (int x = 0; x < img.getWidth(); x = x + 16) {
BufferedImage tile = img.getSubimage(x, y, 16, 16);
tileArray.set(index, tile);
index++;
}
}
}
spawnPoints.add(new Point(42, 5));
spawnPoints.add(new Point(54, 13));
spawnPoints.add(new Point(54, 48));
pathFinding.add(new Pathfinding(this, new Point(16, 18)));
pathFinding.add(new Pathfinding(this, new Point(43, 24)));
pathFinding.add(new Pathfinding(this, new Point(15, 48)));
pathFinding.add(new Pathfinding(this, new Point(42, 2)));
pathFinding.add(new Pathfinding(this, new Point(57, 13)));
pathFinding.add(new Pathfinding(this, new Point(57, 48)));
timer.start();
// nieuwe bezoekers<SUF>
for (int i = 0; i < visitorAmount; i++) {
int spawn = (int) Math.floor(Math.random() * 3);
Pathfinding path = pathFinding.get((int) Math.floor(Math.random() * 3));
Point2D spawnPoint = null;
switch (spawn) {
case 0:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 1:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 2:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
}
Point2D location = new Point2D.Double(spawnPoint.getX(), spawnPoint.getY());
Visitor v = new Visitor(location, this, path);
visitors.add(v);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
// public boolean isSpawnable(ArrayList<Visitor> visitors) {
// boolean spawnable = true;
//
// for (Visitor v : visitors) {
// if (v.getLocation().distance(v.getStartLocation()) < 7)
// spawnable = false;
// }
//
// return spawnable;
// }
public void makeGUI(int visitorAmount) {
JFrame frame = new JFrame("SIM");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.visitorAmount = visitorAmount;
JPanel panel = new TestPanel(visitorAmount);
frame.getContentPane().add(panel);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public ArrayList<BufferedImage> getTileArray() {
return tileArray;
}
public JSONArray getLayer() {
return layers;
}
public ArrayList<Visitor> getVisitors() {
return visitors;
}
public ArrayList<Pathfinding> getPathfinding() {
return pathFinding;
}
@Override
public void actionPerformed(ActionEvent arg0) {
indexTimer++;
if (indexTimer % 3 == 0 && indexTimer != 0) {
for (Visitor v : visitors) {
v.setPath(pathFinding.get((int) Math.floor(Math.random() * 3) + 3));
}
timer.restart();
System.out.println(visitorAmount + " " + visitors.size() + " " + indexTimer);
} else {
makeVisitors();
for (Visitor v : visitors) {
v.setPath(pathFinding.get((int) Math.floor(Math.random() * 3)));
}
timer.restart();
System.out.println(visitorAmount + " " + visitors.size() + " " + indexTimer);
}
}
private void makeVisitors() {
for (int i = 0; visitors.size() <= visitorAmount; i++) {
int spawn = (int) Math.floor(Math.random() * 3);
Pathfinding path = pathFinding.get((int) Math.floor(Math.random() * 3));
Point2D spawnPoint = null;
switch (spawn) {
case 0:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 1:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
case 2:
spawnPoint = spawnPoints.get(spawn);
spawnPoint = new Point((int) spawnPoint.getX() * 16, (int) spawnPoint.getY() * 16);
break;
}
Point2D location = new Point2D.Double(spawnPoint.getX(), spawnPoint.getY());
Visitor v = new Visitor(location, this, path);
visitors.add(v);
}
}
}
class TestPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Simulator tiled;
private TiledLayer layer;
private Point mouseP;
private int newCX;
private int visitorAmount;
private int newCY;
private float cameraZoom = 1;
float rotation = 0;
Timer timer;
GUI gui;
public TestPanel(int visitorAmount) {
timer = new Timer((1000 / 60), this);
timer.start();
this.visitorAmount = visitorAmount;
tiled = new Simulator(visitorAmount);
setPreferredSize(new Dimension((60 * 16), (60 * 16)));
camera();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AffineTransform camera = getCamera();
g2.setTransform(camera);
int a = 0;
for (int i = 0; i < (tiled.getLayer().size() - 1); i++) {
layer = new TiledLayer((JSONObject) tiled.getLayer().get(i));
for (int x = 0; x <= (layer.getHeight() * 16 - 16); x = x + 16) {
for (int y = 0; y <= (layer.getWidth() * 16 - 16); y = y + 16) {
Long b = layer.getData().get(a);
int c = b.intValue();
g2.drawImage(tiled.getTileArray().get(c), y, x, 16, 16, null);
if (a >= (60 * 60 - 1)) {
a = 0;
} else {
a++;
}
}
}
}
for (Visitor v : tiled.getVisitors()) {
v.draw(g2);
}
Iterator<Visitor> iterator = tiled.getVisitors().iterator();
while (iterator.hasNext()) {// for (Visitor v : tiled.getVisitors()) {
Visitor v = iterator.next();
v.update(tiled.getVisitors());
if (v.atTarget() && (v.getPath() == tiled.getPathfinding().get(3)
|| v.getPath() == tiled.getPathfinding().get(4) || v.getPath() == tiled.getPathfinding().get(5))) {
iterator.remove();
}
}
}
public void camera() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
mouseP = me.getPoint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me)) {
newCX -= (int) (mouseP.getX() - me.getX());
newCY -= (int) (mouseP.getY() - me.getY());
}
mouseP = me.getPoint();
repaint();
}
});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent me) {
if (me.isControlDown())
rotation += me.getWheelRotation() / 10.0f;
else {
try {
Point2D mousePD = getCamera().inverseTransform(me.getPoint(), null);
cameraZoom *= 1 - me.getWheelRotation() * 0.05f;
Point2D mousePD2 = getCamera().inverseTransform(me.getPoint(), null);
newCX -= (mousePD.getX() - mousePD2.getX()) * cameraZoom;
newCY -= (mousePD.getY() - mousePD2.getY()) * cameraZoom;
} catch (NoninvertibleTransformException e) {
e.printStackTrace();
}
}
repaint();
}
});
}
public AffineTransform getCamera() {
AffineTransform camera = new AffineTransform();
camera.translate(getWidth() / 2, getHeight() / 2);
camera.rotate(rotation);
camera.translate(newCX, newCY);
camera.scale(cameraZoom, cameraZoom);
return camera;
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
|
37934_6 | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop = 0;
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden.
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
| SBDPlugins/LeastSlackTime-OSM | src/main/java/nl/sbdeveloper/leastslack/LeastSlack.java | 1,540 | //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden. | line_comment | nl | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop = 0;
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er<SUF>
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
|
52553_10 |
/**
* Abstract class Figuur - write a description of the class here
*
* @author (your name here)
* @version (version number or date here)
*/
public abstract class Figuur
{
// instance variables - replace the example below with your own
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
/**
* Maak een nieuw Figuur
*/
public Figuur(int xPosition, int yPosition, String color)
{
this.xPosition = xPosition;
this.yPosition = yPosition;
this.color = color;
}
/**
* Maak dit figuur zichtbaar
*/
public void maakZichtbaar()
{
isVisible = true;
teken();
}
/**
* Maak dit figuur onzichtbaar
*/
public void maakOnzichtbaar()
{
wis();
isVisible = false;
}
/**
* Beweeg dit figuur 20 pixels naar rechts
*/
public void beweegRechts()
{
beweegHorizontaal(20);
}
/**
* Beweeg dit figuur 20 pixels naar links
*/
public void beweegLinks()
{
beweegHorizontaal(-20);
}
/**
* Beweeg dit figuur 20 pixels naar boven
*/
public void beweegBoven()
{
beweegVertikaal(-20);
}
/**
* Beweeg dit figuur 20 pixels naar beneden
*/
public void beweegBeneden()
{
beweegVertikaal(20);
}
/**
* Beweeg dit figuur horizontaal adhv het aantal gegeven pixels
*/
public void beweegHorizontaal(int distance)
{
wis();
xPosition += distance;
teken();
}
/**
* Beweeg dit figuur vertikaal adhv het aantal gegeven pixels
*/
public void beweegVertikaal(int distance)
{
wis();
yPosition += distance;
teken();
}
/**
* Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels
*/
public void traagBeweegHorizontaal(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
xPosition += delta;
teken();
}
}
/**
* Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels
*/
public void traagBeweegVertikaal(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
yPosition += delta;
teken();
}
}
/**
* Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black".
*/
public void veranderKleur(String newColor)
{
color = newColor;
teken();
}
/**
* Wis het figuur van het scherm
*/
public void wis()
{
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.erase(this);
}
}
/**
* Bepaal of het figuur zichtbaar is
*/
public boolean isZichtbaar()
{
return isVisible;
}
/**
* Geef de kleur van het figuur
*/
public String getKleur()
{
return color;
}
/**
* Geef de positie op de x-as
*/
public int getXPositie()
{
return xPosition;
}
/**
* Geef de positie op de y-as
*/
public int getYPositie()
{
return yPosition;
}
/**
* Teken dit figuur op het scherm.
* Dit is een abstracte method, het moet in de subclasses gedefinieerd worden.
*/
public abstract void teken();
}
| BenVandenberk/vdab | 05 OOP/Voorbeelden/FigurenVoorbeeld04/Figuur.java | 1,139 | /**
* Beweeg dit figuur vertikaal adhv het aantal gegeven pixels
*/ | block_comment | nl |
/**
* Abstract class Figuur - write a description of the class here
*
* @author (your name here)
* @version (version number or date here)
*/
public abstract class Figuur
{
// instance variables - replace the example below with your own
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
/**
* Maak een nieuw Figuur
*/
public Figuur(int xPosition, int yPosition, String color)
{
this.xPosition = xPosition;
this.yPosition = yPosition;
this.color = color;
}
/**
* Maak dit figuur zichtbaar
*/
public void maakZichtbaar()
{
isVisible = true;
teken();
}
/**
* Maak dit figuur onzichtbaar
*/
public void maakOnzichtbaar()
{
wis();
isVisible = false;
}
/**
* Beweeg dit figuur 20 pixels naar rechts
*/
public void beweegRechts()
{
beweegHorizontaal(20);
}
/**
* Beweeg dit figuur 20 pixels naar links
*/
public void beweegLinks()
{
beweegHorizontaal(-20);
}
/**
* Beweeg dit figuur 20 pixels naar boven
*/
public void beweegBoven()
{
beweegVertikaal(-20);
}
/**
* Beweeg dit figuur 20 pixels naar beneden
*/
public void beweegBeneden()
{
beweegVertikaal(20);
}
/**
* Beweeg dit figuur horizontaal adhv het aantal gegeven pixels
*/
public void beweegHorizontaal(int distance)
{
wis();
xPosition += distance;
teken();
}
/**
* Beweeg dit figuur<SUF>*/
public void beweegVertikaal(int distance)
{
wis();
yPosition += distance;
teken();
}
/**
* Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels
*/
public void traagBeweegHorizontaal(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
xPosition += delta;
teken();
}
}
/**
* Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels
*/
public void traagBeweegVertikaal(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
yPosition += delta;
teken();
}
}
/**
* Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black".
*/
public void veranderKleur(String newColor)
{
color = newColor;
teken();
}
/**
* Wis het figuur van het scherm
*/
public void wis()
{
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.erase(this);
}
}
/**
* Bepaal of het figuur zichtbaar is
*/
public boolean isZichtbaar()
{
return isVisible;
}
/**
* Geef de kleur van het figuur
*/
public String getKleur()
{
return color;
}
/**
* Geef de positie op de x-as
*/
public int getXPositie()
{
return xPosition;
}
/**
* Geef de positie op de y-as
*/
public int getYPositie()
{
return yPosition;
}
/**
* Teken dit figuur op het scherm.
* Dit is een abstracte method, het moet in de subclasses gedefinieerd worden.
*/
public abstract void teken();
}
|
73158_16 | /*
GeoGebra - Dynamic Mathematics for Everyone
http://www.geogebra.org
This file is part of GeoGebra.
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.
*/
package org.geogebra.common.kernel.geos;
import org.geogebra.common.kernel.Construction;
import org.geogebra.common.kernel.Kernel;
import org.geogebra.common.kernel.MyPoint;
import org.geogebra.common.kernel.PathMover;
import org.geogebra.common.kernel.PathMoverGeneric;
import org.geogebra.common.kernel.PathParameter;
import org.geogebra.common.kernel.StringTemplate;
import org.geogebra.common.kernel.Transform;
import org.geogebra.common.kernel.algos.AlgoJoinPointsSegment;
import org.geogebra.common.kernel.arithmetic.MyDouble;
import org.geogebra.common.kernel.arithmetic.NumberValue;
import org.geogebra.common.kernel.kernelND.GeoCurveCartesianND;
import org.geogebra.common.kernel.kernelND.GeoElementND;
import org.geogebra.common.kernel.kernelND.GeoLineND;
import org.geogebra.common.kernel.kernelND.GeoPointND;
import org.geogebra.common.kernel.kernelND.GeoSegmentND;
import org.geogebra.common.kernel.matrix.Coords;
import org.geogebra.common.plugin.GeoClass;
import org.geogebra.common.util.DoubleUtil;
import org.geogebra.common.util.ExtendedBoolean;
/**
* @author Markus Hohenwarter
*/
final public class GeoSegment extends GeoLine
implements GeoSegmentND, SegmentProperties {
// GeoSegment is constructed by AlgoJoinPointsSegment
// private GeoPoint A, B;
private double length;
private boolean defined;
private boolean allowOutlyingIntersections = false;
private boolean keepTypeOnGeometricTransform = true; // for mirroring,
// rotation, ...
private StringBuilder sbToString = new StringBuilder(30);
private boolean forceSimpleTransform;
private Coords pnt2D;
private GeoElement meta = null;
private SegmentStyle startStyle = SegmentStyle.DEFAULT;
private SegmentStyle endStyle = SegmentStyle.DEFAULT;
/** no decoration */
public static final int SEGMENT_DECORATION_NONE = 0;
/** one tick */
public static final int SEGMENT_DECORATION_ONE_TICK = 1;
/** two ticks */
public static final int SEGMENT_DECORATION_TWO_TICKS = 2;
/** three ticks */
public static final int SEGMENT_DECORATION_THREE_TICKS = 3;
/** one arrow */
public static final int SEGMENT_DECORATION_ONE_ARROW = 4;
/** two arrows */
public static final int SEGMENT_DECORATION_TWO_ARROWS = 5;
/** three arrows */
public static final int SEGMENT_DECORATION_THREE_ARROWS = 6;
/**
* Returns array of all decoration types
*
* @see #SEGMENT_DECORATION_ONE_TICK etc.
* @return array of all decoration types
*/
public static Integer[] getDecoTypes() {
Integer[] ret = { Integer.valueOf(SEGMENT_DECORATION_NONE),
Integer.valueOf(SEGMENT_DECORATION_ONE_TICK),
Integer.valueOf(SEGMENT_DECORATION_TWO_TICKS),
Integer.valueOf(SEGMENT_DECORATION_THREE_TICKS),
Integer.valueOf(SEGMENT_DECORATION_ONE_ARROW),
Integer.valueOf(SEGMENT_DECORATION_TWO_ARROWS),
Integer.valueOf(SEGMENT_DECORATION_THREE_ARROWS) };
return ret;
}
@Override
public void setDecorationType(int type) {
setDecorationType(type, getDecoTypes().length);
}
/**
* Creates new segment
*
* @param c
* construction
* @param A
* first endpoint
* @param B
* second endpoint
*/
public GeoSegment(Construction c, GeoPoint A, GeoPoint B) {
this(c);
setPoints(A, B);
}
/**
* common constructor
*
* @param c
* construction
*/
public GeoSegment(Construction c) {
super(c);
setConstructionDefaults();
}
/**
* sets start and end points
*
* @param A
* start point
* @param B
* end point
*/
public void setPoints(GeoPoint A, GeoPoint B) {
setStartPoint(A);
setEndPoint(B);
}
@Override
public void setTwoPointsInhomCoords(Coords start, Coords end) {
this.startPoint.setCoords(start.get(1), start.get(2), 1);
this.endPoint.setCoords(end.get(1), end.get(2), 1);
// set x, y, z coords for equation
setCoords(start.getY() - end.getY(), end.getX() - start.getX(),
start.getX() * end.getY() - start.getY() * end.getX());
setPoints(this.startPoint, this.endPoint);
calcLength();
}
@Override
public GeoClass getGeoClassType() {
return GeoClass.SEGMENT;
}
/**
* the copy of a segment is a number (!) with its value set to the segments
* current length
*
* public GeoElement copy() { return new GeoNumeric(cons, getLength()); }
*/
@Override
public GeoElement copyInternal(Construction cons1) {
GeoSegment seg;
if (!this.isDefined()) {
seg = new GeoSegment(cons1);
} else {
seg = new GeoSegment(cons1,
(GeoPoint) startPoint.copyInternal(cons1),
(GeoPoint) endPoint.copyInternal(cons1));
}
seg.set(this);
return seg;
}
@Override
public void set(GeoElementND geo) {
super.set(geo);
if (!geo.isGeoSegment()) {
return;
}
GeoSegment seg = (GeoSegment) geo;
length = seg.length;
defined = seg.defined;
keepTypeOnGeometricTransform = seg.keepTypeOnGeometricTransform;
startPoint = (GeoPoint) GeoLine.updatePoint(cons, startPoint,
seg.startPoint);
endPoint = (GeoPoint) GeoLine.updatePoint(cons, endPoint, seg.endPoint);
}
/**
* @param s
* start point
* @param e
* end point
* @param line
* line
*/
public void set(GeoPoint s, GeoPoint e, GeoVec3D line) {
super.set(line);
setStartPoint(s);
setEndPoint(e);
calcLength();
}
@Override
public void setBasicVisualStyle(GeoElement geo) {
super.setBasicVisualStyle(geo);
if (geo.isGeoSegment()) {
GeoSegmentND seg = (GeoSegmentND) geo;
allowOutlyingIntersections = seg.allowOutlyingIntersections();
}
}
/**
* Calculates this segment's length . This method should only be called by
* its parent algorithm of type AlgoJoinPointsSegment
*/
public void calcLength() {
defined = startPoint.isFinite() && endPoint.isFinite();
if (defined) {
length = startPoint.distance(endPoint);
if (DoubleUtil.isZero(length)) {
length = 0;
}
} else {
length = Double.NaN;
}
}
@Override
public double getLength() {
return length;
}
/*
* overwrite GeoLine methods
*/
@Override
public boolean isDefined() {
return defined;
}
@Override
public void setUndefined() {
super.setUndefined();
length = Double.NaN;
defined = false;
}
@Override
public boolean showInEuclidianView() {
// segments of polygons can have thickness 0
return defined && getLineThickness() != 0;
}
/**
* Yields true iff startpoint and endpoint of s are equal to startpoint and
* endpoint of this segment.
*/
// Michael Borcherds 2008-05-01
@Override
public ExtendedBoolean isEqualExtended(GeoElementND geo) {
// test 3D is geo is 3D
if (geo.isGeoElement3D()) {
return geo.isEqualExtended(this);
}
if (!geo.isGeoSegment()) {
return ExtendedBoolean.FALSE;
}
GeoSegmentND s = (GeoSegmentND) geo;
return ExtendedBoolean.newExtendedBoolean((startPoint.isEqualPointND(s.getStartPoint())
&& endPoint.isEqualPointND(s.getEndPoint()))
|| (startPoint.isEqualPointND(s.getEndPoint())
&& endPoint.isEqualPointND(s.getStartPoint())));
}
@Override
public String toString(StringTemplate tpl) {
sbToString.setLength(0);
sbToString.append(label);
sbToString.append(" = ");
sbToString.append(kernel.format(length, tpl));
return sbToString.toString();
}
@Override
public String toValueString(StringTemplate tpl) {
return kernel.format(length, tpl);
}
/**
* interface NumberValue
*/
@Override
public MyDouble getNumber() {
return new MyDouble(kernel, getLength());
}
@Override
public double getDouble() {
return getLength();
}
@Override
public boolean isNumberValue() {
return true;
}
@Override
public boolean allowOutlyingIntersections() {
return allowOutlyingIntersections;
}
@Override
public void setAllowOutlyingIntersections(boolean flag) {
allowOutlyingIntersections = flag;
}
@Override
public boolean keepsTypeOnGeometricTransform() {
return keepTypeOnGeometricTransform;
}
@Override
public void setKeepTypeOnGeometricTransform(boolean flag) {
keepTypeOnGeometricTransform = flag;
}
@Override
public boolean isLimitedPath() {
return true;
}
@Override
public boolean isIntersectionPointIncident(GeoPoint p, double eps) {
if (allowOutlyingIntersections) {
return isOnFullLine(p, eps);
}
return isOnPath(p, eps);
}
/*
* GeoSegmentInterface interface
*/
@Override
public GeoElement getStartPointAsGeoElement() {
return getStartPoint();
}
@Override
public GeoElement getEndPointAsGeoElement() {
return getEndPoint();
}
@Override
public double getPointX(double parameter) {
return startPoint.inhomX + parameter * y;
}
@Override
public double getPointY(double parameter) {
return startPoint.inhomY - parameter * x;
}
/*
* Path interface
*/
@Override
public void pointChanged(GeoPointND P) {
PathParameter pp = P.getPathParameter();
// special case: segment of length 0
if (length == 0) {
P.setCoords2D(startPoint.inhomX, startPoint.inhomY, 1);
P.updateCoordsFrom2D(false, null);
if (!(pp.t >= 0 && pp.t <= 1)) {
pp.t = 0.0;
}
return;
}
// project point on line
super.pointChanged(P);
// ensure that the point doesn't get outside the segment
// i.e. ensure 0 <= t <= 1
if (pp.t < 0.0) {
P.setCoords2D(startPoint.x, startPoint.y, startPoint.z);
P.updateCoordsFrom2D(false, null);
pp.t = 0.0;
} else if (pp.t > 1.0) {
P.setCoords2D(endPoint.x, endPoint.y, endPoint.z);
P.updateCoordsFrom2D(false, null);
pp.t = 1.0;
}
}
@Override
public void pathChanged(GeoPointND P) {
// if kernel doesn't use path/region parameters, do as if point changed
// its coords
if (!getKernel().usePathAndRegionParameters(P)) {
pointChanged(P);
return;
}
PathParameter pp = P.getPathParameter();
// special case: segment of length 0
if (length == 0) {
P.setCoords2D(startPoint.inhomX, startPoint.inhomY, 1);
P.updateCoordsFrom2D(false, null);
if (!(pp.t >= 0 && pp.t <= 1)) {
pp.t = 0.0;
}
return;
}
if (pp.t < 0.0) {
pp.t = 0;
} else if (pp.t > 1.0) {
pp.t = 1;
}
// calc point for given parameter
P.setCoords2D(startPoint.inhomX + pp.t * y,
startPoint.inhomY - pp.t * x, 1);
P.updateCoordsFrom2D(false, null);
}
/**
* Returns the smallest possible parameter value for this path.
*
* @return smallest possible parameter
*/
@Override
public double getMinParameter() {
return 0;
}
/**
* Returns the largest possible parameter value for this path.
*
* @return largest possible parameter
*/
@Override
public double getMaxParameter() {
return 1;
}
@Override
public PathMover createPathMover() {
return new PathMoverGeneric(this);
}
/**
* returns all class-specific xml tags for saveXML
*/
@Override
protected void getStyleXML(StringBuilder sb) {
super.getStyleXML(sb);
// allowOutlyingIntersections
sb.append("\t<outlyingIntersections val=\"");
sb.append(allowOutlyingIntersections);
sb.append("\"/>\n");
// keepTypeOnGeometricTransform
sb.append("\t<keepTypeOnTransform val=\"");
sb.append(keepTypeOnGeometricTransform);
sb.append("\"/>\n");
sb.append("\t<startStyle val=\"");
sb.append(startStyle.toString());
sb.append("\"/>\n");
sb.append("\t<endStyle val=\"");
sb.append(endStyle.toString());
sb.append("\"/>\n");
}
/**
* creates new transformed segment
*/
@Override
public GeoElement[] createTransformedObject(Transform t,
String transformedLabel) {
if (keepTypeOnGeometricTransform && t.isAffine()) {
// mirror endpoints
GeoPointND[] points = { getStartPoint(), getEndPoint() };
points = t.transformPoints(points);
// create SEGMENT
GeoElement segment = (GeoElement) kernel.segmentND(transformedLabel,
points[0], points[1]);
segment.setVisualStyleForTransformations(this);
GeoElement[] geos = { segment, (GeoElement) points[0],
(GeoElement) points[1] };
return geos;
} else if (!t.isAffine()) {
// mirror endpoints
// boolean oldSuppressLabelCreation = cons.isSuppressLabelsActive();
// cons.setSuppressLabelCreation(true);
this.forceSimpleTransform = true;
GeoElement[] geos = { t.transform(this, transformedLabel)[0] };
return geos;
} else {
// create LINE
GeoElement transformedLine = t.getTransformedLine(this);
transformedLine.setLabel(transformedLabel);
transformedLine.setVisualStyleForTransformations(this);
GeoElement[] geos = { transformedLine };
return geos;
}
}
@Override
public boolean isGeoSegment() {
return true;
}
//////////////////////////////////////
// 3D stuff
//////////////////////////////////////
@Override
public boolean hasDrawable3D() {
return true;
}
@Override
public Coords getLabelPosition() {
return new Coords(getPointX(0.5), getPointY(0.5), 0, 1);
}
/**
* returns the paramter for the closest point to P on the Segment
* (extrapolated) so answers can be returned outside the range [0,1]
*
* @param ptx
* point x-coord
* @param pty
* point y-coord
* @return closest parameter
*/
public double getParameter(double ptx, double pty) {
double px = ptx;
double py = pty;
// project P on line
// param of projection point on perpendicular line
double t = -(z + x * px + y * py) / (x * x + y * y);
// calculate projection point using perpendicular line
px += t * x;
py += t * y;
// calculate parameter
if (Math.abs(x) <= Math.abs(y)) {
return (startPoint.z * px - startPoint.x) / (y * startPoint.z);
}
return (startPoint.y - startPoint.z * py) / (x * startPoint.z);
}
/**
* Calculates the euclidian distance between this GeoSegment and GeoPoint P.
*
* returns distance from endpoints if appropriate
*/
@Override
public double distance(GeoPoint p) {
double t = getParameter(p.inhomX, p.inhomY);
// if t is outside the range [0,1] then the closest point is not on the
// Segment
if (t < 0) {
return p.distance(startPoint);
}
if (t > 1) {
return p.distance(endPoint);
}
return super.distance(p);
}
@Override
public double distance(double x0, double y0) {
double t = getParameter(x0, y0);
// if t is outside the range [0,1] then the closest point is not on the
// Segment
if (t < 0) {
return startPoint.distance(x0, y0);
}
if (t > 1) {
return endPoint.distance(x0, y0);
}
return super.distance(x0, y0);
}
@Override
public boolean isOnPath(Coords Pnd, double eps) {
if (pnt2D == null) {
pnt2D = new Coords(3);
}
pnt2D.setCoordsIn2DView(Pnd);
if (!super.isOnFullLine2D(pnt2D, eps)) {
return false;
}
return respectLimitedPath(pnt2D, eps);
}
@Override
public boolean respectLimitedPath(Coords Pnd, double eps) {
if (pnt2D == null) {
pnt2D = new Coords(3);
}
pnt2D.setCoordsIn2DView(Pnd);
double t = projectCoordsAndComputePathParam(pnt2D);
return t >= -eps && t <= 1 + eps;
}
/**
* exact calculation for checking if point is on Segment[segStart,segEnd]
*
* @param segStart
* start coords
* @param segEnd
* end coords
* @param point
* point to be checked
* @param checkOnFullLine
* - if true, do extra calculation to make sure.
* @param eps
* precision
* @return true if point belongs to segment
*/
public static boolean checkOnPath(Coords segStart, Coords segEnd,
Coords point, boolean checkOnFullLine, double eps) {
if (checkOnFullLine) {
if (segEnd.sub(segStart).crossProduct(point.sub(segStart))
.equalsForKernel(new Coords(0, 0, 0),
Kernel.STANDARD_PRECISION)) {
return false;
}
}
double x1 = segStart.getInhom(0);
double x2 = segEnd.getInhom(0);
double x = point.getInhom(0);
if (x1 - eps <= x2 && x2 <= x1 + eps) {
double y1 = segStart.getInhom(1);
double y2 = segEnd.getInhom(1);
double y = point.getInhom(1);
if (y1 - eps <= y2 && y2 <= y1 + eps) {
return true;
}
return y1 - eps <= y && y <= y2 + eps
|| y2 - eps <= y && y <= y1 + eps;
}
return x1 - eps <= x && x <= x2 + eps || x2 - eps <= x && x <= x1 + eps;
}
@Override
public boolean isAllEndpointsLabelsSet() {
return !forceSimpleTransform && startPoint.isLabelSet()
&& endPoint.isLabelSet();
}
@Override
public void modifyInputPoints(GeoPointND P, GeoPointND Q) {
AlgoJoinPointsSegment algo = (AlgoJoinPointsSegment) getParentAlgorithm();
algo.modifyInputPoints(P, Q);
}
@Override
public int getMetasLength() {
if (meta == null) {
return 0;
}
return 1;
}
@Override
public GeoElement[] getMetas() {
return new GeoElement[] { meta };
}
/**
* @param poly
* polygon or polyhedron creating this segment
*/
public void setFromMeta(GeoElement poly) {
meta = poly;
}
@Override
public boolean respectLimitedPath(double parameter) {
return DoubleUtil.isGreaterEqual(parameter, 0)
&& DoubleUtil.isGreaterEqual(1, parameter);
}
/**
* dilate from S by r
*/
@Override
public void dilate(NumberValue rval, Coords S) {
super.dilate(rval, S);
startPoint.dilate(rval, S);
endPoint.dilate(rval, S);
calcLength();
}
/**
* rotate this line by angle phi around (0,0)
*/
@Override
public void rotate(NumberValue phiVal) {
super.rotate(phiVal);
startPoint.rotate(phiVal);
endPoint.rotate(phiVal);
// not needed for rotate
// calcLength();
}
/**
* rotate this line by angle phi around Q
*/
@Override
public void rotate(NumberValue phiVal, GeoPointND point) {
super.rotate(phiVal, point);
Coords sCoords = point.getInhomCoords();
startPoint.rotate(phiVal, sCoords);
endPoint.rotate(phiVal, sCoords);
// not needed for rotate
// calcLength();
}
/**
* mirror this line at point Q
*/
@Override
public void mirror(Coords Q) {
super.mirror(Q);
startPoint.mirror(Q);
endPoint.mirror(Q);
// not needed for mirror
// calcLength();
}
/**
* mirror this point at line g
*/
@Override
public void mirror(GeoLineND g1) {
super.mirror(g1);
startPoint.mirror(g1);
endPoint.mirror(g1);
// not needed for mirror
// calcLength();
}
/**
* translate by vector v
*/
@Override
public void translate(Coords v) {
super.translate(v);
startPoint.translate(v);
endPoint.translate(v);
// not needed for mirror
// calcLength();
}
@Override
public void matrixTransform(double p, double q, double r, double s) {
super.matrixTransform(p, q, r, s);
startPoint.matrixTransform(p, q, r, s);
endPoint.matrixTransform(p, q, r, s);
calcLength();
}
@Override
public void matrixTransform(double a00, double a01, double a02,
double a10, double a11, double a12, double a20, double a21,
double a22) {
super.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
startPoint.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
endPoint.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
calcLength();
}
@Override
public void setCoords(MyPoint locusPoint, MyPoint locusPoint2) {
double x1 = locusPoint.x;
double x2 = locusPoint2.x;
double y1 = locusPoint.y;
double y2 = locusPoint2.y;
// line thro' 2 points
setCoords(y1 - y2, x2 - x1, x1 * y2 - y1 * x2);
startPoint.setCoords(x1, y1, 1.0);
endPoint.setCoords(x2, y2, 1.0);
}
@Override
public GeoElement copyFreeSegment() {
GeoPoint startPoint1 = (GeoPoint) getStartPoint().copyInternal(cons);
GeoPoint endPoint1 = (GeoPoint) getEndPoint().copyInternal(cons);
AlgoJoinPointsSegment algo = new AlgoJoinPointsSegment(cons, startPoint1, endPoint1);
return algo.getSegment();
}
@Override
public ExtendedBoolean isCongruent(GeoElement geo) {
return ExtendedBoolean.newExtendedBoolean(geo.isGeoSegment() && DoubleUtil
.isEqual(getLength(), ((GeoSegmentND) geo).getLength()));
}
@Override
public void setChangeableParentIfNull(ChangeableParent ccp) {
// used for GeoPoint3D
}
@Override
public char getLabelDelimiter() {
return '=';
}
@Override
public void toGeoCurveCartesian(GeoCurveCartesianND curve) {
curve.setFromPolyLine(new GeoPointND[] { startPoint, endPoint }, false);
}
/**
* @param startStyle - segment start style
*/
public void setStartStyle(SegmentStyle startStyle) {
this.startStyle = startStyle;
}
/**
* @param endStyle - segment end style
*/
public void setEndStyle(SegmentStyle endStyle) {
this.endStyle = endStyle;
}
/**
* @return segment start style
*/
public SegmentStyle getStartStyle() {
return startStyle;
}
/**
* @return segment end style
*/
public SegmentStyle getEndStyle() {
return endStyle;
}
public boolean hasSegmentStyle() {
return !(startStyle.isDefault() && endStyle.isDefault());
}
@Override
public Coords getPointInD(int dimension, double lambda) {
if (endPoint != null && endPoint.isFinite()
&& startPoint != null && startPoint.isFinite()) {
return startPoint.getCoordsInD(dimension).mul(1 - lambda)
.addInsideMul(endPoint.getCoordsInD(dimension), lambda);
} else {
return super.getPointInD(dimension, lambda);
}
}
}
| geogebra/geogebra | common/src/main/java/org/geogebra/common/kernel/geos/GeoSegment.java | 7,016 | // test 3D is geo is 3D | line_comment | nl | /*
GeoGebra - Dynamic Mathematics for Everyone
http://www.geogebra.org
This file is part of GeoGebra.
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.
*/
package org.geogebra.common.kernel.geos;
import org.geogebra.common.kernel.Construction;
import org.geogebra.common.kernel.Kernel;
import org.geogebra.common.kernel.MyPoint;
import org.geogebra.common.kernel.PathMover;
import org.geogebra.common.kernel.PathMoverGeneric;
import org.geogebra.common.kernel.PathParameter;
import org.geogebra.common.kernel.StringTemplate;
import org.geogebra.common.kernel.Transform;
import org.geogebra.common.kernel.algos.AlgoJoinPointsSegment;
import org.geogebra.common.kernel.arithmetic.MyDouble;
import org.geogebra.common.kernel.arithmetic.NumberValue;
import org.geogebra.common.kernel.kernelND.GeoCurveCartesianND;
import org.geogebra.common.kernel.kernelND.GeoElementND;
import org.geogebra.common.kernel.kernelND.GeoLineND;
import org.geogebra.common.kernel.kernelND.GeoPointND;
import org.geogebra.common.kernel.kernelND.GeoSegmentND;
import org.geogebra.common.kernel.matrix.Coords;
import org.geogebra.common.plugin.GeoClass;
import org.geogebra.common.util.DoubleUtil;
import org.geogebra.common.util.ExtendedBoolean;
/**
* @author Markus Hohenwarter
*/
final public class GeoSegment extends GeoLine
implements GeoSegmentND, SegmentProperties {
// GeoSegment is constructed by AlgoJoinPointsSegment
// private GeoPoint A, B;
private double length;
private boolean defined;
private boolean allowOutlyingIntersections = false;
private boolean keepTypeOnGeometricTransform = true; // for mirroring,
// rotation, ...
private StringBuilder sbToString = new StringBuilder(30);
private boolean forceSimpleTransform;
private Coords pnt2D;
private GeoElement meta = null;
private SegmentStyle startStyle = SegmentStyle.DEFAULT;
private SegmentStyle endStyle = SegmentStyle.DEFAULT;
/** no decoration */
public static final int SEGMENT_DECORATION_NONE = 0;
/** one tick */
public static final int SEGMENT_DECORATION_ONE_TICK = 1;
/** two ticks */
public static final int SEGMENT_DECORATION_TWO_TICKS = 2;
/** three ticks */
public static final int SEGMENT_DECORATION_THREE_TICKS = 3;
/** one arrow */
public static final int SEGMENT_DECORATION_ONE_ARROW = 4;
/** two arrows */
public static final int SEGMENT_DECORATION_TWO_ARROWS = 5;
/** three arrows */
public static final int SEGMENT_DECORATION_THREE_ARROWS = 6;
/**
* Returns array of all decoration types
*
* @see #SEGMENT_DECORATION_ONE_TICK etc.
* @return array of all decoration types
*/
public static Integer[] getDecoTypes() {
Integer[] ret = { Integer.valueOf(SEGMENT_DECORATION_NONE),
Integer.valueOf(SEGMENT_DECORATION_ONE_TICK),
Integer.valueOf(SEGMENT_DECORATION_TWO_TICKS),
Integer.valueOf(SEGMENT_DECORATION_THREE_TICKS),
Integer.valueOf(SEGMENT_DECORATION_ONE_ARROW),
Integer.valueOf(SEGMENT_DECORATION_TWO_ARROWS),
Integer.valueOf(SEGMENT_DECORATION_THREE_ARROWS) };
return ret;
}
@Override
public void setDecorationType(int type) {
setDecorationType(type, getDecoTypes().length);
}
/**
* Creates new segment
*
* @param c
* construction
* @param A
* first endpoint
* @param B
* second endpoint
*/
public GeoSegment(Construction c, GeoPoint A, GeoPoint B) {
this(c);
setPoints(A, B);
}
/**
* common constructor
*
* @param c
* construction
*/
public GeoSegment(Construction c) {
super(c);
setConstructionDefaults();
}
/**
* sets start and end points
*
* @param A
* start point
* @param B
* end point
*/
public void setPoints(GeoPoint A, GeoPoint B) {
setStartPoint(A);
setEndPoint(B);
}
@Override
public void setTwoPointsInhomCoords(Coords start, Coords end) {
this.startPoint.setCoords(start.get(1), start.get(2), 1);
this.endPoint.setCoords(end.get(1), end.get(2), 1);
// set x, y, z coords for equation
setCoords(start.getY() - end.getY(), end.getX() - start.getX(),
start.getX() * end.getY() - start.getY() * end.getX());
setPoints(this.startPoint, this.endPoint);
calcLength();
}
@Override
public GeoClass getGeoClassType() {
return GeoClass.SEGMENT;
}
/**
* the copy of a segment is a number (!) with its value set to the segments
* current length
*
* public GeoElement copy() { return new GeoNumeric(cons, getLength()); }
*/
@Override
public GeoElement copyInternal(Construction cons1) {
GeoSegment seg;
if (!this.isDefined()) {
seg = new GeoSegment(cons1);
} else {
seg = new GeoSegment(cons1,
(GeoPoint) startPoint.copyInternal(cons1),
(GeoPoint) endPoint.copyInternal(cons1));
}
seg.set(this);
return seg;
}
@Override
public void set(GeoElementND geo) {
super.set(geo);
if (!geo.isGeoSegment()) {
return;
}
GeoSegment seg = (GeoSegment) geo;
length = seg.length;
defined = seg.defined;
keepTypeOnGeometricTransform = seg.keepTypeOnGeometricTransform;
startPoint = (GeoPoint) GeoLine.updatePoint(cons, startPoint,
seg.startPoint);
endPoint = (GeoPoint) GeoLine.updatePoint(cons, endPoint, seg.endPoint);
}
/**
* @param s
* start point
* @param e
* end point
* @param line
* line
*/
public void set(GeoPoint s, GeoPoint e, GeoVec3D line) {
super.set(line);
setStartPoint(s);
setEndPoint(e);
calcLength();
}
@Override
public void setBasicVisualStyle(GeoElement geo) {
super.setBasicVisualStyle(geo);
if (geo.isGeoSegment()) {
GeoSegmentND seg = (GeoSegmentND) geo;
allowOutlyingIntersections = seg.allowOutlyingIntersections();
}
}
/**
* Calculates this segment's length . This method should only be called by
* its parent algorithm of type AlgoJoinPointsSegment
*/
public void calcLength() {
defined = startPoint.isFinite() && endPoint.isFinite();
if (defined) {
length = startPoint.distance(endPoint);
if (DoubleUtil.isZero(length)) {
length = 0;
}
} else {
length = Double.NaN;
}
}
@Override
public double getLength() {
return length;
}
/*
* overwrite GeoLine methods
*/
@Override
public boolean isDefined() {
return defined;
}
@Override
public void setUndefined() {
super.setUndefined();
length = Double.NaN;
defined = false;
}
@Override
public boolean showInEuclidianView() {
// segments of polygons can have thickness 0
return defined && getLineThickness() != 0;
}
/**
* Yields true iff startpoint and endpoint of s are equal to startpoint and
* endpoint of this segment.
*/
// Michael Borcherds 2008-05-01
@Override
public ExtendedBoolean isEqualExtended(GeoElementND geo) {
// test 3D<SUF>
if (geo.isGeoElement3D()) {
return geo.isEqualExtended(this);
}
if (!geo.isGeoSegment()) {
return ExtendedBoolean.FALSE;
}
GeoSegmentND s = (GeoSegmentND) geo;
return ExtendedBoolean.newExtendedBoolean((startPoint.isEqualPointND(s.getStartPoint())
&& endPoint.isEqualPointND(s.getEndPoint()))
|| (startPoint.isEqualPointND(s.getEndPoint())
&& endPoint.isEqualPointND(s.getStartPoint())));
}
@Override
public String toString(StringTemplate tpl) {
sbToString.setLength(0);
sbToString.append(label);
sbToString.append(" = ");
sbToString.append(kernel.format(length, tpl));
return sbToString.toString();
}
@Override
public String toValueString(StringTemplate tpl) {
return kernel.format(length, tpl);
}
/**
* interface NumberValue
*/
@Override
public MyDouble getNumber() {
return new MyDouble(kernel, getLength());
}
@Override
public double getDouble() {
return getLength();
}
@Override
public boolean isNumberValue() {
return true;
}
@Override
public boolean allowOutlyingIntersections() {
return allowOutlyingIntersections;
}
@Override
public void setAllowOutlyingIntersections(boolean flag) {
allowOutlyingIntersections = flag;
}
@Override
public boolean keepsTypeOnGeometricTransform() {
return keepTypeOnGeometricTransform;
}
@Override
public void setKeepTypeOnGeometricTransform(boolean flag) {
keepTypeOnGeometricTransform = flag;
}
@Override
public boolean isLimitedPath() {
return true;
}
@Override
public boolean isIntersectionPointIncident(GeoPoint p, double eps) {
if (allowOutlyingIntersections) {
return isOnFullLine(p, eps);
}
return isOnPath(p, eps);
}
/*
* GeoSegmentInterface interface
*/
@Override
public GeoElement getStartPointAsGeoElement() {
return getStartPoint();
}
@Override
public GeoElement getEndPointAsGeoElement() {
return getEndPoint();
}
@Override
public double getPointX(double parameter) {
return startPoint.inhomX + parameter * y;
}
@Override
public double getPointY(double parameter) {
return startPoint.inhomY - parameter * x;
}
/*
* Path interface
*/
@Override
public void pointChanged(GeoPointND P) {
PathParameter pp = P.getPathParameter();
// special case: segment of length 0
if (length == 0) {
P.setCoords2D(startPoint.inhomX, startPoint.inhomY, 1);
P.updateCoordsFrom2D(false, null);
if (!(pp.t >= 0 && pp.t <= 1)) {
pp.t = 0.0;
}
return;
}
// project point on line
super.pointChanged(P);
// ensure that the point doesn't get outside the segment
// i.e. ensure 0 <= t <= 1
if (pp.t < 0.0) {
P.setCoords2D(startPoint.x, startPoint.y, startPoint.z);
P.updateCoordsFrom2D(false, null);
pp.t = 0.0;
} else if (pp.t > 1.0) {
P.setCoords2D(endPoint.x, endPoint.y, endPoint.z);
P.updateCoordsFrom2D(false, null);
pp.t = 1.0;
}
}
@Override
public void pathChanged(GeoPointND P) {
// if kernel doesn't use path/region parameters, do as if point changed
// its coords
if (!getKernel().usePathAndRegionParameters(P)) {
pointChanged(P);
return;
}
PathParameter pp = P.getPathParameter();
// special case: segment of length 0
if (length == 0) {
P.setCoords2D(startPoint.inhomX, startPoint.inhomY, 1);
P.updateCoordsFrom2D(false, null);
if (!(pp.t >= 0 && pp.t <= 1)) {
pp.t = 0.0;
}
return;
}
if (pp.t < 0.0) {
pp.t = 0;
} else if (pp.t > 1.0) {
pp.t = 1;
}
// calc point for given parameter
P.setCoords2D(startPoint.inhomX + pp.t * y,
startPoint.inhomY - pp.t * x, 1);
P.updateCoordsFrom2D(false, null);
}
/**
* Returns the smallest possible parameter value for this path.
*
* @return smallest possible parameter
*/
@Override
public double getMinParameter() {
return 0;
}
/**
* Returns the largest possible parameter value for this path.
*
* @return largest possible parameter
*/
@Override
public double getMaxParameter() {
return 1;
}
@Override
public PathMover createPathMover() {
return new PathMoverGeneric(this);
}
/**
* returns all class-specific xml tags for saveXML
*/
@Override
protected void getStyleXML(StringBuilder sb) {
super.getStyleXML(sb);
// allowOutlyingIntersections
sb.append("\t<outlyingIntersections val=\"");
sb.append(allowOutlyingIntersections);
sb.append("\"/>\n");
// keepTypeOnGeometricTransform
sb.append("\t<keepTypeOnTransform val=\"");
sb.append(keepTypeOnGeometricTransform);
sb.append("\"/>\n");
sb.append("\t<startStyle val=\"");
sb.append(startStyle.toString());
sb.append("\"/>\n");
sb.append("\t<endStyle val=\"");
sb.append(endStyle.toString());
sb.append("\"/>\n");
}
/**
* creates new transformed segment
*/
@Override
public GeoElement[] createTransformedObject(Transform t,
String transformedLabel) {
if (keepTypeOnGeometricTransform && t.isAffine()) {
// mirror endpoints
GeoPointND[] points = { getStartPoint(), getEndPoint() };
points = t.transformPoints(points);
// create SEGMENT
GeoElement segment = (GeoElement) kernel.segmentND(transformedLabel,
points[0], points[1]);
segment.setVisualStyleForTransformations(this);
GeoElement[] geos = { segment, (GeoElement) points[0],
(GeoElement) points[1] };
return geos;
} else if (!t.isAffine()) {
// mirror endpoints
// boolean oldSuppressLabelCreation = cons.isSuppressLabelsActive();
// cons.setSuppressLabelCreation(true);
this.forceSimpleTransform = true;
GeoElement[] geos = { t.transform(this, transformedLabel)[0] };
return geos;
} else {
// create LINE
GeoElement transformedLine = t.getTransformedLine(this);
transformedLine.setLabel(transformedLabel);
transformedLine.setVisualStyleForTransformations(this);
GeoElement[] geos = { transformedLine };
return geos;
}
}
@Override
public boolean isGeoSegment() {
return true;
}
//////////////////////////////////////
// 3D stuff
//////////////////////////////////////
@Override
public boolean hasDrawable3D() {
return true;
}
@Override
public Coords getLabelPosition() {
return new Coords(getPointX(0.5), getPointY(0.5), 0, 1);
}
/**
* returns the paramter for the closest point to P on the Segment
* (extrapolated) so answers can be returned outside the range [0,1]
*
* @param ptx
* point x-coord
* @param pty
* point y-coord
* @return closest parameter
*/
public double getParameter(double ptx, double pty) {
double px = ptx;
double py = pty;
// project P on line
// param of projection point on perpendicular line
double t = -(z + x * px + y * py) / (x * x + y * y);
// calculate projection point using perpendicular line
px += t * x;
py += t * y;
// calculate parameter
if (Math.abs(x) <= Math.abs(y)) {
return (startPoint.z * px - startPoint.x) / (y * startPoint.z);
}
return (startPoint.y - startPoint.z * py) / (x * startPoint.z);
}
/**
* Calculates the euclidian distance between this GeoSegment and GeoPoint P.
*
* returns distance from endpoints if appropriate
*/
@Override
public double distance(GeoPoint p) {
double t = getParameter(p.inhomX, p.inhomY);
// if t is outside the range [0,1] then the closest point is not on the
// Segment
if (t < 0) {
return p.distance(startPoint);
}
if (t > 1) {
return p.distance(endPoint);
}
return super.distance(p);
}
@Override
public double distance(double x0, double y0) {
double t = getParameter(x0, y0);
// if t is outside the range [0,1] then the closest point is not on the
// Segment
if (t < 0) {
return startPoint.distance(x0, y0);
}
if (t > 1) {
return endPoint.distance(x0, y0);
}
return super.distance(x0, y0);
}
@Override
public boolean isOnPath(Coords Pnd, double eps) {
if (pnt2D == null) {
pnt2D = new Coords(3);
}
pnt2D.setCoordsIn2DView(Pnd);
if (!super.isOnFullLine2D(pnt2D, eps)) {
return false;
}
return respectLimitedPath(pnt2D, eps);
}
@Override
public boolean respectLimitedPath(Coords Pnd, double eps) {
if (pnt2D == null) {
pnt2D = new Coords(3);
}
pnt2D.setCoordsIn2DView(Pnd);
double t = projectCoordsAndComputePathParam(pnt2D);
return t >= -eps && t <= 1 + eps;
}
/**
* exact calculation for checking if point is on Segment[segStart,segEnd]
*
* @param segStart
* start coords
* @param segEnd
* end coords
* @param point
* point to be checked
* @param checkOnFullLine
* - if true, do extra calculation to make sure.
* @param eps
* precision
* @return true if point belongs to segment
*/
public static boolean checkOnPath(Coords segStart, Coords segEnd,
Coords point, boolean checkOnFullLine, double eps) {
if (checkOnFullLine) {
if (segEnd.sub(segStart).crossProduct(point.sub(segStart))
.equalsForKernel(new Coords(0, 0, 0),
Kernel.STANDARD_PRECISION)) {
return false;
}
}
double x1 = segStart.getInhom(0);
double x2 = segEnd.getInhom(0);
double x = point.getInhom(0);
if (x1 - eps <= x2 && x2 <= x1 + eps) {
double y1 = segStart.getInhom(1);
double y2 = segEnd.getInhom(1);
double y = point.getInhom(1);
if (y1 - eps <= y2 && y2 <= y1 + eps) {
return true;
}
return y1 - eps <= y && y <= y2 + eps
|| y2 - eps <= y && y <= y1 + eps;
}
return x1 - eps <= x && x <= x2 + eps || x2 - eps <= x && x <= x1 + eps;
}
@Override
public boolean isAllEndpointsLabelsSet() {
return !forceSimpleTransform && startPoint.isLabelSet()
&& endPoint.isLabelSet();
}
@Override
public void modifyInputPoints(GeoPointND P, GeoPointND Q) {
AlgoJoinPointsSegment algo = (AlgoJoinPointsSegment) getParentAlgorithm();
algo.modifyInputPoints(P, Q);
}
@Override
public int getMetasLength() {
if (meta == null) {
return 0;
}
return 1;
}
@Override
public GeoElement[] getMetas() {
return new GeoElement[] { meta };
}
/**
* @param poly
* polygon or polyhedron creating this segment
*/
public void setFromMeta(GeoElement poly) {
meta = poly;
}
@Override
public boolean respectLimitedPath(double parameter) {
return DoubleUtil.isGreaterEqual(parameter, 0)
&& DoubleUtil.isGreaterEqual(1, parameter);
}
/**
* dilate from S by r
*/
@Override
public void dilate(NumberValue rval, Coords S) {
super.dilate(rval, S);
startPoint.dilate(rval, S);
endPoint.dilate(rval, S);
calcLength();
}
/**
* rotate this line by angle phi around (0,0)
*/
@Override
public void rotate(NumberValue phiVal) {
super.rotate(phiVal);
startPoint.rotate(phiVal);
endPoint.rotate(phiVal);
// not needed for rotate
// calcLength();
}
/**
* rotate this line by angle phi around Q
*/
@Override
public void rotate(NumberValue phiVal, GeoPointND point) {
super.rotate(phiVal, point);
Coords sCoords = point.getInhomCoords();
startPoint.rotate(phiVal, sCoords);
endPoint.rotate(phiVal, sCoords);
// not needed for rotate
// calcLength();
}
/**
* mirror this line at point Q
*/
@Override
public void mirror(Coords Q) {
super.mirror(Q);
startPoint.mirror(Q);
endPoint.mirror(Q);
// not needed for mirror
// calcLength();
}
/**
* mirror this point at line g
*/
@Override
public void mirror(GeoLineND g1) {
super.mirror(g1);
startPoint.mirror(g1);
endPoint.mirror(g1);
// not needed for mirror
// calcLength();
}
/**
* translate by vector v
*/
@Override
public void translate(Coords v) {
super.translate(v);
startPoint.translate(v);
endPoint.translate(v);
// not needed for mirror
// calcLength();
}
@Override
public void matrixTransform(double p, double q, double r, double s) {
super.matrixTransform(p, q, r, s);
startPoint.matrixTransform(p, q, r, s);
endPoint.matrixTransform(p, q, r, s);
calcLength();
}
@Override
public void matrixTransform(double a00, double a01, double a02,
double a10, double a11, double a12, double a20, double a21,
double a22) {
super.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
startPoint.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
endPoint.matrixTransform(a00, a01, a02, a10, a11, a12, a20, a21, a22);
calcLength();
}
@Override
public void setCoords(MyPoint locusPoint, MyPoint locusPoint2) {
double x1 = locusPoint.x;
double x2 = locusPoint2.x;
double y1 = locusPoint.y;
double y2 = locusPoint2.y;
// line thro' 2 points
setCoords(y1 - y2, x2 - x1, x1 * y2 - y1 * x2);
startPoint.setCoords(x1, y1, 1.0);
endPoint.setCoords(x2, y2, 1.0);
}
@Override
public GeoElement copyFreeSegment() {
GeoPoint startPoint1 = (GeoPoint) getStartPoint().copyInternal(cons);
GeoPoint endPoint1 = (GeoPoint) getEndPoint().copyInternal(cons);
AlgoJoinPointsSegment algo = new AlgoJoinPointsSegment(cons, startPoint1, endPoint1);
return algo.getSegment();
}
@Override
public ExtendedBoolean isCongruent(GeoElement geo) {
return ExtendedBoolean.newExtendedBoolean(geo.isGeoSegment() && DoubleUtil
.isEqual(getLength(), ((GeoSegmentND) geo).getLength()));
}
@Override
public void setChangeableParentIfNull(ChangeableParent ccp) {
// used for GeoPoint3D
}
@Override
public char getLabelDelimiter() {
return '=';
}
@Override
public void toGeoCurveCartesian(GeoCurveCartesianND curve) {
curve.setFromPolyLine(new GeoPointND[] { startPoint, endPoint }, false);
}
/**
* @param startStyle - segment start style
*/
public void setStartStyle(SegmentStyle startStyle) {
this.startStyle = startStyle;
}
/**
* @param endStyle - segment end style
*/
public void setEndStyle(SegmentStyle endStyle) {
this.endStyle = endStyle;
}
/**
* @return segment start style
*/
public SegmentStyle getStartStyle() {
return startStyle;
}
/**
* @return segment end style
*/
public SegmentStyle getEndStyle() {
return endStyle;
}
public boolean hasSegmentStyle() {
return !(startStyle.isDefault() && endStyle.isDefault());
}
@Override
public Coords getPointInD(int dimension, double lambda) {
if (endPoint != null && endPoint.isFinite()
&& startPoint != null && startPoint.isFinite()) {
return startPoint.getCoordsInD(dimension).mul(1 - lambda)
.addInsideMul(endPoint.getCoordsInD(dimension), lambda);
} else {
return super.getPointInD(dimension, lambda);
}
}
}
|
28778_4 | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.HashSet;
/**
* Een klasse om klanteninformatie te lezen uit een csv bestand
* DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie
* van 88 klanten verspreid over de wereld.
* <p>
* Het bestand bevat volgende informatie
* CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax
* Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;
*
* @author Marc De Caluwé
* @version 2019-12-01
*/
public class ContactReader {
private String format;
private ArrayList<ContactEntry> entries;
public ContactReader() {
this("contacts.csv");
}
public ContactReader(String filename) {
// The format for the data.
format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";
// Where to store the data.
entries = new ArrayList<>();
// Attempt to read the complete set of data from file.
try {
File pFile = new File("");
File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);
Scanner klantfile = new Scanner(klantFile);
// Lees het klantenbestand tot de laatste lijn
while (klantfile.hasNextLine()) {
String klantlijn = klantfile.nextLine();
// Splits de klant en maak er een nieuw Klant-object van
ContactEntry entry = new ContactEntry(klantlijn);
entries.add(entry);
}
klantfile.close();
} catch (FileNotFoundException e) {
System.out.println("Er dook een probleem op: " + e.getMessage());
}
}
public ArrayList<ContactEntry> getEntries() {
return entries;
}
/**
* Print de data.
*/
public void printData() {
for (ContactEntry entry : entries) {
System.out.println(entry);
}
}
public HashSet<Contact> loadContacts() {
HashSet<Contact> klanten = new HashSet<>();
for(ContactEntry ke : getEntries()) {
String[] data = ke.getData();
Contact k = new Contact(data[ContactEntry.ID]);
k.setName(data[ContactEntry.NAMECONTACT]);
k.setTitle(data[ContactEntry.TITLECONTACT]);
k.setCity(data[ContactEntry.CITY]);
k.setRegion(data[ContactEntry.REGION]);
k.setCountry(data[ContactEntry.COUNTRY]);
klanten.add(k);
}
return klanten;
}
public static void main(String[] args) {
try {
ContactReader kr = new ContactReader();
kr.printData();
System.out.println("---------------------------------------------------------------");
for (ContactEntry ke : kr.getEntries()) {
String[] data = ke.getData();
// we drukken het ID en bijhorende naam van elke klant
System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Boutoku/OOP-test-repository | oefeningen/src/ContactReader.java | 846 | // Lees het klantenbestand tot de laatste lijn
| line_comment | nl | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.HashSet;
/**
* Een klasse om klanteninformatie te lezen uit een csv bestand
* DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie
* van 88 klanten verspreid over de wereld.
* <p>
* Het bestand bevat volgende informatie
* CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax
* Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;
*
* @author Marc De Caluwé
* @version 2019-12-01
*/
public class ContactReader {
private String format;
private ArrayList<ContactEntry> entries;
public ContactReader() {
this("contacts.csv");
}
public ContactReader(String filename) {
// The format for the data.
format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";
// Where to store the data.
entries = new ArrayList<>();
// Attempt to read the complete set of data from file.
try {
File pFile = new File("");
File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);
Scanner klantfile = new Scanner(klantFile);
// Lees het<SUF>
while (klantfile.hasNextLine()) {
String klantlijn = klantfile.nextLine();
// Splits de klant en maak er een nieuw Klant-object van
ContactEntry entry = new ContactEntry(klantlijn);
entries.add(entry);
}
klantfile.close();
} catch (FileNotFoundException e) {
System.out.println("Er dook een probleem op: " + e.getMessage());
}
}
public ArrayList<ContactEntry> getEntries() {
return entries;
}
/**
* Print de data.
*/
public void printData() {
for (ContactEntry entry : entries) {
System.out.println(entry);
}
}
public HashSet<Contact> loadContacts() {
HashSet<Contact> klanten = new HashSet<>();
for(ContactEntry ke : getEntries()) {
String[] data = ke.getData();
Contact k = new Contact(data[ContactEntry.ID]);
k.setName(data[ContactEntry.NAMECONTACT]);
k.setTitle(data[ContactEntry.TITLECONTACT]);
k.setCity(data[ContactEntry.CITY]);
k.setRegion(data[ContactEntry.REGION]);
k.setCountry(data[ContactEntry.COUNTRY]);
klanten.add(k);
}
return klanten;
}
public static void main(String[] args) {
try {
ContactReader kr = new ContactReader();
kr.printData();
System.out.println("---------------------------------------------------------------");
for (ContactEntry ke : kr.getEntries()) {
String[] data = ke.getData();
// we drukken het ID en bijhorende naam van elke klant
System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
77079_3 | /*
* De main applicatie
*/
package corendon;
/*
TODO:
Tijmen:
- PDF, pdf producer bij registreer missing
- Maken Tab "Customer" (copy paste luggage en aanpassen)
Jeroen:
- Update registratie met extra informatie voor klant en bagage
- Exporteer PDF na oplossing van een case
Burak:
- Help knop
- Grafiek
Zouhar:
- Verwijderen van vernietigde bagage beschikbaar maken
Kenan:
- Reset wachtwoord, verander wachtwoord/user gegevens
(reset knop bij inlog scherm zet waarde van LostPassword in DB naar true)
(dus ook nieuwe kolom maken in DB bij users boolean LostPassword)
- Statussen worden missing/found/solved/delivered
*/
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* @author JerryJerr
*/
public class Corendon extends Application {
Connection conn;
ResultSet rs = null;
PreparedStatement pst = null;
static String uname = "";
static String mail = "";
final String fieldStyle = "-fx-border-width: 1;\n" +
"-fx-border-radius: 5;\n" +
"-fx-border-color: #cccccc;\n" +
"-fx-background-color: #ffffff;"+
"-fx-text-inner-color: #555555;";
@Override
public void start(Stage primaryStage) {
CheckConnection(); //de methode CheckConnection() wordt uitgevoerd
/*
MissingForm.java
*/
TabPane tabScreen = new TabPane(); //het hoofdscherm
Tab luggage = new Tab("Luggage");
Tab customers = new Tab("Customers");
Tab missing = new Tab("Missing");
Tab found = new Tab("Found");
Tab users = new Tab("Users");
Tab stats = new Tab("Statistics");
Tab setts = new Tab("Settings");
LuggageOverview luggageContent = new LuggageOverview();
luggageContent.initScreen(primaryStage);
CustomerOverview customerContent = new CustomerOverview();
customerContent.initScreen(primaryStage);
MissingForm missingContent = new MissingForm(); //ipv gridpane maken we een instantie onze eigen versie van gridpane.
missingContent.initScreen(primaryStage); //hier roepen we de methode aan die alle elementen van het formulier toevoegd.
FoundForm foundContent = new FoundForm();
foundContent.initScreen(primaryStage);
UsersOverview usersContent = new UsersOverview();
usersContent.initScreen(primaryStage);
Statistics statsContent = new Statistics();
statsContent.initScreen(primaryStage);
UserSettings settingsContent = new UserSettings();
settingsContent.initScreen(primaryStage);
Scene newscene = new Scene(tabScreen, 1500, 800, Color.rgb(0, 0, 0, 0)); //het hoofdscherm wordt hier weergegeven.
/*
*/
Label loginLabel = new Label("Enter your details.");
//de knoppen op het login scherm
Button login = new Button("Log in");
Hyperlink help = new Hyperlink("Help");
//de fields voor username en password
TextField usrField = new TextField();
PasswordField pwdField = new PasswordField();
//de default tekst wat in de fields staat
usrField.setPromptText("Username");
pwdField.setPromptText("Password");
BorderPane startScreen = new BorderPane(); //maak het startscherm aan
HBox startScreenTop = new HBox(); //"scherm" voor de luggage logo
HBox startScreenBottom = new HBox(); //"scherm" voor de corendon logo
GridPane loginScreen = new GridPane(); //het gedeelte voor het loginscherm
//importeer de logo's
Image logoCorendon = new Image("Corendon-Logo.jpg");
Image logoLuggage = new Image("Luggage_white.png");
//tekst naast de fields
Label usrLabel = new Label("Username:");
Label pwdLabel = new Label("Password:");
//geef de tekst een kleur
usrLabel.setStyle("-fx-text-fill:#D81E05");
pwdLabel.setStyle("-fx-text-fill:#D81E05");
//laat logo zien
ImageView logoCorendonView = new ImageView();
ImageView logoLuggageView = new ImageView();
//geef logo
logoCorendonView.setImage(logoCorendon);
logoLuggageView.setImage(logoLuggage);
pwdField.setOnKeyPressed(new EventHandler<KeyEvent>() {
//deze methode zorgt ervoor dat je met de Enter knop kunt submitten/inloggen
@Override
public void handle(KeyEvent e) {
if (e.getCode() == KeyCode.ENTER) {
try {
String query = "select * from users where Username=? and Password=?";
pst = conn.prepareStatement(query);
pst.setString(1, usrField.getText());
pst.setString(2, pwdField.getText());
rs = pst.executeQuery();
if (rs.next()) {
primaryStage.setScene(newscene);
primaryStage.setTitle("Welcome");
primaryStage.show();
uname = usrField.getText();
if (!(rs.getString("function").contains("admin"))) {
users.setDisable(true);
stats.setDisable(true);
if ((rs.getString("function").contains("amgr"))) {
stats.setDisable(false);
}
}
} else {
loginLabel.setText("Invalid username/password.");
}
usrField.clear();
pwdField.clear();
pst.close();
rs.close();
} catch (Exception e1) {
loginLabel.setText("SQL Error");
System.err.println(e1);
}
}
}
});
//de login knop backend
login.setOnAction(e -> {
try {
String query = "select * from users where Username=? and Password=?";
pst = conn.prepareStatement(query);
pst.setString(1, usrField.getText());
pst.setString(2, pwdField.getText());
rs = pst.executeQuery();
if (rs.next()) {
primaryStage.setScene(newscene);
primaryStage.setTitle("Welcome");
primaryStage.show();
uname = usrField.getText();
} else {
loginLabel.setText("Invalid username/password.");
}
usrField.clear();
pwdField.clear();
pst.close();
rs.close();
} catch (Exception e1) {
loginLabel.setText("SQL Error");
System.err.println(e1);
}
});
/*
*/
loginScreen.setHgap(15);
loginScreen.setVgap(15);
loginScreen.setPadding(new Insets(50, 30, 50, 30));
/*
*/
/*
Het login schermpje
*/
loginScreen.add(loginLabel, 1, 2, 3, 1);
loginScreen.add(usrLabel, 0, 0);
loginScreen.add(pwdLabel, 0, 1);
loginScreen.add(usrField, 1, 0, 2, 1);
loginScreen.add(pwdField, 1, 1, 2, 1);
loginScreen.add(login, 1, 3);
loginScreen.add(help, 2,3);
/*
*/
/*
Luggage logo
*/
startScreenTop.setAlignment(Pos.CENTER);
startScreenTop.setStyle("-fx-background-color:#D81E05");
startScreenTop.getChildren().add(logoLuggageView);
startScreen.setTop(startScreenTop);
/*
*/
startScreen.setCenter(loginScreen); //zet loginScreen in het midden
startScreen.setBottom(startScreenBottom); //zet luggage logo onderin
/*
Corendon logo
*/
startScreenBottom.setAlignment(Pos.TOP_CENTER);
startScreenBottom.setStyle("-fx-background-color:white");
startScreenBottom.getChildren().add(logoCorendonView);
/*
*/
loginScreen.setStyle("-fx-background-color:white"); //achtergrond wit
logoCorendonView.setStyle("-fx-background-color:white"); //idem
/*
Het gehele loginscherm
*/
Scene scene = new Scene(startScreen, 350, 350);
primaryStage.setTitle("Luggage - log in");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
/*
*/
/*
De tabs van het hoofdscherm
*/
newscene.getStylesheets().add("resources/css/style.css");
tabScreen.getTabs().addAll(luggage, customers, missing, found, users, stats, setts);
tabScreen.setSide(Side.LEFT);
luggage.setContent(luggageContent);
luggage.setClosable(false);
customers.setContent(customerContent);
customers.setClosable(false);
missing.setContent(missingContent);
missing.setClosable(false);
found.setContent(foundContent);
found.setClosable(false);
users.setContent(usersContent);
users.setClosable(false);
stats.setContent(statsContent);
stats.setClosable(false);
setts.setContent(settingsContent);
setts.setClosable(false);
help.setOnAction((ActionEvent e) -> {
helpScreen(primaryStage);
});
}
public void helpScreen(Stage primaryStage) {
GridPane helpPage = new GridPane();
Button back = new Button("<- Back ");
Button manual = new Button("User Manual");
Label forgotPassword = new Label("Forgot Password?");
forgotPassword.setTextFill(Color.web("#00bce2"));
forgotPassword.setStyle("-fx-font: 18px UniSansRegular");
TextField emailInput = new TextField();
emailInput.setStyle(fieldStyle);
Button passwordReset = new Button("Request New Password");
emailInput.setPromptText("Fill your E-mail here");
passwordReset.setStyle(";-fx-border-color:transparent;-fx-focus-color: transparent;-fx-faint-focus-color: transparent;");
Label statusRequest = new Label();
Label emailLabel = new Label("E-mail: ");
emailLabel.setStyle("-fx-text-fill:#D81E05");
back.setOnAction(e-> {
start(primaryStage);
});
manual.setOnAction(e-> {
File file = new File("src\\resources\\ReadMe.txt");
Desktop desktop = Desktop.getDesktop();
if (file.exists()) {
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Corendon.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
helpPage.setStyle("-fx-background-color:white");
helpPage.setHgap(15);
helpPage.setVgap(15);
helpPage.setPadding(new Insets(10, 5, 10, 5));
helpPage.add(forgotPassword, 1, 0,5,1);
helpPage.add(passwordReset, 1, 5,7,1);
helpPage.add(emailLabel,1,3);
helpPage.add(emailInput, 2,3,5,1);
helpPage.add(statusRequest, 1, 6,7,1);
helpPage.add(back, 1, 7,8,1);
helpPage.add(manual, 5, 10,11,1);
Scene helpScreen = new Scene(helpPage, 350, 350);
primaryStage.setTitle("Login Help");
primaryStage.setScene(helpScreen);
primaryStage.setResizable(false);
primaryStage.show();
passwordReset.setOnAction(e -> {
PreparedStatement pst2 = null;
try {
String query = "select * from users where Email=?";
pst = conn.prepareStatement(query);
pst.setString(1, emailInput.getText());
rs = pst.executeQuery();
if (rs.next()) {
String query1 = "update users set lost_password = (1) where email = ?";
pst2 = conn.prepareStatement(query1);
mail = emailInput.getText();
pst2.setString(1, mail);
statusRequest.setText("The admin has been notified for a password reset.");
pst2.executeUpdate();
} else {
statusRequest.setText("E-mail address is not found in the database.");
}
emailInput.clear();
pst.close();
rs.close();
} catch (Exception e1) {
System.err.println(e1);
}
});
}
//check van tevoren de db verbinding
public void CheckConnection() {
conn = Sql.DbConnector();
if (conn == null) {
System.out.println("Connection to database failed.");
System.exit(1);
} else {
System.out.println("Connected to Corendon database!");
}
}
}
| buracc/Corendonv2 | src/corendon/Corendon.java | 3,600 | //de methode CheckConnection() wordt uitgevoerd | line_comment | nl | /*
* De main applicatie
*/
package corendon;
/*
TODO:
Tijmen:
- PDF, pdf producer bij registreer missing
- Maken Tab "Customer" (copy paste luggage en aanpassen)
Jeroen:
- Update registratie met extra informatie voor klant en bagage
- Exporteer PDF na oplossing van een case
Burak:
- Help knop
- Grafiek
Zouhar:
- Verwijderen van vernietigde bagage beschikbaar maken
Kenan:
- Reset wachtwoord, verander wachtwoord/user gegevens
(reset knop bij inlog scherm zet waarde van LostPassword in DB naar true)
(dus ook nieuwe kolom maken in DB bij users boolean LostPassword)
- Statussen worden missing/found/solved/delivered
*/
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* @author JerryJerr
*/
public class Corendon extends Application {
Connection conn;
ResultSet rs = null;
PreparedStatement pst = null;
static String uname = "";
static String mail = "";
final String fieldStyle = "-fx-border-width: 1;\n" +
"-fx-border-radius: 5;\n" +
"-fx-border-color: #cccccc;\n" +
"-fx-background-color: #ffffff;"+
"-fx-text-inner-color: #555555;";
@Override
public void start(Stage primaryStage) {
CheckConnection(); //de methode<SUF>
/*
MissingForm.java
*/
TabPane tabScreen = new TabPane(); //het hoofdscherm
Tab luggage = new Tab("Luggage");
Tab customers = new Tab("Customers");
Tab missing = new Tab("Missing");
Tab found = new Tab("Found");
Tab users = new Tab("Users");
Tab stats = new Tab("Statistics");
Tab setts = new Tab("Settings");
LuggageOverview luggageContent = new LuggageOverview();
luggageContent.initScreen(primaryStage);
CustomerOverview customerContent = new CustomerOverview();
customerContent.initScreen(primaryStage);
MissingForm missingContent = new MissingForm(); //ipv gridpane maken we een instantie onze eigen versie van gridpane.
missingContent.initScreen(primaryStage); //hier roepen we de methode aan die alle elementen van het formulier toevoegd.
FoundForm foundContent = new FoundForm();
foundContent.initScreen(primaryStage);
UsersOverview usersContent = new UsersOverview();
usersContent.initScreen(primaryStage);
Statistics statsContent = new Statistics();
statsContent.initScreen(primaryStage);
UserSettings settingsContent = new UserSettings();
settingsContent.initScreen(primaryStage);
Scene newscene = new Scene(tabScreen, 1500, 800, Color.rgb(0, 0, 0, 0)); //het hoofdscherm wordt hier weergegeven.
/*
*/
Label loginLabel = new Label("Enter your details.");
//de knoppen op het login scherm
Button login = new Button("Log in");
Hyperlink help = new Hyperlink("Help");
//de fields voor username en password
TextField usrField = new TextField();
PasswordField pwdField = new PasswordField();
//de default tekst wat in de fields staat
usrField.setPromptText("Username");
pwdField.setPromptText("Password");
BorderPane startScreen = new BorderPane(); //maak het startscherm aan
HBox startScreenTop = new HBox(); //"scherm" voor de luggage logo
HBox startScreenBottom = new HBox(); //"scherm" voor de corendon logo
GridPane loginScreen = new GridPane(); //het gedeelte voor het loginscherm
//importeer de logo's
Image logoCorendon = new Image("Corendon-Logo.jpg");
Image logoLuggage = new Image("Luggage_white.png");
//tekst naast de fields
Label usrLabel = new Label("Username:");
Label pwdLabel = new Label("Password:");
//geef de tekst een kleur
usrLabel.setStyle("-fx-text-fill:#D81E05");
pwdLabel.setStyle("-fx-text-fill:#D81E05");
//laat logo zien
ImageView logoCorendonView = new ImageView();
ImageView logoLuggageView = new ImageView();
//geef logo
logoCorendonView.setImage(logoCorendon);
logoLuggageView.setImage(logoLuggage);
pwdField.setOnKeyPressed(new EventHandler<KeyEvent>() {
//deze methode zorgt ervoor dat je met de Enter knop kunt submitten/inloggen
@Override
public void handle(KeyEvent e) {
if (e.getCode() == KeyCode.ENTER) {
try {
String query = "select * from users where Username=? and Password=?";
pst = conn.prepareStatement(query);
pst.setString(1, usrField.getText());
pst.setString(2, pwdField.getText());
rs = pst.executeQuery();
if (rs.next()) {
primaryStage.setScene(newscene);
primaryStage.setTitle("Welcome");
primaryStage.show();
uname = usrField.getText();
if (!(rs.getString("function").contains("admin"))) {
users.setDisable(true);
stats.setDisable(true);
if ((rs.getString("function").contains("amgr"))) {
stats.setDisable(false);
}
}
} else {
loginLabel.setText("Invalid username/password.");
}
usrField.clear();
pwdField.clear();
pst.close();
rs.close();
} catch (Exception e1) {
loginLabel.setText("SQL Error");
System.err.println(e1);
}
}
}
});
//de login knop backend
login.setOnAction(e -> {
try {
String query = "select * from users where Username=? and Password=?";
pst = conn.prepareStatement(query);
pst.setString(1, usrField.getText());
pst.setString(2, pwdField.getText());
rs = pst.executeQuery();
if (rs.next()) {
primaryStage.setScene(newscene);
primaryStage.setTitle("Welcome");
primaryStage.show();
uname = usrField.getText();
} else {
loginLabel.setText("Invalid username/password.");
}
usrField.clear();
pwdField.clear();
pst.close();
rs.close();
} catch (Exception e1) {
loginLabel.setText("SQL Error");
System.err.println(e1);
}
});
/*
*/
loginScreen.setHgap(15);
loginScreen.setVgap(15);
loginScreen.setPadding(new Insets(50, 30, 50, 30));
/*
*/
/*
Het login schermpje
*/
loginScreen.add(loginLabel, 1, 2, 3, 1);
loginScreen.add(usrLabel, 0, 0);
loginScreen.add(pwdLabel, 0, 1);
loginScreen.add(usrField, 1, 0, 2, 1);
loginScreen.add(pwdField, 1, 1, 2, 1);
loginScreen.add(login, 1, 3);
loginScreen.add(help, 2,3);
/*
*/
/*
Luggage logo
*/
startScreenTop.setAlignment(Pos.CENTER);
startScreenTop.setStyle("-fx-background-color:#D81E05");
startScreenTop.getChildren().add(logoLuggageView);
startScreen.setTop(startScreenTop);
/*
*/
startScreen.setCenter(loginScreen); //zet loginScreen in het midden
startScreen.setBottom(startScreenBottom); //zet luggage logo onderin
/*
Corendon logo
*/
startScreenBottom.setAlignment(Pos.TOP_CENTER);
startScreenBottom.setStyle("-fx-background-color:white");
startScreenBottom.getChildren().add(logoCorendonView);
/*
*/
loginScreen.setStyle("-fx-background-color:white"); //achtergrond wit
logoCorendonView.setStyle("-fx-background-color:white"); //idem
/*
Het gehele loginscherm
*/
Scene scene = new Scene(startScreen, 350, 350);
primaryStage.setTitle("Luggage - log in");
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
/*
*/
/*
De tabs van het hoofdscherm
*/
newscene.getStylesheets().add("resources/css/style.css");
tabScreen.getTabs().addAll(luggage, customers, missing, found, users, stats, setts);
tabScreen.setSide(Side.LEFT);
luggage.setContent(luggageContent);
luggage.setClosable(false);
customers.setContent(customerContent);
customers.setClosable(false);
missing.setContent(missingContent);
missing.setClosable(false);
found.setContent(foundContent);
found.setClosable(false);
users.setContent(usersContent);
users.setClosable(false);
stats.setContent(statsContent);
stats.setClosable(false);
setts.setContent(settingsContent);
setts.setClosable(false);
help.setOnAction((ActionEvent e) -> {
helpScreen(primaryStage);
});
}
public void helpScreen(Stage primaryStage) {
GridPane helpPage = new GridPane();
Button back = new Button("<- Back ");
Button manual = new Button("User Manual");
Label forgotPassword = new Label("Forgot Password?");
forgotPassword.setTextFill(Color.web("#00bce2"));
forgotPassword.setStyle("-fx-font: 18px UniSansRegular");
TextField emailInput = new TextField();
emailInput.setStyle(fieldStyle);
Button passwordReset = new Button("Request New Password");
emailInput.setPromptText("Fill your E-mail here");
passwordReset.setStyle(";-fx-border-color:transparent;-fx-focus-color: transparent;-fx-faint-focus-color: transparent;");
Label statusRequest = new Label();
Label emailLabel = new Label("E-mail: ");
emailLabel.setStyle("-fx-text-fill:#D81E05");
back.setOnAction(e-> {
start(primaryStage);
});
manual.setOnAction(e-> {
File file = new File("src\\resources\\ReadMe.txt");
Desktop desktop = Desktop.getDesktop();
if (file.exists()) {
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Corendon.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
helpPage.setStyle("-fx-background-color:white");
helpPage.setHgap(15);
helpPage.setVgap(15);
helpPage.setPadding(new Insets(10, 5, 10, 5));
helpPage.add(forgotPassword, 1, 0,5,1);
helpPage.add(passwordReset, 1, 5,7,1);
helpPage.add(emailLabel,1,3);
helpPage.add(emailInput, 2,3,5,1);
helpPage.add(statusRequest, 1, 6,7,1);
helpPage.add(back, 1, 7,8,1);
helpPage.add(manual, 5, 10,11,1);
Scene helpScreen = new Scene(helpPage, 350, 350);
primaryStage.setTitle("Login Help");
primaryStage.setScene(helpScreen);
primaryStage.setResizable(false);
primaryStage.show();
passwordReset.setOnAction(e -> {
PreparedStatement pst2 = null;
try {
String query = "select * from users where Email=?";
pst = conn.prepareStatement(query);
pst.setString(1, emailInput.getText());
rs = pst.executeQuery();
if (rs.next()) {
String query1 = "update users set lost_password = (1) where email = ?";
pst2 = conn.prepareStatement(query1);
mail = emailInput.getText();
pst2.setString(1, mail);
statusRequest.setText("The admin has been notified for a password reset.");
pst2.executeUpdate();
} else {
statusRequest.setText("E-mail address is not found in the database.");
}
emailInput.clear();
pst.close();
rs.close();
} catch (Exception e1) {
System.err.println(e1);
}
});
}
//check van tevoren de db verbinding
public void CheckConnection() {
conn = Sql.DbConnector();
if (conn == null) {
System.out.println("Connection to database failed.");
System.exit(1);
} else {
System.out.println("Connected to Corendon database!");
}
}
}
|
124840_4 | /*
* Copyright (c)2006 Tavant Technologies
* All Rights Reserved.
*
* This software is furnished under a license and may be used and copied
* only in accordance with the terms of such license and with the
* inclusion of the above copyright notice. This software or any other
* copies thereof may not be provided or otherwise made available to any
* other person. No title to and ownership of the software is hereby
* transferred.
*
* The information in this software is subject to change without notice
* and should not be construed as a commitment by Tavant Technologies.
*/
package tavant.twms.web.admin.campaign;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.CODE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.COMPLETE_CODE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.ID;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.LABEL;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.NODE_TYPE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.NODE_TYPE_LEAF;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.SERVICE_PROCEDURE_ID;
import static tavant.twms.web.documentOperations.DocumentAction.getDocumentListJSON;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.StringUtils;
import tavant.twms.domain.common.Document;
import tavant.twms.domain.campaign.Campaign;
import tavant.twms.domain.campaign.CampaignAdminService;
import tavant.twms.domain.campaign.CampaignCoverage;
import tavant.twms.domain.campaign.CampaignLaborDetail;
import tavant.twms.domain.campaign.CampaignRangeCoverage;
import tavant.twms.domain.campaign.CampaignSerialNumberCoverage;
import tavant.twms.domain.campaign.CampaignServiceDetail;
import tavant.twms.domain.campaign.CampaignServiceException;
import tavant.twms.domain.campaign.HussPartsToReplace;
import tavant.twms.domain.campaign.NonOEMPartToReplace;
import tavant.twms.domain.campaign.OEMPartToReplace;
import tavant.twms.domain.campaign.validation.CampaignValidationService;
import tavant.twms.domain.catalog.CatalogException;
import tavant.twms.domain.catalog.CatalogService;
import tavant.twms.domain.catalog.Item;
import tavant.twms.domain.catalog.ItemGroup;
import tavant.twms.domain.catalog.ItemGroupService;
import tavant.twms.domain.catalog.MiscellaneousItem;
import tavant.twms.domain.claim.payment.CostCategory;
import tavant.twms.domain.common.I18NNonOemPartsDescription;
import tavant.twms.domain.configuration.ConfigName;
import tavant.twms.domain.configuration.ConfigParamService;
import tavant.twms.domain.failurestruct.FailureStructure;
import tavant.twms.domain.failurestruct.FailureStructureService;
import tavant.twms.domain.failurestruct.ServiceProcedureDefinition;
import tavant.twms.domain.inventory.InventoryItem;
import tavant.twms.domain.orgmodel.NationalAccount;
import tavant.twms.domain.partreturn.PartReturnService;
import tavant.twms.domain.partreturn.PaymentCondition;
import tavant.twms.domain.supplier.contract.Contract;
import tavant.twms.domain.supplier.contract.ContractService;
import tavant.twms.infra.HibernateCast;
import tavant.twms.infra.InstanceOfUtil;
import tavant.twms.security.SelectedBusinessUnitsHolder;
import tavant.twms.web.admin.jobcode.MergedTreeJSONifier;
import tavant.twms.web.claim.ClaimsAction;
import tavant.twms.web.i18n.I18nActionSupport;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.Validateable;
/**
* @author Kiran.Kollipara
*/
@SuppressWarnings("serial")
public class SaveCampaignAction extends I18nActionSupport implements
Preparable, Validateable {
private static final Logger logger = Logger
.getLogger(SaveCampaignAction.class);
private CampaignAdminService campaignAdminService;
private CampaignValidationService campaignValidationService;
private CatalogService catalogService;
private Campaign campaign;
private String number;
private String partCriterion;
private String jsonString;
private boolean partsReplacedInstalledSectionVisible;
private boolean buPartReplaceableByNonBUPart;
private String campaignFor;
private static final String SERIAL_NUMBERS = "SERIAL_NUMBERS";
private static final String SERIAL_NUMBER_RANGES = "SERIAL_NUMBER_RANGES";
private FailureStructureService failureStructureService;
private MergedTreeJSONifier mergedTreeJSONifier;
private List<PaymentCondition> paymentConditions;
private PartReturnService partReturnService;
public static final String SPECIFIED_HOURS = "specifiedLaborHours",
WRAPPER_ID = "wrapperId",
USE_SUGGESTED_HOURS = "useSuggestedHours";
private String locationPrefix;
private List<ItemGroup> products = new ArrayList<ItemGroup>();
private ItemGroupService itemGroupService;
private List<Currency> currencies;
private ConfigParamService configParamService;
private Map<String,CostCategory> configuredCostCategories = new HashMap<String,CostCategory>();
private Contract selectedContract;
private ContractService contractService;
private List<NationalAccount> selectedNationalAccounts=new ArrayList<NationalAccount>();
public void prepare() throws Exception {
// this action is only used for populating the part description
if("oem_part_details".equals(ActionContext.getContext().getName())) return;
products = itemGroupService.findGroupsForGroupType(PRODUCT);
paymentConditions = partReturnService.findAllPaymentConditions();
this.setConfiguredCostCategories(configuredCostCategories);
this.setCurrencies(currencies);
populateCampaignFor();
partsReplacedInstalledSectionVisible = getConfigParamService().
getBooleanValue(ConfigName.PARTS_REPLACED_INSTALLED_SECTION_VISIBLE.getName());
buPartReplaceableByNonBUPart = getConfigParamService().getBooleanValue(ConfigName.BUPART_REPLACEABLEBY_NONBUPART.getName());
if (this.selectedContract != null && this.selectedContract.getId() != null && campaign != null) {
campaign.setContract(this.contractService.findContract(this.selectedContract.getId()));
}else if(this.selectedContract != null && this.selectedContract.getId() == null && campaign != null){
campaign.setContract(null);
}
}
@Override
public void validate() {
try {
campaignValidationService.validate(campaign,campaignFor);
List<InventoryItem> items = campaign.getCampaignCoverage()
.getItems();
if ((items == null || items.isEmpty())
&& SERIAL_NUMBERS.equals(campaignFor)) {
super.validate();
}
} catch (CampaignServiceException e) {
Set<String> errors = new HashSet<String>();
errors.addAll(e.fieldErrors().values());
errors.addAll(e.actionErrors());
for (String anErrorMessage : errors) {
addActionError(anErrorMessage);
}
}
}
public String load() {
if (campaign.getId() != null) {
campaign = campaignAdminService.findById(campaign.getId());
}
return SUCCESS;
}
public String save() throws Exception {
campaignAdminService.save(campaign);
return SUCCESS;
}
// validate Non Oem Parts description for en_US Mandatory
public void validateNonOemPartsDescription() {
if (campaign.getNonOEMpartsToReplace() != null) {
// checking duplicates
Set<String> nonOEMPartToReplaceDescSet = new HashSet<String>(campaign
.getNonOEMpartsToReplace().size());
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getNonOEMpartsToReplace()) {
if (!nonOEMPartToReplaceDescSet.add(nonOEMPartToReplace.getDescription())) {
addActionError("error.campaign.duplicateNonOEMPartDescription", new String[]{nonOEMPartToReplace.getDescription()});
}
}
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getNonOEMpartsToReplace()) {
for (I18NNonOemPartsDescription i18NonOemPartsDescription : nonOEMPartToReplace
.getI18nNonOemPartsDescription()) {
if (i18NonOemPartsDescription != null
&& EN_US.equalsIgnoreCase(i18NonOemPartsDescription.getLocale())
&& !StringUtils.hasText(i18NonOemPartsDescription
.getDescription())) {
addActionError("error.campaign.nonOemDescptionfailureMessageUS");
}
}
if (nonOEMPartToReplace.getNoOfUnits() == null || (nonOEMPartToReplace.getNoOfUnits() != null && nonOEMPartToReplace.getNoOfUnits().intValue() <= 0)) {
addActionError("error.campaign.nonOemPartsQuantity");
}
}
}
}
// validate Miscellaneous Parts
public void validateMiscellaneousParts() {
if (campaign.getMiscPartsToReplace() != null) {
// checking for duplicates Misc. Parts
Set<String> miscPartNumbersSet = new HashSet<String>(campaign.getMiscPartsToReplace().size());
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getMiscPartsToReplace()) {
MiscellaneousItem miscItem = nonOEMPartToReplace.getMiscItem();
if (miscItem != null && !miscPartNumbersSet.add(miscItem.getPartNumber())) {
addActionError("error.campaign.duplicateMiscItem", new String[]{miscItem.getPartNumber()});
}
}
// part number and qty validation
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getMiscPartsToReplace()) {
if (hasActionErrors()) {
break;
}
MiscellaneousItem miscItem = nonOEMPartToReplace.getMiscItem();
if (miscItem == null && nonOEMPartToReplace.getNoOfUnits() == null) {
addActionError("error.campaign.miscPartRequired");
}
if (nonOEMPartToReplace.getNoOfUnits()!= null && miscItem == null) {
addActionError("error.campaign.miscPartRequired");
}
if (miscItem != null && nonOEMPartToReplace.getNoOfUnits() == null || (nonOEMPartToReplace.getNoOfUnits()!= null
&& nonOEMPartToReplace.getNoOfUnits().intValue() <=0 )) {
addActionError("error.campaign.miscPartQtyInvalid", new String[]{miscItem.getPartNumber()});
}
}
}
}
public String update() throws Exception {
if (!StringUtils.hasText(campaign.getStatus())) {
campaign.setStatus(CampaignAdminService.CAMPAIGN_DRAFT_STATUS);
}
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
validateReplacedInstalledPartsSection();
validateHussPartsToReplace();
validateNonOemPartsDescription();
validateCampaignJobCodesSection();
validateMiscellaneousParts();
if(hasActionErrors()){
return INPUT;
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.update(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.saveSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String updateForPrevious() throws Exception {
campaignAdminService.update(campaign);
return SUCCESS;
}
private void validateHussPartsToReplace() {
if (campaign.getHussPartsToReplace() != null && !campaign.getHussPartsToReplace().isEmpty()) {
for (HussPartsToReplace hussPartsToReplace: campaign.getHussPartsToReplace()) {
List<OEMPartToReplace> removedParts = hussPartsToReplace.getRemovedParts();
List<OEMPartToReplace> installedParts = hussPartsToReplace.getInstalledParts();
validateParts(removedParts, 1);
validateParts(installedParts, 2);
}
}
}
private void validateParts(List<OEMPartToReplace> parts, int type) {
if (parts != null && !parts.isEmpty()) {
// checking duplicates replaced/installed parts
Set<String> partNumbersSet = new HashSet<String>(parts.size());
for (OEMPartToReplace oemPartToReplace:parts) {
if (!partNumbersSet.add(oemPartToReplace.getItem().getNumber())) {
addActionError("error.campaign.duplicateReplacedInstalledPart", new String[]{oemPartToReplace.getItem().getNumber()});
}
}
// checking remaining validations
for (OEMPartToReplace oemPartToReplace:parts) {
if (hasActionErrors()) {
break;
}
validatePartUnits(oemPartToReplace, type);
if (type == 1) {
if (((oemPartToReplace.getPaymentCondition() != null && oemPartToReplace.getPaymentCondition().trim().length() > 0)
|| (oemPartToReplace.getDueDays() != null && oemPartToReplace.getDueDays().intValue() > 0))
&& (oemPartToReplace.getReturnLocation() == null || oemPartToReplace.getReturnLocation().getCode() == null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() == 0)) {
addActionError("error.return.location.required");
}
if (((oemPartToReplace.getReturnLocation() != null && oemPartToReplace.getReturnLocation().getCode() != null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() > 0)
|| (oemPartToReplace.getDueDays() != null && oemPartToReplace.getDueDays().intValue() > 0))
&& (oemPartToReplace.getPaymentCondition() == null || oemPartToReplace.getPaymentCondition().trim().length() == 0)) {
addActionError("error.campaign.invalidPaymentCondition");
}
if (((oemPartToReplace.getReturnLocation() != null && oemPartToReplace.getReturnLocation().getCode() != null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() > 0)
|| (oemPartToReplace.getPaymentCondition() != null && oemPartToReplace.getPaymentCondition().trim().length() > 0))
&& (oemPartToReplace.getDueDays() == null || oemPartToReplace.getDueDays().intValue() == 0)) {
addActionError("error.dueDays.required");
}
}
}
}
}
private void validatePartUnits(OEMPartToReplace oemPartToReplace, int type) {
if (!(oemPartToReplace.getNoOfUnits() != null && oemPartToReplace.getNoOfUnits().intValue() > 0)) {
String partType = null;
if (type == 1) {
partType = getText("label.claim.removedParts");
}
if (type == 2) {
partType = getText("label.newClaim.hussmanPartsInstalled");
}
addActionError("error.newClaim.invalidOEMPartUnitsWithParams", new String[]{partType});
}
}
private void validateReplacedInstalledPartsSection() {
if (campaign.getHussPartsToReplace() != null && !campaign.getHussPartsToReplace().isEmpty()) {
for (HussPartsToReplace hussPartsToReplace: campaign.getHussPartsToReplace()) {
List<OEMPartToReplace> removedParts = hussPartsToReplace.getRemovedParts();
if (removedParts != null && !removedParts.isEmpty()) {
if ((hussPartsToReplace.getInstalledParts() == null || hussPartsToReplace.getInstalledParts().isEmpty())) {
if (buPartReplaceableByNonBUPart) {
if (hussPartsToReplace.getNonOEMpartsToReplace() == null || hussPartsToReplace.getNonOEMpartsToReplace().isEmpty()) {
addActionError("error.claim.selectAtleastOneOfInstallParts");
}
} else {
addActionError("error.claim.selectAtleastOneOfTSAInstallParts");
}
}
}
if ((removedParts == null || removedParts.isEmpty()) && ((hussPartsToReplace.getInstalledParts() != null && !hussPartsToReplace.getInstalledParts().isEmpty()) || (hussPartsToReplace.getNonOEMpartsToReplace() != null || !hussPartsToReplace.getNonOEMpartsToReplace().isEmpty()))) {
addActionError("error.claim.selectRemovedParts");
}
}
}
}
private void validateCampaignJobCodesSection() {
List<CampaignLaborDetail> campaignLaborDetailLimits = campaign.getCampaignServiceDetail().getCampaignLaborLimits();
if (campaignLaborDetailLimits != null && !campaignLaborDetailLimits.isEmpty()) {
for (CampaignLaborDetail campaignLaborDetail: campaignLaborDetailLimits) {
if (!campaignLaborDetail.isLaborStandardsUsed()) {
if (campaignLaborDetail.getSpecifiedLaborHours() == null) {
addActionError("error.campaign.invalidJobCodeDetails", new String[] {campaignLaborDetail.getServiceProcedureDefinition().getCode()});
}
if (campaignLaborDetail.getSpecifiedLaborHours() != null && campaignLaborDetail.getSpecifiedLaborHours().floatValue() <= 0.0) {
addActionError("error.campaign.invalidJobCodeHours", new String[] {campaignLaborDetail.getServiceProcedureDefinition().getCode()});
}
}
}
}
}
public String deactivate() throws Exception {
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
if(hasActionErrors()){
return INPUT;
}
campaign.setStatus(CampaignAdminService.CAMPAIGN_INACTIVE_STATUS);
if (campaign.getD() != null) {
campaign.getD().setActive(Boolean.FALSE);
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.deactivateCampaign(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.deactivatedSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String activate() throws Exception {
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
validateReplacedInstalledPartsSection();
validateHussPartsToReplace();
validateNonOemPartsDescription();
validateCampaignJobCodesSection();
validateMiscellaneousParts();
if(hasActionErrors()){
return INPUT;
}
campaign.setStatus(CampaignAdminService.CAMPAIGN_ACTIVE_STATUS);
if (campaign.getD() != null) {
campaign.getD().setActive(Boolean.TRUE);
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.activateCampaign(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.activatedSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String delete() throws Exception {
String code = campaign.getCode();
campaignAdminService.delete(campaign);
addActionMessage("message.campaign.deleteSuccess",
new String[] { code });
return SUCCESS;
}
public String getOEMPartDetails() {
try {
Item item = catalogService.findItemOwnedByManuf(number);
JSONArray oneEntry = new JSONArray();
oneEntry.put(item.getDescription());
jsonString = oneEntry.toString();
} catch (CatalogException e) {
logger.error("Invalid item number entered", e);
}
return SUCCESS;
}
public String listParts() {
return getOemPartItemNumbersStartingWith(getSearchPrefix());
}
String getOemPartItemNumbersStartingWith(String prefix) {
try {
List<Item> items = new ArrayList<Item>();
if (StringUtils.hasText(prefix)) {
String currentSelectedBusinessUnit = SelectedBusinessUnitsHolder.getSelectedBusinessUnit();
//Commented for perf fix instead we will use the new Native SQL query
//items = catalogService.findParts(prefix.toUpperCase());
//since all types of parts should come we have a list of all the types created.
List<Object> itemGroupSet = new ArrayList<Object>(3);
itemGroupSet.add("PART");
itemGroupSet.add("KIT");
itemGroupSet.add("OPTION");
items = catalogService.fetchManufParts(currentSelectedBusinessUnit, prefix, 10, itemGroupSet, false);
}
return generateAndWriteComboboxJson(items,"id","number");
} catch (Exception e) {
logger.error("Error while generating JSON",e);
throw new RuntimeException("Error while generating JSON", e);
}
}
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
public String getJsonString() {
return jsonString;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getPartCriterion() {
return partCriterion;
}
public void setPartCriterion(String partCriterion) {
this.partCriterion = partCriterion;
}
public void setCampaignAdminService(
CampaignAdminService campaignAdminService) {
this.campaignAdminService = campaignAdminService;
}
public void setCampaignValidationService(
CampaignValidationService campaignValidationService) {
this.campaignValidationService = campaignValidationService;
}
public void setCatalogService(CatalogService catalogService) {
this.catalogService = catalogService;
}
public void setFailureStructureService(
FailureStructureService failureStructureService) {
this.failureStructureService = failureStructureService;
}
public void setMergedTreeJSONifier(MergedTreeJSONifier mergedTreeJSONifier) {
this.mergedTreeJSONifier = mergedTreeJSONifier;
}
public List<PaymentCondition> getPaymentConditions() {
return paymentConditions;
}
public void setPaymentConditions(List<PaymentCondition> paymentConditions) {
this.paymentConditions = paymentConditions;
}
public void setPartReturnService(PartReturnService partReturnService) {
this.partReturnService = partReturnService;
}
public String getLocationPrefix() {
return locationPrefix;
}
public void setLocationPrefix(String locationPrefix) {
this.locationPrefix = locationPrefix;
}
public List<ItemGroup> getProducts() {
return products;
}
public void setProducts(List<ItemGroup> products) {
this.products = products;
}
public void setItemGroupService(ItemGroupService itemGroupService) {
this.itemGroupService = itemGroupService;
}
@Required
public void setMergedTreeJsonifier(MergedTreeJSONifier jsonifier) {
mergedTreeJSONifier = jsonifier;
}
public String getCampaignFor() {
return campaignFor;
}
public void setCampaignFor(String campaignFor) {
this.campaignFor = campaignFor;
}
private void populateCampaignFor() {
CampaignCoverage campaignCoverage = campaign.getCampaignCoverage();
if (campaignCoverage != null) {
if (campaignCoverage.getRangeCoverage() != null) {
campaignFor = SERIAL_NUMBER_RANGES;
} else if (campaignCoverage.getSerialNumberCoverage() != null) {
campaignFor = SERIAL_NUMBERS;
}
}
getSelectedNationalAccounts().clear();
getSelectedNationalAccounts().addAll(campaign.getApplicableNationalAccounts());
}
private String getSelectedJobsJSON() {
JSONArray selectedJobs = new JSONArray();
CampaignServiceDetail serviceDetail = campaign
.getCampaignServiceDetail();
if (serviceDetail == null) {
return "[]";
}
List<CampaignLaborDetail> labourDetail = serviceDetail
.getCampaignLaborLimits();
for (CampaignLaborDetail detail : labourDetail) {
Map<String, Object> row = new HashMap<String, Object>();
ServiceProcedureDefinition serviceProcedureDefinition = detail
.getServiceProcedureDefinition();
assert serviceProcedureDefinition != null;
row.put(CODE, serviceProcedureDefinition.getActionDefinition()
.getCode());
row.put(COMPLETE_CODE, serviceProcedureDefinition.getCode());
row.put(ID, serviceProcedureDefinition.getId());
row.put(SERVICE_PROCEDURE_ID, serviceProcedureDefinition.getId());
row.put(LABEL, serviceProcedureDefinition.getActionDefinition()
.getName());
row.put(SPECIFIED_HOURS, detail.getSpecifiedLaborHours());
row.put(NODE_TYPE, NODE_TYPE_LEAF);
row.put(WRAPPER_ID, detail.getId());
row.put(USE_SUGGESTED_HOURS, detail.isLaborStandardsUsed());
selectedJobs.put(row);
}
return selectedJobs.toString();
}
public String getSelectedJobsJsonString() {
return getSelectedJobsJSON();
}
public String getJsonServiceProcedureTree() throws JSONException {
FailureStructure failureStructure = getFailureStructure();
if (failureStructure == null) {
return "{}";
}
return mergedTreeJSONifier.getSerializedJSONStringForCampaign(failureStructure,
new ClaimsAction.ServiceProcedureTreeFilter(), null);
}
private FailureStructure getFailureStructure() {
return failureStructureService
.getMergedFailureStructureForItems(populateItems());
}
private Collection<Item> populateItems() {
Set<Item> items = new HashSet<Item>();
List<InventoryItem> inventoryItems = campaign.getCampaignCoverage()
.getItems();
for (InventoryItem inventoryItem : inventoryItems) {
items.add(inventoryItem.getOfType());
}
return items;
}
// FIXME: Any exception that occurs comes up as a java script
// Hence returning "{}" for any exception that occurs.
public String getJSONifiedAttachmentList() {
try {
List<Document> attachments = campaign.getAttachments();
if (attachments == null || attachments.size() <= 0) {
return "[]";
}
return getDocumentListJSON(attachments).toString();
} catch (Exception e) {
return "[]";
}
}
public String getDefaultLocale() {
return EN_US;
}
public List<Currency> getCurrencies() {
return currencies;
}
public void setCurrencies(List<Currency> currencies) {
this.currencies = orgService.listUniqueCurrencies();
}
public void setConfigParamService(ConfigParamService configParamService) {
this.configParamService = configParamService;
}
public ConfigParamService getConfigParamService() {
return configParamService;
}
public Map<String,CostCategory> getConfiguredCostCategories() {
return configuredCostCategories;
}
public void setConfiguredCostCategories(Map<String,CostCategory> configuredCostCategories) {
List<Object> costCategoryObjects = configParamService
.getListofObjects(ConfigName.CONFIGURED_COST_CATEGORIES.getName());
for (Object object : costCategoryObjects) {
CostCategory costCategory = new HibernateCast<CostCategory>().cast(object);
this.configuredCostCategories.put(costCategory.getCode(),costCategory);
}
}
private void papulateNationalAccounts()
{
if(selectedNationalAccounts!=null)
{ campaign.getApplicableNationalAccounts().clear();
campaign.getApplicableNationalAccounts().addAll(getSelectedNationalAccounts());
}
}
public void setContractService(ContractService contractService) {
this.contractService = contractService;
}
public Contract getSelectedContract() {
return selectedContract;
}
public void setSelectedContract(Contract selectedContract) {
this.selectedContract = selectedContract;
}
public boolean isPartsReplacedInstalledSectionVisible() {
return partsReplacedInstalledSectionVisible;
}
public void setPartsReplacedInstalledSectionVisible(
boolean partsReplacedInstalledSectionVisible) {
this.partsReplacedInstalledSectionVisible = partsReplacedInstalledSectionVisible;
}
public boolean isBuPartReplaceableByNonBUPart() {
return buPartReplaceableByNonBUPart;
}
public void setBuPartReplaceableByNonBUPart(boolean buPartReplaceableByNonBUPart) {
this.buPartReplaceableByNonBUPart = buPartReplaceableByNonBUPart;
}
public List<NationalAccount> getSelectedNationalAccounts() {
return selectedNationalAccounts;
}
public void setSelectedNationalAccounts(
List<NationalAccount> selectedNationalAccounts) {
this.selectedNationalAccounts = selectedNationalAccounts;
}
} | cckmit/nmhg-phase2 | webapp/src/main/java/tavant/twms/web/admin/campaign/SaveCampaignAction.java | 7,317 | // validate Miscellaneous Parts | line_comment | nl | /*
* Copyright (c)2006 Tavant Technologies
* All Rights Reserved.
*
* This software is furnished under a license and may be used and copied
* only in accordance with the terms of such license and with the
* inclusion of the above copyright notice. This software or any other
* copies thereof may not be provided or otherwise made available to any
* other person. No title to and ownership of the software is hereby
* transferred.
*
* The information in this software is subject to change without notice
* and should not be construed as a commitment by Tavant Technologies.
*/
package tavant.twms.web.admin.campaign;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.CODE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.COMPLETE_CODE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.ID;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.LABEL;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.NODE_TYPE;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.NODE_TYPE_LEAF;
import static tavant.twms.web.admin.jobcode.AssemblyTreeJSONifier.SERVICE_PROCEDURE_ID;
import static tavant.twms.web.documentOperations.DocumentAction.getDocumentListJSON;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.StringUtils;
import tavant.twms.domain.common.Document;
import tavant.twms.domain.campaign.Campaign;
import tavant.twms.domain.campaign.CampaignAdminService;
import tavant.twms.domain.campaign.CampaignCoverage;
import tavant.twms.domain.campaign.CampaignLaborDetail;
import tavant.twms.domain.campaign.CampaignRangeCoverage;
import tavant.twms.domain.campaign.CampaignSerialNumberCoverage;
import tavant.twms.domain.campaign.CampaignServiceDetail;
import tavant.twms.domain.campaign.CampaignServiceException;
import tavant.twms.domain.campaign.HussPartsToReplace;
import tavant.twms.domain.campaign.NonOEMPartToReplace;
import tavant.twms.domain.campaign.OEMPartToReplace;
import tavant.twms.domain.campaign.validation.CampaignValidationService;
import tavant.twms.domain.catalog.CatalogException;
import tavant.twms.domain.catalog.CatalogService;
import tavant.twms.domain.catalog.Item;
import tavant.twms.domain.catalog.ItemGroup;
import tavant.twms.domain.catalog.ItemGroupService;
import tavant.twms.domain.catalog.MiscellaneousItem;
import tavant.twms.domain.claim.payment.CostCategory;
import tavant.twms.domain.common.I18NNonOemPartsDescription;
import tavant.twms.domain.configuration.ConfigName;
import tavant.twms.domain.configuration.ConfigParamService;
import tavant.twms.domain.failurestruct.FailureStructure;
import tavant.twms.domain.failurestruct.FailureStructureService;
import tavant.twms.domain.failurestruct.ServiceProcedureDefinition;
import tavant.twms.domain.inventory.InventoryItem;
import tavant.twms.domain.orgmodel.NationalAccount;
import tavant.twms.domain.partreturn.PartReturnService;
import tavant.twms.domain.partreturn.PaymentCondition;
import tavant.twms.domain.supplier.contract.Contract;
import tavant.twms.domain.supplier.contract.ContractService;
import tavant.twms.infra.HibernateCast;
import tavant.twms.infra.InstanceOfUtil;
import tavant.twms.security.SelectedBusinessUnitsHolder;
import tavant.twms.web.admin.jobcode.MergedTreeJSONifier;
import tavant.twms.web.claim.ClaimsAction;
import tavant.twms.web.i18n.I18nActionSupport;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.Validateable;
/**
* @author Kiran.Kollipara
*/
@SuppressWarnings("serial")
public class SaveCampaignAction extends I18nActionSupport implements
Preparable, Validateable {
private static final Logger logger = Logger
.getLogger(SaveCampaignAction.class);
private CampaignAdminService campaignAdminService;
private CampaignValidationService campaignValidationService;
private CatalogService catalogService;
private Campaign campaign;
private String number;
private String partCriterion;
private String jsonString;
private boolean partsReplacedInstalledSectionVisible;
private boolean buPartReplaceableByNonBUPart;
private String campaignFor;
private static final String SERIAL_NUMBERS = "SERIAL_NUMBERS";
private static final String SERIAL_NUMBER_RANGES = "SERIAL_NUMBER_RANGES";
private FailureStructureService failureStructureService;
private MergedTreeJSONifier mergedTreeJSONifier;
private List<PaymentCondition> paymentConditions;
private PartReturnService partReturnService;
public static final String SPECIFIED_HOURS = "specifiedLaborHours",
WRAPPER_ID = "wrapperId",
USE_SUGGESTED_HOURS = "useSuggestedHours";
private String locationPrefix;
private List<ItemGroup> products = new ArrayList<ItemGroup>();
private ItemGroupService itemGroupService;
private List<Currency> currencies;
private ConfigParamService configParamService;
private Map<String,CostCategory> configuredCostCategories = new HashMap<String,CostCategory>();
private Contract selectedContract;
private ContractService contractService;
private List<NationalAccount> selectedNationalAccounts=new ArrayList<NationalAccount>();
public void prepare() throws Exception {
// this action is only used for populating the part description
if("oem_part_details".equals(ActionContext.getContext().getName())) return;
products = itemGroupService.findGroupsForGroupType(PRODUCT);
paymentConditions = partReturnService.findAllPaymentConditions();
this.setConfiguredCostCategories(configuredCostCategories);
this.setCurrencies(currencies);
populateCampaignFor();
partsReplacedInstalledSectionVisible = getConfigParamService().
getBooleanValue(ConfigName.PARTS_REPLACED_INSTALLED_SECTION_VISIBLE.getName());
buPartReplaceableByNonBUPart = getConfigParamService().getBooleanValue(ConfigName.BUPART_REPLACEABLEBY_NONBUPART.getName());
if (this.selectedContract != null && this.selectedContract.getId() != null && campaign != null) {
campaign.setContract(this.contractService.findContract(this.selectedContract.getId()));
}else if(this.selectedContract != null && this.selectedContract.getId() == null && campaign != null){
campaign.setContract(null);
}
}
@Override
public void validate() {
try {
campaignValidationService.validate(campaign,campaignFor);
List<InventoryItem> items = campaign.getCampaignCoverage()
.getItems();
if ((items == null || items.isEmpty())
&& SERIAL_NUMBERS.equals(campaignFor)) {
super.validate();
}
} catch (CampaignServiceException e) {
Set<String> errors = new HashSet<String>();
errors.addAll(e.fieldErrors().values());
errors.addAll(e.actionErrors());
for (String anErrorMessage : errors) {
addActionError(anErrorMessage);
}
}
}
public String load() {
if (campaign.getId() != null) {
campaign = campaignAdminService.findById(campaign.getId());
}
return SUCCESS;
}
public String save() throws Exception {
campaignAdminService.save(campaign);
return SUCCESS;
}
// validate Non Oem Parts description for en_US Mandatory
public void validateNonOemPartsDescription() {
if (campaign.getNonOEMpartsToReplace() != null) {
// checking duplicates
Set<String> nonOEMPartToReplaceDescSet = new HashSet<String>(campaign
.getNonOEMpartsToReplace().size());
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getNonOEMpartsToReplace()) {
if (!nonOEMPartToReplaceDescSet.add(nonOEMPartToReplace.getDescription())) {
addActionError("error.campaign.duplicateNonOEMPartDescription", new String[]{nonOEMPartToReplace.getDescription()});
}
}
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getNonOEMpartsToReplace()) {
for (I18NNonOemPartsDescription i18NonOemPartsDescription : nonOEMPartToReplace
.getI18nNonOemPartsDescription()) {
if (i18NonOemPartsDescription != null
&& EN_US.equalsIgnoreCase(i18NonOemPartsDescription.getLocale())
&& !StringUtils.hasText(i18NonOemPartsDescription
.getDescription())) {
addActionError("error.campaign.nonOemDescptionfailureMessageUS");
}
}
if (nonOEMPartToReplace.getNoOfUnits() == null || (nonOEMPartToReplace.getNoOfUnits() != null && nonOEMPartToReplace.getNoOfUnits().intValue() <= 0)) {
addActionError("error.campaign.nonOemPartsQuantity");
}
}
}
}
// validate Miscellaneous<SUF>
public void validateMiscellaneousParts() {
if (campaign.getMiscPartsToReplace() != null) {
// checking for duplicates Misc. Parts
Set<String> miscPartNumbersSet = new HashSet<String>(campaign.getMiscPartsToReplace().size());
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getMiscPartsToReplace()) {
MiscellaneousItem miscItem = nonOEMPartToReplace.getMiscItem();
if (miscItem != null && !miscPartNumbersSet.add(miscItem.getPartNumber())) {
addActionError("error.campaign.duplicateMiscItem", new String[]{miscItem.getPartNumber()});
}
}
// part number and qty validation
for (NonOEMPartToReplace nonOEMPartToReplace : campaign
.getMiscPartsToReplace()) {
if (hasActionErrors()) {
break;
}
MiscellaneousItem miscItem = nonOEMPartToReplace.getMiscItem();
if (miscItem == null && nonOEMPartToReplace.getNoOfUnits() == null) {
addActionError("error.campaign.miscPartRequired");
}
if (nonOEMPartToReplace.getNoOfUnits()!= null && miscItem == null) {
addActionError("error.campaign.miscPartRequired");
}
if (miscItem != null && nonOEMPartToReplace.getNoOfUnits() == null || (nonOEMPartToReplace.getNoOfUnits()!= null
&& nonOEMPartToReplace.getNoOfUnits().intValue() <=0 )) {
addActionError("error.campaign.miscPartQtyInvalid", new String[]{miscItem.getPartNumber()});
}
}
}
}
public String update() throws Exception {
if (!StringUtils.hasText(campaign.getStatus())) {
campaign.setStatus(CampaignAdminService.CAMPAIGN_DRAFT_STATUS);
}
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
validateReplacedInstalledPartsSection();
validateHussPartsToReplace();
validateNonOemPartsDescription();
validateCampaignJobCodesSection();
validateMiscellaneousParts();
if(hasActionErrors()){
return INPUT;
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.update(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.saveSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String updateForPrevious() throws Exception {
campaignAdminService.update(campaign);
return SUCCESS;
}
private void validateHussPartsToReplace() {
if (campaign.getHussPartsToReplace() != null && !campaign.getHussPartsToReplace().isEmpty()) {
for (HussPartsToReplace hussPartsToReplace: campaign.getHussPartsToReplace()) {
List<OEMPartToReplace> removedParts = hussPartsToReplace.getRemovedParts();
List<OEMPartToReplace> installedParts = hussPartsToReplace.getInstalledParts();
validateParts(removedParts, 1);
validateParts(installedParts, 2);
}
}
}
private void validateParts(List<OEMPartToReplace> parts, int type) {
if (parts != null && !parts.isEmpty()) {
// checking duplicates replaced/installed parts
Set<String> partNumbersSet = new HashSet<String>(parts.size());
for (OEMPartToReplace oemPartToReplace:parts) {
if (!partNumbersSet.add(oemPartToReplace.getItem().getNumber())) {
addActionError("error.campaign.duplicateReplacedInstalledPart", new String[]{oemPartToReplace.getItem().getNumber()});
}
}
// checking remaining validations
for (OEMPartToReplace oemPartToReplace:parts) {
if (hasActionErrors()) {
break;
}
validatePartUnits(oemPartToReplace, type);
if (type == 1) {
if (((oemPartToReplace.getPaymentCondition() != null && oemPartToReplace.getPaymentCondition().trim().length() > 0)
|| (oemPartToReplace.getDueDays() != null && oemPartToReplace.getDueDays().intValue() > 0))
&& (oemPartToReplace.getReturnLocation() == null || oemPartToReplace.getReturnLocation().getCode() == null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() == 0)) {
addActionError("error.return.location.required");
}
if (((oemPartToReplace.getReturnLocation() != null && oemPartToReplace.getReturnLocation().getCode() != null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() > 0)
|| (oemPartToReplace.getDueDays() != null && oemPartToReplace.getDueDays().intValue() > 0))
&& (oemPartToReplace.getPaymentCondition() == null || oemPartToReplace.getPaymentCondition().trim().length() == 0)) {
addActionError("error.campaign.invalidPaymentCondition");
}
if (((oemPartToReplace.getReturnLocation() != null && oemPartToReplace.getReturnLocation().getCode() != null
&& oemPartToReplace.getReturnLocation().getCode().trim().length() > 0)
|| (oemPartToReplace.getPaymentCondition() != null && oemPartToReplace.getPaymentCondition().trim().length() > 0))
&& (oemPartToReplace.getDueDays() == null || oemPartToReplace.getDueDays().intValue() == 0)) {
addActionError("error.dueDays.required");
}
}
}
}
}
private void validatePartUnits(OEMPartToReplace oemPartToReplace, int type) {
if (!(oemPartToReplace.getNoOfUnits() != null && oemPartToReplace.getNoOfUnits().intValue() > 0)) {
String partType = null;
if (type == 1) {
partType = getText("label.claim.removedParts");
}
if (type == 2) {
partType = getText("label.newClaim.hussmanPartsInstalled");
}
addActionError("error.newClaim.invalidOEMPartUnitsWithParams", new String[]{partType});
}
}
private void validateReplacedInstalledPartsSection() {
if (campaign.getHussPartsToReplace() != null && !campaign.getHussPartsToReplace().isEmpty()) {
for (HussPartsToReplace hussPartsToReplace: campaign.getHussPartsToReplace()) {
List<OEMPartToReplace> removedParts = hussPartsToReplace.getRemovedParts();
if (removedParts != null && !removedParts.isEmpty()) {
if ((hussPartsToReplace.getInstalledParts() == null || hussPartsToReplace.getInstalledParts().isEmpty())) {
if (buPartReplaceableByNonBUPart) {
if (hussPartsToReplace.getNonOEMpartsToReplace() == null || hussPartsToReplace.getNonOEMpartsToReplace().isEmpty()) {
addActionError("error.claim.selectAtleastOneOfInstallParts");
}
} else {
addActionError("error.claim.selectAtleastOneOfTSAInstallParts");
}
}
}
if ((removedParts == null || removedParts.isEmpty()) && ((hussPartsToReplace.getInstalledParts() != null && !hussPartsToReplace.getInstalledParts().isEmpty()) || (hussPartsToReplace.getNonOEMpartsToReplace() != null || !hussPartsToReplace.getNonOEMpartsToReplace().isEmpty()))) {
addActionError("error.claim.selectRemovedParts");
}
}
}
}
private void validateCampaignJobCodesSection() {
List<CampaignLaborDetail> campaignLaborDetailLimits = campaign.getCampaignServiceDetail().getCampaignLaborLimits();
if (campaignLaborDetailLimits != null && !campaignLaborDetailLimits.isEmpty()) {
for (CampaignLaborDetail campaignLaborDetail: campaignLaborDetailLimits) {
if (!campaignLaborDetail.isLaborStandardsUsed()) {
if (campaignLaborDetail.getSpecifiedLaborHours() == null) {
addActionError("error.campaign.invalidJobCodeDetails", new String[] {campaignLaborDetail.getServiceProcedureDefinition().getCode()});
}
if (campaignLaborDetail.getSpecifiedLaborHours() != null && campaignLaborDetail.getSpecifiedLaborHours().floatValue() <= 0.0) {
addActionError("error.campaign.invalidJobCodeHours", new String[] {campaignLaborDetail.getServiceProcedureDefinition().getCode()});
}
}
}
}
}
public String deactivate() throws Exception {
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
if(hasActionErrors()){
return INPUT;
}
campaign.setStatus(CampaignAdminService.CAMPAIGN_INACTIVE_STATUS);
if (campaign.getD() != null) {
campaign.getD().setActive(Boolean.FALSE);
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.deactivateCampaign(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.deactivatedSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String activate() throws Exception {
if(!StringUtils.hasText(campaign.getComments()))
{
addActionError("error.campaign.Comments");
}
validateReplacedInstalledPartsSection();
validateHussPartsToReplace();
validateNonOemPartsDescription();
validateCampaignJobCodesSection();
validateMiscellaneousParts();
if(hasActionErrors()){
return INPUT;
}
campaign.setStatus(CampaignAdminService.CAMPAIGN_ACTIVE_STATUS);
if (campaign.getD() != null) {
campaign.getD().setActive(Boolean.TRUE);
}
papulateNationalAccounts();
campaignAdminService.addActionHistory(campaign);
campaignAdminService.activateCampaign(campaign);
String campaignCode = campaign.getCode().toString();
addActionMessage("message.campaign.activatedSuccess",
new String[] { campaignCode });
return SUCCESS;
}
public String delete() throws Exception {
String code = campaign.getCode();
campaignAdminService.delete(campaign);
addActionMessage("message.campaign.deleteSuccess",
new String[] { code });
return SUCCESS;
}
public String getOEMPartDetails() {
try {
Item item = catalogService.findItemOwnedByManuf(number);
JSONArray oneEntry = new JSONArray();
oneEntry.put(item.getDescription());
jsonString = oneEntry.toString();
} catch (CatalogException e) {
logger.error("Invalid item number entered", e);
}
return SUCCESS;
}
public String listParts() {
return getOemPartItemNumbersStartingWith(getSearchPrefix());
}
String getOemPartItemNumbersStartingWith(String prefix) {
try {
List<Item> items = new ArrayList<Item>();
if (StringUtils.hasText(prefix)) {
String currentSelectedBusinessUnit = SelectedBusinessUnitsHolder.getSelectedBusinessUnit();
//Commented for perf fix instead we will use the new Native SQL query
//items = catalogService.findParts(prefix.toUpperCase());
//since all types of parts should come we have a list of all the types created.
List<Object> itemGroupSet = new ArrayList<Object>(3);
itemGroupSet.add("PART");
itemGroupSet.add("KIT");
itemGroupSet.add("OPTION");
items = catalogService.fetchManufParts(currentSelectedBusinessUnit, prefix, 10, itemGroupSet, false);
}
return generateAndWriteComboboxJson(items,"id","number");
} catch (Exception e) {
logger.error("Error while generating JSON",e);
throw new RuntimeException("Error while generating JSON", e);
}
}
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
public String getJsonString() {
return jsonString;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getPartCriterion() {
return partCriterion;
}
public void setPartCriterion(String partCriterion) {
this.partCriterion = partCriterion;
}
public void setCampaignAdminService(
CampaignAdminService campaignAdminService) {
this.campaignAdminService = campaignAdminService;
}
public void setCampaignValidationService(
CampaignValidationService campaignValidationService) {
this.campaignValidationService = campaignValidationService;
}
public void setCatalogService(CatalogService catalogService) {
this.catalogService = catalogService;
}
public void setFailureStructureService(
FailureStructureService failureStructureService) {
this.failureStructureService = failureStructureService;
}
public void setMergedTreeJSONifier(MergedTreeJSONifier mergedTreeJSONifier) {
this.mergedTreeJSONifier = mergedTreeJSONifier;
}
public List<PaymentCondition> getPaymentConditions() {
return paymentConditions;
}
public void setPaymentConditions(List<PaymentCondition> paymentConditions) {
this.paymentConditions = paymentConditions;
}
public void setPartReturnService(PartReturnService partReturnService) {
this.partReturnService = partReturnService;
}
public String getLocationPrefix() {
return locationPrefix;
}
public void setLocationPrefix(String locationPrefix) {
this.locationPrefix = locationPrefix;
}
public List<ItemGroup> getProducts() {
return products;
}
public void setProducts(List<ItemGroup> products) {
this.products = products;
}
public void setItemGroupService(ItemGroupService itemGroupService) {
this.itemGroupService = itemGroupService;
}
@Required
public void setMergedTreeJsonifier(MergedTreeJSONifier jsonifier) {
mergedTreeJSONifier = jsonifier;
}
public String getCampaignFor() {
return campaignFor;
}
public void setCampaignFor(String campaignFor) {
this.campaignFor = campaignFor;
}
private void populateCampaignFor() {
CampaignCoverage campaignCoverage = campaign.getCampaignCoverage();
if (campaignCoverage != null) {
if (campaignCoverage.getRangeCoverage() != null) {
campaignFor = SERIAL_NUMBER_RANGES;
} else if (campaignCoverage.getSerialNumberCoverage() != null) {
campaignFor = SERIAL_NUMBERS;
}
}
getSelectedNationalAccounts().clear();
getSelectedNationalAccounts().addAll(campaign.getApplicableNationalAccounts());
}
private String getSelectedJobsJSON() {
JSONArray selectedJobs = new JSONArray();
CampaignServiceDetail serviceDetail = campaign
.getCampaignServiceDetail();
if (serviceDetail == null) {
return "[]";
}
List<CampaignLaborDetail> labourDetail = serviceDetail
.getCampaignLaborLimits();
for (CampaignLaborDetail detail : labourDetail) {
Map<String, Object> row = new HashMap<String, Object>();
ServiceProcedureDefinition serviceProcedureDefinition = detail
.getServiceProcedureDefinition();
assert serviceProcedureDefinition != null;
row.put(CODE, serviceProcedureDefinition.getActionDefinition()
.getCode());
row.put(COMPLETE_CODE, serviceProcedureDefinition.getCode());
row.put(ID, serviceProcedureDefinition.getId());
row.put(SERVICE_PROCEDURE_ID, serviceProcedureDefinition.getId());
row.put(LABEL, serviceProcedureDefinition.getActionDefinition()
.getName());
row.put(SPECIFIED_HOURS, detail.getSpecifiedLaborHours());
row.put(NODE_TYPE, NODE_TYPE_LEAF);
row.put(WRAPPER_ID, detail.getId());
row.put(USE_SUGGESTED_HOURS, detail.isLaborStandardsUsed());
selectedJobs.put(row);
}
return selectedJobs.toString();
}
public String getSelectedJobsJsonString() {
return getSelectedJobsJSON();
}
public String getJsonServiceProcedureTree() throws JSONException {
FailureStructure failureStructure = getFailureStructure();
if (failureStructure == null) {
return "{}";
}
return mergedTreeJSONifier.getSerializedJSONStringForCampaign(failureStructure,
new ClaimsAction.ServiceProcedureTreeFilter(), null);
}
private FailureStructure getFailureStructure() {
return failureStructureService
.getMergedFailureStructureForItems(populateItems());
}
private Collection<Item> populateItems() {
Set<Item> items = new HashSet<Item>();
List<InventoryItem> inventoryItems = campaign.getCampaignCoverage()
.getItems();
for (InventoryItem inventoryItem : inventoryItems) {
items.add(inventoryItem.getOfType());
}
return items;
}
// FIXME: Any exception that occurs comes up as a java script
// Hence returning "{}" for any exception that occurs.
public String getJSONifiedAttachmentList() {
try {
List<Document> attachments = campaign.getAttachments();
if (attachments == null || attachments.size() <= 0) {
return "[]";
}
return getDocumentListJSON(attachments).toString();
} catch (Exception e) {
return "[]";
}
}
public String getDefaultLocale() {
return EN_US;
}
public List<Currency> getCurrencies() {
return currencies;
}
public void setCurrencies(List<Currency> currencies) {
this.currencies = orgService.listUniqueCurrencies();
}
public void setConfigParamService(ConfigParamService configParamService) {
this.configParamService = configParamService;
}
public ConfigParamService getConfigParamService() {
return configParamService;
}
public Map<String,CostCategory> getConfiguredCostCategories() {
return configuredCostCategories;
}
public void setConfiguredCostCategories(Map<String,CostCategory> configuredCostCategories) {
List<Object> costCategoryObjects = configParamService
.getListofObjects(ConfigName.CONFIGURED_COST_CATEGORIES.getName());
for (Object object : costCategoryObjects) {
CostCategory costCategory = new HibernateCast<CostCategory>().cast(object);
this.configuredCostCategories.put(costCategory.getCode(),costCategory);
}
}
private void papulateNationalAccounts()
{
if(selectedNationalAccounts!=null)
{ campaign.getApplicableNationalAccounts().clear();
campaign.getApplicableNationalAccounts().addAll(getSelectedNationalAccounts());
}
}
public void setContractService(ContractService contractService) {
this.contractService = contractService;
}
public Contract getSelectedContract() {
return selectedContract;
}
public void setSelectedContract(Contract selectedContract) {
this.selectedContract = selectedContract;
}
public boolean isPartsReplacedInstalledSectionVisible() {
return partsReplacedInstalledSectionVisible;
}
public void setPartsReplacedInstalledSectionVisible(
boolean partsReplacedInstalledSectionVisible) {
this.partsReplacedInstalledSectionVisible = partsReplacedInstalledSectionVisible;
}
public boolean isBuPartReplaceableByNonBUPart() {
return buPartReplaceableByNonBUPart;
}
public void setBuPartReplaceableByNonBUPart(boolean buPartReplaceableByNonBUPart) {
this.buPartReplaceableByNonBUPart = buPartReplaceableByNonBUPart;
}
public List<NationalAccount> getSelectedNationalAccounts() {
return selectedNationalAccounts;
}
public void setSelectedNationalAccounts(
List<NationalAccount> selectedNationalAccounts) {
this.selectedNationalAccounts = selectedNationalAccounts;
}
} |
69675_9 | package be.ucll.java.ent.controller;
import be.ucll.java.ent.domain.StudentDTO;
import be.ucll.java.ent.model.InschrijvingEntity;
import be.ucll.java.ent.model.StudentEntity;
import be.ucll.java.ent.repository.InschrijvingDAO;
import be.ucll.java.ent.repository.StudentDAO;
import be.ucll.java.ent.repository.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Controller
@Transactional
public class StudentController {
private Logger logger = LoggerFactory.getLogger(StudentController.class);
private Logger statsLogger = LoggerFactory.getLogger("statistics");
@Autowired
private StudentDAO dao;
@Autowired
private InschrijvingDAO idao;
@Autowired
private StudentRepository studRepo;
@Autowired
@Qualifier("messageSource")
private MessageSource msgSource;
private Locale loc = new Locale("en");
// Create methods
public long createStudent(StudentDTO student) throws IllegalArgumentException {
// Algemene input controle
if (student == null)
throw new IllegalArgumentException(msgSource.getMessage("exception.createstudent.1", null, loc));
// Controle op verplichte velden
if (student.getNaam() == null || student.getNaam().length() == 0)
throw new IllegalArgumentException("Student aanmaken gefaald. Naam ontbreekt");
if (student.getVoornaam() == null || student.getVoornaam().length() == 0)
throw new IllegalArgumentException("Student aanmaken gefaald. Voornaam ontbreekt");
if (student.getGeboortedatum() == null)
throw new IllegalArgumentException("Student aanmaken gefaald. Geboortedatum ontbreekt");
// Waarde te lang
if (student.getNaam().trim().length() >= 128)
throw new IllegalArgumentException("Student aanmaken gefaald. Naam langer dan 128 karakters");
if (student.getVoornaam().trim().length() >= 128)
throw new IllegalArgumentException("Student aanmaken gefaald. Voornaam langer dan 128 karakters");
// Datumcontroles
if (student.getGeboortedatum().after(new Date()))
throw new IllegalArgumentException("Student aanmaken gefaald. Geboortedatum in de toekomst");
// Controleer dat er al een student bestaat met dezelfde naam, voornaam en geboortedatum.
List<StudentDTO> lst = this.getStudents(student.getNaam(), student.getVoornaam());
for (StudentDTO stud : lst) {
if (student.getNaam().equalsIgnoreCase(stud.getNaam()) &&
student.getVoornaam().equalsIgnoreCase(stud.getVoornaam()) && student.getGeboortedatumstr().equalsIgnoreCase(stud.getGeboortedatumstr())) {
throw new IllegalArgumentException("Er is al een student in de databank met deze gegevens");
}
}
long timestamp = System.currentTimeMillis();
StudentEntity s = new StudentEntity(student.getNaam(), student.getVoornaam(), student.getGeboortedatum());
dao.create(s);
statsLogger.info("Executiontime create student | " + (System.currentTimeMillis() - timestamp) + " ms");
student.setId(s.getId());
return s.getId();
}
// Read / get-one methods
public StudentDTO getStudentById(long studentId) throws IllegalArgumentException {
if (studentId <= 0L) throw new IllegalArgumentException("Student ID ontbreekt");
Optional<StudentEntity> value = dao.get(studentId);
if (value.isPresent()) {
return new StudentDTO(value.get().getId(), value.get().getNaam(), value.get().getVoornaam(), value.get().getGeboortedatum());
} else {
throw new IllegalArgumentException("Geen student gevonden met ID: " + studentId);
}
}
public StudentDTO getStudentByName(String studentName) throws IllegalArgumentException {
if (studentName == null) throw new IllegalArgumentException("Ongeldige naam meegegeven");
if (studentName.trim().length() == 0) throw new IllegalArgumentException("Geen naam meegegeven");
Optional<StudentEntity> value = dao.getOneByName(studentName);
if (value.isPresent()) {
return new StudentDTO(value.get().getId(), value.get().getNaam(), value.get().getVoornaam(), value.get().getGeboortedatum());
} else {
throw new IllegalArgumentException("Geen student gevonden met naam: " + studentName);
}
}
// Update / Modify / Change methods
public void updateStudent(StudentDTO student) throws IllegalArgumentException {
if (student == null) throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getId() <= 0) throw new IllegalArgumentException("Student wijzigen gefaald. Student ID ontbreekt");
if (student.getNaam() == null || student.getNaam().trim().equals(""))
throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getVoornaam() == null || student.getVoornaam().trim().equals(""))
throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getNaam().trim().length() >= 128)
throw new IllegalArgumentException("Student wijzigen gefaald. Naam langer dan 128 karakters");
if (student.getVoornaam().trim().length() >= 128)
throw new IllegalArgumentException("Student wijzigen gefaald. Naam langer dan 128 karakters");
if (student.getGeboortedatum() == null)
throw new IllegalArgumentException("Student wijzigen gefaald. Geboortedatum ontbreekt");
if (student.getGeboortedatum().after(new Date()))
throw new IllegalArgumentException("Student wijzigen gefaald. Geboortedatum in de toekomst");
// TODO Controleer dat deze update geen duplicaten veroorzaakt.
long timestamp = System.currentTimeMillis();
dao.update(new StudentEntity(student.getId(), student.getNaam(), student.getVoornaam(), student.getGeboortedatum()));
statsLogger.info("Executiontime update student | " + (System.currentTimeMillis() - timestamp) + " ms");
}
// Delete methods
public void deleteStudent(long studentId) throws IllegalArgumentException {
if (studentId <= 0L) throw new IllegalArgumentException("Ongeldig ID");
// First check if this student exists
// If not the thrown IllegalArgumentException exits out of this method
getStudentById(studentId);
// Controleer of de student is ingeschreven op bepaalde leermodules
List<InschrijvingEntity> inschr = idao.getInschrijvingenVoorStudentId(studentId);
if (inschr != null && inschr.size() > 0) {
throw new IllegalArgumentException("Student heeft inschrijvingen en kan daardoor niet verwijderd worden");
}
// If all is good effectively delete
long timestamp = System.currentTimeMillis();
dao.delete(studentId);
statsLogger.info("Executiontime remove student | " + (System.currentTimeMillis() - timestamp) + " ms");
}
// Search methods
public List<StudentDTO> getStudentsByName(String naam) throws IllegalArgumentException {
if (naam == null) throw new IllegalArgumentException("Student opzoeken op naam gefaald. Inputdata ontbreekt");
if (naam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam gefaald. Naam leeg");
return (queryListToStudentDTOList(studRepo.findAllByNaamContainsIgnoreCaseOrderByNaam(naam)));
}
public List<StudentDTO> getStudents(String naam, String voornaam) throws IllegalArgumentException {
if (naam == null && voornaam == null)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Inputdata ontbreekt");
if (voornaam == null && naam != null && naam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Naam leeg");
if (naam == null && voornaam != null && voornaam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Voornaam leeg");
long timestamp = System.currentTimeMillis();
List<StudentDTO> lst = queryListToStudentDTOList(dao.getStudents(naam, voornaam));
statsLogger.info("Executiontime getStudents | " + (System.currentTimeMillis() - timestamp) + " ms");
return lst;
}
public List<StudentDTO> getAllStudents() {
return queryListToStudentDTOList(dao.getAll());
}
public long countStudents() {
return dao.countAll();
}
public void setLocale(Locale loc) {
this.loc = loc;
}
// private methods
private List<StudentDTO> queryListToStudentDTOList(List<StudentEntity> lst) {
Stream<StudentDTO> stream = lst.stream()
.map(rec -> {
StudentDTO dto = new StudentDTO();
dto.setId(rec.getId());
dto.setNaam(rec.getNaam());
dto.setVoornaam(rec.getVoornaam());
dto.setGeboortedatum(rec.getGeboortedatum());
return dto;
});
return stream.collect(Collectors.toList());
}
}
| UcllJavaEnterprise/stubs-services | src/main/java/be/ucll/java/ent/controller/StudentController.java | 2,412 | // Controleer of de student is ingeschreven op bepaalde leermodules | line_comment | nl | package be.ucll.java.ent.controller;
import be.ucll.java.ent.domain.StudentDTO;
import be.ucll.java.ent.model.InschrijvingEntity;
import be.ucll.java.ent.model.StudentEntity;
import be.ucll.java.ent.repository.InschrijvingDAO;
import be.ucll.java.ent.repository.StudentDAO;
import be.ucll.java.ent.repository.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Controller
@Transactional
public class StudentController {
private Logger logger = LoggerFactory.getLogger(StudentController.class);
private Logger statsLogger = LoggerFactory.getLogger("statistics");
@Autowired
private StudentDAO dao;
@Autowired
private InschrijvingDAO idao;
@Autowired
private StudentRepository studRepo;
@Autowired
@Qualifier("messageSource")
private MessageSource msgSource;
private Locale loc = new Locale("en");
// Create methods
public long createStudent(StudentDTO student) throws IllegalArgumentException {
// Algemene input controle
if (student == null)
throw new IllegalArgumentException(msgSource.getMessage("exception.createstudent.1", null, loc));
// Controle op verplichte velden
if (student.getNaam() == null || student.getNaam().length() == 0)
throw new IllegalArgumentException("Student aanmaken gefaald. Naam ontbreekt");
if (student.getVoornaam() == null || student.getVoornaam().length() == 0)
throw new IllegalArgumentException("Student aanmaken gefaald. Voornaam ontbreekt");
if (student.getGeboortedatum() == null)
throw new IllegalArgumentException("Student aanmaken gefaald. Geboortedatum ontbreekt");
// Waarde te lang
if (student.getNaam().trim().length() >= 128)
throw new IllegalArgumentException("Student aanmaken gefaald. Naam langer dan 128 karakters");
if (student.getVoornaam().trim().length() >= 128)
throw new IllegalArgumentException("Student aanmaken gefaald. Voornaam langer dan 128 karakters");
// Datumcontroles
if (student.getGeboortedatum().after(new Date()))
throw new IllegalArgumentException("Student aanmaken gefaald. Geboortedatum in de toekomst");
// Controleer dat er al een student bestaat met dezelfde naam, voornaam en geboortedatum.
List<StudentDTO> lst = this.getStudents(student.getNaam(), student.getVoornaam());
for (StudentDTO stud : lst) {
if (student.getNaam().equalsIgnoreCase(stud.getNaam()) &&
student.getVoornaam().equalsIgnoreCase(stud.getVoornaam()) && student.getGeboortedatumstr().equalsIgnoreCase(stud.getGeboortedatumstr())) {
throw new IllegalArgumentException("Er is al een student in de databank met deze gegevens");
}
}
long timestamp = System.currentTimeMillis();
StudentEntity s = new StudentEntity(student.getNaam(), student.getVoornaam(), student.getGeboortedatum());
dao.create(s);
statsLogger.info("Executiontime create student | " + (System.currentTimeMillis() - timestamp) + " ms");
student.setId(s.getId());
return s.getId();
}
// Read / get-one methods
public StudentDTO getStudentById(long studentId) throws IllegalArgumentException {
if (studentId <= 0L) throw new IllegalArgumentException("Student ID ontbreekt");
Optional<StudentEntity> value = dao.get(studentId);
if (value.isPresent()) {
return new StudentDTO(value.get().getId(), value.get().getNaam(), value.get().getVoornaam(), value.get().getGeboortedatum());
} else {
throw new IllegalArgumentException("Geen student gevonden met ID: " + studentId);
}
}
public StudentDTO getStudentByName(String studentName) throws IllegalArgumentException {
if (studentName == null) throw new IllegalArgumentException("Ongeldige naam meegegeven");
if (studentName.trim().length() == 0) throw new IllegalArgumentException("Geen naam meegegeven");
Optional<StudentEntity> value = dao.getOneByName(studentName);
if (value.isPresent()) {
return new StudentDTO(value.get().getId(), value.get().getNaam(), value.get().getVoornaam(), value.get().getGeboortedatum());
} else {
throw new IllegalArgumentException("Geen student gevonden met naam: " + studentName);
}
}
// Update / Modify / Change methods
public void updateStudent(StudentDTO student) throws IllegalArgumentException {
if (student == null) throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getId() <= 0) throw new IllegalArgumentException("Student wijzigen gefaald. Student ID ontbreekt");
if (student.getNaam() == null || student.getNaam().trim().equals(""))
throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getVoornaam() == null || student.getVoornaam().trim().equals(""))
throw new IllegalArgumentException("Student wijzigen gefaald. Inputdata ontbreekt");
if (student.getNaam().trim().length() >= 128)
throw new IllegalArgumentException("Student wijzigen gefaald. Naam langer dan 128 karakters");
if (student.getVoornaam().trim().length() >= 128)
throw new IllegalArgumentException("Student wijzigen gefaald. Naam langer dan 128 karakters");
if (student.getGeboortedatum() == null)
throw new IllegalArgumentException("Student wijzigen gefaald. Geboortedatum ontbreekt");
if (student.getGeboortedatum().after(new Date()))
throw new IllegalArgumentException("Student wijzigen gefaald. Geboortedatum in de toekomst");
// TODO Controleer dat deze update geen duplicaten veroorzaakt.
long timestamp = System.currentTimeMillis();
dao.update(new StudentEntity(student.getId(), student.getNaam(), student.getVoornaam(), student.getGeboortedatum()));
statsLogger.info("Executiontime update student | " + (System.currentTimeMillis() - timestamp) + " ms");
}
// Delete methods
public void deleteStudent(long studentId) throws IllegalArgumentException {
if (studentId <= 0L) throw new IllegalArgumentException("Ongeldig ID");
// First check if this student exists
// If not the thrown IllegalArgumentException exits out of this method
getStudentById(studentId);
// Controleer of<SUF>
List<InschrijvingEntity> inschr = idao.getInschrijvingenVoorStudentId(studentId);
if (inschr != null && inschr.size() > 0) {
throw new IllegalArgumentException("Student heeft inschrijvingen en kan daardoor niet verwijderd worden");
}
// If all is good effectively delete
long timestamp = System.currentTimeMillis();
dao.delete(studentId);
statsLogger.info("Executiontime remove student | " + (System.currentTimeMillis() - timestamp) + " ms");
}
// Search methods
public List<StudentDTO> getStudentsByName(String naam) throws IllegalArgumentException {
if (naam == null) throw new IllegalArgumentException("Student opzoeken op naam gefaald. Inputdata ontbreekt");
if (naam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam gefaald. Naam leeg");
return (queryListToStudentDTOList(studRepo.findAllByNaamContainsIgnoreCaseOrderByNaam(naam)));
}
public List<StudentDTO> getStudents(String naam, String voornaam) throws IllegalArgumentException {
if (naam == null && voornaam == null)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Inputdata ontbreekt");
if (voornaam == null && naam != null && naam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Naam leeg");
if (naam == null && voornaam != null && voornaam.trim().length() == 0)
throw new IllegalArgumentException("Student opzoeken op naam + voornaam gefaald. Voornaam leeg");
long timestamp = System.currentTimeMillis();
List<StudentDTO> lst = queryListToStudentDTOList(dao.getStudents(naam, voornaam));
statsLogger.info("Executiontime getStudents | " + (System.currentTimeMillis() - timestamp) + " ms");
return lst;
}
public List<StudentDTO> getAllStudents() {
return queryListToStudentDTOList(dao.getAll());
}
public long countStudents() {
return dao.countAll();
}
public void setLocale(Locale loc) {
this.loc = loc;
}
// private methods
private List<StudentDTO> queryListToStudentDTOList(List<StudentEntity> lst) {
Stream<StudentDTO> stream = lst.stream()
.map(rec -> {
StudentDTO dto = new StudentDTO();
dto.setId(rec.getId());
dto.setNaam(rec.getNaam());
dto.setVoornaam(rec.getVoornaam());
dto.setGeboortedatum(rec.getGeboortedatum());
return dto;
});
return stream.collect(Collectors.toList());
}
}
|
26517_1 | package is.hello.sense.ui.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.text.SpannableStringBuilder;
import is.hello.buruberi.bluetooth.errors.BuruberiException;
import is.hello.commonsense.util.Errors;
import is.hello.commonsense.util.StringRef;
import is.hello.sense.R;
import is.hello.sense.api.model.ApiException;
import is.hello.sense.ui.common.SenseDialogFragment;
import is.hello.sense.ui.common.UserSupport;
import is.hello.sense.ui.widget.SenseAlertDialog;
import is.hello.sense.ui.widget.util.Styles;
import is.hello.sense.util.Analytics;
public class ErrorDialogFragment extends SenseDialogFragment {
public static final String TAG = ErrorDialogFragment.class.getSimpleName();
private static final String ARG_MESSAGE = ErrorDialogFragment.class.getName() + ".ARG_MESSAGE";
private static final String ARG_ERROR_TYPE = ErrorDialogFragment.class.getName() + ".ARG_ERROR_TYPE";
private static final String ARG_IS_WARNING = ErrorDialogFragment.class.getName() + ".ARG_IS_WARNING";
private static final String ARG_CONTEXT_INFO = ErrorDialogFragment.class.getName() + ".ARG_CONTEXT_INFO";
private static final String ARG_OPERATION = ErrorDialogFragment.class.getName() + ".ARG_OPERATION";
private static final String ARG_SHOW_SUPPORT_LINK = ErrorDialogFragment.class.getName() + ".ARG_SHOW_SUPPORT_LINK";
private static final String ARG_ADDENDUM_RES = ErrorDialogFragment.class.getName() + ".ARG_ADDENDUM_RES";
private static final String ARG_ACTION_INTENT = ErrorDialogFragment.class.getName() + ".ARG_ACTION_INTENT";
private static final String ARG_ACTION_RESULT_CODE = ErrorDialogFragment.class.getName() + ".ARG_ACTION_RESULT_CODE";
private static final String ARG_ACTION_TITLE_RES = ErrorDialogFragment.class.getName() + ".ARG_ACTION_TITLE_RES";
private static final String ARG_TITLE_RES = ErrorDialogFragment.class.getName() + ".ARG_TITLE_RES";
private static final String ARG_TITLE_REF = ErrorDialogFragment.class.getName() + ".ARG_TITLE_REF";
private static final String ARG_ACTION_URI_STRING = ErrorDialogFragment.class.getName() + ".ARG_ACTION_URI_STRING";
//region Lifecycle
public static void presentError(@NonNull final Activity activity, @Nullable final Throwable e, @StringRes final int titleRes) {
final ErrorDialogFragment fragment = newInstance(e).withTitle(titleRes)
.build();
fragment.showAllowingStateLoss(activity.getFragmentManager(), TAG);
}
public static void presentError(@NonNull final Activity activity, @Nullable final Throwable e) {
presentError(activity, e, R.string.dialog_error_title);
}
public static PresenterBuilder newInstance(@Nullable final Throwable e) {
return new PresenterBuilder(e);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(true);
}
@Override
public
@NonNull
Dialog onCreateDialog(final Bundle savedInstanceState) {
final SenseAlertDialog dialog = new SenseAlertDialog(getActivity());
final CharSequence message = generateDisplayMessage();
dialog.setMessage(message);
final Bundle arguments = getArguments();
final int titleResId = arguments.getInt(ARG_TITLE_RES, R.string.dialog_error_title);
dialog.setTitle(titleResId);
if (arguments.containsKey(ARG_TITLE_REF)){
final StringRef title = arguments.getParcelable(ARG_TITLE_REF);
if (title != null) {
dialog.setTitle(title.resolve(getActivity()));
}
}
final String errorType = arguments.getString(ARG_ERROR_TYPE);
final String contextInfo = arguments.getString(ARG_CONTEXT_INFO);
final String operation = arguments.getString(ARG_OPERATION);
final boolean isWarning = arguments.getBoolean(ARG_IS_WARNING);
trackError(message.toString(), errorType, contextInfo, operation, isWarning);
if (getTargetFragment() != null) {
dialog.setPositiveButton(android.R.string.ok, (ignored, which) -> {
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
});
} else {
dialog.setPositiveButton(android.R.string.ok, null);
}
if (arguments.containsKey(ARG_ACTION_TITLE_RES)) {
final int titleRes = arguments.getInt(ARG_ACTION_TITLE_RES);
dialog.setButtonDeemphasized(DialogInterface.BUTTON_NEGATIVE, true);
if (arguments.containsKey(ARG_ACTION_INTENT)) {
dialog.setNegativeButton(titleRes, (button, which) -> {
final Intent intent = arguments.getParcelable(ARG_ACTION_INTENT);
startActivity(intent);
});
} else if (arguments.containsKey(ARG_ACTION_URI_STRING)) {
dialog.setNegativeButton(titleRes, (button, which) -> {
final Uri uri = Uri.parse(arguments.getString(ARG_ACTION_URI_STRING));
UserSupport.openUri(getActivity(), uri);
});
} else {
dialog.setNegativeButton(titleRes, (button, which) -> {
if (getTargetFragment() != null) {
final int resultCode = arguments.getInt(ARG_ACTION_RESULT_CODE);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, null);
}
});
}
}
return dialog;
}
//endregion
//region Internal
/**
* Hook for test case.
*/
@VisibleForTesting
void trackError(@NonNull final String message,
@Nullable final String errorType,
@Nullable final String errorContext,
@Nullable final String errorOperation,
final boolean isWarning) {
Analytics.trackError(message, errorType, errorContext, errorOperation, isWarning);
}
@VisibleForTesting
CharSequence generateDisplayMessage() {
final Bundle arguments = getArguments();
CharSequence message;
final StringRef errorMessage = arguments.getParcelable(ARG_MESSAGE);
if (errorMessage != null) {
message = errorMessage.resolve(getActivity());
} else {
message = getString(R.string.dialog_error_generic_message);
}
if (arguments.containsKey(ARG_ADDENDUM_RES)) {
final SpannableStringBuilder plusAddendum = new SpannableStringBuilder(message);
final int fatalMessageRes = arguments.getInt(ARG_ADDENDUM_RES);
plusAddendum.append(getText(fatalMessageRes));
message = plusAddendum;
}
if (arguments.getBoolean(ARG_SHOW_SUPPORT_LINK, false)) {
final SpannableStringBuilder plusSupportLink = Styles.resolveSupportLinks(getActivity(),
getText(R.string.error_addendum_support));
plusSupportLink.insert(0, message);
message = plusSupportLink;
}
return message;
}
//endregion
public static class Builder {
protected final Bundle arguments = new Bundle();
/**
* See {@link is.hello.sense.ui.dialogs.ErrorDialogFragment.PresenterBuilder}
*/
public Builder() {
}
@Deprecated
public Builder(@Nullable final Throwable e, @NonNull final Context context) {
withMessage(Errors.getDisplayMessage(e));
withErrorType(Errors.getType(e));
withContextInfo(Errors.getContextInfo(e));
withWarning(ApiException.isNetworkError(e));
if (BuruberiException.isInstabilityLikely(e)) {
withUnstableBluetoothHelp(context);
}
}
public Builder withTitle(@StringRes final int titleRes) {
arguments.putInt(ARG_TITLE_RES, titleRes);
return this;
}
public Builder withTitle(final StringRef titleRef) {
arguments.putParcelable(ARG_TITLE_REF, titleRef);
return this;
}
public Builder withMessage(@Nullable final StringRef message) {
arguments.putParcelable(ARG_MESSAGE, message);
return this;
}
public Builder withErrorType(@Nullable final String type) {
arguments.putString(ARG_ERROR_TYPE, type);
return this;
}
public Builder withWarning(final boolean isWarning) {
arguments.putBoolean(ARG_IS_WARNING, isWarning);
return this;
}
public Builder withContextInfo(@Nullable final String contextInfo) {
arguments.putString(ARG_CONTEXT_INFO, contextInfo);
return this;
}
public Builder withOperation(@Nullable final String operation) {
arguments.putString(ARG_OPERATION, operation);
return this;
}
public Builder withSupportLink() {
arguments.putBoolean(ARG_SHOW_SUPPORT_LINK, true);
return this;
}
public Builder withAddendum(@StringRes final int messageRes) {
arguments.putInt(ARG_ADDENDUM_RES, messageRes);
return this;
}
public Builder withAction(@NonNull final Intent intent, @StringRes final int titleRes) {
arguments.putParcelable(ARG_ACTION_INTENT, intent);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
public Builder withAction(final int resultCode, @StringRes final int titleRes) {
arguments.putInt(ARG_ACTION_RESULT_CODE, resultCode);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
public Builder withAction(@NonNull final String uriString, @StringRes final int titleRes) {
arguments.putString(ARG_ACTION_URI_STRING, uriString);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
@Deprecated
public Builder withUnstableBluetoothHelp(@NonNull final Context context) {
final Uri uri = UserSupport.DeviceIssue.UNSTABLE_BLUETOOTH.getUri();
final Intent intent = UserSupport.createViewUriIntent(context, uri);
withAction(intent, R.string.action_more_info);
withAddendum(R.string.error_addendum_unstable_stack);
return this;
}
public ErrorDialogFragment build() {
final ErrorDialogFragment instance = new ErrorDialogFragment();
instance.setArguments(arguments);
return instance;
}
}
public static class PresenterBuilder extends Builder {
public PresenterBuilder(@Nullable final Throwable e) {
withMessage(Errors.getDisplayMessage(e));
withErrorType(Errors.getType(e));
withContextInfo(Errors.getContextInfo(e));
withWarning(ApiException.isNetworkError(e));
if (BuruberiException.isInstabilityLikely(e)) {
withUnstableBluetoothHelp();
}
}
public Builder withUnstableBluetoothHelp() {
final Uri uri = UserSupport.DeviceIssue.UNSTABLE_BLUETOOTH.getUri();
withAction(uri.toString(), R.string.action_more_info);
withAddendum(R.string.error_addendum_unstable_stack);
return this;
}
}
}
| hello/suripu-android | app/src/main/java/is/hello/sense/ui/dialogs/ErrorDialogFragment.java | 2,776 | /**
* See {@link is.hello.sense.ui.dialogs.ErrorDialogFragment.PresenterBuilder}
*/ | block_comment | nl | package is.hello.sense.ui.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.text.SpannableStringBuilder;
import is.hello.buruberi.bluetooth.errors.BuruberiException;
import is.hello.commonsense.util.Errors;
import is.hello.commonsense.util.StringRef;
import is.hello.sense.R;
import is.hello.sense.api.model.ApiException;
import is.hello.sense.ui.common.SenseDialogFragment;
import is.hello.sense.ui.common.UserSupport;
import is.hello.sense.ui.widget.SenseAlertDialog;
import is.hello.sense.ui.widget.util.Styles;
import is.hello.sense.util.Analytics;
public class ErrorDialogFragment extends SenseDialogFragment {
public static final String TAG = ErrorDialogFragment.class.getSimpleName();
private static final String ARG_MESSAGE = ErrorDialogFragment.class.getName() + ".ARG_MESSAGE";
private static final String ARG_ERROR_TYPE = ErrorDialogFragment.class.getName() + ".ARG_ERROR_TYPE";
private static final String ARG_IS_WARNING = ErrorDialogFragment.class.getName() + ".ARG_IS_WARNING";
private static final String ARG_CONTEXT_INFO = ErrorDialogFragment.class.getName() + ".ARG_CONTEXT_INFO";
private static final String ARG_OPERATION = ErrorDialogFragment.class.getName() + ".ARG_OPERATION";
private static final String ARG_SHOW_SUPPORT_LINK = ErrorDialogFragment.class.getName() + ".ARG_SHOW_SUPPORT_LINK";
private static final String ARG_ADDENDUM_RES = ErrorDialogFragment.class.getName() + ".ARG_ADDENDUM_RES";
private static final String ARG_ACTION_INTENT = ErrorDialogFragment.class.getName() + ".ARG_ACTION_INTENT";
private static final String ARG_ACTION_RESULT_CODE = ErrorDialogFragment.class.getName() + ".ARG_ACTION_RESULT_CODE";
private static final String ARG_ACTION_TITLE_RES = ErrorDialogFragment.class.getName() + ".ARG_ACTION_TITLE_RES";
private static final String ARG_TITLE_RES = ErrorDialogFragment.class.getName() + ".ARG_TITLE_RES";
private static final String ARG_TITLE_REF = ErrorDialogFragment.class.getName() + ".ARG_TITLE_REF";
private static final String ARG_ACTION_URI_STRING = ErrorDialogFragment.class.getName() + ".ARG_ACTION_URI_STRING";
//region Lifecycle
public static void presentError(@NonNull final Activity activity, @Nullable final Throwable e, @StringRes final int titleRes) {
final ErrorDialogFragment fragment = newInstance(e).withTitle(titleRes)
.build();
fragment.showAllowingStateLoss(activity.getFragmentManager(), TAG);
}
public static void presentError(@NonNull final Activity activity, @Nullable final Throwable e) {
presentError(activity, e, R.string.dialog_error_title);
}
public static PresenterBuilder newInstance(@Nullable final Throwable e) {
return new PresenterBuilder(e);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(true);
}
@Override
public
@NonNull
Dialog onCreateDialog(final Bundle savedInstanceState) {
final SenseAlertDialog dialog = new SenseAlertDialog(getActivity());
final CharSequence message = generateDisplayMessage();
dialog.setMessage(message);
final Bundle arguments = getArguments();
final int titleResId = arguments.getInt(ARG_TITLE_RES, R.string.dialog_error_title);
dialog.setTitle(titleResId);
if (arguments.containsKey(ARG_TITLE_REF)){
final StringRef title = arguments.getParcelable(ARG_TITLE_REF);
if (title != null) {
dialog.setTitle(title.resolve(getActivity()));
}
}
final String errorType = arguments.getString(ARG_ERROR_TYPE);
final String contextInfo = arguments.getString(ARG_CONTEXT_INFO);
final String operation = arguments.getString(ARG_OPERATION);
final boolean isWarning = arguments.getBoolean(ARG_IS_WARNING);
trackError(message.toString(), errorType, contextInfo, operation, isWarning);
if (getTargetFragment() != null) {
dialog.setPositiveButton(android.R.string.ok, (ignored, which) -> {
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
});
} else {
dialog.setPositiveButton(android.R.string.ok, null);
}
if (arguments.containsKey(ARG_ACTION_TITLE_RES)) {
final int titleRes = arguments.getInt(ARG_ACTION_TITLE_RES);
dialog.setButtonDeemphasized(DialogInterface.BUTTON_NEGATIVE, true);
if (arguments.containsKey(ARG_ACTION_INTENT)) {
dialog.setNegativeButton(titleRes, (button, which) -> {
final Intent intent = arguments.getParcelable(ARG_ACTION_INTENT);
startActivity(intent);
});
} else if (arguments.containsKey(ARG_ACTION_URI_STRING)) {
dialog.setNegativeButton(titleRes, (button, which) -> {
final Uri uri = Uri.parse(arguments.getString(ARG_ACTION_URI_STRING));
UserSupport.openUri(getActivity(), uri);
});
} else {
dialog.setNegativeButton(titleRes, (button, which) -> {
if (getTargetFragment() != null) {
final int resultCode = arguments.getInt(ARG_ACTION_RESULT_CODE);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, null);
}
});
}
}
return dialog;
}
//endregion
//region Internal
/**
* Hook for test case.
*/
@VisibleForTesting
void trackError(@NonNull final String message,
@Nullable final String errorType,
@Nullable final String errorContext,
@Nullable final String errorOperation,
final boolean isWarning) {
Analytics.trackError(message, errorType, errorContext, errorOperation, isWarning);
}
@VisibleForTesting
CharSequence generateDisplayMessage() {
final Bundle arguments = getArguments();
CharSequence message;
final StringRef errorMessage = arguments.getParcelable(ARG_MESSAGE);
if (errorMessage != null) {
message = errorMessage.resolve(getActivity());
} else {
message = getString(R.string.dialog_error_generic_message);
}
if (arguments.containsKey(ARG_ADDENDUM_RES)) {
final SpannableStringBuilder plusAddendum = new SpannableStringBuilder(message);
final int fatalMessageRes = arguments.getInt(ARG_ADDENDUM_RES);
plusAddendum.append(getText(fatalMessageRes));
message = plusAddendum;
}
if (arguments.getBoolean(ARG_SHOW_SUPPORT_LINK, false)) {
final SpannableStringBuilder plusSupportLink = Styles.resolveSupportLinks(getActivity(),
getText(R.string.error_addendum_support));
plusSupportLink.insert(0, message);
message = plusSupportLink;
}
return message;
}
//endregion
public static class Builder {
protected final Bundle arguments = new Bundle();
/**
* See {@link is.hello.sense.ui.dialogs.ErrorDialogFragment.PresenterBuilder}<SUF>*/
public Builder() {
}
@Deprecated
public Builder(@Nullable final Throwable e, @NonNull final Context context) {
withMessage(Errors.getDisplayMessage(e));
withErrorType(Errors.getType(e));
withContextInfo(Errors.getContextInfo(e));
withWarning(ApiException.isNetworkError(e));
if (BuruberiException.isInstabilityLikely(e)) {
withUnstableBluetoothHelp(context);
}
}
public Builder withTitle(@StringRes final int titleRes) {
arguments.putInt(ARG_TITLE_RES, titleRes);
return this;
}
public Builder withTitle(final StringRef titleRef) {
arguments.putParcelable(ARG_TITLE_REF, titleRef);
return this;
}
public Builder withMessage(@Nullable final StringRef message) {
arguments.putParcelable(ARG_MESSAGE, message);
return this;
}
public Builder withErrorType(@Nullable final String type) {
arguments.putString(ARG_ERROR_TYPE, type);
return this;
}
public Builder withWarning(final boolean isWarning) {
arguments.putBoolean(ARG_IS_WARNING, isWarning);
return this;
}
public Builder withContextInfo(@Nullable final String contextInfo) {
arguments.putString(ARG_CONTEXT_INFO, contextInfo);
return this;
}
public Builder withOperation(@Nullable final String operation) {
arguments.putString(ARG_OPERATION, operation);
return this;
}
public Builder withSupportLink() {
arguments.putBoolean(ARG_SHOW_SUPPORT_LINK, true);
return this;
}
public Builder withAddendum(@StringRes final int messageRes) {
arguments.putInt(ARG_ADDENDUM_RES, messageRes);
return this;
}
public Builder withAction(@NonNull final Intent intent, @StringRes final int titleRes) {
arguments.putParcelable(ARG_ACTION_INTENT, intent);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
public Builder withAction(final int resultCode, @StringRes final int titleRes) {
arguments.putInt(ARG_ACTION_RESULT_CODE, resultCode);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
public Builder withAction(@NonNull final String uriString, @StringRes final int titleRes) {
arguments.putString(ARG_ACTION_URI_STRING, uriString);
arguments.putInt(ARG_ACTION_TITLE_RES, titleRes);
return this;
}
@Deprecated
public Builder withUnstableBluetoothHelp(@NonNull final Context context) {
final Uri uri = UserSupport.DeviceIssue.UNSTABLE_BLUETOOTH.getUri();
final Intent intent = UserSupport.createViewUriIntent(context, uri);
withAction(intent, R.string.action_more_info);
withAddendum(R.string.error_addendum_unstable_stack);
return this;
}
public ErrorDialogFragment build() {
final ErrorDialogFragment instance = new ErrorDialogFragment();
instance.setArguments(arguments);
return instance;
}
}
public static class PresenterBuilder extends Builder {
public PresenterBuilder(@Nullable final Throwable e) {
withMessage(Errors.getDisplayMessage(e));
withErrorType(Errors.getType(e));
withContextInfo(Errors.getContextInfo(e));
withWarning(ApiException.isNetworkError(e));
if (BuruberiException.isInstabilityLikely(e)) {
withUnstableBluetoothHelp();
}
}
public Builder withUnstableBluetoothHelp() {
final Uri uri = UserSupport.DeviceIssue.UNSTABLE_BLUETOOTH.getUri();
withAction(uri.toString(), R.string.action_more_info);
withAddendum(R.string.error_addendum_unstable_stack);
return this;
}
}
}
|
74842_39 | package nl.markrensen.aoc.days;
import nl.markrensen.aoc.common.Day;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Day10 implements Day<Long> {
final char VER = '|';
final char HOR = '-';
final char NE = 'L';
final char NW = 'J';
final char SW = '7';
final char SE = 'F';
final char GRO = '.';
final char STA = 'S';
@Override
public Long part1(List<String> input) {
return parse(input, false);
}
@Override
public Long part2(List<String> input) {
return parse(input, true);
}
public enum Orientation{
UP,DOWN,LEFT,RIGHT, NONE
}
public class Point{
public int i;
public int j;
public char value;
public Point previous;
public Orientation orientation;
public int id = -1;
public Point(){
this.i=-1;
this.j=-1;
};
public Point(int i, int j, char value) {
this.i = i;
this.j = j;
this.value = value;
}
}
private long parse(List<String> input, boolean part2) {
Point[][] board = new Point[input.size()][input.get(0).length()];
boolean[][] visited = new boolean[board.length][board[0].length];
// int SI = -1;
// int SJ = -1;
Point S = new Point();
for(int i = 0; i < input.size(); i++){
char[] chars = input.get(i).toCharArray();
for(int j = 0; j < input.get(0).length(); j++) {
board[i][j] = new Point(i,j,chars[j]);
int SJcheck = input.get(i).indexOf("S");
if (SJcheck > -1) {
S.j = SJcheck;
S.i = i;
S.value = 'S';
}
}
}
// // check welke richting op
// System.out.println(SI);
// System.out.println(SJ);
// System.out.println("i+1 => 7 ? " + board[SI+1][SJ]); //omlaag
// System.out.println("i-1 => 7 ? " + board[SI-1][SJ]); //omhoog
// System.out.println("j-1 => J ? " + board[SI][SJ-1]); //links
// System.out.println("j+1 => - ? " + board[SI][SJ+1]); //rechts
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
// List<Integer> iList = new ArrayList<>();
// List<Integer> jList = new ArrayList<>();
List<Point> pList = new ArrayList<>();
// iList.add(SI);
// jList.add(SJ);
pList.add(S);
// current coords
// int X.i = -1;
// int X.j = -1;
Point X = new Point(-1,-1,'0');
X.previous = new Point(-1,-1,'0');
// previous coords
// int X.previous.i = -1;
// int X.previous.j = -1;
while(X.i!=S.i || X.j!=S.j){
if(X.i == -1 && X.j == -1){
X.i = S.i;
X.j = S.j;
}
char node = board[X.i][X.j].value;
if(node == STA){
boolean first, second, third, fourth;
try {
first = board[X.i+1][X.j].value == NE || board[X.i+1][X.j].value == NW|| board[X.i+1][X.j].value == VER;
} catch (IndexOutOfBoundsException e){ first = false;}
try {
second = board[X.i-1][X.j].value == SE || board[X.i-1][X.j].value == SW|| board[X.i-1][X.j].value == VER;
} catch (IndexOutOfBoundsException e){second = false;}
try{
third = board[X.i][X.j-1].value == NW || board[X.i][X.j-1].value == SW|| board[X.i][X.j-1].value == HOR;
} catch (IndexOutOfBoundsException e){third = false;}
try{
fourth = board[X.i][X.j+1].value == NE || board[X.i][X.j+1].value == SE|| board[X.i][X.j+1].value == HOR;
} catch (IndexOutOfBoundsException e){fourth = false;}
if(first){ // move down
X.i = X.i+1;
} else if(second){ //move up
X.i=X.i-1;
} else if(third){ //move left
X.j = X.j-1;
} else if(fourth){ //move right
X.j = X.j+1;
}
X.previous.i = S.i;
X.previous.j = S.j;
} else {
switch (node){
case NE -> {
if(X.j == X.previous.j) {
X.previous.j = X.j;
X.previous.i = X.i;
X.j++;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case NW -> {
if(X.j == X.previous.j) {
X.previous.j = X.j;
X.previous.i=X.i;
X.j--;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case SE -> {
if (X.j == X.previous.j) {
X.previous.i = X.i;
X.previous.j=X.j;
X.j++; /**/
} else {
X.previous.j = X.j;
X.previous.i=X.i;
X.i++;
}
}
case SW -> {
if(X.j == X.previous.j){
X.previous.i = X.i;
X.previous.j=X.j;
X.j--;
} else {
X.previous.j=X.j;
X.previous.i=X.i;
X.i++;
}
}
case HOR -> {
if(X.previous.j < X.j){
X.previous.j = X.j;
X.previous.i=X.i;
X.j++;
} else {
X.previous.j=X.j;
X.previous.i=X.i;
X.j--;
}
}
case VER -> {
if(X.previous.i < X.i){
X.previous.i = X.i;
X.previous.j=X.j;
X.i++;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case GRO -> throw new RuntimeException("hit the ground");
default -> throw new RuntimeException("should not hit default");
}
}
Point p = board[X.i][X.j];
visited[X.i][X.j] = true;
p.previous = pList.get(pList.size()-1);
p.id = 0;
p.orientation = getOrientationLeft(X);
pList.add(p);
}
// close the loop.
S.previous = board[X.i][X.j];
S.orientation = getOrientationLeft(S);
pList.remove(0);
if(part2){
// boolean keepgoing = true;
// int currentId = 0;
// while (keepgoing){
// boolean[][] visited = new boolean[board.length][board[0].length];
// for(Point[] row : board){
// Point usePoint = null;
// for (Point p : row){
// if(isValidPoint(p, board, -1, visited)){
// usePoint = p;
// }
// }
// if(usePoint == null){
// keepgoing = false;
// break;
// } else {
// currentId++;
// visited = new boolean[board.length][board[0].length];
// floodFill(usePoint, currentId, board, visited);
// }
// }
// }
boolean keepgoing = true;
// while (keepgoing) {
int id = 1;
for(Point p : pList.reversed()){
// Point p = pList.get(i);
checkLeft(p, id, board, visited);
}
// keepgoing = containsUnvisited(board);
// }
// loop while still -1 id's
// do fill-algoritm as soon as you find a -1 id to change all -1 id's in reach to a new id (2)
// id++
// do another search for for a -1 id and do a fill algortim on that to change the id (to 3)
// id++
// etc
// check how many different id's have been used and count how many fields each id has. (id 1 is for the tubes in the actual loop)
// combine and make a guess.
printboard(board);
return countnests(board);
}
return (long) pList.size() / 2;
}
private long countnests(Point[][] board) {
long count = 0L;
for (Point[] ps : board){
for (Point p: ps){
if(p.id == 1 && p.i >0 && p.j > 0){
count++;
}
// 441 -> too high
// 341 -> wrong
// 162 -> too low
}
}
return count;
}
private void checkLeft(Point p, int id, Point[][] board, boolean[][] visited) {
Point leftp = null;
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
if(p.i==8 && p.j==5){
System.out.println();
}
// System.out.println("( " + p.i + " , " + p.j + " )");
// printboard(board);
switch(p.orientation){
case LEFT -> {
if (isValid(p.i+1, p.j, board, visited)) {
// visited[p.i+1][p.j] = true;
leftp = board[p.i+1][p.j];
}
}
case RIGHT -> {
if(isValid(p.i-1, p.j, board, visited)){
// visited[p.i-1][p.j] = true;
leftp = board[p.i-1][p.j];
}
}
case UP -> {
if(isValid(p.i, p.j-1, board, visited)){
// visited[p.i][p.j-1] = true;
leftp = board[p.i][p.j-1];
}
}
case DOWN -> {
if(isValid(p.i, p.j+1, board, visited)){
// visited[p.i][p.j+1] = true;
leftp = board[p.i][p.j+1];
}
}
default -> throw new RuntimeException("what is going on?!!!");
}
if(leftp != null) {
try {
List<Point> toPaint = floodFill(leftp, id, board, visited);
for(Point paint : toPaint){
paint.id=1;
}
}catch(FloodException ignore){}
}
}
private boolean containsUnvisited(Point[][] board){
for(Point[] ps : board){
for(Point p : ps){
if(p.id == -1){
return true;
}
}
}
return false;
}
private Orientation getOrientationLeft(Point x){
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
if(x.previous.i > x.i){
return Orientation.UP;
}
if(x.previous.i < x.i){
return Orientation.DOWN;
}
if(x.previous.j < x.j){
return Orientation.RIGHT;
}
if(x.previous.j > x.j){
return Orientation.LEFT;
}
return Orientation.NONE;
}
private Orientation getOrientationRight(Point x) {
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
if(x.previous.i > x.i){
return Orientation.DOWN;
}
if(x.previous.i < x.i){
return Orientation.UP;
}
if(x.previous.j < x.j){
return Orientation.LEFT;
}
if(x.previous.j > x.j){
return Orientation.RIGHT;
}
return Orientation.NONE;
}
private class FloodException extends RuntimeException{
}
private List<Point> floodFill (Point p, int id, Point[][] board, boolean[][] visited){
List<Point> points = new ArrayList<>();
int[] deltai = new int[]{1,-1,0,0};
int[] deltaj = new int[]{0,0,1,-1};
visited[p.i][p.j] = true;
//TODO set "id" or "1"
p.id = 1;
for(int i = 0; i < deltai.length; i++){
int newi =p.i + deltai[i];
int newj = p.j + deltaj[i];
if(isValid(newi, newj, board, visited)){
Point n = board[newi][newj];
points.addAll(floodFill(n, id, board, visited));
} else if(newi < 1 || newj < 1 || newi > board.length -1 || newj > board[0].length -1){
throw new FloodException();
}
}
return points;
}
private boolean isValid(int i, int j, Point[][] board, boolean[][] visited){
if (i < 1 || i >= board.length-1){
return false;
}
if (j < 1 || j >= board[0].length-1){
return false;
}
Point p = board[i][j];
if(p.id != -1 || visited[p.i][p.j]){
return false;
}
return true;
}
private boolean isValidPoint(Point p, Point[][] board, int id, boolean[][] visited){
if (p.i < 0 || p.i > board.length){
return false;
}
if (p.j < 0 || p.j > board[0].length){
return false;
}
if(p.id != id || visited[p.i][p.j]){
return false;
}
return true;
}
private void printboard(Point[][] board){
int i = 0;
System.out.print(" |");
for(int j = 0; j < board[0].length; j++){
if(j<10){
System.out.print(" " + j);
} else{
System.out.print(j);
}
}
System.out.print("\n");
for(Point[] points : board){
if(i < 10){
System.out.print(" ");
}
System.out.print(i + " |");
for (Point p : points){
if(p.id>=0){
System.out.print(" ");
}
System.out.print(p.id);
}
System.out.print("\n");
i++;
}
}
}
| MRensen/aoc2023 | src/main/java/nl/markrensen/aoc/days/Day10.java | 4,227 | /*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/ | block_comment | nl | package nl.markrensen.aoc.days;
import nl.markrensen.aoc.common.Day;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Day10 implements Day<Long> {
final char VER = '|';
final char HOR = '-';
final char NE = 'L';
final char NW = 'J';
final char SW = '7';
final char SE = 'F';
final char GRO = '.';
final char STA = 'S';
@Override
public Long part1(List<String> input) {
return parse(input, false);
}
@Override
public Long part2(List<String> input) {
return parse(input, true);
}
public enum Orientation{
UP,DOWN,LEFT,RIGHT, NONE
}
public class Point{
public int i;
public int j;
public char value;
public Point previous;
public Orientation orientation;
public int id = -1;
public Point(){
this.i=-1;
this.j=-1;
};
public Point(int i, int j, char value) {
this.i = i;
this.j = j;
this.value = value;
}
}
private long parse(List<String> input, boolean part2) {
Point[][] board = new Point[input.size()][input.get(0).length()];
boolean[][] visited = new boolean[board.length][board[0].length];
// int SI = -1;
// int SJ = -1;
Point S = new Point();
for(int i = 0; i < input.size(); i++){
char[] chars = input.get(i).toCharArray();
for(int j = 0; j < input.get(0).length(); j++) {
board[i][j] = new Point(i,j,chars[j]);
int SJcheck = input.get(i).indexOf("S");
if (SJcheck > -1) {
S.j = SJcheck;
S.i = i;
S.value = 'S';
}
}
}
// // check welke richting op
// System.out.println(SI);
// System.out.println(SJ);
// System.out.println("i+1 => 7 ? " + board[SI+1][SJ]); //omlaag
// System.out.println("i-1 => 7 ? " + board[SI-1][SJ]); //omhoog
// System.out.println("j-1 => J ? " + board[SI][SJ-1]); //links
// System.out.println("j+1 => - ? " + board[SI][SJ+1]); //rechts
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
// List<Integer> iList = new ArrayList<>();
// List<Integer> jList = new ArrayList<>();
List<Point> pList = new ArrayList<>();
// iList.add(SI);
// jList.add(SJ);
pList.add(S);
// current coords
// int X.i = -1;
// int X.j = -1;
Point X = new Point(-1,-1,'0');
X.previous = new Point(-1,-1,'0');
// previous coords
// int X.previous.i = -1;
// int X.previous.j = -1;
while(X.i!=S.i || X.j!=S.j){
if(X.i == -1 && X.j == -1){
X.i = S.i;
X.j = S.j;
}
char node = board[X.i][X.j].value;
if(node == STA){
boolean first, second, third, fourth;
try {
first = board[X.i+1][X.j].value == NE || board[X.i+1][X.j].value == NW|| board[X.i+1][X.j].value == VER;
} catch (IndexOutOfBoundsException e){ first = false;}
try {
second = board[X.i-1][X.j].value == SE || board[X.i-1][X.j].value == SW|| board[X.i-1][X.j].value == VER;
} catch (IndexOutOfBoundsException e){second = false;}
try{
third = board[X.i][X.j-1].value == NW || board[X.i][X.j-1].value == SW|| board[X.i][X.j-1].value == HOR;
} catch (IndexOutOfBoundsException e){third = false;}
try{
fourth = board[X.i][X.j+1].value == NE || board[X.i][X.j+1].value == SE|| board[X.i][X.j+1].value == HOR;
} catch (IndexOutOfBoundsException e){fourth = false;}
if(first){ // move down
X.i = X.i+1;
} else if(second){ //move up
X.i=X.i-1;
} else if(third){ //move left
X.j = X.j-1;
} else if(fourth){ //move right
X.j = X.j+1;
}
X.previous.i = S.i;
X.previous.j = S.j;
} else {
switch (node){
case NE -> {
if(X.j == X.previous.j) {
X.previous.j = X.j;
X.previous.i = X.i;
X.j++;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case NW -> {
if(X.j == X.previous.j) {
X.previous.j = X.j;
X.previous.i=X.i;
X.j--;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case SE -> {
if (X.j == X.previous.j) {
X.previous.i = X.i;
X.previous.j=X.j;
X.j++; /**/
} else {
X.previous.j = X.j;
X.previous.i=X.i;
X.i++;
}
}
case SW -> {
if(X.j == X.previous.j){
X.previous.i = X.i;
X.previous.j=X.j;
X.j--;
} else {
X.previous.j=X.j;
X.previous.i=X.i;
X.i++;
}
}
case HOR -> {
if(X.previous.j < X.j){
X.previous.j = X.j;
X.previous.i=X.i;
X.j++;
} else {
X.previous.j=X.j;
X.previous.i=X.i;
X.j--;
}
}
case VER -> {
if(X.previous.i < X.i){
X.previous.i = X.i;
X.previous.j=X.j;
X.i++;
} else {
X.previous.i = X.i;
X.previous.j=X.j;
X.i--;
}
}
case GRO -> throw new RuntimeException("hit the ground");
default -> throw new RuntimeException("should not hit default");
}
}
Point p = board[X.i][X.j];
visited[X.i][X.j] = true;
p.previous = pList.get(pList.size()-1);
p.id = 0;
p.orientation = getOrientationLeft(X);
pList.add(p);
}
// close the loop.
S.previous = board[X.i][X.j];
S.orientation = getOrientationLeft(S);
pList.remove(0);
if(part2){
// boolean keepgoing = true;
// int currentId = 0;
// while (keepgoing){
// boolean[][] visited = new boolean[board.length][board[0].length];
// for(Point[] row : board){
// Point usePoint = null;
// for (Point p : row){
// if(isValidPoint(p, board, -1, visited)){
// usePoint = p;
// }
// }
// if(usePoint == null){
// keepgoing = false;
// break;
// } else {
// currentId++;
// visited = new boolean[board.length][board[0].length];
// floodFill(usePoint, currentId, board, visited);
// }
// }
// }
boolean keepgoing = true;
// while (keepgoing) {
int id = 1;
for(Point p : pList.reversed()){
// Point p = pList.get(i);
checkLeft(p, id, board, visited);
}
// keepgoing = containsUnvisited(board);
// }
// loop while still -1 id's
// do fill-algoritm as soon as you find a -1 id to change all -1 id's in reach to a new id (2)
// id++
// do another search for for a -1 id and do a fill algortim on that to change the id (to 3)
// id++
// etc
// check how many different id's have been used and count how many fields each id has. (id 1 is for the tubes in the actual loop)
// combine and make a guess.
printboard(board);
return countnests(board);
}
return (long) pList.size() / 2;
}
private long countnests(Point[][] board) {
long count = 0L;
for (Point[] ps : board){
for (Point p: ps){
if(p.id == 1 && p.i >0 && p.j > 0){
count++;
}
// 441 -> too high
// 341 -> wrong
// 162 -> too low
}
}
return count;
}
private void checkLeft(Point p, int id, Point[][] board, boolean[][] visited) {
Point leftp = null;
/*
i+ -> omlaag<SUF>*/
if(p.i==8 && p.j==5){
System.out.println();
}
// System.out.println("( " + p.i + " , " + p.j + " )");
// printboard(board);
switch(p.orientation){
case LEFT -> {
if (isValid(p.i+1, p.j, board, visited)) {
// visited[p.i+1][p.j] = true;
leftp = board[p.i+1][p.j];
}
}
case RIGHT -> {
if(isValid(p.i-1, p.j, board, visited)){
// visited[p.i-1][p.j] = true;
leftp = board[p.i-1][p.j];
}
}
case UP -> {
if(isValid(p.i, p.j-1, board, visited)){
// visited[p.i][p.j-1] = true;
leftp = board[p.i][p.j-1];
}
}
case DOWN -> {
if(isValid(p.i, p.j+1, board, visited)){
// visited[p.i][p.j+1] = true;
leftp = board[p.i][p.j+1];
}
}
default -> throw new RuntimeException("what is going on?!!!");
}
if(leftp != null) {
try {
List<Point> toPaint = floodFill(leftp, id, board, visited);
for(Point paint : toPaint){
paint.id=1;
}
}catch(FloodException ignore){}
}
}
private boolean containsUnvisited(Point[][] board){
for(Point[] ps : board){
for(Point p : ps){
if(p.id == -1){
return true;
}
}
}
return false;
}
private Orientation getOrientationLeft(Point x){
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
if(x.previous.i > x.i){
return Orientation.UP;
}
if(x.previous.i < x.i){
return Orientation.DOWN;
}
if(x.previous.j < x.j){
return Orientation.RIGHT;
}
if(x.previous.j > x.j){
return Orientation.LEFT;
}
return Orientation.NONE;
}
private Orientation getOrientationRight(Point x) {
/*
i+ -> omlaag
i- -> omhoog
j+ -> rechts
j- -> links
*/
if(x.previous.i > x.i){
return Orientation.DOWN;
}
if(x.previous.i < x.i){
return Orientation.UP;
}
if(x.previous.j < x.j){
return Orientation.LEFT;
}
if(x.previous.j > x.j){
return Orientation.RIGHT;
}
return Orientation.NONE;
}
private class FloodException extends RuntimeException{
}
private List<Point> floodFill (Point p, int id, Point[][] board, boolean[][] visited){
List<Point> points = new ArrayList<>();
int[] deltai = new int[]{1,-1,0,0};
int[] deltaj = new int[]{0,0,1,-1};
visited[p.i][p.j] = true;
//TODO set "id" or "1"
p.id = 1;
for(int i = 0; i < deltai.length; i++){
int newi =p.i + deltai[i];
int newj = p.j + deltaj[i];
if(isValid(newi, newj, board, visited)){
Point n = board[newi][newj];
points.addAll(floodFill(n, id, board, visited));
} else if(newi < 1 || newj < 1 || newi > board.length -1 || newj > board[0].length -1){
throw new FloodException();
}
}
return points;
}
private boolean isValid(int i, int j, Point[][] board, boolean[][] visited){
if (i < 1 || i >= board.length-1){
return false;
}
if (j < 1 || j >= board[0].length-1){
return false;
}
Point p = board[i][j];
if(p.id != -1 || visited[p.i][p.j]){
return false;
}
return true;
}
private boolean isValidPoint(Point p, Point[][] board, int id, boolean[][] visited){
if (p.i < 0 || p.i > board.length){
return false;
}
if (p.j < 0 || p.j > board[0].length){
return false;
}
if(p.id != id || visited[p.i][p.j]){
return false;
}
return true;
}
private void printboard(Point[][] board){
int i = 0;
System.out.print(" |");
for(int j = 0; j < board[0].length; j++){
if(j<10){
System.out.print(" " + j);
} else{
System.out.print(j);
}
}
System.out.print("\n");
for(Point[] points : board){
if(i < 10){
System.out.print(" ");
}
System.out.print(i + " |");
for (Point p : points){
if(p.id>=0){
System.out.print(" ");
}
System.out.print(p.id);
}
System.out.print("\n");
i++;
}
}
}
|
74859_2 | package com.games.Android.Laser_Cube.Objects;
import java.util.ArrayList;
import com.games.Android.Laser_Cube.Load.Vector;
public class Laser
{
private float level = 0;
private float breedte = 85;
private float hoogte = 45;
public float laser_time_opening = 0.4f;
public float laser_time_level1 = 1f;
public float Speed = 2.5f;
public Vector position = new Vector( );
public boolean Weg = false;
public boolean laser_weg = false;
//up/down or left/right
public boolean vertical = true;
//when up/down up or down, when left/right left or right, true is up for up/down and left for left/right
public boolean up_left = true;
private float laser_y = 100;
private float laser_x = 100;
private float laser_y_end = 100;
private float laser_x_end = 100;
private float length_laser = 0;
public float laser_size = 0f;
private float[] distance_cube = new float[30];
private float[] distance_mirror = new float[30];
private float[] distance_block = new float[30];
private float[] distance_radiation_tile = new float[30];
private float[] distance_colour_changer = new float[30];
private float distance_opening_tile = 100;
public boolean touched_opening_tile = false;
public boolean[] touched_radiation_tile = new boolean[30];
public boolean[] touched_block = new boolean[30];
//de 4 zijden van de mirrors
public boolean[] touched_mirror_top = new boolean[30];
public boolean[] touched_mirror_bottom = new boolean[30];
public boolean[] touched_mirror_left = new boolean[30];
public boolean[] touched_mirror_right = new boolean[30];
public boolean[] touched_colour_changer_top = new boolean[30];
public boolean[] touched_colour_changer_bottom = new boolean[30];
public boolean[] touched_colour_changer_left = new boolean[30];
public boolean[] touched_colour_changer_right = new boolean[30];
private float stroom = 0;
private int number_of_cubes = 0;
private int number_of_mirrors = 0;
private int number_of_radiation_tiles = 0;
private int number_of_blocks = 0;
private int number_of_colour_changers = 0;
public void Level( ArrayList<Cube> cubes, ArrayList<Mirror> mirrors, ArrayList<Radiation_Tile> radiation_tiles, ArrayList<Block> blocks, ArrayList<Colour_Changer> colour_changers )
{
reset_variabels();
if( mirrors == null )
{
number_of_mirrors = 0;
}
else
{
number_of_mirrors = ( mirrors.size() - 1 );
}
if( cubes == null )
{
number_of_cubes = 0;
}
else
{
number_of_cubes = ( cubes.size() - 1 );
}
if( radiation_tiles == null )
{
number_of_radiation_tiles = 0;
}
else
{
number_of_radiation_tiles = ( radiation_tiles.size() - 1 );
}
if( blocks == null )
{
number_of_blocks = 0;
}
else
{
number_of_blocks = ( blocks.size() - 1 );
}
if( colour_changers == null )
{
number_of_colour_changers = 0;
}
else
{
number_of_colour_changers = ( colour_changers.size() - 1 );
}
for( int i = 1; i <= number_of_cubes; i++ )
{
distance_cube[i] = cubes.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_mirrors; i++ )
{
distance_mirror[i] = mirrors.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_radiation_tiles; i++ )
{
distance_radiation_tile[i] = radiation_tiles.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_blocks; i++ )
{
distance_block[i] = blocks.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_colour_changers; i++ )
{
distance_colour_changer[i] = colour_changers.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
level = 1;
}
public void Opening_Screen( ArrayList<Mirror> mirrors )
{
reset_variabels();
distance_mirror[1] = mirrors.get(1).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[2] = mirrors.get(2).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[3] = mirrors.get(3).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[4] = mirrors.get(4).position.distance( new Vector( laser_x, laser_y, 0));
level = 8008;
}
private void reset_variabels()
{
for( int k = 0; k < 30; k++)
{
distance_mirror[k] = 100;
distance_radiation_tile[k] = 100;
distance_cube[k] = 100;
distance_block[k] = 100;
distance_colour_changer[k] = 100;
}
}
public void direction (boolean vertical, boolean up_left)
{
this.vertical = vertical;
this.up_left = up_left;
}
public void update()
{
//de laser gaat verticaal
if( vertical )
{
laser_y = (position.y + (laser_size + laser_size));
laser_y_end = ( position.y + laser_size );
laser_x = position.x;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x, laser_y_end, 0));
//de laser gaat verticaal omhoog
if ( up_left )
{
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_bottom[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_bottom[i] = false;
}
}
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if ( laser_y >= hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( laser_y_end > laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//de laser gaat verticaal omlaag
else
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_top[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_top[i] = false;
}
}
if ( laser_y <= -hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( laser_y_end < laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//Log.d( " mirror ", " distance " + laser_y );
}
else
{
laser_x = (position.x + (laser_size + laser_size));
laser_x_end = ( position.x + laser_size );
laser_y = position.y;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x_end, laser_y, 0));
//de laser gaat left (links)
if( up_left )
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if (distance_opening_tile < 30 )
{
touched_opening_tile = true;
}
else
{
touched_opening_tile = false;
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_right[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_right[i] = false;
}
}
if ( laser_x >= breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end > laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
else
{
//de laser gaat naar rechts
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_left[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_left[i] = false;
}
}
if ( laser_x <= -breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end < laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
}
//Log.d( " mirror ", " distance " + laser_y);
}
} | Grabot/Laser-Cube | Laser_Cube/src/com/games/Android/Laser_Cube/Objects/Laser.java | 5,068 | //de 4 zijden van de mirrors | line_comment | nl | package com.games.Android.Laser_Cube.Objects;
import java.util.ArrayList;
import com.games.Android.Laser_Cube.Load.Vector;
public class Laser
{
private float level = 0;
private float breedte = 85;
private float hoogte = 45;
public float laser_time_opening = 0.4f;
public float laser_time_level1 = 1f;
public float Speed = 2.5f;
public Vector position = new Vector( );
public boolean Weg = false;
public boolean laser_weg = false;
//up/down or left/right
public boolean vertical = true;
//when up/down up or down, when left/right left or right, true is up for up/down and left for left/right
public boolean up_left = true;
private float laser_y = 100;
private float laser_x = 100;
private float laser_y_end = 100;
private float laser_x_end = 100;
private float length_laser = 0;
public float laser_size = 0f;
private float[] distance_cube = new float[30];
private float[] distance_mirror = new float[30];
private float[] distance_block = new float[30];
private float[] distance_radiation_tile = new float[30];
private float[] distance_colour_changer = new float[30];
private float distance_opening_tile = 100;
public boolean touched_opening_tile = false;
public boolean[] touched_radiation_tile = new boolean[30];
public boolean[] touched_block = new boolean[30];
//de 4<SUF>
public boolean[] touched_mirror_top = new boolean[30];
public boolean[] touched_mirror_bottom = new boolean[30];
public boolean[] touched_mirror_left = new boolean[30];
public boolean[] touched_mirror_right = new boolean[30];
public boolean[] touched_colour_changer_top = new boolean[30];
public boolean[] touched_colour_changer_bottom = new boolean[30];
public boolean[] touched_colour_changer_left = new boolean[30];
public boolean[] touched_colour_changer_right = new boolean[30];
private float stroom = 0;
private int number_of_cubes = 0;
private int number_of_mirrors = 0;
private int number_of_radiation_tiles = 0;
private int number_of_blocks = 0;
private int number_of_colour_changers = 0;
public void Level( ArrayList<Cube> cubes, ArrayList<Mirror> mirrors, ArrayList<Radiation_Tile> radiation_tiles, ArrayList<Block> blocks, ArrayList<Colour_Changer> colour_changers )
{
reset_variabels();
if( mirrors == null )
{
number_of_mirrors = 0;
}
else
{
number_of_mirrors = ( mirrors.size() - 1 );
}
if( cubes == null )
{
number_of_cubes = 0;
}
else
{
number_of_cubes = ( cubes.size() - 1 );
}
if( radiation_tiles == null )
{
number_of_radiation_tiles = 0;
}
else
{
number_of_radiation_tiles = ( radiation_tiles.size() - 1 );
}
if( blocks == null )
{
number_of_blocks = 0;
}
else
{
number_of_blocks = ( blocks.size() - 1 );
}
if( colour_changers == null )
{
number_of_colour_changers = 0;
}
else
{
number_of_colour_changers = ( colour_changers.size() - 1 );
}
for( int i = 1; i <= number_of_cubes; i++ )
{
distance_cube[i] = cubes.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_mirrors; i++ )
{
distance_mirror[i] = mirrors.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_radiation_tiles; i++ )
{
distance_radiation_tile[i] = radiation_tiles.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_blocks; i++ )
{
distance_block[i] = blocks.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_colour_changers; i++ )
{
distance_colour_changer[i] = colour_changers.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
level = 1;
}
public void Opening_Screen( ArrayList<Mirror> mirrors )
{
reset_variabels();
distance_mirror[1] = mirrors.get(1).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[2] = mirrors.get(2).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[3] = mirrors.get(3).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[4] = mirrors.get(4).position.distance( new Vector( laser_x, laser_y, 0));
level = 8008;
}
private void reset_variabels()
{
for( int k = 0; k < 30; k++)
{
distance_mirror[k] = 100;
distance_radiation_tile[k] = 100;
distance_cube[k] = 100;
distance_block[k] = 100;
distance_colour_changer[k] = 100;
}
}
public void direction (boolean vertical, boolean up_left)
{
this.vertical = vertical;
this.up_left = up_left;
}
public void update()
{
//de laser gaat verticaal
if( vertical )
{
laser_y = (position.y + (laser_size + laser_size));
laser_y_end = ( position.y + laser_size );
laser_x = position.x;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x, laser_y_end, 0));
//de laser gaat verticaal omhoog
if ( up_left )
{
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_bottom[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_bottom[i] = false;
}
}
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if ( laser_y >= hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( laser_y_end > laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//de laser gaat verticaal omlaag
else
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_top[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_top[i] = false;
}
}
if ( laser_y <= -hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( laser_y_end < laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//Log.d( " mirror ", " distance " + laser_y );
}
else
{
laser_x = (position.x + (laser_size + laser_size));
laser_x_end = ( position.x + laser_size );
laser_y = position.y;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x_end, laser_y, 0));
//de laser gaat left (links)
if( up_left )
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if (distance_opening_tile < 30 )
{
touched_opening_tile = true;
}
else
{
touched_opening_tile = false;
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_right[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_right[i] = false;
}
}
if ( laser_x >= breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end > laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
else
{
//de laser gaat naar rechts
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_left[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_left[i] = false;
}
}
if ( laser_x <= -breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end < laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
}
//Log.d( " mirror ", " distance " + laser_y);
}
} |
157044_23 | /*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* 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 com.sun.org.apache.xerces.internal.dom;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.XSComplexTypeDecl;
import com.sun.org.apache.xerces.internal.util.URI;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
/**
* ElementNSImpl inherits from ElementImpl and adds namespace support.
* <P>
* The qualified name is the node name, and we store localName which is also
* used in all queries. On the other hand we recompute the prefix when
* necessary.
*
* @xerces.internal
*
* @author Elena litani, IBM
* @author Neeraj Bajaj, Sun Microsystems
*/
public class ElementNSImpl
extends ElementImpl {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = -9142310625494392642L;
static final String xmlURI = "http://www.w3.org/XML/1998/namespace";
//
// Data
//
/** DOM2: Namespace URI. */
protected String namespaceURI;
/** DOM2: localName. */
protected String localName;
/** DOM3: type information */
// REVISIT: we are losing the type information in DOM during serialization
transient XSTypeDefinition type;
protected ElementNSImpl() {
super();
}
/**
* DOM2: Constructor for Namespace implementation.
*/
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI,
String qualifiedName)
throws DOMException
{
super(ownerDocument, qualifiedName);
setName(namespaceURI, qualifiedName);
}
private void setName(String namespaceURI, String qname) {
String prefix;
// DOM Level 3: namespace URI is never empty string.
this.namespaceURI = namespaceURI;
if (namespaceURI != null) {
//convert the empty string to 'null'
this.namespaceURI = (namespaceURI.length() == 0) ? null : namespaceURI;
}
int colon1, colon2 ;
//NAMESPACE_ERR:
//1. if the qualified name is 'null' it is malformed.
//2. or if the qualifiedName is null and the namespaceURI is different from null,
// We dont need to check for namespaceURI != null, if qualified name is null throw DOMException.
if(qname == null){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
else{
colon1 = qname.indexOf(':');
colon2 = qname.lastIndexOf(':');
}
ownerDocument.checkNamespaceWF(qname, colon1, colon2);
if (colon1 < 0) {
// there is no prefix
localName = qname;
if (ownerDocument.errorChecking) {
ownerDocument.checkQName(null, localName);
if (qname.equals("xmlns")
&& (namespaceURI == null
|| !namespaceURI.equals(NamespaceContext.XMLNS_URI))
|| (namespaceURI!=null && namespaceURI.equals(NamespaceContext.XMLNS_URI)
&& !qname.equals("xmlns"))) {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}//there is a prefix
else {
prefix = qname.substring(0, colon1);
localName = qname.substring(colon2 + 1);
//NAMESPACE_ERR:
//1. if the qualifiedName has a prefix and the namespaceURI is null,
//2. or if the qualifiedName has a prefix that is "xml" and the namespaceURI
//is different from " http://www.w3.org/XML/1998/namespace"
if (ownerDocument.errorChecking) {
if( namespaceURI == null || ( prefix.equals("xml") && !namespaceURI.equals(NamespaceContext.XML_URI) )){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
ownerDocument.checkQName(prefix, localName);
ownerDocument.checkDOMNSErr(prefix, namespaceURI);
}
}
}
// when local name is known
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName)
throws DOMException
{
super(ownerDocument, qualifiedName);
this.localName = localName;
this.namespaceURI = namespaceURI;
}
// for DeferredElementImpl
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String value) {
super(ownerDocument, value);
}
// Support for DOM Level 3 renameNode method.
// Note: This only deals with part of the pb. CoreDocumentImpl
// does all the work.
void rename(String namespaceURI, String qualifiedName)
{
if (needsSyncData()) {
synchronizeData();
}
this.name = qualifiedName;
setName(namespaceURI, qualifiedName);
reconcileDefaultAttributes();
}
/**
* NON-DOM: resets this node and sets specified values for the node
*
* @param ownerDocument
* @param namespaceURI
* @param qualifiedName
* @param localName
*/
protected void setValues (CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName){
// remove children first
firstChild = null;
previousSibling = null;
nextSibling = null;
fNodeListCache = null;
// set owner document
attributes = null;
super.flags = 0;
setOwnerDocument(ownerDocument);
// synchronizeData will initialize attributes
needsSyncData(true);
super.name = qualifiedName;
this.localName = localName;
this.namespaceURI = namespaceURI;
}
//
// Node methods
//
//
//DOM2: Namespace methods.
//
/**
* Introduced in DOM Level 2. <p>
*
* The namespace URI of this node, or null if it is unspecified.<p>
*
* This is not a computed value that is the result of a namespace lookup based on
* an examination of the namespace declarations in scope. It is merely the
* namespace URI given at creation time.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null.
* @since WD-DOM-Level-2-19990923
*/
public String getNamespaceURI()
{
if (needsSyncData()) {
synchronizeData();
}
return namespaceURI;
}
/**
* Introduced in DOM Level 2. <p>
*
* The namespace prefix of this node, or null if it is unspecified. <p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null. <p>
*
* @since WD-DOM-Level-2-19990923
*/
public String getPrefix()
{
if (needsSyncData()) {
synchronizeData();
}
int index = name.indexOf(':');
return index < 0 ? null : name.substring(0, index);
}
/**
* Introduced in DOM Level 2. <p>
*
* Note that setting this attribute changes the nodeName attribute, which holds the
* qualified name, as well as the tagName and name attributes of the Element
* and Attr interfaces, when applicable.<p>
*
* @param prefix The namespace prefix of this node, or null(empty string) if it is unspecified.
*
* @exception INVALID_CHARACTER_ERR
* Raised if the specified
* prefix contains an invalid character.
* @exception DOMException
* @since WD-DOM-Level-2-19990923
*/
public void setPrefix(String prefix)
throws DOMException
{
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null);
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
msg);
}
if (prefix != null && prefix.length() != 0) {
if (!CoreDocumentImpl.isXMLName(prefix,ownerDocument.isXML11Version())) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_CHARACTER_ERR", null);
throw new DOMException(DOMException.INVALID_CHARACTER_ERR, msg);
}
if (namespaceURI == null || prefix.indexOf(':') >=0) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
} else if (prefix.equals("xml")) {
if (!namespaceURI.equals(xmlURI)) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}
}
// update node name with new qualifiedName
if (prefix !=null && prefix.length() != 0) {
name = prefix + ":" + localName;
}
else {
name = localName;
}
}
/**
* Introduced in DOM Level 2. <p>
*
* Returns the local part of the qualified name of this node.
* @since WD-DOM-Level-2-19990923
*/
public String getLocalName()
{
if (needsSyncData()) {
synchronizeData();
}
return localName;
}
/**
* DOM Level 3 WD - Experimental.
* Retrieve baseURI
*/
public String getBaseURI() {
if (needsSyncData()) {
synchronizeData();
}
// Absolute base URI is computed according to XML Base (http://www.w3.org/TR/xmlbase/#granularity)
// 1. the base URI specified by an xml:base attribute on the element, if one exists
if (attributes != null) {
Attr attrNode = (Attr)attributes.getNamedItemNS("http://www.w3.org/XML/1998/namespace", "base");
if (attrNode != null) {
String uri = attrNode.getNodeValue();
if (uri.length() != 0 ) {// attribute value is always empty string
try {
uri = new URI(uri).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e) {
// This may be a relative URI.
// Start from the base URI of the parent, or if this node has no parent, the owner node.
NodeImpl parentOrOwner = (parentNode() != null) ? parentNode() : ownerNode;
// Make any parentURI into a URI object to use with the URI(URI, String) constructor.
String parentBaseURI = (parentOrOwner != null) ? parentOrOwner.getBaseURI() : null;
if (parentBaseURI != null) {
try {
uri = new URI(new URI(parentBaseURI), uri).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException ex){
// This should never happen: parent should have checked the URI and returned null if invalid.
return null;
}
return uri;
}
// REVISIT: what should happen in this case?
return null;
}
return uri;
}
}
}
//2.the base URI of the element's parent element within the document or external entity,
//if one exists
String parentElementBaseURI = (this.parentNode() != null) ? this.parentNode().getBaseURI() : null ;
//base URI of parent element is not null
if(parentElementBaseURI != null){
try {
//return valid absolute base URI
return new URI(parentElementBaseURI).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
//3. the base URI of the document entity or external entity containing the element
String baseURI = (this.ownerNode != null) ? this.ownerNode.getBaseURI() : null ;
if(baseURI != null){
try {
//return valid absolute base URI
return new URI(baseURI).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeName()
*/
public String getTypeName() {
if (type !=null){
if (type instanceof XSSimpleTypeDecl) {
return ((XSSimpleTypeDecl) type).getTypeName();
} else if (type instanceof XSComplexTypeDecl) {
return ((XSComplexTypeDecl) type).getTypeName();
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeNamespace()
*/
public String getTypeNamespace() {
if (type !=null){
return type.getNamespace();
}
return null;
}
/**
* Introduced in DOM Level 2. <p>
* Checks if a type is derived from another by restriction. See:
* http://www.w3.org/TR/DOM-Level-3-Core/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by restriciton for the
* reference type
*/
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg,
int derivationMethod) {
if(needsSyncData()) {
synchronizeData();
}
if (type != null) {
if (type instanceof XSSimpleTypeDecl) {
return ((XSSimpleTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
} else if (type instanceof XSComplexTypeDecl) {
return ((XSComplexTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
}
}
return false;
}
/**
* NON-DOM: setting type used by the DOM parser
* @see NodeImpl#setReadOnly
*/
public void setType(XSTypeDefinition type) {
this.type = type;
}
}
| zxiaofan/JDK | jdk-12/src/java.xml/com/sun/org/apache/xerces/internal/dom/ElementNSImpl.java | 4,201 | // set owner document | line_comment | nl | /*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* 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 com.sun.org.apache.xerces.internal.dom;
import com.sun.org.apache.xerces.internal.xs.XSSimpleTypeDefinition;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import com.sun.org.apache.xerces.internal.impl.dv.xs.XSSimpleTypeDecl;
import com.sun.org.apache.xerces.internal.impl.xs.XSComplexTypeDecl;
import com.sun.org.apache.xerces.internal.util.URI;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
/**
* ElementNSImpl inherits from ElementImpl and adds namespace support.
* <P>
* The qualified name is the node name, and we store localName which is also
* used in all queries. On the other hand we recompute the prefix when
* necessary.
*
* @xerces.internal
*
* @author Elena litani, IBM
* @author Neeraj Bajaj, Sun Microsystems
*/
public class ElementNSImpl
extends ElementImpl {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = -9142310625494392642L;
static final String xmlURI = "http://www.w3.org/XML/1998/namespace";
//
// Data
//
/** DOM2: Namespace URI. */
protected String namespaceURI;
/** DOM2: localName. */
protected String localName;
/** DOM3: type information */
// REVISIT: we are losing the type information in DOM during serialization
transient XSTypeDefinition type;
protected ElementNSImpl() {
super();
}
/**
* DOM2: Constructor for Namespace implementation.
*/
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI,
String qualifiedName)
throws DOMException
{
super(ownerDocument, qualifiedName);
setName(namespaceURI, qualifiedName);
}
private void setName(String namespaceURI, String qname) {
String prefix;
// DOM Level 3: namespace URI is never empty string.
this.namespaceURI = namespaceURI;
if (namespaceURI != null) {
//convert the empty string to 'null'
this.namespaceURI = (namespaceURI.length() == 0) ? null : namespaceURI;
}
int colon1, colon2 ;
//NAMESPACE_ERR:
//1. if the qualified name is 'null' it is malformed.
//2. or if the qualifiedName is null and the namespaceURI is different from null,
// We dont need to check for namespaceURI != null, if qualified name is null throw DOMException.
if(qname == null){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
else{
colon1 = qname.indexOf(':');
colon2 = qname.lastIndexOf(':');
}
ownerDocument.checkNamespaceWF(qname, colon1, colon2);
if (colon1 < 0) {
// there is no prefix
localName = qname;
if (ownerDocument.errorChecking) {
ownerDocument.checkQName(null, localName);
if (qname.equals("xmlns")
&& (namespaceURI == null
|| !namespaceURI.equals(NamespaceContext.XMLNS_URI))
|| (namespaceURI!=null && namespaceURI.equals(NamespaceContext.XMLNS_URI)
&& !qname.equals("xmlns"))) {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}//there is a prefix
else {
prefix = qname.substring(0, colon1);
localName = qname.substring(colon2 + 1);
//NAMESPACE_ERR:
//1. if the qualifiedName has a prefix and the namespaceURI is null,
//2. or if the qualifiedName has a prefix that is "xml" and the namespaceURI
//is different from " http://www.w3.org/XML/1998/namespace"
if (ownerDocument.errorChecking) {
if( namespaceURI == null || ( prefix.equals("xml") && !namespaceURI.equals(NamespaceContext.XML_URI) )){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
ownerDocument.checkQName(prefix, localName);
ownerDocument.checkDOMNSErr(prefix, namespaceURI);
}
}
}
// when local name is known
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName)
throws DOMException
{
super(ownerDocument, qualifiedName);
this.localName = localName;
this.namespaceURI = namespaceURI;
}
// for DeferredElementImpl
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String value) {
super(ownerDocument, value);
}
// Support for DOM Level 3 renameNode method.
// Note: This only deals with part of the pb. CoreDocumentImpl
// does all the work.
void rename(String namespaceURI, String qualifiedName)
{
if (needsSyncData()) {
synchronizeData();
}
this.name = qualifiedName;
setName(namespaceURI, qualifiedName);
reconcileDefaultAttributes();
}
/**
* NON-DOM: resets this node and sets specified values for the node
*
* @param ownerDocument
* @param namespaceURI
* @param qualifiedName
* @param localName
*/
protected void setValues (CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName){
// remove children first
firstChild = null;
previousSibling = null;
nextSibling = null;
fNodeListCache = null;
// set owner<SUF>
attributes = null;
super.flags = 0;
setOwnerDocument(ownerDocument);
// synchronizeData will initialize attributes
needsSyncData(true);
super.name = qualifiedName;
this.localName = localName;
this.namespaceURI = namespaceURI;
}
//
// Node methods
//
//
//DOM2: Namespace methods.
//
/**
* Introduced in DOM Level 2. <p>
*
* The namespace URI of this node, or null if it is unspecified.<p>
*
* This is not a computed value that is the result of a namespace lookup based on
* an examination of the namespace declarations in scope. It is merely the
* namespace URI given at creation time.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null.
* @since WD-DOM-Level-2-19990923
*/
public String getNamespaceURI()
{
if (needsSyncData()) {
synchronizeData();
}
return namespaceURI;
}
/**
* Introduced in DOM Level 2. <p>
*
* The namespace prefix of this node, or null if it is unspecified. <p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null. <p>
*
* @since WD-DOM-Level-2-19990923
*/
public String getPrefix()
{
if (needsSyncData()) {
synchronizeData();
}
int index = name.indexOf(':');
return index < 0 ? null : name.substring(0, index);
}
/**
* Introduced in DOM Level 2. <p>
*
* Note that setting this attribute changes the nodeName attribute, which holds the
* qualified name, as well as the tagName and name attributes of the Element
* and Attr interfaces, when applicable.<p>
*
* @param prefix The namespace prefix of this node, or null(empty string) if it is unspecified.
*
* @exception INVALID_CHARACTER_ERR
* Raised if the specified
* prefix contains an invalid character.
* @exception DOMException
* @since WD-DOM-Level-2-19990923
*/
public void setPrefix(String prefix)
throws DOMException
{
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null);
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
msg);
}
if (prefix != null && prefix.length() != 0) {
if (!CoreDocumentImpl.isXMLName(prefix,ownerDocument.isXML11Version())) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_CHARACTER_ERR", null);
throw new DOMException(DOMException.INVALID_CHARACTER_ERR, msg);
}
if (namespaceURI == null || prefix.indexOf(':') >=0) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
} else if (prefix.equals("xml")) {
if (!namespaceURI.equals(xmlURI)) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}
}
// update node name with new qualifiedName
if (prefix !=null && prefix.length() != 0) {
name = prefix + ":" + localName;
}
else {
name = localName;
}
}
/**
* Introduced in DOM Level 2. <p>
*
* Returns the local part of the qualified name of this node.
* @since WD-DOM-Level-2-19990923
*/
public String getLocalName()
{
if (needsSyncData()) {
synchronizeData();
}
return localName;
}
/**
* DOM Level 3 WD - Experimental.
* Retrieve baseURI
*/
public String getBaseURI() {
if (needsSyncData()) {
synchronizeData();
}
// Absolute base URI is computed according to XML Base (http://www.w3.org/TR/xmlbase/#granularity)
// 1. the base URI specified by an xml:base attribute on the element, if one exists
if (attributes != null) {
Attr attrNode = (Attr)attributes.getNamedItemNS("http://www.w3.org/XML/1998/namespace", "base");
if (attrNode != null) {
String uri = attrNode.getNodeValue();
if (uri.length() != 0 ) {// attribute value is always empty string
try {
uri = new URI(uri).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e) {
// This may be a relative URI.
// Start from the base URI of the parent, or if this node has no parent, the owner node.
NodeImpl parentOrOwner = (parentNode() != null) ? parentNode() : ownerNode;
// Make any parentURI into a URI object to use with the URI(URI, String) constructor.
String parentBaseURI = (parentOrOwner != null) ? parentOrOwner.getBaseURI() : null;
if (parentBaseURI != null) {
try {
uri = new URI(new URI(parentBaseURI), uri).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException ex){
// This should never happen: parent should have checked the URI and returned null if invalid.
return null;
}
return uri;
}
// REVISIT: what should happen in this case?
return null;
}
return uri;
}
}
}
//2.the base URI of the element's parent element within the document or external entity,
//if one exists
String parentElementBaseURI = (this.parentNode() != null) ? this.parentNode().getBaseURI() : null ;
//base URI of parent element is not null
if(parentElementBaseURI != null){
try {
//return valid absolute base URI
return new URI(parentElementBaseURI).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
//3. the base URI of the document entity or external entity containing the element
String baseURI = (this.ownerNode != null) ? this.ownerNode.getBaseURI() : null ;
if(baseURI != null){
try {
//return valid absolute base URI
return new URI(baseURI).toString();
}
catch (com.sun.org.apache.xerces.internal.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeName()
*/
public String getTypeName() {
if (type !=null){
if (type instanceof XSSimpleTypeDecl) {
return ((XSSimpleTypeDecl) type).getTypeName();
} else if (type instanceof XSComplexTypeDecl) {
return ((XSComplexTypeDecl) type).getTypeName();
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeNamespace()
*/
public String getTypeNamespace() {
if (type !=null){
return type.getNamespace();
}
return null;
}
/**
* Introduced in DOM Level 2. <p>
* Checks if a type is derived from another by restriction. See:
* http://www.w3.org/TR/DOM-Level-3-Core/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by restriciton for the
* reference type
*/
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg,
int derivationMethod) {
if(needsSyncData()) {
synchronizeData();
}
if (type != null) {
if (type instanceof XSSimpleTypeDecl) {
return ((XSSimpleTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
} else if (type instanceof XSComplexTypeDecl) {
return ((XSComplexTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
}
}
return false;
}
/**
* NON-DOM: setting type used by the DOM parser
* @see NodeImpl#setReadOnly
*/
public void setType(XSTypeDefinition type) {
this.type = type;
}
}
|
75889_10 | package com.carp.casper2.chitchat;
import com.carp.nlp.lexicon.Word;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
/**
* Gebruikt de synoniemen lijst om onbekende woorden af te beeld op de bekende woorden uit de
* patterns. Met een synoniemen lijst breid deze de patterns uit met rules om van onbekende woorden
* op bekende te komen Hij maakt dus het (wiskundige) domein groter omdat er op meer dingen
* getriggerd wordt, vandaar de naam. Het is een beetje onhandig om door DomainExpander gemaakt
* rules weer toe te voegen. Voordat je de terminals uit een grammar haalt wil je meestal eerst die
* synoniemen rules er uit plukken. <br> Je stopt er een hashset met bekende dingen in en je krijgt
* een mapping terug.
*
* @author Oebele van der Veen
* @version 1.0
*/
public class DomainExpander {
Vector baselevel = new Vector();
// idee
// Er is een baseset waarop geprojecteerd moet worden
// dit gaat met een reduction graph die iteratief opgebouwd word
// reductiongraph = vector of level
// level = vector of (word,backref)
// baseset word in level 0 gezet en dan wordt elke element bij na gegaan
// is er een synoniem s van woord x dan krijgt s een ref naar x en komt s een level hoger
// daarna wordt het volgende level verwerkt.
// Als er niks meer toegevoegd kan worden, dan wordt bij elke woord uit de baseset alle synoniemen
// verzameld en wordt er een rule (synoniem1|..|synoniemx) do rewrite(woord) end van gemaakt. (collapsen)
// mischien frontref ipv backref. Dan gaat het collapsen makkelijker. laten we dat ook doen ja
// merk op dat er geen dubbelen in de reduction graph mogen voorkomen
// een node van de reduction tree
Set noDubArea = new HashSet(); // elk woord gooien we ook hierin (bij reference)
// Dat is fijn want dan kunnen we snel doublures voorkomen
Vector reductionGraph = new Vector(); //elk element is een level met nodes
SynonymList synlist;
/**
* Maakt een Domain Expander bij een baseset en synoniemenlijst. Gegeven de bekende woorden van de
* patterns in de baseset kan deze DomainExpander met de synoniemen nieuwe patterns maken
*
* @param baseset een HashSet met de terminals van de patterns
* @param synlist een synonymList,
*/
public DomainExpander(Set baseset, SynonymList synlist) {
// we zetten de basisset op level 0 van de reductionGraph;
setBase(baseset);
// even onthouden
this.synlist = synlist;
}
/**
* Slaat de mapping plat zodat deze weggeschreven kan worden Als er genoeg woorden zijn toegevoegd
* dan zorgt deze functie er voor dat de data structuur wordt aangepast voor wegschrijven als
* grammar rules
*/
public void collapse() {
// de nodes van de base level hebben nu alle kinderen als hun kinderen
Vector base = (Vector)reductionGraph.firstElement();
Node thisnode;
for (int i = 0; i < base.size(); i++) {
thisnode = (Node)base.elementAt(i);
thisnode.children = thisnode.getChildren(); // de kinderen gelijk stellen aan alle kinderen
}
}
/**
* Voegt meer woorden toe aan de mapping. Dit ding voegt meer woorden toe aan de mapping.
* expand(3);expand(4) is hetzelfde als expand(7)
*
* @param max het maximum aantal hops door de synoniemen vanaf de bekende woorden
* @return hoeveel hops de laatste woorden echt zijn. Dit kan kleiner zijn dan max als er geen
* synoniemen meer zijn.
*/
public int expand(int max) {
int curlevels = reductionGraph.size();
Vector newlevel;
boolean adding = true; // houd bij of er wat toegevoegd wordt, anders kunnen we ook wel stoppen.
while ((adding) && (reductionGraph.size() - curlevels) < max) {
newlevel = expandLevel((Vector)reductionGraph.lastElement());
reductionGraph.add(newlevel);
if (newlevel.size() == 0) {
adding = false;
}
}
return reductionGraph.size() - curlevels;
}
private Vector expandLevel(Vector level) {
System.out.println("Expanding level with " + level.size() + " elements");
System.out.println("Strings in noDubArea: " + noDubArea.size());
Vector synonyms;
Node thisnode, newnode;
Vector newlevel = new Vector();
String aword;
for (int i = 0; i < level.size(); i++) {
thisnode = ((Node)level.elementAt(i));
synonyms = synlist.getSynonymsOf(thisnode.word);
if (synonyms != null) {
for (int s = 0; s < synonyms.size(); s++) {
aword = (String)synonyms.elementAt(s);
if (!noDubArea.contains(aword)) {
newnode = new Node(aword); //Node(s) stopts s ook direct in de noDubArea
newlevel.add(newnode);
thisnode.addChild(newnode);
}
}
}
}
return newlevel;
}
private void setBase(Set baseSet) {
Word word;
String str;
System.out.println("Adding base set");
if (baseSet == null) {
System.out.println("Given baseset is null");
return;
}
Vector newlevel = new Vector(200);
Iterator iterator = baseSet.iterator();
while (iterator.hasNext()) {
word = (Word)iterator.next();
if (word != null) {
str = word.toString();
if (str != null) {
newlevel.add(new Node(str));
}
}
}
reductionGraph.add(newlevel);
System.out.println("Done");
}
/**
* Schrijf de synoniemen mapping naar rules. Stopt de mapping in de writer
*
* @param w een Writer waar de rules heen geschreven worden.
*/
public void writeToGrammar(Writer w) throws IOException {
BufferedWriter writer = new BufferedWriter(w);
String setting = "rule ^setIgnoreHead(true) ^setIgnoreTail(true) ^setMaxIgnored(256) end";
String commentaar =
"// Dit bestand is automatisch gegenereert door een DomainExpander object, Het is absoluut slim hier af te blijven.";
String line;
Vector base = (Vector)reductionGraph.firstElement();
Node thisnode;
try {
writer.write(commentaar, 0, commentaar.length());
writer.newLine();
writer.newLine();
writer.newLine();
writer.write(setting, 0, setting.length());
writer.newLine();
for (int i = 0; i < base.size(); i++) {
thisnode = (Node)base.elementAt(i);
line = thisnode.toParserString();
if (line.length() > 0) {
writer.write(line, 0, line.length());
writer.newLine();
}
}
}
finally {
writer.close();
}
}
private class Node {
private Vector children = new Vector(); // de synonymen van dit woord in een hoger level
private String word;
Node(String word) {
this.word = word;
noDubArea.add(word); // Kijk stoppen we er gewoon direct in
}
public void addChild(Node node) {
children.add(node);
}
//recursief alle kinderen verzamelen
public Vector getChildren() {
Vector result = new Vector();
for (int i = 0; i < children.size(); i++) {
result.addAll(((Node)children.elementAt(i)).getChildren());
}
result.addAll(children);
return result;
}
public String toParserString() {
// maak een "rule (childer1|childer2...) do rewrite(word) end"
if (children.size() == 0) {
return ""; // geen kinderen, geen regel
}
if (children.size() == 1) {
return "rule \"" + ((Node)children.firstElement()).word + "\" do rewrite(" + word + ") end";
}
StringBuffer result = new StringBuffer();
result.append("rule (");
for (int i = 0; i < children.size(); i++) {
if (i > 0) {
result.append("|");
}
result.append("\"");
result.append(((Node)children.elementAt(i)).word);
result.append("\"");
}
result.append(") do rewrite(" + word + ") end");
return result.toString();
}
}
} | dmarcotte/intellij-community | plugins/rearranger/test/testData/com/wrq/rearranger/DomainExpanderTest.java | 2,252 | // mischien frontref ipv backref. Dan gaat het collapsen makkelijker. laten we dat ook doen ja | line_comment | nl | package com.carp.casper2.chitchat;
import com.carp.nlp.lexicon.Word;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
/**
* Gebruikt de synoniemen lijst om onbekende woorden af te beeld op de bekende woorden uit de
* patterns. Met een synoniemen lijst breid deze de patterns uit met rules om van onbekende woorden
* op bekende te komen Hij maakt dus het (wiskundige) domein groter omdat er op meer dingen
* getriggerd wordt, vandaar de naam. Het is een beetje onhandig om door DomainExpander gemaakt
* rules weer toe te voegen. Voordat je de terminals uit een grammar haalt wil je meestal eerst die
* synoniemen rules er uit plukken. <br> Je stopt er een hashset met bekende dingen in en je krijgt
* een mapping terug.
*
* @author Oebele van der Veen
* @version 1.0
*/
public class DomainExpander {
Vector baselevel = new Vector();
// idee
// Er is een baseset waarop geprojecteerd moet worden
// dit gaat met een reduction graph die iteratief opgebouwd word
// reductiongraph = vector of level
// level = vector of (word,backref)
// baseset word in level 0 gezet en dan wordt elke element bij na gegaan
// is er een synoniem s van woord x dan krijgt s een ref naar x en komt s een level hoger
// daarna wordt het volgende level verwerkt.
// Als er niks meer toegevoegd kan worden, dan wordt bij elke woord uit de baseset alle synoniemen
// verzameld en wordt er een rule (synoniem1|..|synoniemx) do rewrite(woord) end van gemaakt. (collapsen)
// mischien frontref<SUF>
// merk op dat er geen dubbelen in de reduction graph mogen voorkomen
// een node van de reduction tree
Set noDubArea = new HashSet(); // elk woord gooien we ook hierin (bij reference)
// Dat is fijn want dan kunnen we snel doublures voorkomen
Vector reductionGraph = new Vector(); //elk element is een level met nodes
SynonymList synlist;
/**
* Maakt een Domain Expander bij een baseset en synoniemenlijst. Gegeven de bekende woorden van de
* patterns in de baseset kan deze DomainExpander met de synoniemen nieuwe patterns maken
*
* @param baseset een HashSet met de terminals van de patterns
* @param synlist een synonymList,
*/
public DomainExpander(Set baseset, SynonymList synlist) {
// we zetten de basisset op level 0 van de reductionGraph;
setBase(baseset);
// even onthouden
this.synlist = synlist;
}
/**
* Slaat de mapping plat zodat deze weggeschreven kan worden Als er genoeg woorden zijn toegevoegd
* dan zorgt deze functie er voor dat de data structuur wordt aangepast voor wegschrijven als
* grammar rules
*/
public void collapse() {
// de nodes van de base level hebben nu alle kinderen als hun kinderen
Vector base = (Vector)reductionGraph.firstElement();
Node thisnode;
for (int i = 0; i < base.size(); i++) {
thisnode = (Node)base.elementAt(i);
thisnode.children = thisnode.getChildren(); // de kinderen gelijk stellen aan alle kinderen
}
}
/**
* Voegt meer woorden toe aan de mapping. Dit ding voegt meer woorden toe aan de mapping.
* expand(3);expand(4) is hetzelfde als expand(7)
*
* @param max het maximum aantal hops door de synoniemen vanaf de bekende woorden
* @return hoeveel hops de laatste woorden echt zijn. Dit kan kleiner zijn dan max als er geen
* synoniemen meer zijn.
*/
public int expand(int max) {
int curlevels = reductionGraph.size();
Vector newlevel;
boolean adding = true; // houd bij of er wat toegevoegd wordt, anders kunnen we ook wel stoppen.
while ((adding) && (reductionGraph.size() - curlevels) < max) {
newlevel = expandLevel((Vector)reductionGraph.lastElement());
reductionGraph.add(newlevel);
if (newlevel.size() == 0) {
adding = false;
}
}
return reductionGraph.size() - curlevels;
}
private Vector expandLevel(Vector level) {
System.out.println("Expanding level with " + level.size() + " elements");
System.out.println("Strings in noDubArea: " + noDubArea.size());
Vector synonyms;
Node thisnode, newnode;
Vector newlevel = new Vector();
String aword;
for (int i = 0; i < level.size(); i++) {
thisnode = ((Node)level.elementAt(i));
synonyms = synlist.getSynonymsOf(thisnode.word);
if (synonyms != null) {
for (int s = 0; s < synonyms.size(); s++) {
aword = (String)synonyms.elementAt(s);
if (!noDubArea.contains(aword)) {
newnode = new Node(aword); //Node(s) stopts s ook direct in de noDubArea
newlevel.add(newnode);
thisnode.addChild(newnode);
}
}
}
}
return newlevel;
}
private void setBase(Set baseSet) {
Word word;
String str;
System.out.println("Adding base set");
if (baseSet == null) {
System.out.println("Given baseset is null");
return;
}
Vector newlevel = new Vector(200);
Iterator iterator = baseSet.iterator();
while (iterator.hasNext()) {
word = (Word)iterator.next();
if (word != null) {
str = word.toString();
if (str != null) {
newlevel.add(new Node(str));
}
}
}
reductionGraph.add(newlevel);
System.out.println("Done");
}
/**
* Schrijf de synoniemen mapping naar rules. Stopt de mapping in de writer
*
* @param w een Writer waar de rules heen geschreven worden.
*/
public void writeToGrammar(Writer w) throws IOException {
BufferedWriter writer = new BufferedWriter(w);
String setting = "rule ^setIgnoreHead(true) ^setIgnoreTail(true) ^setMaxIgnored(256) end";
String commentaar =
"// Dit bestand is automatisch gegenereert door een DomainExpander object, Het is absoluut slim hier af te blijven.";
String line;
Vector base = (Vector)reductionGraph.firstElement();
Node thisnode;
try {
writer.write(commentaar, 0, commentaar.length());
writer.newLine();
writer.newLine();
writer.newLine();
writer.write(setting, 0, setting.length());
writer.newLine();
for (int i = 0; i < base.size(); i++) {
thisnode = (Node)base.elementAt(i);
line = thisnode.toParserString();
if (line.length() > 0) {
writer.write(line, 0, line.length());
writer.newLine();
}
}
}
finally {
writer.close();
}
}
private class Node {
private Vector children = new Vector(); // de synonymen van dit woord in een hoger level
private String word;
Node(String word) {
this.word = word;
noDubArea.add(word); // Kijk stoppen we er gewoon direct in
}
public void addChild(Node node) {
children.add(node);
}
//recursief alle kinderen verzamelen
public Vector getChildren() {
Vector result = new Vector();
for (int i = 0; i < children.size(); i++) {
result.addAll(((Node)children.elementAt(i)).getChildren());
}
result.addAll(children);
return result;
}
public String toParserString() {
// maak een "rule (childer1|childer2...) do rewrite(word) end"
if (children.size() == 0) {
return ""; // geen kinderen, geen regel
}
if (children.size() == 1) {
return "rule \"" + ((Node)children.firstElement()).word + "\" do rewrite(" + word + ") end";
}
StringBuffer result = new StringBuffer();
result.append("rule (");
for (int i = 0; i < children.size(); i++) {
if (i > 0) {
result.append("|");
}
result.append("\"");
result.append(((Node)children.elementAt(i)).word);
result.append("\"");
}
result.append(") do rewrite(" + word + ") end");
return result.toString();
}
}
} |
126158_22 | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2013 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons GIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* OGCCommunication.java
*
* Created on 11-10-2013
*
* Superklasse van OGCRequest.java en OGCResponse.java
*/
package nl.b3p.ogc.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author Chris van Lith
*/
public class OGCCommunication implements OGCConstants {
protected HashMap nameSpaces;
protected HashMap schemaLocations;
public void addOrReplaceNameSpace(String prefix, String nsUrl) {
if (prefix != null && nsUrl != null && !nsUrl.isEmpty()) {
if (nameSpaces == null) {
addOpengisNamespaces();
}
nameSpaces.put(prefix, nsUrl);
}
}
public final void findNameSpace(Node node) {
NamedNodeMap map = node.getAttributes();
if (map != null) {
for (int i = 0; map.getLength() > i; i++) {
String value = map.item(i).getNodeValue();
if (value == null || value.length() == 0) {
continue;
}
String name = map.item(i).getNodeName();
String[] tokens = name.split(":");
if (tokens[0].equalsIgnoreCase("xmlns")) {
if (tokens.length > 1) {
addOrReplaceNameSpace(tokens[1], value);
} else {
// namespace context kent een default ns
addOrReplaceNameSpace("", value);
}
} else if (tokens.length == 2) {
if (tokens[1].equalsIgnoreCase("SchemaLocation")) {
addOrReplaceSchemaLocation(tokens[1], value);
}
}
}
}
if (node.hasChildNodes()) {
NodeList lijst = node.getChildNodes();
for (int i = 0; i < lijst.getLength(); i++) {
findNameSpace(lijst.item(i));
}
}
}
protected void addOrReplaceSchemaLocation(String prefix, String location) {
if (prefix != null && location != null) {
if (schemaLocations == null) {
addOpengisSchemaLocations();
}
schemaLocations.put(prefix, location);
}
}
protected final void setNameSpaces(HashMap nameSpaces) {
this.nameSpaces = nameSpaces;
}
protected HashMap getNameSpaces() {
return nameSpaces;
}
/**
* @return the schemaLocations
*/
protected HashMap getSchemaLocations() {
return schemaLocations;
}
/**
* @param schemaLocations the schemaLocations to set
*/
protected final void setSchemaLocations(HashMap schemaLocations) {
this.schemaLocations = schemaLocations;
}
protected String getNameSpace(String param) {
if (param == null || nameSpaces == null) {
return null;
}
return (String) nameSpaces.get(param);
}
public String getNameSpacePrefix(String namespaceUrl) {
return getNameSpacePrefix(namespaceUrl, false);
}
public String getNameSpacePrefix(String namespaceUrl, boolean create) {
if (nameSpaces == null || nameSpaces.isEmpty()) {
return null;
}
for (Iterator iterator = nameSpaces.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
if (entry.getValue().equals(namespaceUrl)) {
String prefix = (String) entry.getKey();
if (prefix.isEmpty() && create) {
//default namespace moet voor xpath calcs een prefix
//hebben, deze wordt daarom verderop gecreerd.
} else {
return (String) entry.getKey();
}
}
}
String prefix = ""; //default namespace
if (create) {
//als namespace nog niet is toegevoegd en het is niet de default ns
int nsTeller = 1;
//kijk of de namespace prefix al bestaat anders ophogen en nogmaals proberen
String ns = getNameSpace("ns" + nsTeller);
while (ns != null) {
nsTeller++;
ns = getNameSpace("ns" + nsTeller);
}
prefix = "ns" + nsTeller;
}
addOrReplaceNameSpace(prefix, namespaceUrl);
return prefix;
}
protected String[] getNameSpacesArray() {
if (nameSpaces == null) {
return null;
}
String[] returnvalue = new String[nameSpaces.size()];
Set keys = nameSpaces.keySet();
Iterator it = keys.iterator();
for (int i = 0; it.hasNext(); i++) {
String prefix = (String) it.next();
String location = (String) nameSpaces.get(prefix);
returnvalue[i] = "xmlns:" + prefix + "=\"" + location + "\"";
}
return returnvalue;
}
protected String[] getSchemaLocationsArray() {
if (schemaLocations == null) {
return null;
}
String[] returnvalue = new String[schemaLocations.size()];
Set keys = schemaLocations.keySet();
Iterator it = keys.iterator();
for (int i = 0; it.hasNext(); i++) {
String prefix = (String) it.next();
String location = (String) schemaLocations.get(prefix);
returnvalue[i] = prefix + ":schemaLocation=\"" + location + "\"";
}
return returnvalue;
}
/**
* Adds all namespaces needed for OpenGis
*/
protected final void addOpengisNamespaces() {
if (nameSpaces == null) {
nameSpaces = new HashMap();
}
if (!nameSpaces.containsKey("wfs")) {
addOrReplaceNameSpace("wfs", "http://www.opengis.net/wfs");
}
if (!nameSpaces.containsKey("xsi")) {
addOrReplaceNameSpace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
if (!nameSpaces.containsKey("gml")) {
addOrReplaceNameSpace("gml", "http://www.opengis.net/gml");
}
if (!nameSpaces.containsKey("ogc")) {
addOrReplaceNameSpace("ogc", "http://www.opengis.net/ogc");
}
if (!nameSpaces.containsKey("ows")) {
addOrReplaceNameSpace("ows", "http://www.opengis.net/ows");
}
}
/**
* Adds all Schemalocations needed for OpenGis
*/
protected final void addOpengisSchemaLocations() {
if (schemaLocations == null) {
schemaLocations = new HashMap();
}
if (!schemaLocations.containsKey("xsi")) {
// cvl: uitgezet want wfs 1.0.0 en 1.1.0 hebben zelfde url
// addOrReplaceSchemaLocation("xsi", "http://www.opengis.net/wfs ../wfs/1.1.0/WFS.xsd");
}
}
public NamespaceContext getNamespaceContext() {
return new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return (String) nameSpaces.get(prefix);
}
// Dummy implementation - not used!
public Iterator getPrefixes(String val) {
return null;
}
// Dummy implemenation - not used!
public String getPrefix(String uri) {
return null;
}
};
}
public LayerSummary splitLayerInParts(String fullLayerName) throws Exception {
return splitLayerInParts(fullLayerName, true, null, null);
}
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName) throws Exception {
return splitLayerWithoutNsFix(fullLayerName, true, null, null);
}
public LayerSummary splitLayerInParts(String fullLayerName, boolean splitName, String defaultSp, String defaultNs) throws Exception {
LayerSummary m = splitLayerWithoutNsFix(fullLayerName, splitName, defaultSp, defaultNs);
String tPrefix = m.getPrefix();
String tNsUrl = m.getNsUrl();
if (tNsUrl!= null && !tNsUrl.isEmpty()) {
tPrefix = getNameSpacePrefix(tNsUrl);
m.setPrefix(tPrefix);
} else if (tPrefix!= null && !tPrefix.isEmpty()) {
tNsUrl = getNameSpace(tPrefix);
m.setNsUrl(tNsUrl);
}
return m;
}
/**
* parse full name of layer, use splitName boolean to parse layernames
* known to not have a service provider in the name to prevend problems
* with underscores in names.
*
* <li>{ns-uri}sp_layername
* <li>{ns-uri}layername (no service provider)
* <li>ns:layername (no service provider)
* <li>sp_ns:layername
* <li>sp_layername (no name space)
* <li>layername (no service provider and name space)
*
* @param fullLayerName
* @param splitName try to split out service provider
* @return
* @throws Exception
*/
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName, boolean splitName) throws Exception {
return splitLayerWithoutNsFix(fullLayerName, splitName, null, null);
}
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName, boolean splitName, String defaultSp, String defaultNs) throws Exception {
String tPrefix = null;
String tLayerName = null;
String tSpAbbr = null;
String tSpLayerName = null;
String tNsUrl = null;
if (fullLayerName == null) {
return null;
}
String[] temp = fullLayerName.split("}");
if (temp.length > 1) {
tSpLayerName = temp[1];
int index1 = fullLayerName.indexOf("{");
int index2 = fullLayerName.indexOf("}");
tNsUrl = fullLayerName.substring(index1 + 1, index2);
} else {
String temp2[] = temp[0].split(":");
if (temp2.length > 1) {
tSpLayerName = temp2[1];
tPrefix = temp2[0];
} else {
tSpLayerName = fullLayerName;
}
}
tLayerName = tSpLayerName;
if (splitName ||
tSpLayerName.startsWith(KBConfiguration.SERVICEPROVIDER_BASE_ABBR + "_")) {
int index1 = tSpLayerName.indexOf("_");
if (index1 != -1) {
tSpAbbr = tSpLayerName.substring(0, index1);
tLayerName = tSpLayerName.substring(index1 + 1);
}
}
if (tLayerName.isEmpty()) {
throw new Exception(KBConfiguration.REQUEST_LAYERNAME_EXCEPTION + ": " + tLayerName);
}
if (defaultSp!=null && tSpAbbr==null) {
tSpAbbr = defaultSp;
}
if (defaultNs!=null && tPrefix==null) {
tPrefix = defaultNs;
}
LayerSummary returnMap = new LayerSummary();
returnMap.setPrefix(tPrefix);
returnMap.setSpAbbr(tSpAbbr);
returnMap.setLayerName(tLayerName);
returnMap.setNsUrl(tNsUrl);
return returnMap;
}
/**
* methode splitst lange layer naam volgens abbr_layer in een service provider
* deel (layerCode genoemd) en een echte layer naam (layerName)
* <p>
* @param completeLayerName lange layer naam
* @return straing array met 2 strings: abbr en layer
* @throws java.lang.Exception fout in format lange layer naam
*/
public static String[] toCodeAndName(String completeLayerName) throws Exception {
LayerSummary m = splitLayerWithoutNsFix(completeLayerName);
if (m==null) {
return null;
}
String layerCode = m.getSpAbbr();
// plak de oorspronkelijke ns weer aan de kaartlaag indien van toepassing
String layerName = buildLayerNameWithoutSp(m);
return new String[]{layerCode, layerName};
}
public static String getLayerName(String ln) {
try {
LayerSummary m = splitLayerWithoutNsFix(ln);
return buildLayerNameWithoutNs(m);
} catch (Exception ex) {
// uitzoeken of deze niet gewoon gegooid kan worden
}
return null;
}
static public String attachSp(String sp, String l) {
try {
LayerSummary m = splitLayerWithoutNsFix(l, false, sp, null);
return buildFullLayerName(m);
} catch (Exception ex) {
// uitzoeken of deze niet gewoon gegooid kan worden
}
return null;
}
static public String attachSpNs(String sp, String l, String ns) {
if (l == null || l.isEmpty()) {
return null;
}
if (sp == null || sp.isEmpty()) {
if (ns == null || ns.isEmpty()) {
return l;
} else {
return ns + ":" + l;
}
}
if (ns == null || ns.isEmpty()) {
return sp + "_" + l;
} else {
return ns + ":" + sp + "_" + l;
}
}
public static String buildFullLayerName(LayerSummary m) {
String tPrefix = m.getPrefix();
String tSpAbbr = m.getSpAbbr();
String tLayerName = m.getLayerName();
return attachSpNs(tSpAbbr, tLayerName, tPrefix);
}
public static String buildLayerNameWithoutSp(LayerSummary m) {
String tPrefix = m.getPrefix();
String tLayerName = m.getLayerName();
return attachSpNs(null, tLayerName, tPrefix);
}
public static String buildLayerNameWithoutNs(LayerSummary m) {
String tSpAbbr = m.getSpAbbr();
String tLayerName = m.getLayerName();
return attachSpNs(tSpAbbr, tLayerName, null);
}
public static String replaceIds(String originalId, String sp, String ns) {
if (sp==null) {
if (ns==null) {
return originalId;
} else {
return ns + ":" + originalId;
}
}
String[] idSplit = originalId.split(sp + "_");
String newId = "";
for (int i = 0; i < idSplit.length; i++) {
newId += idSplit[i];
if (i < (idSplit.length - 1) && ns!=null) {
newId += ns + ":";
}
}
return newId;
}
protected final String stripNs(String key) {
String[] temp = key.split("}");
if (temp.length == 2) {
return temp[1];
} else {
return key;
}
}
public String fixNsPrefix(String ft) {
int index1 = ft.indexOf("{");
int index2 = ft.indexOf("}");
if (index1 >= 0 && index2 >= 0) {
String nameSpaceUri = ft.substring(index1 + 1, index2);
String prefix = getNameSpacePrefix(nameSpaceUri);
if (prefix.isEmpty()) {
// default namespace
return ft.substring(index2 + 1);
}
return prefix + ":" + ft.substring(index2 + 1);
}
return ft;
}
/**
* This method determines the featureTypeName based on the given layer and
* prefix. Since the layer contains a {namespaceUrl} in the layer, it first
* needs to determine the namespace prefix. This value is saved in the
* featureTypeNamespacePrefix instance variable, for later use.
*
* @param prefix
* @param layer
* @return
*/
protected final String determineFeatureTypeName(String spAbbr, String layer) {
try {
LayerSummary m = splitLayerInParts(layer, false, spAbbr, null);
return buildFullLayerName(m);
} catch (Exception ex) {
// uitzoeken of deze niet gegooid kan worden
}
return null;
}
protected static String cleanPrefixInBody(String body, String prefix, String nsUrl, String ns) {
String old = "";
if (nsUrl != null) {
old += nsUrl;
}
if (prefix != null) {
old += prefix;
}
if (old.length() == 0) {
return body;
}
String nsnew = "";
if (ns != null) {
nsnew += ns;
}
StringBuffer bBody = new StringBuffer(body);
for (int start = bBody.indexOf(old); start >= 0;) {
bBody.replace(start, start + old.length(), nsnew);
}
return bBody.toString();
}
}
| B3Partners/b3p-commons-gis | src/main/java/nl/b3p/ogc/utils/OGCCommunication.java | 4,622 | // uitzoeken of deze niet gegooid kan worden | line_comment | nl | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2013 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Commons GIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* OGCCommunication.java
*
* Created on 11-10-2013
*
* Superklasse van OGCRequest.java en OGCResponse.java
*/
package nl.b3p.ogc.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.NamespaceContext;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author Chris van Lith
*/
public class OGCCommunication implements OGCConstants {
protected HashMap nameSpaces;
protected HashMap schemaLocations;
public void addOrReplaceNameSpace(String prefix, String nsUrl) {
if (prefix != null && nsUrl != null && !nsUrl.isEmpty()) {
if (nameSpaces == null) {
addOpengisNamespaces();
}
nameSpaces.put(prefix, nsUrl);
}
}
public final void findNameSpace(Node node) {
NamedNodeMap map = node.getAttributes();
if (map != null) {
for (int i = 0; map.getLength() > i; i++) {
String value = map.item(i).getNodeValue();
if (value == null || value.length() == 0) {
continue;
}
String name = map.item(i).getNodeName();
String[] tokens = name.split(":");
if (tokens[0].equalsIgnoreCase("xmlns")) {
if (tokens.length > 1) {
addOrReplaceNameSpace(tokens[1], value);
} else {
// namespace context kent een default ns
addOrReplaceNameSpace("", value);
}
} else if (tokens.length == 2) {
if (tokens[1].equalsIgnoreCase("SchemaLocation")) {
addOrReplaceSchemaLocation(tokens[1], value);
}
}
}
}
if (node.hasChildNodes()) {
NodeList lijst = node.getChildNodes();
for (int i = 0; i < lijst.getLength(); i++) {
findNameSpace(lijst.item(i));
}
}
}
protected void addOrReplaceSchemaLocation(String prefix, String location) {
if (prefix != null && location != null) {
if (schemaLocations == null) {
addOpengisSchemaLocations();
}
schemaLocations.put(prefix, location);
}
}
protected final void setNameSpaces(HashMap nameSpaces) {
this.nameSpaces = nameSpaces;
}
protected HashMap getNameSpaces() {
return nameSpaces;
}
/**
* @return the schemaLocations
*/
protected HashMap getSchemaLocations() {
return schemaLocations;
}
/**
* @param schemaLocations the schemaLocations to set
*/
protected final void setSchemaLocations(HashMap schemaLocations) {
this.schemaLocations = schemaLocations;
}
protected String getNameSpace(String param) {
if (param == null || nameSpaces == null) {
return null;
}
return (String) nameSpaces.get(param);
}
public String getNameSpacePrefix(String namespaceUrl) {
return getNameSpacePrefix(namespaceUrl, false);
}
public String getNameSpacePrefix(String namespaceUrl, boolean create) {
if (nameSpaces == null || nameSpaces.isEmpty()) {
return null;
}
for (Iterator iterator = nameSpaces.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
if (entry.getValue().equals(namespaceUrl)) {
String prefix = (String) entry.getKey();
if (prefix.isEmpty() && create) {
//default namespace moet voor xpath calcs een prefix
//hebben, deze wordt daarom verderop gecreerd.
} else {
return (String) entry.getKey();
}
}
}
String prefix = ""; //default namespace
if (create) {
//als namespace nog niet is toegevoegd en het is niet de default ns
int nsTeller = 1;
//kijk of de namespace prefix al bestaat anders ophogen en nogmaals proberen
String ns = getNameSpace("ns" + nsTeller);
while (ns != null) {
nsTeller++;
ns = getNameSpace("ns" + nsTeller);
}
prefix = "ns" + nsTeller;
}
addOrReplaceNameSpace(prefix, namespaceUrl);
return prefix;
}
protected String[] getNameSpacesArray() {
if (nameSpaces == null) {
return null;
}
String[] returnvalue = new String[nameSpaces.size()];
Set keys = nameSpaces.keySet();
Iterator it = keys.iterator();
for (int i = 0; it.hasNext(); i++) {
String prefix = (String) it.next();
String location = (String) nameSpaces.get(prefix);
returnvalue[i] = "xmlns:" + prefix + "=\"" + location + "\"";
}
return returnvalue;
}
protected String[] getSchemaLocationsArray() {
if (schemaLocations == null) {
return null;
}
String[] returnvalue = new String[schemaLocations.size()];
Set keys = schemaLocations.keySet();
Iterator it = keys.iterator();
for (int i = 0; it.hasNext(); i++) {
String prefix = (String) it.next();
String location = (String) schemaLocations.get(prefix);
returnvalue[i] = prefix + ":schemaLocation=\"" + location + "\"";
}
return returnvalue;
}
/**
* Adds all namespaces needed for OpenGis
*/
protected final void addOpengisNamespaces() {
if (nameSpaces == null) {
nameSpaces = new HashMap();
}
if (!nameSpaces.containsKey("wfs")) {
addOrReplaceNameSpace("wfs", "http://www.opengis.net/wfs");
}
if (!nameSpaces.containsKey("xsi")) {
addOrReplaceNameSpace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
if (!nameSpaces.containsKey("gml")) {
addOrReplaceNameSpace("gml", "http://www.opengis.net/gml");
}
if (!nameSpaces.containsKey("ogc")) {
addOrReplaceNameSpace("ogc", "http://www.opengis.net/ogc");
}
if (!nameSpaces.containsKey("ows")) {
addOrReplaceNameSpace("ows", "http://www.opengis.net/ows");
}
}
/**
* Adds all Schemalocations needed for OpenGis
*/
protected final void addOpengisSchemaLocations() {
if (schemaLocations == null) {
schemaLocations = new HashMap();
}
if (!schemaLocations.containsKey("xsi")) {
// cvl: uitgezet want wfs 1.0.0 en 1.1.0 hebben zelfde url
// addOrReplaceSchemaLocation("xsi", "http://www.opengis.net/wfs ../wfs/1.1.0/WFS.xsd");
}
}
public NamespaceContext getNamespaceContext() {
return new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return (String) nameSpaces.get(prefix);
}
// Dummy implementation - not used!
public Iterator getPrefixes(String val) {
return null;
}
// Dummy implemenation - not used!
public String getPrefix(String uri) {
return null;
}
};
}
public LayerSummary splitLayerInParts(String fullLayerName) throws Exception {
return splitLayerInParts(fullLayerName, true, null, null);
}
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName) throws Exception {
return splitLayerWithoutNsFix(fullLayerName, true, null, null);
}
public LayerSummary splitLayerInParts(String fullLayerName, boolean splitName, String defaultSp, String defaultNs) throws Exception {
LayerSummary m = splitLayerWithoutNsFix(fullLayerName, splitName, defaultSp, defaultNs);
String tPrefix = m.getPrefix();
String tNsUrl = m.getNsUrl();
if (tNsUrl!= null && !tNsUrl.isEmpty()) {
tPrefix = getNameSpacePrefix(tNsUrl);
m.setPrefix(tPrefix);
} else if (tPrefix!= null && !tPrefix.isEmpty()) {
tNsUrl = getNameSpace(tPrefix);
m.setNsUrl(tNsUrl);
}
return m;
}
/**
* parse full name of layer, use splitName boolean to parse layernames
* known to not have a service provider in the name to prevend problems
* with underscores in names.
*
* <li>{ns-uri}sp_layername
* <li>{ns-uri}layername (no service provider)
* <li>ns:layername (no service provider)
* <li>sp_ns:layername
* <li>sp_layername (no name space)
* <li>layername (no service provider and name space)
*
* @param fullLayerName
* @param splitName try to split out service provider
* @return
* @throws Exception
*/
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName, boolean splitName) throws Exception {
return splitLayerWithoutNsFix(fullLayerName, splitName, null, null);
}
public static LayerSummary splitLayerWithoutNsFix(String fullLayerName, boolean splitName, String defaultSp, String defaultNs) throws Exception {
String tPrefix = null;
String tLayerName = null;
String tSpAbbr = null;
String tSpLayerName = null;
String tNsUrl = null;
if (fullLayerName == null) {
return null;
}
String[] temp = fullLayerName.split("}");
if (temp.length > 1) {
tSpLayerName = temp[1];
int index1 = fullLayerName.indexOf("{");
int index2 = fullLayerName.indexOf("}");
tNsUrl = fullLayerName.substring(index1 + 1, index2);
} else {
String temp2[] = temp[0].split(":");
if (temp2.length > 1) {
tSpLayerName = temp2[1];
tPrefix = temp2[0];
} else {
tSpLayerName = fullLayerName;
}
}
tLayerName = tSpLayerName;
if (splitName ||
tSpLayerName.startsWith(KBConfiguration.SERVICEPROVIDER_BASE_ABBR + "_")) {
int index1 = tSpLayerName.indexOf("_");
if (index1 != -1) {
tSpAbbr = tSpLayerName.substring(0, index1);
tLayerName = tSpLayerName.substring(index1 + 1);
}
}
if (tLayerName.isEmpty()) {
throw new Exception(KBConfiguration.REQUEST_LAYERNAME_EXCEPTION + ": " + tLayerName);
}
if (defaultSp!=null && tSpAbbr==null) {
tSpAbbr = defaultSp;
}
if (defaultNs!=null && tPrefix==null) {
tPrefix = defaultNs;
}
LayerSummary returnMap = new LayerSummary();
returnMap.setPrefix(tPrefix);
returnMap.setSpAbbr(tSpAbbr);
returnMap.setLayerName(tLayerName);
returnMap.setNsUrl(tNsUrl);
return returnMap;
}
/**
* methode splitst lange layer naam volgens abbr_layer in een service provider
* deel (layerCode genoemd) en een echte layer naam (layerName)
* <p>
* @param completeLayerName lange layer naam
* @return straing array met 2 strings: abbr en layer
* @throws java.lang.Exception fout in format lange layer naam
*/
public static String[] toCodeAndName(String completeLayerName) throws Exception {
LayerSummary m = splitLayerWithoutNsFix(completeLayerName);
if (m==null) {
return null;
}
String layerCode = m.getSpAbbr();
// plak de oorspronkelijke ns weer aan de kaartlaag indien van toepassing
String layerName = buildLayerNameWithoutSp(m);
return new String[]{layerCode, layerName};
}
public static String getLayerName(String ln) {
try {
LayerSummary m = splitLayerWithoutNsFix(ln);
return buildLayerNameWithoutNs(m);
} catch (Exception ex) {
// uitzoeken of deze niet gewoon gegooid kan worden
}
return null;
}
static public String attachSp(String sp, String l) {
try {
LayerSummary m = splitLayerWithoutNsFix(l, false, sp, null);
return buildFullLayerName(m);
} catch (Exception ex) {
// uitzoeken of deze niet gewoon gegooid kan worden
}
return null;
}
static public String attachSpNs(String sp, String l, String ns) {
if (l == null || l.isEmpty()) {
return null;
}
if (sp == null || sp.isEmpty()) {
if (ns == null || ns.isEmpty()) {
return l;
} else {
return ns + ":" + l;
}
}
if (ns == null || ns.isEmpty()) {
return sp + "_" + l;
} else {
return ns + ":" + sp + "_" + l;
}
}
public static String buildFullLayerName(LayerSummary m) {
String tPrefix = m.getPrefix();
String tSpAbbr = m.getSpAbbr();
String tLayerName = m.getLayerName();
return attachSpNs(tSpAbbr, tLayerName, tPrefix);
}
public static String buildLayerNameWithoutSp(LayerSummary m) {
String tPrefix = m.getPrefix();
String tLayerName = m.getLayerName();
return attachSpNs(null, tLayerName, tPrefix);
}
public static String buildLayerNameWithoutNs(LayerSummary m) {
String tSpAbbr = m.getSpAbbr();
String tLayerName = m.getLayerName();
return attachSpNs(tSpAbbr, tLayerName, null);
}
public static String replaceIds(String originalId, String sp, String ns) {
if (sp==null) {
if (ns==null) {
return originalId;
} else {
return ns + ":" + originalId;
}
}
String[] idSplit = originalId.split(sp + "_");
String newId = "";
for (int i = 0; i < idSplit.length; i++) {
newId += idSplit[i];
if (i < (idSplit.length - 1) && ns!=null) {
newId += ns + ":";
}
}
return newId;
}
protected final String stripNs(String key) {
String[] temp = key.split("}");
if (temp.length == 2) {
return temp[1];
} else {
return key;
}
}
public String fixNsPrefix(String ft) {
int index1 = ft.indexOf("{");
int index2 = ft.indexOf("}");
if (index1 >= 0 && index2 >= 0) {
String nameSpaceUri = ft.substring(index1 + 1, index2);
String prefix = getNameSpacePrefix(nameSpaceUri);
if (prefix.isEmpty()) {
// default namespace
return ft.substring(index2 + 1);
}
return prefix + ":" + ft.substring(index2 + 1);
}
return ft;
}
/**
* This method determines the featureTypeName based on the given layer and
* prefix. Since the layer contains a {namespaceUrl} in the layer, it first
* needs to determine the namespace prefix. This value is saved in the
* featureTypeNamespacePrefix instance variable, for later use.
*
* @param prefix
* @param layer
* @return
*/
protected final String determineFeatureTypeName(String spAbbr, String layer) {
try {
LayerSummary m = splitLayerInParts(layer, false, spAbbr, null);
return buildFullLayerName(m);
} catch (Exception ex) {
// uitzoeken of<SUF>
}
return null;
}
protected static String cleanPrefixInBody(String body, String prefix, String nsUrl, String ns) {
String old = "";
if (nsUrl != null) {
old += nsUrl;
}
if (prefix != null) {
old += prefix;
}
if (old.length() == 0) {
return body;
}
String nsnew = "";
if (ns != null) {
nsnew += ns;
}
StringBuffer bBody = new StringBuffer(body);
for (int start = bBody.indexOf(old); start >= 0;) {
bBody.replace(start, start + old.length(), nsnew);
}
return bBody.toString();
}
}
|
36394_35 | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjgl.util.glu.tessellation;
import static org.lwjgl.util.glu.GLU.GLU_INVALID_ENUM;
import static org.lwjgl.util.glu.GLU.GLU_INVALID_VALUE;
import static org.lwjgl.util.glu.GLU.GLU_OUT_OF_MEMORY;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BEGIN;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BEGIN_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BOUNDARY_ONLY;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COMBINE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COMBINE_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COORD_TOO_LARGE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_EDGE_FLAG;
import static org.lwjgl.util.glu.GLU.GLU_TESS_EDGE_FLAG_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_END;
import static org.lwjgl.util.glu.GLU.GLU_TESS_END_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_ERROR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_ERROR_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MAX_COORD;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_BEGIN_CONTOUR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_BEGIN_POLYGON;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_END_CONTOUR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_END_POLYGON;
import static org.lwjgl.util.glu.GLU.GLU_TESS_TOLERANCE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_VERTEX;
import static org.lwjgl.util.glu.GLU.GLU_TESS_VERTEX_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_ABS_GEQ_TWO;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_NEGATIVE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_NONZERO;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_ODD;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_POSITIVE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_RULE;
import org.lwjgl.util.glu.GLUtessellator;
import org.lwjgl.util.glu.GLUtessellatorCallback;
import org.lwjgl.util.glu.GLUtessellatorCallbackAdapter;
public class GLUtessellatorImpl implements GLUtessellator {
public static final int TESS_MAX_CACHE = 100;
private int state; /* what begin/end calls have we seen? */
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
the tessellation itself */
/*** state needed for projecting onto the sweep plane ***/
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
/*** state needed for the line sweep ***/
private double relTolerance; /* tolerance for merging features */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
/*** state needed for rendering callbacks (see render.c) ***/
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean boundaryOnly; /* Extract contours, not triangles */
GLUface lonelyTriList;
/* list of triangles which could not be rendered as strips or fans */
/*** state needed to cache single-contour polygons for renderCache() */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
/*** rendering callbacks that also pass polygon data ***/
private Object polygonData; /* client data for current polygon */
private GLUtessellatorCallback callBegin;
private GLUtessellatorCallback callEdgeFlag;
private GLUtessellatorCallback callVertex;
private GLUtessellatorCallback callEnd;
// private GLUtessellatorCallback callMesh;
private GLUtessellatorCallback callError;
private GLUtessellatorCallback callCombine;
private GLUtessellatorCallback callBeginData;
private GLUtessellatorCallback callEdgeFlagData;
private GLUtessellatorCallback callVertexData;
private GLUtessellatorCallback callEndData;
// private GLUtessellatorCallback callMeshData;
private GLUtessellatorCallback callErrorData;
private GLUtessellatorCallback callCombineData;
private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0;
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter();
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
public GLUtessellatorImpl() {
state = TessState.T_DORMANT;
normal[0] = 0;
normal[1] = 0;
normal[2] = 0;
relTolerance = GLU_TESS_DEFAULT_TOLERANCE;
windingRule = GLU_TESS_WINDING_ODD;
flagBoundary = false;
boundaryOnly = false;
callBegin = NULL_CB;
callEdgeFlag = NULL_CB;
callVertex = NULL_CB;
callEnd = NULL_CB;
callError = NULL_CB;
callCombine = NULL_CB;
// callMesh = NULL_CB;
callBeginData = NULL_CB;
callEdgeFlagData = NULL_CB;
callVertexData = NULL_CB;
callEndData = NULL_CB;
callErrorData = NULL_CB;
callCombineData = NULL_CB;
polygonData = null;
for (int i = 0; i < cache.length; i++) {
cache[i] = new CachedVertex();
}
}
public static GLUtessellator gluNewTess()
{
return new GLUtessellatorImpl();
}
private void makeDormant() {
/* Return the tessellator to its original dormant state. */
if (mesh != null) {
Mesh.__gl_meshDeleteMesh(mesh);
}
state = TessState.T_DORMANT;
lastEdge = null;
mesh = null;
}
private void requireState(int newState) {
if (state != newState) gotoState(newState);
}
private void gotoState(int newState) {
while (state != newState) {
/* We change the current state one level at a time, to get to
* the desired state.
*/
if (state < newState) {
if (state == TessState.T_DORMANT) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_POLYGON);
gluTessBeginPolygon(null);
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_CONTOUR);
gluTessBeginContour();
}
} else {
if (state == TessState.T_IN_CONTOUR) {
callErrorOrErrorData(GLU_TESS_MISSING_END_CONTOUR);
gluTessEndContour();
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_END_POLYGON);
/* gluTessEndPolygon( tess ) is too much work! */
makeDormant();
}
}
}
}
public void gluDeleteTess() {
requireState(TessState.T_DORMANT);
}
public void gluTessProperty(int which, double value) {
switch (which) {
case GLU_TESS_TOLERANCE:
if (value < 0.0 || value > 1.0) break;
relTolerance = value;
return;
case GLU_TESS_WINDING_RULE:
int windingRule = (int) value;
if (windingRule != value) break; /* not an integer */
switch (windingRule) {
case GLU_TESS_WINDING_ODD:
case GLU_TESS_WINDING_NONZERO:
case GLU_TESS_WINDING_POSITIVE:
case GLU_TESS_WINDING_NEGATIVE:
case GLU_TESS_WINDING_ABS_GEQ_TWO:
this.windingRule = windingRule;
return;
default:
break;
}
case GLU_TESS_BOUNDARY_ONLY:
boundaryOnly = (value != 0);
return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
callErrorOrErrorData(GLU_INVALID_VALUE);
}
/* Returns tessellator property */
public void gluGetTessProperty(int which, double[] value, int value_offset) {
switch (which) {
case GLU_TESS_TOLERANCE:
/* tolerance should be in range [0..1] */
assert (0.0 <= relTolerance && relTolerance <= 1.0);
value[value_offset] = relTolerance;
break;
case GLU_TESS_WINDING_RULE:
assert (windingRule == GLU_TESS_WINDING_ODD ||
windingRule == GLU_TESS_WINDING_NONZERO ||
windingRule == GLU_TESS_WINDING_POSITIVE ||
windingRule == GLU_TESS_WINDING_NEGATIVE ||
windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
value[value_offset] = windingRule;
break;
case GLU_TESS_BOUNDARY_ONLY:
assert (boundaryOnly == true || boundaryOnly == false);
value[value_offset] = boundaryOnly ? 1 : 0;
break;
default:
value[value_offset] = 0.0;
callErrorOrErrorData(GLU_INVALID_ENUM);
break;
}
} /* gluGetTessProperty() */
public void gluTessNormal(double x, double y, double z) {
normal[0] = x;
normal[1] = y;
normal[2] = z;
}
public void gluTessCallback(int which, GLUtessellatorCallback aCallback) {
switch (which) {
case GLU_TESS_BEGIN:
callBegin = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_BEGIN_DATA:
callBeginData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_EDGE_FLAG:
callEdgeFlag = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = aCallback != null;
return;
case GLU_TESS_EDGE_FLAG_DATA:
callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = (aCallback != null);
return;
case GLU_TESS_VERTEX:
callVertex = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_VERTEX_DATA:
callVertexData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END:
callEnd = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END_DATA:
callEndData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR:
callError = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR_DATA:
callErrorData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE:
callCombine = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE_DATA:
callCombineData = aCallback == null ? NULL_CB : aCallback;
return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
}
private boolean addVertex(double[] coords, Object vertexData) {
GLUhalfEdge e;
e = lastEdge;
if (e == null) {
/* Make a self-loop (one vertex, one edge). */
e = Mesh.__gl_meshMakeEdge(mesh);
if (e == null) return false;
if (!Mesh.__gl_meshSplice(e, e.Sym)) return false;
} else {
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.__gl_meshSplitEdge(e) == null) return false;
e = e.Lnext;
}
/* The new vertex is now e.Org. */
e.Org.data = vertexData;
e.Org.coords[0] = coords[0];
e.Org.coords[1] = coords[1];
e.Org.coords[2] = coords[2];
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.Sym.winding = -1;
lastEdge = e;
return true;
}
private void cacheVertex(double[] coords, Object vertexData) {
if (cache[cacheCount] == null) {
cache[cacheCount] = new CachedVertex();
}
CachedVertex v = cache[cacheCount];
v.data = vertexData;
v.coords[0] = coords[0];
v.coords[1] = coords[1];
v.coords[2] = coords[2];
++cacheCount;
}
private boolean flushCache() {
CachedVertex[] v = cache;
mesh = Mesh.__gl_meshNewMesh();
if (mesh == null) return false;
for (int i = 0; i < cacheCount; i++) {
CachedVertex vertex = v[i];
if (!addVertex(vertex.coords, vertex.data)) return false;
}
cacheCount = 0;
flushCacheOnNextVertex = false;
return true;
}
public void gluTessVertex(double[] coords, int coords_offset, Object vertexData) {
int i;
boolean tooLarge = false;
double x;
double[] clamped = new double[3];
requireState(TessState.T_IN_CONTOUR);
if (flushCacheOnNextVertex) {
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
lastEdge = null;
}
for (i = 0; i < 3; ++i) {
x = coords[i+coords_offset];
if (x < -GLU_TESS_MAX_COORD) {
x = -GLU_TESS_MAX_COORD;
tooLarge = true;
}
if (x > GLU_TESS_MAX_COORD) {
x = GLU_TESS_MAX_COORD;
tooLarge = true;
}
clamped[i] = x;
}
if (tooLarge) {
callErrorOrErrorData(GLU_TESS_COORD_TOO_LARGE);
}
if (mesh == null) {
if (cacheCount < TESS_MAX_CACHE) {
cacheVertex(clamped, vertexData);
return;
}
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
}
if (!addVertex(clamped, vertexData)) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
public void gluTessBeginPolygon(Object data) {
requireState(TessState.T_DORMANT);
state = TessState.T_IN_POLYGON;
cacheCount = 0;
flushCacheOnNextVertex = false;
mesh = null;
polygonData = data;
}
public void gluTessBeginContour() {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_IN_CONTOUR;
lastEdge = null;
if (cacheCount > 0) {
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
flushCacheOnNextVertex = true;
}
}
public void gluTessEndContour() {
requireState(TessState.T_IN_CONTOUR);
state = TessState.T_IN_POLYGON;
}
public void gluTessEndPolygon() {
GLUmesh mesh;
try {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_DORMANT;
if (this.mesh == null) {
if (!flagBoundary /*&& callMesh == NULL_CB*/) {
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (Render.__gl_renderCache(this)) {
polygonData = null;
return;
}
}
if (!flushCache()) throw new RuntimeException(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
Normal.__gl_projectPolygon(this);
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
if (!Sweep.__gl_computeInterior(this)) {
throw new RuntimeException(); /* could've used a label */
}
mesh = this.mesh;
if (!fatalError) {
boolean rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly) {
rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true);
} else {
rc = TessMono.__gl_meshTessellateInterior(mesh);
}
if (!rc) throw new RuntimeException(); /* could've used a label */
Mesh.__gl_meshCheckMesh(mesh);
if (callBegin != NULL_CB || callEnd != NULL_CB
|| callVertex != NULL_CB || callEdgeFlag != NULL_CB
|| callBeginData != NULL_CB
|| callEndData != NULL_CB
|| callVertexData != NULL_CB
|| callEdgeFlagData != NULL_CB) {
if (boundaryOnly) {
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
} else {
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
}
}
// if (callMesh != NULL_CB) {
//
///* Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
}
Mesh.__gl_meshDeleteMesh(mesh);
polygonData = null;
mesh = null;
} catch (Exception e) {
e.printStackTrace();
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
public void gluBeginPolygon() {
gluTessBeginPolygon(null);
gluTessBeginContour();
}
/*ARGSUSED*/
public void gluNextContour(int type) {
gluTessEndContour();
gluTessBeginContour();
}
public void gluEndPolygon() {
gluTessEndContour();
gluTessEndPolygon();
}
void callBeginOrBeginData(int a) {
if (callBeginData != NULL_CB)
callBeginData.beginData(a, polygonData);
else
callBegin.begin(a);
}
void callVertexOrVertexData(Object a) {
if (callVertexData != NULL_CB)
callVertexData.vertexData(a, polygonData);
else
callVertex.vertex(a);
}
void callEdgeFlagOrEdgeFlagData(boolean a) {
if (callEdgeFlagData != NULL_CB)
callEdgeFlagData.edgeFlagData(a, polygonData);
else
callEdgeFlag.edgeFlag(a);
}
void callEndOrEndData() {
if (callEndData != NULL_CB)
callEndData.endData(polygonData);
else
callEnd.end();
}
void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) {
if (callCombineData != NULL_CB)
callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else
callCombine.combine(coords, vertexData, weights, outData);
}
void callErrorOrErrorData(int a) {
if (callErrorData != NULL_CB)
callErrorData.errorData(a, polygonData);
else
callError.error(a);
}
}
| FCL-Team/FoldCraftLauncher | LWJGL/src/main/java/org/lwjgl/util/glu/tessellation/GLUtessellatorImpl.java | 7,017 | /* not an integer */ | block_comment | nl | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package org.lwjgl.util.glu.tessellation;
import static org.lwjgl.util.glu.GLU.GLU_INVALID_ENUM;
import static org.lwjgl.util.glu.GLU.GLU_INVALID_VALUE;
import static org.lwjgl.util.glu.GLU.GLU_OUT_OF_MEMORY;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BEGIN;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BEGIN_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_BOUNDARY_ONLY;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COMBINE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COMBINE_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_COORD_TOO_LARGE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_EDGE_FLAG;
import static org.lwjgl.util.glu.GLU.GLU_TESS_EDGE_FLAG_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_END;
import static org.lwjgl.util.glu.GLU.GLU_TESS_END_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_ERROR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_ERROR_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MAX_COORD;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_BEGIN_CONTOUR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_BEGIN_POLYGON;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_END_CONTOUR;
import static org.lwjgl.util.glu.GLU.GLU_TESS_MISSING_END_POLYGON;
import static org.lwjgl.util.glu.GLU.GLU_TESS_TOLERANCE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_VERTEX;
import static org.lwjgl.util.glu.GLU.GLU_TESS_VERTEX_DATA;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_ABS_GEQ_TWO;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_NEGATIVE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_NONZERO;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_ODD;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_POSITIVE;
import static org.lwjgl.util.glu.GLU.GLU_TESS_WINDING_RULE;
import org.lwjgl.util.glu.GLUtessellator;
import org.lwjgl.util.glu.GLUtessellatorCallback;
import org.lwjgl.util.glu.GLUtessellatorCallbackAdapter;
public class GLUtessellatorImpl implements GLUtessellator {
public static final int TESS_MAX_CACHE = 100;
private int state; /* what begin/end calls have we seen? */
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
the tessellation itself */
/*** state needed for projecting onto the sweep plane ***/
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
/*** state needed for the line sweep ***/
private double relTolerance; /* tolerance for merging features */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
/*** state needed for rendering callbacks (see render.c) ***/
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean boundaryOnly; /* Extract contours, not triangles */
GLUface lonelyTriList;
/* list of triangles which could not be rendered as strips or fans */
/*** state needed to cache single-contour polygons for renderCache() */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
/*** rendering callbacks that also pass polygon data ***/
private Object polygonData; /* client data for current polygon */
private GLUtessellatorCallback callBegin;
private GLUtessellatorCallback callEdgeFlag;
private GLUtessellatorCallback callVertex;
private GLUtessellatorCallback callEnd;
// private GLUtessellatorCallback callMesh;
private GLUtessellatorCallback callError;
private GLUtessellatorCallback callCombine;
private GLUtessellatorCallback callBeginData;
private GLUtessellatorCallback callEdgeFlagData;
private GLUtessellatorCallback callVertexData;
private GLUtessellatorCallback callEndData;
// private GLUtessellatorCallback callMeshData;
private GLUtessellatorCallback callErrorData;
private GLUtessellatorCallback callCombineData;
private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0;
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter();
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
public GLUtessellatorImpl() {
state = TessState.T_DORMANT;
normal[0] = 0;
normal[1] = 0;
normal[2] = 0;
relTolerance = GLU_TESS_DEFAULT_TOLERANCE;
windingRule = GLU_TESS_WINDING_ODD;
flagBoundary = false;
boundaryOnly = false;
callBegin = NULL_CB;
callEdgeFlag = NULL_CB;
callVertex = NULL_CB;
callEnd = NULL_CB;
callError = NULL_CB;
callCombine = NULL_CB;
// callMesh = NULL_CB;
callBeginData = NULL_CB;
callEdgeFlagData = NULL_CB;
callVertexData = NULL_CB;
callEndData = NULL_CB;
callErrorData = NULL_CB;
callCombineData = NULL_CB;
polygonData = null;
for (int i = 0; i < cache.length; i++) {
cache[i] = new CachedVertex();
}
}
public static GLUtessellator gluNewTess()
{
return new GLUtessellatorImpl();
}
private void makeDormant() {
/* Return the tessellator to its original dormant state. */
if (mesh != null) {
Mesh.__gl_meshDeleteMesh(mesh);
}
state = TessState.T_DORMANT;
lastEdge = null;
mesh = null;
}
private void requireState(int newState) {
if (state != newState) gotoState(newState);
}
private void gotoState(int newState) {
while (state != newState) {
/* We change the current state one level at a time, to get to
* the desired state.
*/
if (state < newState) {
if (state == TessState.T_DORMANT) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_POLYGON);
gluTessBeginPolygon(null);
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_CONTOUR);
gluTessBeginContour();
}
} else {
if (state == TessState.T_IN_CONTOUR) {
callErrorOrErrorData(GLU_TESS_MISSING_END_CONTOUR);
gluTessEndContour();
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_END_POLYGON);
/* gluTessEndPolygon( tess ) is too much work! */
makeDormant();
}
}
}
}
public void gluDeleteTess() {
requireState(TessState.T_DORMANT);
}
public void gluTessProperty(int which, double value) {
switch (which) {
case GLU_TESS_TOLERANCE:
if (value < 0.0 || value > 1.0) break;
relTolerance = value;
return;
case GLU_TESS_WINDING_RULE:
int windingRule = (int) value;
if (windingRule != value) break; /* not an integer<SUF>*/
switch (windingRule) {
case GLU_TESS_WINDING_ODD:
case GLU_TESS_WINDING_NONZERO:
case GLU_TESS_WINDING_POSITIVE:
case GLU_TESS_WINDING_NEGATIVE:
case GLU_TESS_WINDING_ABS_GEQ_TWO:
this.windingRule = windingRule;
return;
default:
break;
}
case GLU_TESS_BOUNDARY_ONLY:
boundaryOnly = (value != 0);
return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
callErrorOrErrorData(GLU_INVALID_VALUE);
}
/* Returns tessellator property */
public void gluGetTessProperty(int which, double[] value, int value_offset) {
switch (which) {
case GLU_TESS_TOLERANCE:
/* tolerance should be in range [0..1] */
assert (0.0 <= relTolerance && relTolerance <= 1.0);
value[value_offset] = relTolerance;
break;
case GLU_TESS_WINDING_RULE:
assert (windingRule == GLU_TESS_WINDING_ODD ||
windingRule == GLU_TESS_WINDING_NONZERO ||
windingRule == GLU_TESS_WINDING_POSITIVE ||
windingRule == GLU_TESS_WINDING_NEGATIVE ||
windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
value[value_offset] = windingRule;
break;
case GLU_TESS_BOUNDARY_ONLY:
assert (boundaryOnly == true || boundaryOnly == false);
value[value_offset] = boundaryOnly ? 1 : 0;
break;
default:
value[value_offset] = 0.0;
callErrorOrErrorData(GLU_INVALID_ENUM);
break;
}
} /* gluGetTessProperty() */
public void gluTessNormal(double x, double y, double z) {
normal[0] = x;
normal[1] = y;
normal[2] = z;
}
public void gluTessCallback(int which, GLUtessellatorCallback aCallback) {
switch (which) {
case GLU_TESS_BEGIN:
callBegin = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_BEGIN_DATA:
callBeginData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_EDGE_FLAG:
callEdgeFlag = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = aCallback != null;
return;
case GLU_TESS_EDGE_FLAG_DATA:
callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = (aCallback != null);
return;
case GLU_TESS_VERTEX:
callVertex = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_VERTEX_DATA:
callVertexData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END:
callEnd = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END_DATA:
callEndData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR:
callError = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR_DATA:
callErrorData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE:
callCombine = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE_DATA:
callCombineData = aCallback == null ? NULL_CB : aCallback;
return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
}
private boolean addVertex(double[] coords, Object vertexData) {
GLUhalfEdge e;
e = lastEdge;
if (e == null) {
/* Make a self-loop (one vertex, one edge). */
e = Mesh.__gl_meshMakeEdge(mesh);
if (e == null) return false;
if (!Mesh.__gl_meshSplice(e, e.Sym)) return false;
} else {
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.__gl_meshSplitEdge(e) == null) return false;
e = e.Lnext;
}
/* The new vertex is now e.Org. */
e.Org.data = vertexData;
e.Org.coords[0] = coords[0];
e.Org.coords[1] = coords[1];
e.Org.coords[2] = coords[2];
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.Sym.winding = -1;
lastEdge = e;
return true;
}
private void cacheVertex(double[] coords, Object vertexData) {
if (cache[cacheCount] == null) {
cache[cacheCount] = new CachedVertex();
}
CachedVertex v = cache[cacheCount];
v.data = vertexData;
v.coords[0] = coords[0];
v.coords[1] = coords[1];
v.coords[2] = coords[2];
++cacheCount;
}
private boolean flushCache() {
CachedVertex[] v = cache;
mesh = Mesh.__gl_meshNewMesh();
if (mesh == null) return false;
for (int i = 0; i < cacheCount; i++) {
CachedVertex vertex = v[i];
if (!addVertex(vertex.coords, vertex.data)) return false;
}
cacheCount = 0;
flushCacheOnNextVertex = false;
return true;
}
public void gluTessVertex(double[] coords, int coords_offset, Object vertexData) {
int i;
boolean tooLarge = false;
double x;
double[] clamped = new double[3];
requireState(TessState.T_IN_CONTOUR);
if (flushCacheOnNextVertex) {
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
lastEdge = null;
}
for (i = 0; i < 3; ++i) {
x = coords[i+coords_offset];
if (x < -GLU_TESS_MAX_COORD) {
x = -GLU_TESS_MAX_COORD;
tooLarge = true;
}
if (x > GLU_TESS_MAX_COORD) {
x = GLU_TESS_MAX_COORD;
tooLarge = true;
}
clamped[i] = x;
}
if (tooLarge) {
callErrorOrErrorData(GLU_TESS_COORD_TOO_LARGE);
}
if (mesh == null) {
if (cacheCount < TESS_MAX_CACHE) {
cacheVertex(clamped, vertexData);
return;
}
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
}
if (!addVertex(clamped, vertexData)) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
public void gluTessBeginPolygon(Object data) {
requireState(TessState.T_DORMANT);
state = TessState.T_IN_POLYGON;
cacheCount = 0;
flushCacheOnNextVertex = false;
mesh = null;
polygonData = data;
}
public void gluTessBeginContour() {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_IN_CONTOUR;
lastEdge = null;
if (cacheCount > 0) {
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
flushCacheOnNextVertex = true;
}
}
public void gluTessEndContour() {
requireState(TessState.T_IN_CONTOUR);
state = TessState.T_IN_POLYGON;
}
public void gluTessEndPolygon() {
GLUmesh mesh;
try {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_DORMANT;
if (this.mesh == null) {
if (!flagBoundary /*&& callMesh == NULL_CB*/) {
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (Render.__gl_renderCache(this)) {
polygonData = null;
return;
}
}
if (!flushCache()) throw new RuntimeException(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
Normal.__gl_projectPolygon(this);
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
if (!Sweep.__gl_computeInterior(this)) {
throw new RuntimeException(); /* could've used a label */
}
mesh = this.mesh;
if (!fatalError) {
boolean rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly) {
rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true);
} else {
rc = TessMono.__gl_meshTessellateInterior(mesh);
}
if (!rc) throw new RuntimeException(); /* could've used a label */
Mesh.__gl_meshCheckMesh(mesh);
if (callBegin != NULL_CB || callEnd != NULL_CB
|| callVertex != NULL_CB || callEdgeFlag != NULL_CB
|| callBeginData != NULL_CB
|| callEndData != NULL_CB
|| callVertexData != NULL_CB
|| callEdgeFlagData != NULL_CB) {
if (boundaryOnly) {
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
} else {
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
}
}
// if (callMesh != NULL_CB) {
//
///* Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
}
Mesh.__gl_meshDeleteMesh(mesh);
polygonData = null;
mesh = null;
} catch (Exception e) {
e.printStackTrace();
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
public void gluBeginPolygon() {
gluTessBeginPolygon(null);
gluTessBeginContour();
}
/*ARGSUSED*/
public void gluNextContour(int type) {
gluTessEndContour();
gluTessBeginContour();
}
public void gluEndPolygon() {
gluTessEndContour();
gluTessEndPolygon();
}
void callBeginOrBeginData(int a) {
if (callBeginData != NULL_CB)
callBeginData.beginData(a, polygonData);
else
callBegin.begin(a);
}
void callVertexOrVertexData(Object a) {
if (callVertexData != NULL_CB)
callVertexData.vertexData(a, polygonData);
else
callVertex.vertex(a);
}
void callEdgeFlagOrEdgeFlagData(boolean a) {
if (callEdgeFlagData != NULL_CB)
callEdgeFlagData.edgeFlagData(a, polygonData);
else
callEdgeFlag.edgeFlag(a);
}
void callEndOrEndData() {
if (callEndData != NULL_CB)
callEndData.endData(polygonData);
else
callEnd.end();
}
void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) {
if (callCombineData != NULL_CB)
callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else
callCombine.combine(coords, vertexData, weights, outData);
}
void callErrorOrErrorData(int a) {
if (callErrorData != NULL_CB)
callErrorData.errorData(a, polygonData);
else
callError.error(a);
}
}
|
32568_26 | /* Dit voorbeeld: Gert den Neijsel 20221207 (origineel 20201216) (in puur sequentiële Arduino stijl)
Eenvoudig verzenden en ontvangen van data via seriële poort.
Zie bron: https://github.com/RishiGupta12/SerialPundit voor meer gevanceerde voorbeelden
Geen threads - geen timers - geen events (alleen voor de gui).
Dat betekent dat het programma stilstaat als je een stukje code toevoegd waar het programma op moet wachten.
Is te testen in combinatie met Arduino sketch "Microbit_SerieelInvoerUitvoer.ino"
Voer na installatie de volgende commando's uit in MySQL server/workbench:
CREATE DATABASE vb1;
CREATE TABLE vb1.tbl1(tijdstip TEXT, temperatuur FLOAT);
CREATE USER microbit IDENTIFIED BY 'geheim';
GRANT INSERT, UPDATE, SELECT, DELETE ON vb1.* TO 'microbit';
Nadat dit programma data ingevoerd heeft in de database, dan kun je dit opvragen maken met dit commando:
SELECT * FROM vb1.tbl1;
*/
package nl.hhs.challenge;
import com.serialpundit.serial.SerialComManager;
import com.serialpundit.serial.SerialComManager.*;
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;
//import java.time.Clock; // voor de millis()
public class SerialInOutExample extends JFrame {
private JPanel mainPanel;
private JTextField inkomend;
private JTextField uitgaand;
private JButton verstuurButton;
private String teVerzenden;
public static void main(String[] args) {
JFrame frame = new SerialInOutExample("SerialInOutExample");
frame.setVisible(true);
}
public SerialInOutExample(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(mainPanel);
this.pack();
verstuurButton.addActionListener(e -> {
teVerzenden = uitgaand.getText();
uitgaand.setText("");
});
// Stukje code om elke 2 seconden iets via seriële poort te verzenden (om te testen ofzo)
// Clock clock = Clock.systemDefaultZone();
// long millis = 0;
// long vorigeMillis = 0;
// int interval = 2000; // interval van verzenden
// Begin van het "hoofdprogramma"
InsertIntoSQL database = new InsertIntoSQL(); //Deze regel uitcommenten als SQL nog niet werkt.
String port = "";
try {
SerialComManager scm = new SerialComManager();
// Blok hieronder: automatisch de poort met de Microbit kiezen (werkt alleen voor Microbit).
String[] poorten = scm.listAvailableComPorts();
for (String poort : poorten) {
String p = "";
try {
p = scm.findDriverServingComPort(poort);
}
catch (Exception e) {
// Geen behoefte aan foutmeldingen, dit is alleen om te voorkomen dat het programma crasht.
}
System.out.println();
if(p.contains("usbser")) { // Microbit
port = poort;
System.out.println("Poort " + poort + " (" + p + ") gekozen..."); // beschikbare poorten afdrukken
}
}
if (port.isEmpty()) {
System.out.print("Geen Microbit gevonden!");
System.exit(1); // Programma afbreken
}
// COM poort kun je ook hard invullen, zoek via Arduino of Device Manager uit welke COM poort je gebruikt:
// long handle = scm.openComPort("COM3", true, true, true);
long handle = scm.openComPort(port, true, true, true);
scm.configureComPortData(handle, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0);
scm.configureComPortControl(handle, FLOWCONTROL.NONE, 'x', 'x', false, false);
scm.writeString(handle, "test", 0);
this.setVisible(true); // de gui
while (true) { // gewoon altijd doorgaan, vergelijkbaar met de Arduino loop()
this.mainPanel.updateUI();
// tijdstip = nu, dit moment.
String tijdstip = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
tijdstip = tijdstip.replaceAll("[\\n\\r]", ""); // tijdstip om af te drukken, handig...
// Stukje code om elke 2 seconden iets via seriële poort te verzenden (om te testen ofzo)
// millis = clock.millis(); // tijdafhandeling op dezelfde manier als op Arduino/Microbit
// if (millis > vorigeMillis + interval) {
// String dataVerzenden = "\n";
// scm.writeString(handle, dataVerzenden, 0);
//// System.out.println(tijdstip + " Data verzonden: " + dataVerzenden);
// vorigeMillis = millis;
// }
// Data verzenden via serieel
if (teVerzenden != null) {
scm.writeString(handle, teVerzenden, 0);
System.out.println(tijdstip + " Data verzonden: " + teVerzenden);
teVerzenden = null;
}
// Data ontvangen via serieel
String dataOntvangen = scm.readString(handle);
if (dataOntvangen != null) { // Er is data ontvangen
// verwijder alle newlines '\n' en carriage_returns '\r':
dataOntvangen = dataOntvangen.replaceAll("[\\n\\r]", "");
System.out.println(tijdstip + " Ontvangen data: " + dataOntvangen);
this.inkomend.setText("Ontvangen op " + tijdstip + ": " + dataOntvangen);
try {
int waterverbruik = Integer.parseInt(dataOntvangen);
database.insert(waterverbruik);
} catch (Exception e) {
System.out.println("Lege data");
}
// afronden op 1 cijfer achter de komma
// temperatuur = (float) (Math.round(temperatuur * 10.0) / 10.0);
//System.out.println("Float: " + temperatuur); // Kun je mee testen of er correct verstuurd wordt.
//Deze regel uitcommenten als SQL nog niet werkt.
// if (dataOntvangen.contains("1")) { // Piepje als er een 1 gelezen wordt vanaf de seriële poort
// System.out.println("\"1\" ontvangen, dus: Windows default beep");
// Toolkit.getDefaultToolkit().beep(); // Piep
// }
}
}
} catch (Exception e) { // Stukje foutafhandeling, wordt als het goed is nooit gebruikt
System.out.print("\033[1;93m\033[41m"); // Dikke gele tekst in rode achtergrond (ANSI colors Java)
System.out.print("Ai, er zit een fout in je programma. Kijk eerst naar de onderste rode foutmeldingen en werk omhoog:");
System.out.println("\033[0m"); // Tekstkleuren weer resetten naar standaard.
e.printStackTrace(); // Dit drukt de foutmeldingen af.
System.exit(2); // Programma afbreken
}
}
}
| ShiverP/chiclaps-java | Embedded/SerialInOutExample/src/nl/hhs/challenge/SerialInOutExample.java | 1,812 | // Er is data ontvangen | line_comment | nl | /* Dit voorbeeld: Gert den Neijsel 20221207 (origineel 20201216) (in puur sequentiële Arduino stijl)
Eenvoudig verzenden en ontvangen van data via seriële poort.
Zie bron: https://github.com/RishiGupta12/SerialPundit voor meer gevanceerde voorbeelden
Geen threads - geen timers - geen events (alleen voor de gui).
Dat betekent dat het programma stilstaat als je een stukje code toevoegd waar het programma op moet wachten.
Is te testen in combinatie met Arduino sketch "Microbit_SerieelInvoerUitvoer.ino"
Voer na installatie de volgende commando's uit in MySQL server/workbench:
CREATE DATABASE vb1;
CREATE TABLE vb1.tbl1(tijdstip TEXT, temperatuur FLOAT);
CREATE USER microbit IDENTIFIED BY 'geheim';
GRANT INSERT, UPDATE, SELECT, DELETE ON vb1.* TO 'microbit';
Nadat dit programma data ingevoerd heeft in de database, dan kun je dit opvragen maken met dit commando:
SELECT * FROM vb1.tbl1;
*/
package nl.hhs.challenge;
import com.serialpundit.serial.SerialComManager;
import com.serialpundit.serial.SerialComManager.*;
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;
//import java.time.Clock; // voor de millis()
public class SerialInOutExample extends JFrame {
private JPanel mainPanel;
private JTextField inkomend;
private JTextField uitgaand;
private JButton verstuurButton;
private String teVerzenden;
public static void main(String[] args) {
JFrame frame = new SerialInOutExample("SerialInOutExample");
frame.setVisible(true);
}
public SerialInOutExample(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(mainPanel);
this.pack();
verstuurButton.addActionListener(e -> {
teVerzenden = uitgaand.getText();
uitgaand.setText("");
});
// Stukje code om elke 2 seconden iets via seriële poort te verzenden (om te testen ofzo)
// Clock clock = Clock.systemDefaultZone();
// long millis = 0;
// long vorigeMillis = 0;
// int interval = 2000; // interval van verzenden
// Begin van het "hoofdprogramma"
InsertIntoSQL database = new InsertIntoSQL(); //Deze regel uitcommenten als SQL nog niet werkt.
String port = "";
try {
SerialComManager scm = new SerialComManager();
// Blok hieronder: automatisch de poort met de Microbit kiezen (werkt alleen voor Microbit).
String[] poorten = scm.listAvailableComPorts();
for (String poort : poorten) {
String p = "";
try {
p = scm.findDriverServingComPort(poort);
}
catch (Exception e) {
// Geen behoefte aan foutmeldingen, dit is alleen om te voorkomen dat het programma crasht.
}
System.out.println();
if(p.contains("usbser")) { // Microbit
port = poort;
System.out.println("Poort " + poort + " (" + p + ") gekozen..."); // beschikbare poorten afdrukken
}
}
if (port.isEmpty()) {
System.out.print("Geen Microbit gevonden!");
System.exit(1); // Programma afbreken
}
// COM poort kun je ook hard invullen, zoek via Arduino of Device Manager uit welke COM poort je gebruikt:
// long handle = scm.openComPort("COM3", true, true, true);
long handle = scm.openComPort(port, true, true, true);
scm.configureComPortData(handle, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0);
scm.configureComPortControl(handle, FLOWCONTROL.NONE, 'x', 'x', false, false);
scm.writeString(handle, "test", 0);
this.setVisible(true); // de gui
while (true) { // gewoon altijd doorgaan, vergelijkbaar met de Arduino loop()
this.mainPanel.updateUI();
// tijdstip = nu, dit moment.
String tijdstip = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
tijdstip = tijdstip.replaceAll("[\\n\\r]", ""); // tijdstip om af te drukken, handig...
// Stukje code om elke 2 seconden iets via seriële poort te verzenden (om te testen ofzo)
// millis = clock.millis(); // tijdafhandeling op dezelfde manier als op Arduino/Microbit
// if (millis > vorigeMillis + interval) {
// String dataVerzenden = "\n";
// scm.writeString(handle, dataVerzenden, 0);
//// System.out.println(tijdstip + " Data verzonden: " + dataVerzenden);
// vorigeMillis = millis;
// }
// Data verzenden via serieel
if (teVerzenden != null) {
scm.writeString(handle, teVerzenden, 0);
System.out.println(tijdstip + " Data verzonden: " + teVerzenden);
teVerzenden = null;
}
// Data ontvangen via serieel
String dataOntvangen = scm.readString(handle);
if (dataOntvangen != null) { // Er is<SUF>
// verwijder alle newlines '\n' en carriage_returns '\r':
dataOntvangen = dataOntvangen.replaceAll("[\\n\\r]", "");
System.out.println(tijdstip + " Ontvangen data: " + dataOntvangen);
this.inkomend.setText("Ontvangen op " + tijdstip + ": " + dataOntvangen);
try {
int waterverbruik = Integer.parseInt(dataOntvangen);
database.insert(waterverbruik);
} catch (Exception e) {
System.out.println("Lege data");
}
// afronden op 1 cijfer achter de komma
// temperatuur = (float) (Math.round(temperatuur * 10.0) / 10.0);
//System.out.println("Float: " + temperatuur); // Kun je mee testen of er correct verstuurd wordt.
//Deze regel uitcommenten als SQL nog niet werkt.
// if (dataOntvangen.contains("1")) { // Piepje als er een 1 gelezen wordt vanaf de seriële poort
// System.out.println("\"1\" ontvangen, dus: Windows default beep");
// Toolkit.getDefaultToolkit().beep(); // Piep
// }
}
}
} catch (Exception e) { // Stukje foutafhandeling, wordt als het goed is nooit gebruikt
System.out.print("\033[1;93m\033[41m"); // Dikke gele tekst in rode achtergrond (ANSI colors Java)
System.out.print("Ai, er zit een fout in je programma. Kijk eerst naar de onderste rode foutmeldingen en werk omhoog:");
System.out.println("\033[0m"); // Tekstkleuren weer resetten naar standaard.
e.printStackTrace(); // Dit drukt de foutmeldingen af.
System.exit(2); // Programma afbreken
}
}
}
|
203855_4 | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.widgets;
import static com.google.gapid.models.Follower.nullPrefetcher;
import static com.google.gapid.util.Arrays.last;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.withAsyncRefresh;
import com.google.gapid.models.Follower;
import com.google.gapid.proto.service.path.Path;
import com.google.gapid.util.Events;
import com.google.gapid.util.GeoUtils;
import com.google.gapid.util.MouseAdapter;
import com.google.gapid.views.Formatter.LinkableStyledString;
import com.google.gapid.views.Formatter.StylingString;
import com.google.gapid.widgets.CopySources.ColumnTextProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.OwnerDrawLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import java.util.function.Predicate;
/**
* A {@link TreeViewer} where each label can have rich formatting (using
* {@link com.google.gapid.views.Formatter.StylingString}), links, and custom background color.
*/
public abstract class LinkifiedTree<T, F> extends Composite {
private final TreeViewer viewer;
protected final Widgets.Refresher refresher;
protected final ContentProvider<T> contentProvider;
protected final LabelProvider labelProvider;
public LinkifiedTree(Composite parent, int treeStyle, Widgets widgets) {
super(parent, SWT.NONE);
setLayout(new FillLayout());
this.viewer = createTreeViewer(this, treeStyle);
this.refresher = withAsyncRefresh(viewer);
this.contentProvider = createContentProvider();
this.labelProvider = createLabelProvider(widgets.theme);
viewer.setContentProvider(contentProvider);
viewer.setLabelProvider(labelProvider);
addListener(SWT.Dispose, e -> {
reset();
});
Tree tree = viewer.getTree();
MouseAdapter mouseHandler = new MouseAdapter() {
@Override
public void mouseMove(MouseEvent e) {
updateHover(Events.getLocation(e));
}
@Override
public void mouseScrolled(MouseEvent e) {
updateHover(Events.getLocation(e));
}
@Override
public void widgetSelected(SelectionEvent e) {
// Scrollbar was moved / mouse wheel caused scrolling. This is required for systems with
// a touchpad with scrolling inertia, where the view keeps scrolling long after the mouse
// wheel event has been processed.
Display disp = getDisplay();
updateHover(disp.map(null, tree, disp.getCursorLocation()));
}
@Override
public void mouseExit(MouseEvent e) {
labelProvider.hoverItem(null, null);
}
@Override
public void mouseUp(MouseEvent e) {
Point location = new Point(e.x, e.y);
Path.Any follow = labelProvider.getFollow(tree.getItem(location), location);
if (follow != null) {
follow(follow);
}
}
private void updateHover(Point location) {
TreeItem item = tree.getItem(location);
// When hovering over the far left of deep items, getItem returns null. Let's check a few
// more places to the right.
if (item == null) {
for (int testX = location.x + 20; item == null && testX < 300; testX += 20) {
item = tree.getItem(new Point(testX, location.y));
}
}
if (labelProvider.hoverItem(item, location)) {
Path.Any follow = labelProvider.getFollow(item, location);
setCursor((follow == null) ? null : getDisplay().getSystemCursor(SWT.CURSOR_HAND));
} else {
setCursor(null);
}
}
};
tree.addMouseListener(mouseHandler);
tree.addMouseTrackListener(mouseHandler);
tree.addMouseMoveListener(mouseHandler);
tree.addMouseWheelListener(mouseHandler);
tree.getVerticalBar().addSelectionListener(mouseHandler);
}
protected LabelProvider createLabelProvider(Theme theme) {
return new LabelProvider(theme);
}
public void setInput(T root) {
// Clear the selection, since we handle maintaining the selection ourselves and so
// don't want JFace's selection preserving, as it appears to be broken on input
// change (see https://github.com/google/gapid/issues/1264)
setSelection(null);
viewer.setInput(root);
if (root != null && viewer.getTree().getItemCount() > 0) {
viewer.getTree().setSelection(viewer.getTree().getItem(0));
viewer.getTree().showSelection();
}
}
public Control getControl() {
return viewer.getControl();
}
public T getSelection() {
if (viewer.getTree().getSelectionCount() >= 1) {
return getElement(last(viewer.getTree().getSelection()));
}
return null;
}
public void setSelection(TreePath selection) {
if (selection == null || (selection.getSegmentCount() == 0)) {
viewer.setSelection(new TreeSelection(), true);
} else {
viewer.setSelection(new TreeSelection(selection), true);
}
}
public Object[] getExpandedElements() {
return viewer.getExpandedElements();
}
public boolean getExpandedState(TreePath path) {
return viewer.getExpandedState(path);
}
public void setExpandedState(TreePath path, boolean state) {
viewer.setExpandedState(path, state);
}
public Point getScrollPos() {
TreeItem topItem = viewer.getTree().getTopItem();
return (topItem == null) ? null : GeoUtils.center(topItem.getBounds());
}
public void scrollTo(Point pos) {
TreeItem topItem = (pos == null) ? null : viewer.getTree().getItem(pos);
if (topItem != null) {
viewer.getTree().setTopItem(topItem);
}
}
public void setPopupMenu(Menu popup, Predicate<T> shouldShow) {
Tree tree = viewer.getTree();
tree.setMenu(popup);
Predicate<T> pred = o -> o != null && shouldShow.test(o);
tree.addListener(SWT.MenuDetect, e -> {
TreeItem item = tree.getItem(tree.toControl(e.x, e.y));
e.doit = item != null && pred.test(getElement(item));
});
}
@SuppressWarnings("unchecked")
public void registerAsCopySource(CopyPaste cp, ColumnTextProvider<T> columns, boolean align) {
CopySources.registerTreeAsCopySource(cp, viewer, (ColumnTextProvider<Object>)columns, align);
}
protected abstract ContentProvider<T> createContentProvider();
protected abstract <S extends StylingString> S
format(T node, S string, Follower.Prefetcher<F> follower);
protected abstract Color getBackgroundColor(T node);
protected abstract Follower.Prefetcher<F> prepareFollower(T node, Runnable callback);
protected abstract void follow(Path.Any path);
protected void reset() {
labelProvider.reset();
}
@SuppressWarnings("unchecked")
protected static <T> T cast(Object o) {
return (T)o;
}
protected T getElement(Widget item) {
return cast(item.getData());
}
/**
* View data model for the tree.
*/
protected abstract static class ContentProvider<T> implements ITreeContentProvider {
@Override
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
@Override
public Object[] getChildren(Object parent) {
return getChildNodes(cast(parent));
}
@Override
public boolean hasChildren(Object element) {
return hasChildNodes(cast(element));
}
@Override
public Object getParent(Object element) {
return getParentNode(cast(element));
}
protected abstract boolean hasChildNodes(T element);
protected abstract T[] getChildNodes(T parent);
protected abstract T getParentNode(T child);
protected abstract boolean isLoaded(T element);
protected abstract void load(T node, Runnable callback);
}
/**
* Renders the labels in the tree.
*/
protected class LabelProvider extends OwnerDrawLabelProvider
implements VisibilityTrackingTreeViewer.Listener {
private final Theme theme;
private final TextLayout layout;
private TreeItem lastHovered;
private Follower.Prefetcher<F> lastPrefetcher = nullPrefetcher();
public LabelProvider(Theme theme) {
this.theme = theme;
this.layout = new TextLayout(getDisplay());
}
@Override
public void onShow(TreeItem item) {
T element = getElement(item);
contentProvider.load(element, () -> {
if (!item.isDisposed()) {
update(item);
refresher.refresh();
}
});
}
@Override
protected void erase(Event event, Object element) {
Label label = getLabel(event);
if (!shouldIgnoreColors(event) && label.background != null) {
Color oldBackground = event.gc.getBackground();
event.gc.setBackground(label.background);
event.gc.fillRectangle(event.x, event.y, event.width, event.height);
event.gc.setBackground(oldBackground);
}
// Clear the foreground bit, as we'll do our own foreground rendering.
event.detail &= ~SWT.FOREGROUND;
}
@Override
protected void measure(Event event, Object element) {
Label label = getLabel(event);
if (label.bounds == null) {
updateLayout(label.string, false);
label.bounds = layout.getBounds();
}
event.width = label.bounds.width;
event.height =label.bounds.height;
}
@Override
protected void paint(Event event, Object element) {
GC gc = event.gc;
Label label = getLabel(event);
boolean ignoreColors = shouldIgnoreColors(event);
Color oldForeground = event.gc.getForeground();
Color oldBackground = event.gc.getBackground();
if (!ignoreColors && label.background != null) {
event.gc.setBackground(label.background);
}
drawText(event, label, ignoreColors);
if (shouldDrawFocus(event)) {
drawFocus(event);
}
if (!ignoreColors) {
gc.setForeground(oldForeground);
gc.setBackground(oldBackground);
}
}
private void drawText(Event event, Label label, boolean ignoreColors) {
Rectangle bounds = ((TreeItem)event.item).getTextBounds(0);
if (bounds == null) {
return;
}
drawText(getElement(event.item), event.gc, bounds, label, ignoreColors);
}
protected void drawText(@SuppressWarnings("unused") T node, GC gc, Rectangle bounds,
Label label, boolean ignoreColors) {
updateLayout(label.string, ignoreColors);
Rectangle clip = gc.getClipping();
gc.setClipping(bounds);
layout.draw(gc, bounds.x, bounds.y + (bounds.height - label.bounds.height) / 2);
gc.setClipping(clip);
}
private void drawFocus(Event event) {
Rectangle focusBounds = ((TreeItem)event.item).getBounds();
event.gc.drawFocus(focusBounds.x, focusBounds.y, focusBounds.width, focusBounds.height);
}
private void updateLayout(StyledString string, boolean ignoreColors) {
layout.setText(string.getString());
for (StyleRange range : string.getStyleRanges()) {
if (ignoreColors && (range.foreground != null || range.background != null)) {
range = (StyleRange)range.clone();
range.foreground = null;
range.background = null;
}
layout.setStyle(range, range.start, range.start + range.length - 1);
}
}
private boolean shouldDrawFocus(Event event) {
return (event.detail & SWT.FOCUSED) != 0;
}
private boolean shouldIgnoreColors(Event event) {
return (event.detail & SWT.SELECTED) != 0;
}
private void update(TreeItem item) {
Label label = getLabelNoUpdate(item);
T element = getElement(item);
label.background = getBackgroundColor(element);
updateText(item, label, element);
label.bounds = null;
label.loaded = contentProvider.isLoaded(element);
item.setText(label.string.getString());
}
private void updateText(TreeItem item, Label label, T element) {
label.string = format(element, LinkableStyledString.ignoring(theme),
(item == lastHovered) ? lastPrefetcher : nullPrefetcher()).getString();
}
public boolean hoverItem(TreeItem item, @SuppressWarnings("unused") Point location) {
if (item != lastHovered) {
TreeItem tmp = lastHovered;
lastHovered = item;
lastPrefetcher.cancel();
if (tmp != null && !tmp.isDisposed()) {
updateText(tmp, getLabelNoUpdate(tmp), getElement(tmp));
}
if (item == null) {
lastPrefetcher = nullPrefetcher();
} else {
lastPrefetcher = prepareFollower(getElement(item), () -> {
Widgets.scheduleIfNotDisposed(item, () -> {
updateText(item, getLabelNoUpdate(item), getElement(item));
refresher.refresh();
});
});
}
refresher.refresh();
}
return item != null;
}
public Path.Any getFollow(TreeItem item, Point location) {
if (item == null || item != lastHovered) {
return null;
}
Rectangle bounds = item.getTextBounds(0);
if (!bounds.contains(location)) {
return null;
}
LinkableStyledString string =
format(getElement(item), LinkableStyledString.create(theme), lastPrefetcher);
string.endLink();
string.append("dummy", string.defaultStyle());
updateLayout(string.getString(), false);
Rectangle textBounds = layout.getBounds();
textBounds.x = bounds.x;
textBounds.y = bounds.y + (bounds.height - textBounds.height) / 2;
if (!textBounds.contains(location)) {
return null;
}
int offset = layout.getOffset(location.x - textBounds.x, location.y - textBounds.y, null);
return (Path.Any)string.getLinkTarget(offset);
}
private Label getLabel(Event event) {
return getLabel(event.item);
}
private Label getLabel(Widget item) {
Label result = (Label)item.getData(Label.KEY);
if (result == null) {
item.setData(Label.KEY, result = new Label(theme));
update((TreeItem)item);
} else if (contentProvider.isLoaded(getElement(item)) != result.loaded) {
update((TreeItem)item);
}
return result;
}
private Label getLabelNoUpdate(Widget item) {
Label result = (Label)item.getData(Label.KEY);
if (result == null) {
item.setData(Label.KEY, result = new Label(theme));
}
return result;
}
public void reset() {
layout.dispose();
}
}
/**
* POJO containing cached rendering information for a label.
*/
protected static class Label {
public static String KEY = Label.class.getName();
public Color background;
public StyledString string;
public Rectangle bounds;
public boolean loaded;
public Label(Theme theme) {
this.background = null;
this.string = new StyledString("Loading...", theme.structureStyler());
this.bounds = null;
this.loaded = false;
}
}
}
| google/gapid | gapic/src/main/com/google/gapid/widgets/LinkifiedTree.java | 4,425 | // wheel event has been processed. | line_comment | nl | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.widgets;
import static com.google.gapid.models.Follower.nullPrefetcher;
import static com.google.gapid.util.Arrays.last;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.withAsyncRefresh;
import com.google.gapid.models.Follower;
import com.google.gapid.proto.service.path.Path;
import com.google.gapid.util.Events;
import com.google.gapid.util.GeoUtils;
import com.google.gapid.util.MouseAdapter;
import com.google.gapid.views.Formatter.LinkableStyledString;
import com.google.gapid.views.Formatter.StylingString;
import com.google.gapid.widgets.CopySources.ColumnTextProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.OwnerDrawLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import java.util.function.Predicate;
/**
* A {@link TreeViewer} where each label can have rich formatting (using
* {@link com.google.gapid.views.Formatter.StylingString}), links, and custom background color.
*/
public abstract class LinkifiedTree<T, F> extends Composite {
private final TreeViewer viewer;
protected final Widgets.Refresher refresher;
protected final ContentProvider<T> contentProvider;
protected final LabelProvider labelProvider;
public LinkifiedTree(Composite parent, int treeStyle, Widgets widgets) {
super(parent, SWT.NONE);
setLayout(new FillLayout());
this.viewer = createTreeViewer(this, treeStyle);
this.refresher = withAsyncRefresh(viewer);
this.contentProvider = createContentProvider();
this.labelProvider = createLabelProvider(widgets.theme);
viewer.setContentProvider(contentProvider);
viewer.setLabelProvider(labelProvider);
addListener(SWT.Dispose, e -> {
reset();
});
Tree tree = viewer.getTree();
MouseAdapter mouseHandler = new MouseAdapter() {
@Override
public void mouseMove(MouseEvent e) {
updateHover(Events.getLocation(e));
}
@Override
public void mouseScrolled(MouseEvent e) {
updateHover(Events.getLocation(e));
}
@Override
public void widgetSelected(SelectionEvent e) {
// Scrollbar was moved / mouse wheel caused scrolling. This is required for systems with
// a touchpad with scrolling inertia, where the view keeps scrolling long after the mouse
// wheel event<SUF>
Display disp = getDisplay();
updateHover(disp.map(null, tree, disp.getCursorLocation()));
}
@Override
public void mouseExit(MouseEvent e) {
labelProvider.hoverItem(null, null);
}
@Override
public void mouseUp(MouseEvent e) {
Point location = new Point(e.x, e.y);
Path.Any follow = labelProvider.getFollow(tree.getItem(location), location);
if (follow != null) {
follow(follow);
}
}
private void updateHover(Point location) {
TreeItem item = tree.getItem(location);
// When hovering over the far left of deep items, getItem returns null. Let's check a few
// more places to the right.
if (item == null) {
for (int testX = location.x + 20; item == null && testX < 300; testX += 20) {
item = tree.getItem(new Point(testX, location.y));
}
}
if (labelProvider.hoverItem(item, location)) {
Path.Any follow = labelProvider.getFollow(item, location);
setCursor((follow == null) ? null : getDisplay().getSystemCursor(SWT.CURSOR_HAND));
} else {
setCursor(null);
}
}
};
tree.addMouseListener(mouseHandler);
tree.addMouseTrackListener(mouseHandler);
tree.addMouseMoveListener(mouseHandler);
tree.addMouseWheelListener(mouseHandler);
tree.getVerticalBar().addSelectionListener(mouseHandler);
}
protected LabelProvider createLabelProvider(Theme theme) {
return new LabelProvider(theme);
}
public void setInput(T root) {
// Clear the selection, since we handle maintaining the selection ourselves and so
// don't want JFace's selection preserving, as it appears to be broken on input
// change (see https://github.com/google/gapid/issues/1264)
setSelection(null);
viewer.setInput(root);
if (root != null && viewer.getTree().getItemCount() > 0) {
viewer.getTree().setSelection(viewer.getTree().getItem(0));
viewer.getTree().showSelection();
}
}
public Control getControl() {
return viewer.getControl();
}
public T getSelection() {
if (viewer.getTree().getSelectionCount() >= 1) {
return getElement(last(viewer.getTree().getSelection()));
}
return null;
}
public void setSelection(TreePath selection) {
if (selection == null || (selection.getSegmentCount() == 0)) {
viewer.setSelection(new TreeSelection(), true);
} else {
viewer.setSelection(new TreeSelection(selection), true);
}
}
public Object[] getExpandedElements() {
return viewer.getExpandedElements();
}
public boolean getExpandedState(TreePath path) {
return viewer.getExpandedState(path);
}
public void setExpandedState(TreePath path, boolean state) {
viewer.setExpandedState(path, state);
}
public Point getScrollPos() {
TreeItem topItem = viewer.getTree().getTopItem();
return (topItem == null) ? null : GeoUtils.center(topItem.getBounds());
}
public void scrollTo(Point pos) {
TreeItem topItem = (pos == null) ? null : viewer.getTree().getItem(pos);
if (topItem != null) {
viewer.getTree().setTopItem(topItem);
}
}
public void setPopupMenu(Menu popup, Predicate<T> shouldShow) {
Tree tree = viewer.getTree();
tree.setMenu(popup);
Predicate<T> pred = o -> o != null && shouldShow.test(o);
tree.addListener(SWT.MenuDetect, e -> {
TreeItem item = tree.getItem(tree.toControl(e.x, e.y));
e.doit = item != null && pred.test(getElement(item));
});
}
@SuppressWarnings("unchecked")
public void registerAsCopySource(CopyPaste cp, ColumnTextProvider<T> columns, boolean align) {
CopySources.registerTreeAsCopySource(cp, viewer, (ColumnTextProvider<Object>)columns, align);
}
protected abstract ContentProvider<T> createContentProvider();
protected abstract <S extends StylingString> S
format(T node, S string, Follower.Prefetcher<F> follower);
protected abstract Color getBackgroundColor(T node);
protected abstract Follower.Prefetcher<F> prepareFollower(T node, Runnable callback);
protected abstract void follow(Path.Any path);
protected void reset() {
labelProvider.reset();
}
@SuppressWarnings("unchecked")
protected static <T> T cast(Object o) {
return (T)o;
}
protected T getElement(Widget item) {
return cast(item.getData());
}
/**
* View data model for the tree.
*/
protected abstract static class ContentProvider<T> implements ITreeContentProvider {
@Override
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
@Override
public Object[] getChildren(Object parent) {
return getChildNodes(cast(parent));
}
@Override
public boolean hasChildren(Object element) {
return hasChildNodes(cast(element));
}
@Override
public Object getParent(Object element) {
return getParentNode(cast(element));
}
protected abstract boolean hasChildNodes(T element);
protected abstract T[] getChildNodes(T parent);
protected abstract T getParentNode(T child);
protected abstract boolean isLoaded(T element);
protected abstract void load(T node, Runnable callback);
}
/**
* Renders the labels in the tree.
*/
protected class LabelProvider extends OwnerDrawLabelProvider
implements VisibilityTrackingTreeViewer.Listener {
private final Theme theme;
private final TextLayout layout;
private TreeItem lastHovered;
private Follower.Prefetcher<F> lastPrefetcher = nullPrefetcher();
public LabelProvider(Theme theme) {
this.theme = theme;
this.layout = new TextLayout(getDisplay());
}
@Override
public void onShow(TreeItem item) {
T element = getElement(item);
contentProvider.load(element, () -> {
if (!item.isDisposed()) {
update(item);
refresher.refresh();
}
});
}
@Override
protected void erase(Event event, Object element) {
Label label = getLabel(event);
if (!shouldIgnoreColors(event) && label.background != null) {
Color oldBackground = event.gc.getBackground();
event.gc.setBackground(label.background);
event.gc.fillRectangle(event.x, event.y, event.width, event.height);
event.gc.setBackground(oldBackground);
}
// Clear the foreground bit, as we'll do our own foreground rendering.
event.detail &= ~SWT.FOREGROUND;
}
@Override
protected void measure(Event event, Object element) {
Label label = getLabel(event);
if (label.bounds == null) {
updateLayout(label.string, false);
label.bounds = layout.getBounds();
}
event.width = label.bounds.width;
event.height =label.bounds.height;
}
@Override
protected void paint(Event event, Object element) {
GC gc = event.gc;
Label label = getLabel(event);
boolean ignoreColors = shouldIgnoreColors(event);
Color oldForeground = event.gc.getForeground();
Color oldBackground = event.gc.getBackground();
if (!ignoreColors && label.background != null) {
event.gc.setBackground(label.background);
}
drawText(event, label, ignoreColors);
if (shouldDrawFocus(event)) {
drawFocus(event);
}
if (!ignoreColors) {
gc.setForeground(oldForeground);
gc.setBackground(oldBackground);
}
}
private void drawText(Event event, Label label, boolean ignoreColors) {
Rectangle bounds = ((TreeItem)event.item).getTextBounds(0);
if (bounds == null) {
return;
}
drawText(getElement(event.item), event.gc, bounds, label, ignoreColors);
}
protected void drawText(@SuppressWarnings("unused") T node, GC gc, Rectangle bounds,
Label label, boolean ignoreColors) {
updateLayout(label.string, ignoreColors);
Rectangle clip = gc.getClipping();
gc.setClipping(bounds);
layout.draw(gc, bounds.x, bounds.y + (bounds.height - label.bounds.height) / 2);
gc.setClipping(clip);
}
private void drawFocus(Event event) {
Rectangle focusBounds = ((TreeItem)event.item).getBounds();
event.gc.drawFocus(focusBounds.x, focusBounds.y, focusBounds.width, focusBounds.height);
}
private void updateLayout(StyledString string, boolean ignoreColors) {
layout.setText(string.getString());
for (StyleRange range : string.getStyleRanges()) {
if (ignoreColors && (range.foreground != null || range.background != null)) {
range = (StyleRange)range.clone();
range.foreground = null;
range.background = null;
}
layout.setStyle(range, range.start, range.start + range.length - 1);
}
}
private boolean shouldDrawFocus(Event event) {
return (event.detail & SWT.FOCUSED) != 0;
}
private boolean shouldIgnoreColors(Event event) {
return (event.detail & SWT.SELECTED) != 0;
}
private void update(TreeItem item) {
Label label = getLabelNoUpdate(item);
T element = getElement(item);
label.background = getBackgroundColor(element);
updateText(item, label, element);
label.bounds = null;
label.loaded = contentProvider.isLoaded(element);
item.setText(label.string.getString());
}
private void updateText(TreeItem item, Label label, T element) {
label.string = format(element, LinkableStyledString.ignoring(theme),
(item == lastHovered) ? lastPrefetcher : nullPrefetcher()).getString();
}
public boolean hoverItem(TreeItem item, @SuppressWarnings("unused") Point location) {
if (item != lastHovered) {
TreeItem tmp = lastHovered;
lastHovered = item;
lastPrefetcher.cancel();
if (tmp != null && !tmp.isDisposed()) {
updateText(tmp, getLabelNoUpdate(tmp), getElement(tmp));
}
if (item == null) {
lastPrefetcher = nullPrefetcher();
} else {
lastPrefetcher = prepareFollower(getElement(item), () -> {
Widgets.scheduleIfNotDisposed(item, () -> {
updateText(item, getLabelNoUpdate(item), getElement(item));
refresher.refresh();
});
});
}
refresher.refresh();
}
return item != null;
}
public Path.Any getFollow(TreeItem item, Point location) {
if (item == null || item != lastHovered) {
return null;
}
Rectangle bounds = item.getTextBounds(0);
if (!bounds.contains(location)) {
return null;
}
LinkableStyledString string =
format(getElement(item), LinkableStyledString.create(theme), lastPrefetcher);
string.endLink();
string.append("dummy", string.defaultStyle());
updateLayout(string.getString(), false);
Rectangle textBounds = layout.getBounds();
textBounds.x = bounds.x;
textBounds.y = bounds.y + (bounds.height - textBounds.height) / 2;
if (!textBounds.contains(location)) {
return null;
}
int offset = layout.getOffset(location.x - textBounds.x, location.y - textBounds.y, null);
return (Path.Any)string.getLinkTarget(offset);
}
private Label getLabel(Event event) {
return getLabel(event.item);
}
private Label getLabel(Widget item) {
Label result = (Label)item.getData(Label.KEY);
if (result == null) {
item.setData(Label.KEY, result = new Label(theme));
update((TreeItem)item);
} else if (contentProvider.isLoaded(getElement(item)) != result.loaded) {
update((TreeItem)item);
}
return result;
}
private Label getLabelNoUpdate(Widget item) {
Label result = (Label)item.getData(Label.KEY);
if (result == null) {
item.setData(Label.KEY, result = new Label(theme));
}
return result;
}
public void reset() {
layout.dispose();
}
}
/**
* POJO containing cached rendering information for a label.
*/
protected static class Label {
public static String KEY = Label.class.getName();
public Color background;
public StyledString string;
public Rectangle bounds;
public boolean loaded;
public Label(Theme theme) {
this.background = null;
this.string = new StyledString("Loading...", theme.structureStyler());
this.bounds = null;
this.loaded = false;
}
}
}
|
79171_9 | package app.Tednir.model;
import java.util.Observable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Person class that contains all user information
* @author Senne Wertelaers
*/
public class Person extends Observable {
private HashMap<String, ArrayList<String>> $_attributes; // contains all the attributes a person can have
private Family $_family; // has family members of person
public Person(HashMap<String, ArrayList<String>> attributes, Family family){
this.$_attributes = new HashMap<>();
initAttributes(attributes);
$_family = family;
}
/**
* copy constructor
* @param person
*/
Person(Person person){
this.$_attributes = person.$_attributes;
this.$_family = person.$_family;
}
/**
*
*/
private void initAttributes(HashMap<String, ArrayList<String>> attributes){
ArrayList<String> attrKeys = new ArrayList<>(Arrays.asList("name", "age", "gender", "hobbies",
"education", "residence", "amChildren", "favMovies", "favArtists", "religion",
"languages", "favDish", "favVacationDest", "smokingHabits", "sports"));
for (String attr : attrKeys){
this.$_attributes.put(attr, attributes.get(attr));
}
}
/**
* Check if a person is of name @name
* @param name
* @return true if person has @name, false if not
*/
public boolean hasName(String name){
return this.$_attributes.get("name").get(0) == name;
}
public boolean hasFamilyMember(Person person){ return $_family.hasFamilyMember(person); }
public String getName(){ return $_attributes.get("name").get(0);}
/**
* Returns a copy of an object
* @param attr
* @return
*/
public ArrayList<String> getAttr(String attr){
return new ArrayList<>($_attributes.get(attr));
}
public static ArrayList<String> getNames(ArrayList<Person> persons){
ArrayList<String> names = new ArrayList<>();
for (Person person : persons)
names.add(person.getName());
return names;
}
public static HashMap<String,ArrayList<String>> genHash(String name, int age, int amChildren, String gender, String education, ArrayList<Integer> location, String religion, String favVacationDest, String favDish, String sports, ArrayList<String> languages, ArrayList<String> hobbies, boolean smokingHabits, ArrayList<String> favMovies, ArrayList<String> favArtists){
HashMap<String,ArrayList<String>> hash = new HashMap<>();
try{
hash.put("", new ArrayList<>(Arrays.asList()));
hash.put("name", new ArrayList<>(Arrays.asList(name)));
hash.put("age", new ArrayList<>(Arrays.asList(Integer.toString(age))));
hash.put("amChildren", new ArrayList<>(Arrays.asList(Integer.toString(amChildren))));
hash.put("gender", new ArrayList<>(Arrays.asList(gender)));
String p1 = Integer.toString(location.get(0));
String p2 = Integer.toString(location.get(1));
hash.put("residence", new ArrayList<>(Arrays.asList(p1, p2)));
hash.put("religion", new ArrayList<>(Arrays.asList(religion)));
hash.put("favVacationDest", new ArrayList<>(Arrays.asList(favVacationDest)));
hash.put("hobbies", new ArrayList<>(hobbies));
hash.put("favDish", new ArrayList<>(Arrays.asList(favDish)));
hash.put("languages", new ArrayList<>(languages));
hash.put("favArtists", new ArrayList<>(favArtists));
hash.put("education", new ArrayList<>(Arrays.asList(education)));
hash.put("favMovies", new ArrayList<>(favMovies));
hash.put("smokingHabits", new ArrayList<>(Arrays.asList(smokingHabits ? "true" : "false")));
hash.put("sports", new ArrayList<>(Arrays.asList(sports)));
}
catch(Exception e){
System.out.println(e.getMessage());
}
return hash;
}
}
// private String $_name; // name of person
// private int age; // age
// private int m_aantalKinderen; // number of children
// private String $_geslacht; // sex
// private String $_opleiding; // schooling
// // private Pair<int ,int> m_woonplaats;
// private boolean m_rookgewoontes; // kan een enum voorstellen van hoeveelheid
// private String $_religie; // religion
// private String $_favorieteKeuken; // favorite cultural kitchen
// private String $_favorieteReisbestemming; // favorite travel destination
// private String $_sport; // sport
// private ArrayList<String> $_talen; // spoken languages
// private ArrayList<String> $_hobbies; // hobby
// private String[] $_favorieteFilms; // favorite movies
// private String[] $_favorieteMuzikanten; // favorite musiscians | SenneW-2158088/Tednir | app/Tednir/model/Person.java | 1,211 | // private String $_geslacht; // sex | line_comment | nl | package app.Tednir.model;
import java.util.Observable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Person class that contains all user information
* @author Senne Wertelaers
*/
public class Person extends Observable {
private HashMap<String, ArrayList<String>> $_attributes; // contains all the attributes a person can have
private Family $_family; // has family members of person
public Person(HashMap<String, ArrayList<String>> attributes, Family family){
this.$_attributes = new HashMap<>();
initAttributes(attributes);
$_family = family;
}
/**
* copy constructor
* @param person
*/
Person(Person person){
this.$_attributes = person.$_attributes;
this.$_family = person.$_family;
}
/**
*
*/
private void initAttributes(HashMap<String, ArrayList<String>> attributes){
ArrayList<String> attrKeys = new ArrayList<>(Arrays.asList("name", "age", "gender", "hobbies",
"education", "residence", "amChildren", "favMovies", "favArtists", "religion",
"languages", "favDish", "favVacationDest", "smokingHabits", "sports"));
for (String attr : attrKeys){
this.$_attributes.put(attr, attributes.get(attr));
}
}
/**
* Check if a person is of name @name
* @param name
* @return true if person has @name, false if not
*/
public boolean hasName(String name){
return this.$_attributes.get("name").get(0) == name;
}
public boolean hasFamilyMember(Person person){ return $_family.hasFamilyMember(person); }
public String getName(){ return $_attributes.get("name").get(0);}
/**
* Returns a copy of an object
* @param attr
* @return
*/
public ArrayList<String> getAttr(String attr){
return new ArrayList<>($_attributes.get(attr));
}
public static ArrayList<String> getNames(ArrayList<Person> persons){
ArrayList<String> names = new ArrayList<>();
for (Person person : persons)
names.add(person.getName());
return names;
}
public static HashMap<String,ArrayList<String>> genHash(String name, int age, int amChildren, String gender, String education, ArrayList<Integer> location, String religion, String favVacationDest, String favDish, String sports, ArrayList<String> languages, ArrayList<String> hobbies, boolean smokingHabits, ArrayList<String> favMovies, ArrayList<String> favArtists){
HashMap<String,ArrayList<String>> hash = new HashMap<>();
try{
hash.put("", new ArrayList<>(Arrays.asList()));
hash.put("name", new ArrayList<>(Arrays.asList(name)));
hash.put("age", new ArrayList<>(Arrays.asList(Integer.toString(age))));
hash.put("amChildren", new ArrayList<>(Arrays.asList(Integer.toString(amChildren))));
hash.put("gender", new ArrayList<>(Arrays.asList(gender)));
String p1 = Integer.toString(location.get(0));
String p2 = Integer.toString(location.get(1));
hash.put("residence", new ArrayList<>(Arrays.asList(p1, p2)));
hash.put("religion", new ArrayList<>(Arrays.asList(religion)));
hash.put("favVacationDest", new ArrayList<>(Arrays.asList(favVacationDest)));
hash.put("hobbies", new ArrayList<>(hobbies));
hash.put("favDish", new ArrayList<>(Arrays.asList(favDish)));
hash.put("languages", new ArrayList<>(languages));
hash.put("favArtists", new ArrayList<>(favArtists));
hash.put("education", new ArrayList<>(Arrays.asList(education)));
hash.put("favMovies", new ArrayList<>(favMovies));
hash.put("smokingHabits", new ArrayList<>(Arrays.asList(smokingHabits ? "true" : "false")));
hash.put("sports", new ArrayList<>(Arrays.asList(sports)));
}
catch(Exception e){
System.out.println(e.getMessage());
}
return hash;
}
}
// private String $_name; // name of person
// private int age; // age
// private int m_aantalKinderen; // number of children
// private String<SUF>
// private String $_opleiding; // schooling
// // private Pair<int ,int> m_woonplaats;
// private boolean m_rookgewoontes; // kan een enum voorstellen van hoeveelheid
// private String $_religie; // religion
// private String $_favorieteKeuken; // favorite cultural kitchen
// private String $_favorieteReisbestemming; // favorite travel destination
// private String $_sport; // sport
// private ArrayList<String> $_talen; // spoken languages
// private ArrayList<String> $_hobbies; // hobby
// private String[] $_favorieteFilms; // favorite movies
// private String[] $_favorieteMuzikanten; // favorite musiscians |
31192_8 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(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);
// 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);
// 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
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(150), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-gijsdl | DemoWorld.java | 3,460 | // 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 DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de<SUF>
Camera camera = new Camera(te);
// 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);
// 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
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(150), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
|
109118_5 | package de._13ducks.spacebatz.server.gamelogic;
import de._13ducks.spacebatz.server.data.Client;
import de._13ducks.spacebatz.server.data.quests.Quest;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Verwaltet die Quests.
*
* @author Tobias Fleig <[email protected]>
*/
public class QuestManager {
/**
* Alle aktiven Quests.
*/
private ArrayList<Quest> activeQuests = new ArrayList<>();
/**
* Quests, die im nächsten Tick hinzugefügt werden.
* Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden.
*/
private ArrayList<Quest> newQuests = new ArrayList<>();
/**
* Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests.
*/
public void tick() {
// Neue Quests hinzufügen
activeQuests.addAll(newQuests);
for (Quest q : newQuests) {
// An Client senden
if (!q.isHidden()) {
STC_NEW_QUEST.sendQuest(q);
}
}
newQuests.clear();
Iterator<Quest> iter = activeQuests.iterator();
while (iter.hasNext()) {
Quest quest = iter.next();
try {
// Quest ticken, dann Status abfragen
quest.tick();
int state = quest.check();
// Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht
if (state != -1) {
if (state == Quest.STATE_RUNNING) {
// Nichts spannendes, weiterlaufen lassen
continue;
}
if (state == Quest.STATE_COMPLETED) {
// Erfolgreich
//@TODO: Belohnung verteilen?
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed.");
} else if (state == Quest.STATE_FAILED) {
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed.");
} else if (state == Quest.STATE_ABORTED) {
System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons...");
}
// Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss
iter.remove();
// Client quest entfernen lassen
STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state);
}
} catch (Exception ex) {
// Quest ist abgestürzt - Loggen und Quest löschen
iter.remove();
System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:");
ex.printStackTrace();
}
}
}
/**
* Fügt einen neuen Quest hinzu.
* Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen.
*
* @param quest der neue Quest, läuft ab dem nächsten Tick mit
*/
public void addQuest(Quest quest) {
newQuests.add(quest);
}
/**
* Aufrufen, wenn ein neuer Client eingefügt wurde.
* Sendet alle aktiven, nicht geheimen Quests an den neuen.
*
* @param client
*/
void newClient(Client client) {
for (Quest quest : activeQuests) {
if (!quest.isHidden()) {
STC_NEW_QUEST.sendQuest(quest);
}
}
}
}
| tfg13/spacebatz | src/de/_13ducks/spacebatz/server/gamelogic/QuestManager.java | 914 | // An Client senden | line_comment | nl | package de._13ducks.spacebatz.server.gamelogic;
import de._13ducks.spacebatz.server.data.Client;
import de._13ducks.spacebatz.server.data.quests.Quest;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_NEW_QUEST;
import de._13ducks.spacebatz.shared.network.messages.STC.STC_QUEST_RESULT;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Verwaltet die Quests.
*
* @author Tobias Fleig <[email protected]>
*/
public class QuestManager {
/**
* Alle aktiven Quests.
*/
private ArrayList<Quest> activeQuests = new ArrayList<>();
/**
* Quests, die im nächsten Tick hinzugefügt werden.
* Notwendig, sonst funktioniert der Iterator in tick() nicht sauber, wenn neue Quests von alten Quests eingefügt werden.
*/
private ArrayList<Quest> newQuests = new ArrayList<>();
/**
* Muss ein Mal pro Tick aufgerufen werden, tickt alle aktiven Quests.
*/
public void tick() {
// Neue Quests hinzufügen
activeQuests.addAll(newQuests);
for (Quest q : newQuests) {
// An Client<SUF>
if (!q.isHidden()) {
STC_NEW_QUEST.sendQuest(q);
}
}
newQuests.clear();
Iterator<Quest> iter = activeQuests.iterator();
while (iter.hasNext()) {
Quest quest = iter.next();
try {
// Quest ticken, dann Status abfragen
quest.tick();
int state = quest.check();
// Bei -1 wurde das Statusberechnen verschoben, das wird nur ein Mal pro Tick gemacht
if (state != -1) {
if (state == Quest.STATE_RUNNING) {
// Nichts spannendes, weiterlaufen lassen
continue;
}
if (state == Quest.STATE_COMPLETED) {
// Erfolgreich
//@TODO: Belohnung verteilen?
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " completed.");
} else if (state == Quest.STATE_FAILED) {
System.out.println("[INFO][QuestManager]: Quest " + quest.getName() + " failed.");
} else if (state == Quest.STATE_ABORTED) {
System.out.println("[WARNING][QuestManager]: Quest " + quest.getName() + " was aborted for unknown reasons...");
}
// Jeder der drei Zustände bedeutet, dass der Quest in Zukunft nichtmehr laufen muss
iter.remove();
// Client quest entfernen lassen
STC_QUEST_RESULT.sendQuestResult(quest.questID, (byte) state);
}
} catch (Exception ex) {
// Quest ist abgestürzt - Loggen und Quest löschen
iter.remove();
System.out.println("[ERROR][QuestManager]: Quest " + quest.getName() + " crashed and has been deleted. Exception:");
ex.printStackTrace();
}
}
}
/**
* Fügt einen neuen Quest hinzu.
* Es ist sicher, diese Methode während der Bearbeitung eines anderen Quests aufzurufen.
*
* @param quest der neue Quest, läuft ab dem nächsten Tick mit
*/
public void addQuest(Quest quest) {
newQuests.add(quest);
}
/**
* Aufrufen, wenn ein neuer Client eingefügt wurde.
* Sendet alle aktiven, nicht geheimen Quests an den neuen.
*
* @param client
*/
void newClient(Client client) {
for (Quest quest : activeQuests) {
if (!quest.isHidden()) {
STC_NEW_QUEST.sendQuest(quest);
}
}
}
}
|
82269_0 | package person;
import org.json.simple.JSONObject;
public class Person {
private final String name;
private double expensesPaid; // Hoeveel ik zelf heb betaald.
public Person(String name) {
this.name = name;
expensesPaid = 0.0;
}
public String getName() {
return name;
}
public double getExpensesPaid() {
return expensesPaid;
}
public void addExpense(double expense) {
this.expensesPaid += expense;
}
public void setExpensesPaid(double money){
this.expensesPaid = money;
}
public void resetExpenses() {
this.expensesPaid = 0.0;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", expensesPaid=" + expensesPaid +
'}';
}
public JSONObject toJson() {
JSONObject personJson = new JSONObject();
personJson.put("name", name);
personJson.put("expensesPaid", expensesPaid);
return personJson;
}
}
| ahmadshakleya/MoneyTracker | src/main/java/person/Person.java | 271 | // Hoeveel ik zelf heb betaald. | line_comment | nl | package person;
import org.json.simple.JSONObject;
public class Person {
private final String name;
private double expensesPaid; // Hoeveel ik<SUF>
public Person(String name) {
this.name = name;
expensesPaid = 0.0;
}
public String getName() {
return name;
}
public double getExpensesPaid() {
return expensesPaid;
}
public void addExpense(double expense) {
this.expensesPaid += expense;
}
public void setExpensesPaid(double money){
this.expensesPaid = money;
}
public void resetExpenses() {
this.expensesPaid = 0.0;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", expensesPaid=" + expensesPaid +
'}';
}
public JSONObject toJson() {
JSONObject personJson = new JSONObject();
personJson.put("name", name);
personJson.put("expensesPaid", expensesPaid);
return personJson;
}
}
|
60542_7 | package org.immopoly.appengine;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
/*
This is the server side Google App Engine component of Immopoly
http://immopoly.appspot.com
Copyright (C) 2011 Mister Schtief
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/>.
*/
@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {
static Logger LOG = Logger.getLogger(IndexServlet.class.getName());
public final String LOGIN = "login";
static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"dd.MM.yyyy HH:mm", Locale.GERMANY);
// static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("",
// Locale.GERMANY);
private static String colorArray[] = new String[] { "", "black", "green",
"green", "red" };
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// for (User user : users) {
// int numExposes = DBManager.getExposes(pm, user.getId()).size();
//// if(0==numExposes && user.getBalance()==5000.00)
//// {
////// pm.deletePersistent(user);
//// }
//// else
//// {
// user.setNumExposes(numExposes);
// pm.makePersistent(user);
//// }
// }
// giveAllActionItem(pm);
MemcacheServiceFactory.getMemcacheService().clearAll();
// giveAllEarlyAdopterBadgeBoolean(pm);
// createDummyBadge(pm);
// createDummyBadge2(pm);
// updateDB(pm, 0,0);
// updateDB(pm, Long.parseLong(req.getParameter("start")),
// Long.parseLong(req.getParameter("end")));
// String html = getBase();
// // top5
// html = generatetop5(pm, html);
// // history
// html = generateHistory(pm, html);
// resp.getOutputStream().write(html.getBytes("utf-8"));
// // memcache stats
// Stats stats = MemcacheServiceFactory.getMemcacheService().getStatistics();
// LOG.log(Level.INFO,stats.toString());
} catch (Exception e) {
LOG.log(Level.SEVERE, "", e);
} finally {
pm.close();
}
}
// private String generateHistory(PersistenceManager pm,String html ) {
// List<History> histories = DBManager.getAllHistory(pm, 10);
// StringBuffer history = new StringBuffer("");
// for (History h : histories) {
// try {
// User u = DBManager.getUser(pm, h.getUserId());
// if (u == null) {
// // TODO schtief dunno why its a local problem
// LOG.log(Level.WARNING, "user null " + h.getUserId());
// continue;
// }
// // history.append("<p class='c'><span>");
// history.append("<tr><td><a href='/user/profile/").append(
// u.getUserName()).append("'>").append(
// u.getUserName()).append("</a></td><td> ").append(
// DATE_FORMAT
// .format(h.getTime() + 2 * 60 * 60 * 1000))
// .append(
// "</td><td>")
// .append(h.getText()).append("</td></tr>");
// // history.append("</span></p>");
// } catch (Exception e) {
// LOG.log(Level.WARNING, h.getText(), e);
// }
// }
// html = html.replace("_HISTORY_", history.toString());
// return html;
// }
//
// private String generatetop5(PersistenceManager pm, String html) {
// List<User> top5 = DBManager.getTopUser(pm, 0, 20);
// StringBuffer t5 = new StringBuffer("");
// int i = 1;
// for (User u : top5) {
// try {
// t5.append("<trfoo><td>").append(i).append(".</td><td>").append("<a href='/user/profile/");
// t5.append(u.getUserName()).append("'>").append(u.getUserName()).append("</a></td>");
// t5.append("<td>").append(History.MONEYFORMAT.format(u.getBalance())).append("</td>");
// t5.append("</tr>");
// i++;
// } catch (Exception e) {
// LOG.log(Level.WARNING, "lalala ", e);
// System.out.println(e.getMessage());
// }
// }
//
// html = html.replace("_TOP5_", t5.toString());
// return html;
// }
// private void createDummyBadge(PersistenceManager pm) {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// for (User u : users) {
// Badge b = new Badge(1, u.getId(), System.currentTimeMillis(), "Du wars schon dabei als Immopoly noch nicht cool war!",
// "http://immopoly.appspot.com/img/immopoly.png", 0.0,
// null);
// pm.makePersistent(b);
// }
// }
private void giveAllEarlyAdopterBadgeBoolean(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
int i = 0;
for (User user : users) {
if (!user.getReleaseBadge() && user.hasBadge(pm, Badge.ONE_OF_THE_FIRST)) {
user.setReleaseBadge(true);
pm.makePersistent(user);
i++;
LOG.info("user " + user.getUserName() + " " + i);
if (i == 200)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void giveAllActionItem(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
int i = 0;
for (User user : users) {
if (!user.hasActionItem(pm, ActionItem.TYPE_ACTION_FREEEXPOSES)) {
ActionItem actionItem = new ActionItem(user.getId(), System.currentTimeMillis(), ActionItem.TYPE_ACTION_FREEEXPOSES, 1,
"Konkurrenzspion: Zeigt alle freien Wohnungen an, die noch nicht übernommen worden sind",
ActionItem.IMAGE.get(ActionItem.TYPE_ACTION_FREEEXPOSES));
pm.makePersistent(actionItem);
i++;
LOG.info("user " + user.getUserName() + " " + i);
if (i == 100)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void sendAllEarlyAdopterMail(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, " WHERE releaseBadge == true");
int i = 0;
for (User user : users) {
if (user.getReleaseBadge()) {
i++;
LOG.info("user " + user.getUserName() + " " + i);
try {
sendMail(user);
// user.setMailsent(true);
// pm.makePersistent(user);
} catch (Exception e) {
LOG.log(Level.SEVERE, "could not mail", e);
}
if (i == 200)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void sendMail(User user) throws Exception {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
String msgBody = "Klicke auf den Link um dein Passwort zu ändern http://immopoly.appspot.com/resetpasswd.html?token="
+ user.getToken() + " \n your Immopoly Team";
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]", "Immopoly Team"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail(), user.getUserName()));
msg.setSubject("Immopoly Password setzen");
msg.setText(msgBody);
Transport.send(msg);
}
// private void giveAllEarlyAdopterBadgesBoolean(PersistenceManager pm) {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// // for (User user : users) {
// // user.giveBadge(pm, Badge.EARLY_ADOPTER,
// // "Du warst schon dabei, als Immopoly nur ein bisschen cool war ;)");
// // }
// LOG.info("Counted all user and gave badges " + users.size());
// Counter counter = DBManager.getLatestCounter(pm);
// counter.setUser(users.size());
// LOG.info("Counter" + counter.toJSON().toString());
// pm.makePersistent(counter);
// }
private void createDummyBadge2(PersistenceManager pm) {
{
User u = DBManager.getUser(pm, "pointkilla");
Badge b = new Badge(444, u.getId(), System.currentTimeMillis(), "Du hast die Februar 2012 Wertung gewonnen!",
"http://immopoly.org/img/badges/feb121.png", 0.0, null);
pm.makePersistent(b);
}
{
User u = DBManager.getUser(pm, "tobi_h");
Badge b = new Badge(4444, u.getId(), System.currentTimeMillis(), "Du bist 2ter in der Februar 2012 Wertung geworden!",
"http://immopoly.org/img/badges/feb122.png", 0.0, null);
pm.makePersistent(b);
}
{
User u = DBManager.getUser(pm, "Tom");
Badge b = new Badge(44444, u.getId(), System.currentTimeMillis(), "Du bist 3ter in der Februar 2012 Wertung geworden!",
"http://immopoly.org/img/badges/feb123.png", 0.0, null);
pm.makePersistent(b);
}
}
private void updateDB(PersistenceManager pm, long start, long end) {
List<Expose> exposes = DBManager.getExposes(pm);
LOG.info("updateDB " + start + " - " + end + " number of entries: " + exposes.size());
for (Expose expose : exposes) {
if (expose.getDeleted() == Long.MAX_VALUE) {
if (expose.getLastcalculation() == null) {
LOG.info("updateDB lastcalculation is null " + expose.getExposeId());
continue;
}
expose.setDeleted(null);
pm.makePersistent(expose);
}
}
// User u = new User("wwaoname", "2password", "[email protected]",
// "twitter");
// u.setBalance(2149127);
// pm.makePersistent(u);
//
// History h = new History(History.TYPE_EXPOSE_ADDED, u.getId(),
// System.currentTimeMillis(),
// "jemand hat versucht mit einer Kettensaege in die wohnung einzubrechen und sich dabei den fuss verstaucht",
// 42, (long) -42);
// pm.makePersistent(h);
}
private String getBase() {
return readFileAsString("Immopoly.html");
}
static String readFileAsString(String filePath) {
try {
byte[] buffer = new byte[(int) new File(filePath).length()];
BufferedInputStream f = new BufferedInputStream(
new FileInputStream(filePath));
f.read(buffer);
return new String(buffer);
} catch (Exception e) {
LOG.severe("Konnte template " + filePath + " nich lesen "
+ e.getMessage());
return "";
}
}
}
| immopoly/appengine | src/org/immopoly/appengine/IndexServlet.java | 3,409 | // html = generatetop5(pm, html); | line_comment | nl | package org.immopoly.appengine;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
/*
This is the server side Google App Engine component of Immopoly
http://immopoly.appspot.com
Copyright (C) 2011 Mister Schtief
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/>.
*/
@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {
static Logger LOG = Logger.getLogger(IndexServlet.class.getName());
public final String LOGIN = "login";
static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"dd.MM.yyyy HH:mm", Locale.GERMANY);
// static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("",
// Locale.GERMANY);
private static String colorArray[] = new String[] { "", "black", "green",
"green", "red" };
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// for (User user : users) {
// int numExposes = DBManager.getExposes(pm, user.getId()).size();
//// if(0==numExposes && user.getBalance()==5000.00)
//// {
////// pm.deletePersistent(user);
//// }
//// else
//// {
// user.setNumExposes(numExposes);
// pm.makePersistent(user);
//// }
// }
// giveAllActionItem(pm);
MemcacheServiceFactory.getMemcacheService().clearAll();
// giveAllEarlyAdopterBadgeBoolean(pm);
// createDummyBadge(pm);
// createDummyBadge2(pm);
// updateDB(pm, 0,0);
// updateDB(pm, Long.parseLong(req.getParameter("start")),
// Long.parseLong(req.getParameter("end")));
// String html = getBase();
// // top5
// html =<SUF>
// // history
// html = generateHistory(pm, html);
// resp.getOutputStream().write(html.getBytes("utf-8"));
// // memcache stats
// Stats stats = MemcacheServiceFactory.getMemcacheService().getStatistics();
// LOG.log(Level.INFO,stats.toString());
} catch (Exception e) {
LOG.log(Level.SEVERE, "", e);
} finally {
pm.close();
}
}
// private String generateHistory(PersistenceManager pm,String html ) {
// List<History> histories = DBManager.getAllHistory(pm, 10);
// StringBuffer history = new StringBuffer("");
// for (History h : histories) {
// try {
// User u = DBManager.getUser(pm, h.getUserId());
// if (u == null) {
// // TODO schtief dunno why its a local problem
// LOG.log(Level.WARNING, "user null " + h.getUserId());
// continue;
// }
// // history.append("<p class='c'><span>");
// history.append("<tr><td><a href='/user/profile/").append(
// u.getUserName()).append("'>").append(
// u.getUserName()).append("</a></td><td> ").append(
// DATE_FORMAT
// .format(h.getTime() + 2 * 60 * 60 * 1000))
// .append(
// "</td><td>")
// .append(h.getText()).append("</td></tr>");
// // history.append("</span></p>");
// } catch (Exception e) {
// LOG.log(Level.WARNING, h.getText(), e);
// }
// }
// html = html.replace("_HISTORY_", history.toString());
// return html;
// }
//
// private String generatetop5(PersistenceManager pm, String html) {
// List<User> top5 = DBManager.getTopUser(pm, 0, 20);
// StringBuffer t5 = new StringBuffer("");
// int i = 1;
// for (User u : top5) {
// try {
// t5.append("<trfoo><td>").append(i).append(".</td><td>").append("<a href='/user/profile/");
// t5.append(u.getUserName()).append("'>").append(u.getUserName()).append("</a></td>");
// t5.append("<td>").append(History.MONEYFORMAT.format(u.getBalance())).append("</td>");
// t5.append("</tr>");
// i++;
// } catch (Exception e) {
// LOG.log(Level.WARNING, "lalala ", e);
// System.out.println(e.getMessage());
// }
// }
//
// html = html.replace("_TOP5_", t5.toString());
// return html;
// }
// private void createDummyBadge(PersistenceManager pm) {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// for (User u : users) {
// Badge b = new Badge(1, u.getId(), System.currentTimeMillis(), "Du wars schon dabei als Immopoly noch nicht cool war!",
// "http://immopoly.appspot.com/img/immopoly.png", 0.0,
// null);
// pm.makePersistent(b);
// }
// }
private void giveAllEarlyAdopterBadgeBoolean(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
int i = 0;
for (User user : users) {
if (!user.getReleaseBadge() && user.hasBadge(pm, Badge.ONE_OF_THE_FIRST)) {
user.setReleaseBadge(true);
pm.makePersistent(user);
i++;
LOG.info("user " + user.getUserName() + " " + i);
if (i == 200)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void giveAllActionItem(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
int i = 0;
for (User user : users) {
if (!user.hasActionItem(pm, ActionItem.TYPE_ACTION_FREEEXPOSES)) {
ActionItem actionItem = new ActionItem(user.getId(), System.currentTimeMillis(), ActionItem.TYPE_ACTION_FREEEXPOSES, 1,
"Konkurrenzspion: Zeigt alle freien Wohnungen an, die noch nicht übernommen worden sind",
ActionItem.IMAGE.get(ActionItem.TYPE_ACTION_FREEEXPOSES));
pm.makePersistent(actionItem);
i++;
LOG.info("user " + user.getUserName() + " " + i);
if (i == 100)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void sendAllEarlyAdopterMail(PersistenceManager pm) {
List<User> users = DBManager.getUsers(pm, " WHERE releaseBadge == true");
int i = 0;
for (User user : users) {
if (user.getReleaseBadge()) {
i++;
LOG.info("user " + user.getUserName() + " " + i);
try {
sendMail(user);
// user.setMailsent(true);
// pm.makePersistent(user);
} catch (Exception e) {
LOG.log(Level.SEVERE, "could not mail", e);
}
if (i == 200)
break;
}
}
LOG.info("Counted all user with EA badges " + i);
Counter counter = DBManager.getLatestCounter(pm);
LOG.info("Counter" + counter.toJSON().toString());
}
private void sendMail(User user) throws Exception {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
String msgBody = "Klicke auf den Link um dein Passwort zu ändern http://immopoly.appspot.com/resetpasswd.html?token="
+ user.getToken() + " \n your Immopoly Team";
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]", "Immopoly Team"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail(), user.getUserName()));
msg.setSubject("Immopoly Password setzen");
msg.setText(msgBody);
Transport.send(msg);
}
// private void giveAllEarlyAdopterBadgesBoolean(PersistenceManager pm) {
// List<User> users = DBManager.getUsers(pm, Long.MAX_VALUE);
// // for (User user : users) {
// // user.giveBadge(pm, Badge.EARLY_ADOPTER,
// // "Du warst schon dabei, als Immopoly nur ein bisschen cool war ;)");
// // }
// LOG.info("Counted all user and gave badges " + users.size());
// Counter counter = DBManager.getLatestCounter(pm);
// counter.setUser(users.size());
// LOG.info("Counter" + counter.toJSON().toString());
// pm.makePersistent(counter);
// }
private void createDummyBadge2(PersistenceManager pm) {
{
User u = DBManager.getUser(pm, "pointkilla");
Badge b = new Badge(444, u.getId(), System.currentTimeMillis(), "Du hast die Februar 2012 Wertung gewonnen!",
"http://immopoly.org/img/badges/feb121.png", 0.0, null);
pm.makePersistent(b);
}
{
User u = DBManager.getUser(pm, "tobi_h");
Badge b = new Badge(4444, u.getId(), System.currentTimeMillis(), "Du bist 2ter in der Februar 2012 Wertung geworden!",
"http://immopoly.org/img/badges/feb122.png", 0.0, null);
pm.makePersistent(b);
}
{
User u = DBManager.getUser(pm, "Tom");
Badge b = new Badge(44444, u.getId(), System.currentTimeMillis(), "Du bist 3ter in der Februar 2012 Wertung geworden!",
"http://immopoly.org/img/badges/feb123.png", 0.0, null);
pm.makePersistent(b);
}
}
private void updateDB(PersistenceManager pm, long start, long end) {
List<Expose> exposes = DBManager.getExposes(pm);
LOG.info("updateDB " + start + " - " + end + " number of entries: " + exposes.size());
for (Expose expose : exposes) {
if (expose.getDeleted() == Long.MAX_VALUE) {
if (expose.getLastcalculation() == null) {
LOG.info("updateDB lastcalculation is null " + expose.getExposeId());
continue;
}
expose.setDeleted(null);
pm.makePersistent(expose);
}
}
// User u = new User("wwaoname", "2password", "[email protected]",
// "twitter");
// u.setBalance(2149127);
// pm.makePersistent(u);
//
// History h = new History(History.TYPE_EXPOSE_ADDED, u.getId(),
// System.currentTimeMillis(),
// "jemand hat versucht mit einer Kettensaege in die wohnung einzubrechen und sich dabei den fuss verstaucht",
// 42, (long) -42);
// pm.makePersistent(h);
}
private String getBase() {
return readFileAsString("Immopoly.html");
}
static String readFileAsString(String filePath) {
try {
byte[] buffer = new byte[(int) new File(filePath).length()];
BufferedInputStream f = new BufferedInputStream(
new FileInputStream(filePath));
f.read(buffer);
return new String(buffer);
} catch (Exception e) {
LOG.severe("Konnte template " + filePath + " nich lesen "
+ e.getMessage());
return "";
}
}
}
|
4773_8 | /*
* KleurCanvas.java 13 maart 2003, Paul Bergervoet
*
*/
package kleurapplet;
import java.awt.*;
import kleurapplet.grnuminput.*;
class KleurCanvas extends Canvas
implements NumberListener
{ // Variables for double buffering
Dimension dd;
private Image bufferTekening; // Image tbv offline painting
private Graphics bufferGraphics; // Graphics object van bufferTekening
private Dimension bufferGrootte = new Dimension(0, 0);
// Size of Image, check with Frame size
// Variables
private int roodval;
private int groenval;
private int blauwval;
private float[] hsbvalues;
// Constants
private static Color echtRood = new Color(255, 0, 0);
private static Color echtGroen = new Color(0, 255, 0);
private static Color echtBlauw = new Color(0, 0, 255);
private static Font displayfont = new Font("SansSerif", Font.PLAIN, 12);
// Panels
RGBInvoerPaneel rgbip;
HSBInvoerPaneel hsbip;
public KleurCanvas()
{ roodval = 127;
groenval = 127;
blauwval = 127;
hsbvalues = Color.RGBtoHSB(roodval, groenval, blauwval, hsbvalues);
setBackground(Color.white);
setSize(360, 340);
}
/**
* Vertaalt een RGB-component in een tweecijferige hexamdecimale waarde.
*/
public String hexValue(int c)
{ String h = Integer.toHexString(c);
if ( h.length() == 1 ) // add zero voor eencijferige string
{ h = "0".concat(h);
}
return h;
}
/**
* Tekent naam van de kleurcomponent plus vlakje gekleurd in die component.
* bij RGB zetten we klein blokje in volle kleur voor de naam (argument fc)
* Bij HSB niet, dan is dat arg null.
*
* @param naam Naam van de Kleurcomponent (Tint, Verzadiging, .., Rood ...)
* @param c De te tekenen Kleurcomponent
* @param fc Kleur van het blokje met volle kleur R, G of B. ja/nee
* @param x De x-positie
* @param y De y-positie
* @param g De Graphics-context
*/
private void paintKleurComponent(String naam, Color c, Color fc, int x, int y, Graphics g)
{ int schuifx = 0;
if ( fc != null ) // blokje echt rood/groen/blauw
{ g.setColor(fc);
g.fillRect(x, y+5, 10, 10);
schuifx = 15; // naam zometeen 15 pixels naar rechts
}
g.setColor(c);
g.fillRoundRect(x, y+20, 60, 40, 5, 5);
g.setColor(Color.black);
g.drawString(naam, x+schuifx, y+15);
g.drawRoundRect(x, y+20, 60, 40, 5, 5);
}
public void paint(Graphics g)
{ g.setFont(displayfont);
Color c;
// --- tint ----
c = Color.getHSBColor(hsbvalues[0], 1, 1); // helderheid, verzadiging vol
paintKleurComponent("Tint", c, null, 30, 20, g);
// --- verzadiging ----
c = Color.getHSBColor(hsbvalues[0], hsbvalues[1], 1); // helderheid vol
paintKleurComponent("Verzadiging", c, null, 30, 100, g);
// --- helderheid ----
c = Color.getHSBColor(hsbvalues[0], 0, hsbvalues[2]); // verzadiging 0: grijs dus
paintKleurComponent("Helderheid", c, null, 30, 180, g);
// --- rood ----
c = new Color(roodval, 0, 0);
paintKleurComponent("Rood", c, echtRood, 270, 20, g);
// --- groen ----
c = new Color(0, groenval, 0);
paintKleurComponent("Groen", c, echtGroen, 270, 100, g);
// --- blauw ----
c = new Color(0, 0, blauwval);
paintKleurComponent("Blauw", c, echtBlauw, 270, 180, g);
// --- menging ----
g.setColor(new Color(roodval, groenval, blauwval));
g.fillRoundRect(120, 40, 120, 280, 5, 5);
g.setColor(Color.black);
g.drawString("De kleur", 120, 35);
g.drawRoundRect(120, 40, 120, 280, 5, 5);
// --- hexadecimaal RGB ---
g.setColor(Color.black);
g.drawString("Hex. RGB:", 270, 300);
String hrgb = "#";
hrgb = hrgb.concat(hexValue(roodval));
hrgb = hrgb.concat(hexValue(groenval));
hrgb = hrgb.concat(hexValue(blauwval));
g.drawString(hrgb, 270, 315);
}
// Event handler
/**
* Bij verandering van RGB moet HSB worden aangepast
*/
private void adjustHSBValues()
{ hsbvalues = Color.RGBtoHSB(roodval, groenval, blauwval, hsbvalues);
}
/**
* Bij verandering van HSB moet RGB worden aangepast
*/
private void adjustRGBValues()
{ Color c = Color.getHSBColor(hsbvalues[0], hsbvalues[1], hsbvalues[2]);
roodval = c.getRed();
groenval = c.getGreen();
blauwval = c.getBlue();
}
public void numberChanged(String naam, double v)
{ if ( naam.equals("Rood") )
{ roodval = (int)v; // harde cast!! v loopt van 0 tot 255 met 0 decimalen!
adjustHSBValues();
} else if ( naam.equals("Groen") )
{ groenval = (int)v;
adjustHSBValues();
} else if ( naam.equals("Blauw") )
{ blauwval = (int)v;
adjustHSBValues();
} else if ( naam.equals("Tint") )
{ hsbvalues[0] = (float)v; // harde cast!! v loopt van 0 tot 1 met 3 decimalen!
adjustRGBValues();
} else if ( naam.equals("Verzadiging") )
{ hsbvalues[1] = (float)v;
adjustRGBValues();
} else // must be "Helderheid"
{ hsbvalues[2] = (float)v;
adjustRGBValues();
}
repaint();
}
// ----- tbv double buffering
public void update(Graphics g)
{ dd = getSize(); // check eventuele resize...
if ( bufferTekening == null || // Image is er nog niet of ..
bufferGrootte.width != dd.width || // breedte/lengte van Canvas
bufferGrootte.height != dd.height // veranderd: dan nieuwe!
)
{ bufferTekening = createImage(dd.width, dd.height);
bufferGrootte = dd;
bufferGraphics = bufferTekening.getGraphics();
}
// Teken het nieuwe plaatje...
bufferGraphics.setColor(Color.white); // background vullen
bufferGraphics.fillRect(0, 0, bufferGrootte.width, bufferGrootte.height);
paint(bufferGraphics); // laat paint in Image werken!
g.drawImage(bufferTekening, 0, 0, null); // zet Image op Canvas....
}
}
| ddoa/dea-code-examples | exercises/kleurenmenger/src/main/java/kleurapplet/KleurCanvas.java | 2,117 | /**
* Tekent naam van de kleurcomponent plus vlakje gekleurd in die component.
* bij RGB zetten we klein blokje in volle kleur voor de naam (argument fc)
* Bij HSB niet, dan is dat arg null.
*
* @param naam Naam van de Kleurcomponent (Tint, Verzadiging, .., Rood ...)
* @param c De te tekenen Kleurcomponent
* @param fc Kleur van het blokje met volle kleur R, G of B. ja/nee
* @param x De x-positie
* @param y De y-positie
* @param g De Graphics-context
*/ | block_comment | nl | /*
* KleurCanvas.java 13 maart 2003, Paul Bergervoet
*
*/
package kleurapplet;
import java.awt.*;
import kleurapplet.grnuminput.*;
class KleurCanvas extends Canvas
implements NumberListener
{ // Variables for double buffering
Dimension dd;
private Image bufferTekening; // Image tbv offline painting
private Graphics bufferGraphics; // Graphics object van bufferTekening
private Dimension bufferGrootte = new Dimension(0, 0);
// Size of Image, check with Frame size
// Variables
private int roodval;
private int groenval;
private int blauwval;
private float[] hsbvalues;
// Constants
private static Color echtRood = new Color(255, 0, 0);
private static Color echtGroen = new Color(0, 255, 0);
private static Color echtBlauw = new Color(0, 0, 255);
private static Font displayfont = new Font("SansSerif", Font.PLAIN, 12);
// Panels
RGBInvoerPaneel rgbip;
HSBInvoerPaneel hsbip;
public KleurCanvas()
{ roodval = 127;
groenval = 127;
blauwval = 127;
hsbvalues = Color.RGBtoHSB(roodval, groenval, blauwval, hsbvalues);
setBackground(Color.white);
setSize(360, 340);
}
/**
* Vertaalt een RGB-component in een tweecijferige hexamdecimale waarde.
*/
public String hexValue(int c)
{ String h = Integer.toHexString(c);
if ( h.length() == 1 ) // add zero voor eencijferige string
{ h = "0".concat(h);
}
return h;
}
/**
* Tekent naam van<SUF>*/
private void paintKleurComponent(String naam, Color c, Color fc, int x, int y, Graphics g)
{ int schuifx = 0;
if ( fc != null ) // blokje echt rood/groen/blauw
{ g.setColor(fc);
g.fillRect(x, y+5, 10, 10);
schuifx = 15; // naam zometeen 15 pixels naar rechts
}
g.setColor(c);
g.fillRoundRect(x, y+20, 60, 40, 5, 5);
g.setColor(Color.black);
g.drawString(naam, x+schuifx, y+15);
g.drawRoundRect(x, y+20, 60, 40, 5, 5);
}
public void paint(Graphics g)
{ g.setFont(displayfont);
Color c;
// --- tint ----
c = Color.getHSBColor(hsbvalues[0], 1, 1); // helderheid, verzadiging vol
paintKleurComponent("Tint", c, null, 30, 20, g);
// --- verzadiging ----
c = Color.getHSBColor(hsbvalues[0], hsbvalues[1], 1); // helderheid vol
paintKleurComponent("Verzadiging", c, null, 30, 100, g);
// --- helderheid ----
c = Color.getHSBColor(hsbvalues[0], 0, hsbvalues[2]); // verzadiging 0: grijs dus
paintKleurComponent("Helderheid", c, null, 30, 180, g);
// --- rood ----
c = new Color(roodval, 0, 0);
paintKleurComponent("Rood", c, echtRood, 270, 20, g);
// --- groen ----
c = new Color(0, groenval, 0);
paintKleurComponent("Groen", c, echtGroen, 270, 100, g);
// --- blauw ----
c = new Color(0, 0, blauwval);
paintKleurComponent("Blauw", c, echtBlauw, 270, 180, g);
// --- menging ----
g.setColor(new Color(roodval, groenval, blauwval));
g.fillRoundRect(120, 40, 120, 280, 5, 5);
g.setColor(Color.black);
g.drawString("De kleur", 120, 35);
g.drawRoundRect(120, 40, 120, 280, 5, 5);
// --- hexadecimaal RGB ---
g.setColor(Color.black);
g.drawString("Hex. RGB:", 270, 300);
String hrgb = "#";
hrgb = hrgb.concat(hexValue(roodval));
hrgb = hrgb.concat(hexValue(groenval));
hrgb = hrgb.concat(hexValue(blauwval));
g.drawString(hrgb, 270, 315);
}
// Event handler
/**
* Bij verandering van RGB moet HSB worden aangepast
*/
private void adjustHSBValues()
{ hsbvalues = Color.RGBtoHSB(roodval, groenval, blauwval, hsbvalues);
}
/**
* Bij verandering van HSB moet RGB worden aangepast
*/
private void adjustRGBValues()
{ Color c = Color.getHSBColor(hsbvalues[0], hsbvalues[1], hsbvalues[2]);
roodval = c.getRed();
groenval = c.getGreen();
blauwval = c.getBlue();
}
public void numberChanged(String naam, double v)
{ if ( naam.equals("Rood") )
{ roodval = (int)v; // harde cast!! v loopt van 0 tot 255 met 0 decimalen!
adjustHSBValues();
} else if ( naam.equals("Groen") )
{ groenval = (int)v;
adjustHSBValues();
} else if ( naam.equals("Blauw") )
{ blauwval = (int)v;
adjustHSBValues();
} else if ( naam.equals("Tint") )
{ hsbvalues[0] = (float)v; // harde cast!! v loopt van 0 tot 1 met 3 decimalen!
adjustRGBValues();
} else if ( naam.equals("Verzadiging") )
{ hsbvalues[1] = (float)v;
adjustRGBValues();
} else // must be "Helderheid"
{ hsbvalues[2] = (float)v;
adjustRGBValues();
}
repaint();
}
// ----- tbv double buffering
public void update(Graphics g)
{ dd = getSize(); // check eventuele resize...
if ( bufferTekening == null || // Image is er nog niet of ..
bufferGrootte.width != dd.width || // breedte/lengte van Canvas
bufferGrootte.height != dd.height // veranderd: dan nieuwe!
)
{ bufferTekening = createImage(dd.width, dd.height);
bufferGrootte = dd;
bufferGraphics = bufferTekening.getGraphics();
}
// Teken het nieuwe plaatje...
bufferGraphics.setColor(Color.white); // background vullen
bufferGraphics.fillRect(0, 0, bufferGrootte.width, bufferGrootte.height);
paint(bufferGraphics); // laat paint in Image werken!
g.drawImage(bufferTekening, 0, 0, null); // zet Image op Canvas....
}
}
|
23370_21 | package be.msec.client;
import be.msec.ServiceProviderAction;
import be.msec.client.connection.Connection;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import be.msec.client.connection.IConnection;
import be.msec.client.connection.SimulatedConnection;
//import javacard.security.KeyBuilder;
//import javacard.security.RSAPublicKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.smartcardio.*;
public class MiddlewareMain extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private MiddlewareController middlewareController;
private final static byte IDENTITY_CARD_CLA = (byte) 0x80;
private static final byte VALIDATE_PIN_INS = 0x22;
private final static short SW_VERIFICATION_FAILED = 0x6300;
private final static short SW_PIN_VERIFICATION_REQUIRED = 0x6301;
private static final byte GET_SERIAL_INS = 0x26;
private static final byte UPDATE_TIME = 0x25;
private static final byte GET_NAME_INS = 0x24;
private static final byte SIGN_RANDOM_BYTE = 0x27;
private static final byte GET_CERTIFICATE = 0x28;
private static final byte AUTHENTICATE_SP = 0x21;
private static final byte VERIFY_CHALLENGE = 0x29;
private static final byte AUTHENTICATE_CARD = 0x30;
private static final byte RELEASE_ATTRIBUTE = 0x31;
private final static short ERROR_AUTHENTICATESP = (short) 0x8889;
static final int portG = 8001;
static final int portSP = 8003;
private Socket timestampSocket = null;
private Socket serviceProviderSocket = null;
IConnection c;
CommandAPDU a;
ResponseAPDU r;
boolean connectedWithSC = false;
boolean pinVerified = false;
private ServerSocket socket;
private Socket middlewareSocket;
// for testing
private byte[] pubMod_CA = new byte[] { (byte) -40, (byte) -96, (byte) 115, (byte) 21, (byte) -10, (byte) -66,
(byte) 80, (byte) 28, (byte) -124, (byte) 29, (byte) 98, (byte) -23, (byte) -72, (byte) 60, (byte) 89,
(byte) 21, (byte) -37, (byte) -122, (byte) -14, (byte) 94, (byte) -92, (byte) 48, (byte) 98, (byte) -35,
(byte) 5, (byte) -37, (byte) -50, (byte) -46, (byte) 21, (byte) -117, (byte) -48, (byte) -20, (byte) 50,
(byte) -80, (byte) -41, (byte) -126, (byte) -102, (byte) 63, (byte) -2, (byte) -10, (byte) 3, (byte) -86,
(byte) -54, (byte) 105, (byte) -64, (byte) 47, (byte) -23, (byte) -104, (byte) -39, (byte) 35, (byte) 107,
(byte) -46, (byte) -73, (byte) 2, (byte) 120, (byte) 112, (byte) -127, (byte) -37, (byte) 117, (byte) -79,
(byte) 15, (byte) 9, (byte) 48, (byte) -45 };
private byte[] pubExp_CA = new byte[] { (byte) 1, (byte) 0, (byte) 1 };
public void start(Stage stage) throws IOException {
this.primaryStage = stage;
this.primaryStage.setTitle("Card reader UI");
launchPinInputScreen();
try {
UPDATE_TIME_ON_CARD_ROUTINE();
// connectToCard(true);
connectServiceProvider();
// askName();
// UPDATE_TIME_ON_CARD_ROUTINE();
// checkChallenge();
} catch (Exception e) {
e.printStackTrace();
}
}
private void UPDATE_TIME_ON_CARD_ROUTINE() throws Exception {
connectToCard(true); //true = simulated connection
if (connectTimestampServer()) {
TimeInfoStruct signedTime = askTimeToTimestampServer();
if (signedTime != null) {
//send the bytes
sendTimeToCard(signedTime);
}
}
}
// -------------------------------------------------
// ------- TEST METHODES wITH USEFULL CODE ----------
// -------------------------------------------------
/**
* Test Methode First get the certificate with the public key then send
* challenge and check the challenge! ( transfer big amount of data)
*
* @throws Exception
*/
public void checkChallenge() throws Exception {
// first get the certificate with the public key
// then send challenge and check the challenge!
// 5. transferring large amounts of data
// ask for the public key (certificate)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] byteCertificate = new byte[256];
// System.out.println("Ask for the certificate");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_CERTIFICATE, (byte) 0x00, (byte) 0x00);
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR, verification failed");
else if (r.getSW() != 0x9000) {
throw new Exception("ERROR, " + r.getSW()); // print error number if not succeded
} else {
// System.out.println(" status 9000 ! dus oke");
byteCertificate = Arrays.copyOfRange(r.getBytes(), 0, r.getBytes().length - 2); // -2 bytes to cut off the
// SW-bytes
// System.out.println(bytesToHex(byteCertificate));
}
// change Byte array into Certificate object
CertificateFactory certFac = CertificateFactory.getInstance("X.509");
InputStream is = new ByteArrayInputStream(byteCertificate);
X509Certificate certificateObj = (X509Certificate) certFac.generateCertificate(is);
// System.out.println("Succesfully created certificate on the host app.");
// test Sign methode on card
// System.out.println("Send random byte array :");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(1);
// send 10 random bytes
byte[] randbytes = new byte[20];
random.nextBytes(randbytes);
// System.out.println(bytesToDec(randbytes));
a = new CommandAPDU(IDENTITY_CARD_CLA, SIGN_RANDOM_BYTE, 0x00, 0x00, randbytes);
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
// System.out.println("Signed is:");
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(certificateObj.getPublicKey());
signature.update(randbytes);
byte[] signedBytes = Arrays.copyOfRange(r.getData(), 1, r.getData().length); // receive signed data from card.
// Wel nog niet helemaal duidelijk wnr je hoeveel bytes er af moet knippen. Bij
// het doorsturen van het certificaat werden de SW bits op het einde ook
// duurgestuurd.
// Nu is dit niet het geval dus mogen de twee laatste er ook niet afgeknipt
// worden. Dus steeds checken met debugger!
// System.out.println(bytesToDec(signedBytes));
boolean ok = signature.verify(signedBytes);
// System.out.println(ok);
}
public void askName() {
try {
// 2. Send PIN
// die cla is altijd zelfde: gwn aangeven welke instructieset
// ins geeft aan wat er moet gebeuren --> dit getal staat ook vast in applet
// new byte[] geeft de pincode aan dus dit zou je normaal ingeven door de
// gebruiker
// System.out.println("Asking serial number");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_SERIAL_INS, 0x00, 0x00, new byte[] { 0x31, 0x32, 0x33, 0x34 });
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
String str = new String(r.getData(), StandardCharsets.UTF_8);
// System.out.println("SN is: " + str);
// 3. ask name
// System.out.println("Get name");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_NAME_INS, 0x00, 0x00, new byte[] { 0x31, 0x32, 0x33, 0x34 });
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
str = new String(r.getData(), StandardCharsets.UTF_8);
System.out.println("Name is: " + str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ---------------------------
// ------- INIT GUI ----------
// ---------------------------
public void launchPinInputScreen() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MiddlewareMain.class.getResource("/RootMenu.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// scene.getStylesheets().add("be.msec.stylesheet.css");
// Give the controller access to the main app.
RootMenuController controllerRoot = loader.getController();
controllerRoot.setMain(this);
primaryStage.show();
initPinLoginView();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initPinLoginView() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MiddlewareMain.class.getResource("/pinLoginView.fxml"));
System.out.println("Loading Main login Page");
AnchorPane loginView = (AnchorPane) loader.load();
// controller initialiseren + koppelen aan mainClient
middlewareController = loader.getController();
middlewareController.setMain(this);
rootLayout.setCenter(loginView);
}
// ----------------------------------
// ------- CONNECT TO CARD ----------
// ----------------------------------
/**
* Connect to the javacard
*
* @param simulatedConnection,
* true= simulated connection ; false = connect to real card terminal
* @throws Exception
*/
public boolean connectToCard(boolean simulatedConnection) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (simulatedConnection) {
System.out.println("Make a simulated connection.");
c = new SimulatedConnection();
c.connect();
createAppletForSimulator();
} else {
// System.out.println("Real connection");
c = new Connection();
((Connection) c).setTerminal(0); // depending on which cardreader you use
c.connect();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
private void createAppletForSimulator() {
try {
// 0. create applet (only for simulator!!!)
a = new CommandAPDU(0x00, 0xa4, 0x04, 0x00,
new byte[] { (byte) 0xa0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x08, 0x01 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
if (r.getSW() != 0x9000)
throw new Exception("select installer applet failed");
a = new CommandAPDU(0x80, 0xB8, 0x00, 0x00,
new byte[] { 0xb, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
if (r.getSW() != 0x9000)
throw new Exception("Applet creation failed");
// 1. Select applet (not required on a real card, applet is selected by default)
a = new CommandAPDU(0x00, 0xa4, 0x04, 0x00,
new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
System.out.println("Succesfully connected to the virtual javacard.");
if (r.getSW() != 0x9000)
throw new Exception("Applet selection failed");
} catch (Exception e) {
System.out.println("ERROR IN MAKING CONNECTION WITH SIMULATOR: " + e);
}
}
// -------------------------------------------------
// ------- TIMESTAMP SERVER COMMUNICATION ----------
// -------------------------------------------------
public boolean connectTimestampServer() {
System.out.println("---- 1. updateTime() ----");
// setup ssl properties
System.setProperty("javax.net.ssl.keyStore", "sslKeyStore.store");
System.setProperty("javax.net.ssl.keyStorePassword", "jonasaxel");
System.setProperty("javax.net.ssl.trustStore", "sslKeyStore.store");
System.setProperty("javax.net.ssl.trustStorePassword", "jonasaxel");
System.out.println("Ask the time from the SC");
System.out.println("There is need to update the time! --> connect to the timestampserver.");
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try {
timestampSocket = sslSocketFactory.createSocket("localhost", portG);
} catch (IOException ex) {
System.out.println("ERROR WITH CONNECTION TO G: " + ex);
return false;
}
System.out.println("Connected to timestamp server:" + timestampSocket);
return true;
}
public TimeInfoStruct askTimeToTimestampServer() throws Exception {
// hiervoor is eigenlijk geen certificaat nodig want de smartcard heeft de PKg
// hier wil ik enkel de tijd terug krijgen: eenmaal gehashed endan gesigned met
// SKg en eenmaal plain text
TimeInfoStruct timeInfoStruct = null;
ObjectOutputStream objectoutputstream = null;
ObjectInputStream objectinputstream = null;
try {
System.out.println("Send message to timestampserver to ask the time!");
try {
objectoutputstream = new ObjectOutputStream(timestampSocket.getOutputStream());
// Command = 1 => GetSignedTime
objectoutputstream.writeObject(1);
objectinputstream = new ObjectInputStream(timestampSocket.getInputStream());
// Cast serialized object into new object
timeInfoStruct = (TimeInfoStruct) objectinputstream.readObject();
System.out.println("Received date and signedData from the timestampserver!");
// System.out.println("Date from server: " + timeInfoStruct.getDate());
// System.out.println(bytesToDec(timeInfoStruct.getSignedData()));
objectinputstream.close();
} catch (EOFException | ClassNotFoundException exc) {
objectinputstream.close();
}
} catch (IOException ex) {
System.out.println("ERROR WITH RECEIVING TIME: " + ex);
}
return timeInfoStruct;
}
// -------------------------------------------------
// ------- SERVICE PROVIDER COMMUNICATION ----------
// -------------------------------------------------
public void connectServiceProvider() {
try {
socket = new ServerSocket(portSP);
System.out.println("Serversocket is listening");
middlewareSocket = socket.accept();
System.out.println("Socket connection accepted");
// start thread to listen for commands from ServiceProvider client
Thread listenerThread = new ListenForServiceProviderCommandThread();
listenerThread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendToServiceProvider(Object message) {
ObjectOutputStream out;
try {
System.out.println("SENDING TO SP");
out = new ObjectOutputStream(middlewareSocket.getOutputStream());
out.writeObject(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ------------------------------------------
// ------- JAVA CARD COMMUNICATION ----------
// ------------------------------------------
/**
* Send the signedtimestamp to the card so the time can be verifyed and updated
*
* @param timeInfoStruct
*/
private boolean sendTimeToCard(TimeInfoStruct timeInfoStruct) {
// concatenate all bytes into one big data array, this toSend needs to be given
// to the card
byte[] toSend = new byte[timeInfoStruct.getSignedData().length + timeInfoStruct.getDate().length];
System.arraycopy(timeInfoStruct.getSignedData(), 0, toSend, 0, timeInfoStruct.getSignedData().length);
System.arraycopy(timeInfoStruct.getDate(), 0, toSend, timeInfoStruct.getSignedData().length,
timeInfoStruct.getDate().length);
//
System.out.println("Send time to card!");
a = new CommandAPDU(IDENTITY_CARD_CLA, UPDATE_TIME, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
System.out.println("Date is succesfully updated on the card!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public Boolean loginWithPin(byte[] pin) throws Exception {
if (pin.length != 4) { // limit length of the pin to prevent dangerous input
throw new Exception("Pin has to be 4 characters");
}
// System.out.println(bytesToHex(pin));
a = new CommandAPDU(IDENTITY_CARD_CLA, VALIDATE_PIN_INS, 0x00, 0x00, pin);
r = c.transmit(a);
System.out.print("Pin ok? " + r.getSW());
if (r.getSW() == SW_VERIFICATION_FAILED) {
pinVerified = false;
return false;
} else if (r.getSW() == 0x26368)
throw new Exception("Wrong Pin size!");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
pinVerified = true;
return true;
}
public static void main(String[] args) throws Exception {
launch(args);
}
private boolean authenticateCertificate(ServiceProviderAction received) {
byte[] signedCertificateBytes = received.getSignedCertificate().getSignatureBytes();
CertificateServiceProvider certificateServiceProvider = (CertificateServiceProvider) received
.getSignedCertificate().getCertificateBasic();
// prepare everything to send to the card
byte[] certificateBytes = certificateServiceProvider.getBytes();
byte[] toSend = new byte[signedCertificateBytes.length + certificateBytes.length];
System.arraycopy(signedCertificateBytes, 0, toSend, 0, signedCertificateBytes.length);
System.arraycopy(certificateBytes, 0, toSend, signedCertificateBytes.length, certificateBytes.length);
//FOR DEMO DO SOMETHING WRONG!!
// toSend[2] = (byte) 0x53;
a = new CommandAPDU(IDENTITY_CARD_CLA, AUTHENTICATE_SP, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000) {
System.out.println("Not succesfully verified");
sendToServiceProvider(null);
}
else {
System.out.println("Certificate succesfully verified: " + r.getSW());
// get response data and send to SP
byte[] response = r.getData();
System.out.println(response.length + " response " + bytesToDec(response)); // first byte = length of
// response
Challenge challengeToSP = new Challenge(Arrays.copyOfRange(response, 1, 65),
Arrays.copyOfRange(response, 65, 81), Arrays.copyOfRange(response, 81, response.length));
// System.out.println(challengeToSP);
sendToServiceProvider(challengeToSP);
System.out.println("send challenge to SP done");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private boolean verifyChallenge(ServiceProviderAction received) {
byte[] toSend = new byte[received.getChallengeBytes().length];
System.arraycopy(received.getChallengeBytes(), 0, toSend, 0, received.getChallengeBytes().length);
a = new CommandAPDU(IDENTITY_CARD_CLA, VERIFY_CHALLENGE, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
else {
System.out.println("succesfully verified challenge");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private void authenticateCardSendChallenge(ServiceProviderAction received) {
byte[] toSend = received.getChallengeBytes();
a = new CommandAPDU(IDENTITY_CARD_CLA, AUTHENTICATE_CARD, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
else {
byte[] response = r.getData();
System.out.println(bytesToHex(response));
sendToServiceProvider(new MessageToAuthCard(Arrays.copyOfRange(response, 0, response.length)));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
private byte[] getDataFromCard(ServiceProviderAction receivedQuery) {
System.out.println("Getting data from card");
// a = new CommandAPDU(IDENTITY_CARD_CLA, RELEASE_ATTRIBUTE, 0x00, 0x00);
System.out.println("Ask with query: " + receivedQuery.getDataQuery());
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(receivedQuery.getDataQuery());
byte[] toSend = buffer.array();
a = new CommandAPDU(IDENTITY_CARD_CLA, RELEASE_ATTRIBUTE, 0x00, 0x00, receivedQuery.getDataQuery());
try {
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("Not verified, no access");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
System.out.println("Received encrypted data from the card.");
return r.getBytes();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
class WaitForPinThread extends Thread {
ServiceProviderAction query;
public WaitForPinThread(ServiceProviderAction query) {
this.query = query;
}
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
primaryStage.setAlwaysOnTop(true);
primaryStage.setAlwaysOnTop(false);
middlewareController.setMainMessage("Enter pin to get data...");
}
});
System.out.println("User must give in correct PIN...");
while (!pinVerified) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("PIN is correct!");
byte[] data = getDataFromCard(query);
sendToServiceProvider(data);
}
}
class ListenForServiceProviderCommandThread extends Thread {
public void run() {
ObjectInputStream objectinputstream = null;
try {
while (true) {
System.out.println("Listening to service provider...");
objectinputstream = new ObjectInputStream(middlewareSocket.getInputStream());
ServiceProviderAction receivedObject = (ServiceProviderAction) objectinputstream.readObject();
// System.out.println("received: " + receivedObject.getAction().getCommand());
switch (receivedObject.getAction().getCommand()) {
case AUTH_SP:
System.out.println("AUTH SP COMMAND");
// sendToServiceProvider("AUTH command received");
authenticateCertificate(receivedObject);
break;
case GET_DATA:
System.out.println("GET DATA COMMAND");
WaitForPinThread pinWaitingThread = new WaitForPinThread(receivedObject);
pinWaitingThread.start();
break;
case VERIFY_CHALLENGE:
System.out.println("VERIFY CHALLENGE COMMAND");
verifyChallenge(receivedObject);
break;
case AUTH_CARD:
System.out.println("AuthenticateCard COMMAND");
authenticateCardSendChallenge(receivedObject);
break;
default:
sendToServiceProvider("Command doesn't exists.");
}
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ------------------------------------
// ------- UTILITY FUNCTIONS ----------
// ------------------------------------
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
String str = "";
for (int j = 0; j < hexChars.length; j += 2) {
str += "0x" + hexChars[j] + hexChars[j + 1] + ", ";
}
return str;
}
public String bytesToDec(byte[] barray) {
String str = "";
for (byte b : barray)
str += (int) b + ", ";
return str;
}
} | Axxeption/smartcard | workspace2/Middleware/src/be/msec/client/MiddlewareMain.java | 7,529 | // worden. Dus steeds checken met debugger! | line_comment | nl | package be.msec.client;
import be.msec.ServiceProviderAction;
import be.msec.client.connection.Connection;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import be.msec.client.connection.IConnection;
import be.msec.client.connection.SimulatedConnection;
//import javacard.security.KeyBuilder;
//import javacard.security.RSAPublicKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.smartcardio.*;
public class MiddlewareMain extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private MiddlewareController middlewareController;
private final static byte IDENTITY_CARD_CLA = (byte) 0x80;
private static final byte VALIDATE_PIN_INS = 0x22;
private final static short SW_VERIFICATION_FAILED = 0x6300;
private final static short SW_PIN_VERIFICATION_REQUIRED = 0x6301;
private static final byte GET_SERIAL_INS = 0x26;
private static final byte UPDATE_TIME = 0x25;
private static final byte GET_NAME_INS = 0x24;
private static final byte SIGN_RANDOM_BYTE = 0x27;
private static final byte GET_CERTIFICATE = 0x28;
private static final byte AUTHENTICATE_SP = 0x21;
private static final byte VERIFY_CHALLENGE = 0x29;
private static final byte AUTHENTICATE_CARD = 0x30;
private static final byte RELEASE_ATTRIBUTE = 0x31;
private final static short ERROR_AUTHENTICATESP = (short) 0x8889;
static final int portG = 8001;
static final int portSP = 8003;
private Socket timestampSocket = null;
private Socket serviceProviderSocket = null;
IConnection c;
CommandAPDU a;
ResponseAPDU r;
boolean connectedWithSC = false;
boolean pinVerified = false;
private ServerSocket socket;
private Socket middlewareSocket;
// for testing
private byte[] pubMod_CA = new byte[] { (byte) -40, (byte) -96, (byte) 115, (byte) 21, (byte) -10, (byte) -66,
(byte) 80, (byte) 28, (byte) -124, (byte) 29, (byte) 98, (byte) -23, (byte) -72, (byte) 60, (byte) 89,
(byte) 21, (byte) -37, (byte) -122, (byte) -14, (byte) 94, (byte) -92, (byte) 48, (byte) 98, (byte) -35,
(byte) 5, (byte) -37, (byte) -50, (byte) -46, (byte) 21, (byte) -117, (byte) -48, (byte) -20, (byte) 50,
(byte) -80, (byte) -41, (byte) -126, (byte) -102, (byte) 63, (byte) -2, (byte) -10, (byte) 3, (byte) -86,
(byte) -54, (byte) 105, (byte) -64, (byte) 47, (byte) -23, (byte) -104, (byte) -39, (byte) 35, (byte) 107,
(byte) -46, (byte) -73, (byte) 2, (byte) 120, (byte) 112, (byte) -127, (byte) -37, (byte) 117, (byte) -79,
(byte) 15, (byte) 9, (byte) 48, (byte) -45 };
private byte[] pubExp_CA = new byte[] { (byte) 1, (byte) 0, (byte) 1 };
public void start(Stage stage) throws IOException {
this.primaryStage = stage;
this.primaryStage.setTitle("Card reader UI");
launchPinInputScreen();
try {
UPDATE_TIME_ON_CARD_ROUTINE();
// connectToCard(true);
connectServiceProvider();
// askName();
// UPDATE_TIME_ON_CARD_ROUTINE();
// checkChallenge();
} catch (Exception e) {
e.printStackTrace();
}
}
private void UPDATE_TIME_ON_CARD_ROUTINE() throws Exception {
connectToCard(true); //true = simulated connection
if (connectTimestampServer()) {
TimeInfoStruct signedTime = askTimeToTimestampServer();
if (signedTime != null) {
//send the bytes
sendTimeToCard(signedTime);
}
}
}
// -------------------------------------------------
// ------- TEST METHODES wITH USEFULL CODE ----------
// -------------------------------------------------
/**
* Test Methode First get the certificate with the public key then send
* challenge and check the challenge! ( transfer big amount of data)
*
* @throws Exception
*/
public void checkChallenge() throws Exception {
// first get the certificate with the public key
// then send challenge and check the challenge!
// 5. transferring large amounts of data
// ask for the public key (certificate)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] byteCertificate = new byte[256];
// System.out.println("Ask for the certificate");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_CERTIFICATE, (byte) 0x00, (byte) 0x00);
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR, verification failed");
else if (r.getSW() != 0x9000) {
throw new Exception("ERROR, " + r.getSW()); // print error number if not succeded
} else {
// System.out.println(" status 9000 ! dus oke");
byteCertificate = Arrays.copyOfRange(r.getBytes(), 0, r.getBytes().length - 2); // -2 bytes to cut off the
// SW-bytes
// System.out.println(bytesToHex(byteCertificate));
}
// change Byte array into Certificate object
CertificateFactory certFac = CertificateFactory.getInstance("X.509");
InputStream is = new ByteArrayInputStream(byteCertificate);
X509Certificate certificateObj = (X509Certificate) certFac.generateCertificate(is);
// System.out.println("Succesfully created certificate on the host app.");
// test Sign methode on card
// System.out.println("Send random byte array :");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(1);
// send 10 random bytes
byte[] randbytes = new byte[20];
random.nextBytes(randbytes);
// System.out.println(bytesToDec(randbytes));
a = new CommandAPDU(IDENTITY_CARD_CLA, SIGN_RANDOM_BYTE, 0x00, 0x00, randbytes);
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
// System.out.println("Signed is:");
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(certificateObj.getPublicKey());
signature.update(randbytes);
byte[] signedBytes = Arrays.copyOfRange(r.getData(), 1, r.getData().length); // receive signed data from card.
// Wel nog niet helemaal duidelijk wnr je hoeveel bytes er af moet knippen. Bij
// het doorsturen van het certificaat werden de SW bits op het einde ook
// duurgestuurd.
// Nu is dit niet het geval dus mogen de twee laatste er ook niet afgeknipt
// worden. Dus<SUF>
// System.out.println(bytesToDec(signedBytes));
boolean ok = signature.verify(signedBytes);
// System.out.println(ok);
}
public void askName() {
try {
// 2. Send PIN
// die cla is altijd zelfde: gwn aangeven welke instructieset
// ins geeft aan wat er moet gebeuren --> dit getal staat ook vast in applet
// new byte[] geeft de pincode aan dus dit zou je normaal ingeven door de
// gebruiker
// System.out.println("Asking serial number");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_SERIAL_INS, 0x00, 0x00, new byte[] { 0x31, 0x32, 0x33, 0x34 });
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
String str = new String(r.getData(), StandardCharsets.UTF_8);
// System.out.println("SN is: " + str);
// 3. ask name
// System.out.println("Get name");
a = new CommandAPDU(IDENTITY_CARD_CLA, GET_NAME_INS, 0x00, 0x00, new byte[] { 0x31, 0x32, 0x33, 0x34 });
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("ERROR");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
str = new String(r.getData(), StandardCharsets.UTF_8);
System.out.println("Name is: " + str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ---------------------------
// ------- INIT GUI ----------
// ---------------------------
public void launchPinInputScreen() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MiddlewareMain.class.getResource("/RootMenu.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// scene.getStylesheets().add("be.msec.stylesheet.css");
// Give the controller access to the main app.
RootMenuController controllerRoot = loader.getController();
controllerRoot.setMain(this);
primaryStage.show();
initPinLoginView();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initPinLoginView() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MiddlewareMain.class.getResource("/pinLoginView.fxml"));
System.out.println("Loading Main login Page");
AnchorPane loginView = (AnchorPane) loader.load();
// controller initialiseren + koppelen aan mainClient
middlewareController = loader.getController();
middlewareController.setMain(this);
rootLayout.setCenter(loginView);
}
// ----------------------------------
// ------- CONNECT TO CARD ----------
// ----------------------------------
/**
* Connect to the javacard
*
* @param simulatedConnection,
* true= simulated connection ; false = connect to real card terminal
* @throws Exception
*/
public boolean connectToCard(boolean simulatedConnection) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (simulatedConnection) {
System.out.println("Make a simulated connection.");
c = new SimulatedConnection();
c.connect();
createAppletForSimulator();
} else {
// System.out.println("Real connection");
c = new Connection();
((Connection) c).setTerminal(0); // depending on which cardreader you use
c.connect();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
private void createAppletForSimulator() {
try {
// 0. create applet (only for simulator!!!)
a = new CommandAPDU(0x00, 0xa4, 0x04, 0x00,
new byte[] { (byte) 0xa0, 0x00, 0x00, 0x00, 0x62, 0x03, 0x01, 0x08, 0x01 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
if (r.getSW() != 0x9000)
throw new Exception("select installer applet failed");
a = new CommandAPDU(0x80, 0xB8, 0x00, 0x00,
new byte[] { 0xb, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
if (r.getSW() != 0x9000)
throw new Exception("Applet creation failed");
// 1. Select applet (not required on a real card, applet is selected by default)
a = new CommandAPDU(0x00, 0xa4, 0x04, 0x00,
new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00 }, 0x7f);
r = c.transmit(a);
// System.out.println(r);
System.out.println("Succesfully connected to the virtual javacard.");
if (r.getSW() != 0x9000)
throw new Exception("Applet selection failed");
} catch (Exception e) {
System.out.println("ERROR IN MAKING CONNECTION WITH SIMULATOR: " + e);
}
}
// -------------------------------------------------
// ------- TIMESTAMP SERVER COMMUNICATION ----------
// -------------------------------------------------
public boolean connectTimestampServer() {
System.out.println("---- 1. updateTime() ----");
// setup ssl properties
System.setProperty("javax.net.ssl.keyStore", "sslKeyStore.store");
System.setProperty("javax.net.ssl.keyStorePassword", "jonasaxel");
System.setProperty("javax.net.ssl.trustStore", "sslKeyStore.store");
System.setProperty("javax.net.ssl.trustStorePassword", "jonasaxel");
System.out.println("Ask the time from the SC");
System.out.println("There is need to update the time! --> connect to the timestampserver.");
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try {
timestampSocket = sslSocketFactory.createSocket("localhost", portG);
} catch (IOException ex) {
System.out.println("ERROR WITH CONNECTION TO G: " + ex);
return false;
}
System.out.println("Connected to timestamp server:" + timestampSocket);
return true;
}
public TimeInfoStruct askTimeToTimestampServer() throws Exception {
// hiervoor is eigenlijk geen certificaat nodig want de smartcard heeft de PKg
// hier wil ik enkel de tijd terug krijgen: eenmaal gehashed endan gesigned met
// SKg en eenmaal plain text
TimeInfoStruct timeInfoStruct = null;
ObjectOutputStream objectoutputstream = null;
ObjectInputStream objectinputstream = null;
try {
System.out.println("Send message to timestampserver to ask the time!");
try {
objectoutputstream = new ObjectOutputStream(timestampSocket.getOutputStream());
// Command = 1 => GetSignedTime
objectoutputstream.writeObject(1);
objectinputstream = new ObjectInputStream(timestampSocket.getInputStream());
// Cast serialized object into new object
timeInfoStruct = (TimeInfoStruct) objectinputstream.readObject();
System.out.println("Received date and signedData from the timestampserver!");
// System.out.println("Date from server: " + timeInfoStruct.getDate());
// System.out.println(bytesToDec(timeInfoStruct.getSignedData()));
objectinputstream.close();
} catch (EOFException | ClassNotFoundException exc) {
objectinputstream.close();
}
} catch (IOException ex) {
System.out.println("ERROR WITH RECEIVING TIME: " + ex);
}
return timeInfoStruct;
}
// -------------------------------------------------
// ------- SERVICE PROVIDER COMMUNICATION ----------
// -------------------------------------------------
public void connectServiceProvider() {
try {
socket = new ServerSocket(portSP);
System.out.println("Serversocket is listening");
middlewareSocket = socket.accept();
System.out.println("Socket connection accepted");
// start thread to listen for commands from ServiceProvider client
Thread listenerThread = new ListenForServiceProviderCommandThread();
listenerThread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendToServiceProvider(Object message) {
ObjectOutputStream out;
try {
System.out.println("SENDING TO SP");
out = new ObjectOutputStream(middlewareSocket.getOutputStream());
out.writeObject(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ------------------------------------------
// ------- JAVA CARD COMMUNICATION ----------
// ------------------------------------------
/**
* Send the signedtimestamp to the card so the time can be verifyed and updated
*
* @param timeInfoStruct
*/
private boolean sendTimeToCard(TimeInfoStruct timeInfoStruct) {
// concatenate all bytes into one big data array, this toSend needs to be given
// to the card
byte[] toSend = new byte[timeInfoStruct.getSignedData().length + timeInfoStruct.getDate().length];
System.arraycopy(timeInfoStruct.getSignedData(), 0, toSend, 0, timeInfoStruct.getSignedData().length);
System.arraycopy(timeInfoStruct.getDate(), 0, toSend, timeInfoStruct.getSignedData().length,
timeInfoStruct.getDate().length);
//
System.out.println("Send time to card!");
a = new CommandAPDU(IDENTITY_CARD_CLA, UPDATE_TIME, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
System.out.println("Date is succesfully updated on the card!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public Boolean loginWithPin(byte[] pin) throws Exception {
if (pin.length != 4) { // limit length of the pin to prevent dangerous input
throw new Exception("Pin has to be 4 characters");
}
// System.out.println(bytesToHex(pin));
a = new CommandAPDU(IDENTITY_CARD_CLA, VALIDATE_PIN_INS, 0x00, 0x00, pin);
r = c.transmit(a);
System.out.print("Pin ok? " + r.getSW());
if (r.getSW() == SW_VERIFICATION_FAILED) {
pinVerified = false;
return false;
} else if (r.getSW() == 0x26368)
throw new Exception("Wrong Pin size!");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
pinVerified = true;
return true;
}
public static void main(String[] args) throws Exception {
launch(args);
}
private boolean authenticateCertificate(ServiceProviderAction received) {
byte[] signedCertificateBytes = received.getSignedCertificate().getSignatureBytes();
CertificateServiceProvider certificateServiceProvider = (CertificateServiceProvider) received
.getSignedCertificate().getCertificateBasic();
// prepare everything to send to the card
byte[] certificateBytes = certificateServiceProvider.getBytes();
byte[] toSend = new byte[signedCertificateBytes.length + certificateBytes.length];
System.arraycopy(signedCertificateBytes, 0, toSend, 0, signedCertificateBytes.length);
System.arraycopy(certificateBytes, 0, toSend, signedCertificateBytes.length, certificateBytes.length);
//FOR DEMO DO SOMETHING WRONG!!
// toSend[2] = (byte) 0x53;
a = new CommandAPDU(IDENTITY_CARD_CLA, AUTHENTICATE_SP, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000) {
System.out.println("Not succesfully verified");
sendToServiceProvider(null);
}
else {
System.out.println("Certificate succesfully verified: " + r.getSW());
// get response data and send to SP
byte[] response = r.getData();
System.out.println(response.length + " response " + bytesToDec(response)); // first byte = length of
// response
Challenge challengeToSP = new Challenge(Arrays.copyOfRange(response, 1, 65),
Arrays.copyOfRange(response, 65, 81), Arrays.copyOfRange(response, 81, response.length));
// System.out.println(challengeToSP);
sendToServiceProvider(challengeToSP);
System.out.println("send challenge to SP done");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private boolean verifyChallenge(ServiceProviderAction received) {
byte[] toSend = new byte[received.getChallengeBytes().length];
System.arraycopy(received.getChallengeBytes(), 0, toSend, 0, received.getChallengeBytes().length);
a = new CommandAPDU(IDENTITY_CARD_CLA, VERIFY_CHALLENGE, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
else {
System.out.println("succesfully verified challenge");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private void authenticateCardSendChallenge(ServiceProviderAction received) {
byte[] toSend = received.getChallengeBytes();
a = new CommandAPDU(IDENTITY_CARD_CLA, AUTHENTICATE_CARD, 0x00, 0x00, toSend);
try {
r = c.transmit(a);
if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
else {
byte[] response = r.getData();
System.out.println(bytesToHex(response));
sendToServiceProvider(new MessageToAuthCard(Arrays.copyOfRange(response, 0, response.length)));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
private byte[] getDataFromCard(ServiceProviderAction receivedQuery) {
System.out.println("Getting data from card");
// a = new CommandAPDU(IDENTITY_CARD_CLA, RELEASE_ATTRIBUTE, 0x00, 0x00);
System.out.println("Ask with query: " + receivedQuery.getDataQuery());
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(receivedQuery.getDataQuery());
byte[] toSend = buffer.array();
a = new CommandAPDU(IDENTITY_CARD_CLA, RELEASE_ATTRIBUTE, 0x00, 0x00, receivedQuery.getDataQuery());
try {
r = c.transmit(a);
if (r.getSW() == SW_VERIFICATION_FAILED)
throw new Exception("Not verified, no access");
else if (r.getSW() != 0x9000)
throw new Exception("Exception on the card: " + r.getSW());
System.out.println("Received encrypted data from the card.");
return r.getBytes();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
class WaitForPinThread extends Thread {
ServiceProviderAction query;
public WaitForPinThread(ServiceProviderAction query) {
this.query = query;
}
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
primaryStage.setAlwaysOnTop(true);
primaryStage.setAlwaysOnTop(false);
middlewareController.setMainMessage("Enter pin to get data...");
}
});
System.out.println("User must give in correct PIN...");
while (!pinVerified) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("PIN is correct!");
byte[] data = getDataFromCard(query);
sendToServiceProvider(data);
}
}
class ListenForServiceProviderCommandThread extends Thread {
public void run() {
ObjectInputStream objectinputstream = null;
try {
while (true) {
System.out.println("Listening to service provider...");
objectinputstream = new ObjectInputStream(middlewareSocket.getInputStream());
ServiceProviderAction receivedObject = (ServiceProviderAction) objectinputstream.readObject();
// System.out.println("received: " + receivedObject.getAction().getCommand());
switch (receivedObject.getAction().getCommand()) {
case AUTH_SP:
System.out.println("AUTH SP COMMAND");
// sendToServiceProvider("AUTH command received");
authenticateCertificate(receivedObject);
break;
case GET_DATA:
System.out.println("GET DATA COMMAND");
WaitForPinThread pinWaitingThread = new WaitForPinThread(receivedObject);
pinWaitingThread.start();
break;
case VERIFY_CHALLENGE:
System.out.println("VERIFY CHALLENGE COMMAND");
verifyChallenge(receivedObject);
break;
case AUTH_CARD:
System.out.println("AuthenticateCard COMMAND");
authenticateCardSendChallenge(receivedObject);
break;
default:
sendToServiceProvider("Command doesn't exists.");
}
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ------------------------------------
// ------- UTILITY FUNCTIONS ----------
// ------------------------------------
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
String str = "";
for (int j = 0; j < hexChars.length; j += 2) {
str += "0x" + hexChars[j] + hexChars[j + 1] + ", ";
}
return str;
}
public String bytesToDec(byte[] barray) {
String str = "";
for (byte b : barray)
str += (int) b + ", ";
return str;
}
} |
101952_8 | import java.io.*;
import java.util.Scanner;
public class BinaireFileDemo {
public void opslaanGetallen(String bestandsnaam){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
// objectOutputStream initaliseren met FileOutputStream object)
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);
// int wegschrijven naar ObjectOutputStream
}
while (getal >= 0);
output.close();
// Stream sluiten
} 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 (IOException e) {
e.printStackTrace();
}
}
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 bewarenStudenten2(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[] lezenStudenten2(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";
//BinaireFileDemo demo1 = new BinaireFileDemo();
//demo1.opslaanGetallen(bestandsnaam1);
//demo1.lezenGetallen(bestandsnaam1);
//Demo 2
//String bestandsnaam2 = "student.dat";
//BinaireFileDemo demo2 = new BinaireFileDemo();
//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";
BinaireFileDemo demo3 = new BinaireFileDemo();
demo3.bewarenStudenten2(bestandsnaam3,studenten);
Student[] studenten2 = demo3.lezenStudenten2(bestandsnaam3);
}
}
| UGent-AD2223-BusinessEngineering/CodevoorbeeldenHOC-2223 | IO/BinaireFileDemo.java | 1,207 | //ObjectOutputStream object aanmaken` | line_comment | nl | import java.io.*;
import java.util.Scanner;
public class BinaireFileDemo {
public void opslaanGetallen(String bestandsnaam){
//ObjectOutputStream object aanmaken`
ObjectOutputStream output = null;
try {
// objectOutputStream initaliseren met FileOutputStream object)
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);
// int wegschrijven naar ObjectOutputStream
}
while (getal >= 0);
output.close();
// Stream sluiten
} 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 (IOException e) {
e.printStackTrace();
}
}
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 bewarenStudenten2(String bestandsnaam, Student[] studenten){
//ObjectOutputStream object<SUF>
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[] lezenStudenten2(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";
//BinaireFileDemo demo1 = new BinaireFileDemo();
//demo1.opslaanGetallen(bestandsnaam1);
//demo1.lezenGetallen(bestandsnaam1);
//Demo 2
//String bestandsnaam2 = "student.dat";
//BinaireFileDemo demo2 = new BinaireFileDemo();
//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";
BinaireFileDemo demo3 = new BinaireFileDemo();
demo3.bewarenStudenten2(bestandsnaam3,studenten);
Student[] studenten2 = demo3.lezenStudenten2(bestandsnaam3);
}
}
|
68644_4 | package nl.hu.dp;
import nl.hu.dp.P5.Product;
import nl.hu.dp.P5.ProductDAOPsql;
import nl.hu.dp.p2.domain.Reiziger;
import nl.hu.dp.p2.domain.ReizigerDAO;
import nl.hu.dp.p2.domain.ReizigerDAOPsql;
import nl.hu.dp.p3.Adres;
import nl.hu.dp.p3.AdresDAO;
import nl.hu.dp.p3.AdresDAOPsql;
import nl.hu.dp.p4.OVChipkaart;
import nl.hu.dp.p4.OVChipkaartDAO;
import nl.hu.dp.p4.OVChipkaartDAOPsql;
import java.sql.*;
import java.util.List;
public class Main {
static Connection connection;
public static void main(String[] args) throws SQLException{
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ovchip", "postgres", "Pietermortier1");
try {
ReizigerDAO rdao = new ReizigerDAOPsql(connection);
AdresDAO adao = new AdresDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
ProductDAOPsql pdao = new ProductDAOPsql(connection);
testProductDAO(pdao);
//testOVChipkaartDAO(odao);
// testReizigerDAO(rdao);
System.out.println();
//testAdresDAO(adao, rdao);
} catch (Exception exc) {
exc.printStackTrace();
}
}
private static void testOVChipkaartDAO(OVChipkaartDAO odao) throws SQLException {
System.out.println("\n---------- Test OVChipkaartDAO -------------");
List<OVChipkaart> ovChipkaarts = odao.findAll();
System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende kaarten:");
for (OVChipkaart ovChipkaart : ovChipkaarts) {
System.out.println(ovChipkaart);
}
System.out.println();
String gbdatum = "2000-09-29";
String gdtot = "2025-09-29";
Reiziger lucas = new Reiziger(5, "L", "", "Caslu", java.sql.Date.valueOf(gbdatum));
OVChipkaart ovChipkaart = new OVChipkaart(18326, java.sql.Date.valueOf(gdtot), 2, 5.50, 5);
System.out.print("[Test] Eerst " + ovChipkaarts.size() + " Ovchipkaarts, na ovchipkaart.save() ");
odao.save(ovChipkaart);
ovChipkaarts = odao.findAll();
System.out.println(ovChipkaarts.size() + " reizigers\n");
List<OVChipkaart> OvList = odao.findByReiziger(lucas);
System.out.println("[Test] OVChipkaart.findByReiziger() geeft de lijst:");
System.out.println(OvList);
System.out.println();
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
rdao.save(lucas);
System.out.println("[Test] delete(): " + odao.delete(ovChipkaart));
List<OVChipkaart> ovChipkaarts1 = odao.findAll();
System.out.println("[Test] ovCHipkaarten.size() ");
System.out.println(ovChipkaarts1.size()+ " kaarten");
OVChipkaart ovChipkaart1 = new OVChipkaart(90537, java.sql.Date.valueOf(gdtot), 2, 5.50, 5);
System.out.println(lucas);
System.out.println("[Test] update(): " + odao.update(ovChipkaart1));
System.out.println(odao.findByReiziger(lucas));
closeConnection();
}
private static void testProductDAO(ProductDAOPsql pdao) throws SQLException {
System.out.println("\n---------- Test ProductDao -------------");
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
// Haal alle Producten op uit de database
List<Product> productList = pdao.findAll();
System.out.println("[Test] ProductDao.findAll() geeft de volgende reizigers:");
for (Product product : productList) {
System.out.println(product);
}
System.out.println(productList.size()+ "producten");
// aanmaken product en ov
System.out.println();
String gbdatum = "2000-1-11";
String geldigtot = "2025-10-13";
Product product = new Product(10, "Gratis", "Fijne reis", 0.00);
Reiziger pedro = new Reiziger(12, "P", "", "Ordep", java.sql.Date.valueOf(gbdatum));
OVChipkaart ovChipkaart = new OVChipkaart(1836, java.sql.Date.valueOf(geldigtot), 2, 5.50, 12);
product.voegChipkaartToe(ovChipkaart);
System.out.println(product);
pdao.save(product);
List<Product> productList1 = pdao.findAll();
System.out.println(productList1.size()+ " producten");
System.out.println();
Product product1 = new Product(3, "Dal Voordeel 100%", "10 korting ", 40.00);
System.out.println("[Test] update(): " + pdao.update(product1));
System.out.println("[Test] findByOVChipkaart(): " + pdao.findByOVChipkaart(ovChipkaart));
System.out.println("[Test] delete(): " + pdao.delete(product));
List<Product> productList2 = pdao.findAll();
System.out.println(productList2.size()+ "producten");
closeConnection();
}
private static void testAdresDAO(AdresDAO adao,ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test AdresDAO -------------");
//
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende reizigers:");
for (Adres a : adressen) {
System.out.println(a);
}
// Eerst een nieuwe reiziger maken en opslaan
String gbdatum = "2000-03-14";
Reiziger sietske = new Reiziger(7, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
rdao.save(sietske);
// Een adres maken met de opgeslagen reiziger en opslaan
Adres a = new Adres(6, "1234TB", "25A", "HUStraat", "Groningen", 12);
System.out.println("[Test] AdresDAO.save() ");
System.out.println(adressen.size() + " adressen\n");
adao.save(a);
sietske.setAdres(a);
rdao.update(sietske);
adressen = adao.findAll();
System.out.println(adressen.size() + " adressen na de test\n");
//
Adres aa = adao.findByReiziger(sietske);
System.out.println(sietske);
System.out.println("[Test] AdresDAO.findByReiziger() geeft de adres:");
System.out.println(aa);
System.out.println();
System.out.println(adressen.size() + " adressen\n");
System.out.println("[Test] delete(): " + adao.delete(a));
List<Adres> aaa = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende reizigers:");
System.out.println(aaa.size());
System.out.println();
Adres b = new Adres(2, "16e64TB", "voorstraat", "49", "Utrecht", 12);
System.out.println("[Test] update(): " + adao.update(b));
System.out.println(b);
//
closeConnection();
//
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(6, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Voeg aanvullende tests van de ontbrekende CRUD-operaties in.
sietske.setVoorletters("T");
sietske.setTussenvoegsel("aa");
sietske.setAchternaam("Pieter");
System.out.println("Uitgevoerde SQL-query: " + sietske);
System.out.println("Voorletters: " + sietske.getVoorletters());
System.out.println("Tussenvoegsel: " + sietske.getTussenvoegsel());
System.out.println("Achternaam: " + sietske.getAchternaam());
System.out.println("Geboortedatum: " + sietske.getGeboortedatum());
System.out.println("Reiziger ID: " + sietske.getReiziger_id());
System.out.println("[Test] Na de Update met nieuwe naam " + sietske);
if (rdao.update(sietske)) {
System.out.println("[Test] ReizigerDAO.update() gelukt: " + sietske);
} else {
System.out.println("[Test] ReizigerDAO.update() gaat nog niet helemaal goed");
}
System.out.println();
System.out.println("[Test] ReizigerDAO.findById() geeft de volgende reiziger:");
Reiziger gevondenReiziger = rdao.findById(sietske.getReiziger_id());
System.out.println(gevondenReiziger);
System.out.println("[Test] ReizigerDAO.delete() probeert de bovenstaande reiziger te verwijderen...");
if (rdao.delete(gevondenReiziger)) {
System.out.println("[Test] ReizigerDAO.delete() geslaagd, reiziger verwijderd");
} else {
System.out.println("[Test] ReizigerDAO.delete() mislukt");
}
reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers na delete:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
}
private static void closeConnection() throws SQLException {
if (connection != null && !connection.isClosed()) {
connection.close();
}
}
private static void testConnection() throws SQLException {
String query = "SELECT * FROM reiziger;";
PreparedStatement statement = connection.prepareStatement(query);
ResultSet set = statement.executeQuery();
System.out.println("Alle reizigers:");
while (set != null && set.next()) {
System.out.println(" #" + set.getString("reiziger_id") + ": " + set.getString("voorletters") + ". " + set.getString("achternaam") + " (" + set.getString("geboortedatum") + ")");
}
closeConnection();
}
} | Pmortier2019/DataPers | src/nl/hu/dp/Main.java | 3,081 | // Een adres maken met de opgeslagen reiziger en opslaan | line_comment | nl | package nl.hu.dp;
import nl.hu.dp.P5.Product;
import nl.hu.dp.P5.ProductDAOPsql;
import nl.hu.dp.p2.domain.Reiziger;
import nl.hu.dp.p2.domain.ReizigerDAO;
import nl.hu.dp.p2.domain.ReizigerDAOPsql;
import nl.hu.dp.p3.Adres;
import nl.hu.dp.p3.AdresDAO;
import nl.hu.dp.p3.AdresDAOPsql;
import nl.hu.dp.p4.OVChipkaart;
import nl.hu.dp.p4.OVChipkaartDAO;
import nl.hu.dp.p4.OVChipkaartDAOPsql;
import java.sql.*;
import java.util.List;
public class Main {
static Connection connection;
public static void main(String[] args) throws SQLException{
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ovchip", "postgres", "Pietermortier1");
try {
ReizigerDAO rdao = new ReizigerDAOPsql(connection);
AdresDAO adao = new AdresDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
ProductDAOPsql pdao = new ProductDAOPsql(connection);
testProductDAO(pdao);
//testOVChipkaartDAO(odao);
// testReizigerDAO(rdao);
System.out.println();
//testAdresDAO(adao, rdao);
} catch (Exception exc) {
exc.printStackTrace();
}
}
private static void testOVChipkaartDAO(OVChipkaartDAO odao) throws SQLException {
System.out.println("\n---------- Test OVChipkaartDAO -------------");
List<OVChipkaart> ovChipkaarts = odao.findAll();
System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende kaarten:");
for (OVChipkaart ovChipkaart : ovChipkaarts) {
System.out.println(ovChipkaart);
}
System.out.println();
String gbdatum = "2000-09-29";
String gdtot = "2025-09-29";
Reiziger lucas = new Reiziger(5, "L", "", "Caslu", java.sql.Date.valueOf(gbdatum));
OVChipkaart ovChipkaart = new OVChipkaart(18326, java.sql.Date.valueOf(gdtot), 2, 5.50, 5);
System.out.print("[Test] Eerst " + ovChipkaarts.size() + " Ovchipkaarts, na ovchipkaart.save() ");
odao.save(ovChipkaart);
ovChipkaarts = odao.findAll();
System.out.println(ovChipkaarts.size() + " reizigers\n");
List<OVChipkaart> OvList = odao.findByReiziger(lucas);
System.out.println("[Test] OVChipkaart.findByReiziger() geeft de lijst:");
System.out.println(OvList);
System.out.println();
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
rdao.save(lucas);
System.out.println("[Test] delete(): " + odao.delete(ovChipkaart));
List<OVChipkaart> ovChipkaarts1 = odao.findAll();
System.out.println("[Test] ovCHipkaarten.size() ");
System.out.println(ovChipkaarts1.size()+ " kaarten");
OVChipkaart ovChipkaart1 = new OVChipkaart(90537, java.sql.Date.valueOf(gdtot), 2, 5.50, 5);
System.out.println(lucas);
System.out.println("[Test] update(): " + odao.update(ovChipkaart1));
System.out.println(odao.findByReiziger(lucas));
closeConnection();
}
private static void testProductDAO(ProductDAOPsql pdao) throws SQLException {
System.out.println("\n---------- Test ProductDao -------------");
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
// Haal alle Producten op uit de database
List<Product> productList = pdao.findAll();
System.out.println("[Test] ProductDao.findAll() geeft de volgende reizigers:");
for (Product product : productList) {
System.out.println(product);
}
System.out.println(productList.size()+ "producten");
// aanmaken product en ov
System.out.println();
String gbdatum = "2000-1-11";
String geldigtot = "2025-10-13";
Product product = new Product(10, "Gratis", "Fijne reis", 0.00);
Reiziger pedro = new Reiziger(12, "P", "", "Ordep", java.sql.Date.valueOf(gbdatum));
OVChipkaart ovChipkaart = new OVChipkaart(1836, java.sql.Date.valueOf(geldigtot), 2, 5.50, 12);
product.voegChipkaartToe(ovChipkaart);
System.out.println(product);
pdao.save(product);
List<Product> productList1 = pdao.findAll();
System.out.println(productList1.size()+ " producten");
System.out.println();
Product product1 = new Product(3, "Dal Voordeel 100%", "10 korting ", 40.00);
System.out.println("[Test] update(): " + pdao.update(product1));
System.out.println("[Test] findByOVChipkaart(): " + pdao.findByOVChipkaart(ovChipkaart));
System.out.println("[Test] delete(): " + pdao.delete(product));
List<Product> productList2 = pdao.findAll();
System.out.println(productList2.size()+ "producten");
closeConnection();
}
private static void testAdresDAO(AdresDAO adao,ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test AdresDAO -------------");
//
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende reizigers:");
for (Adres a : adressen) {
System.out.println(a);
}
// Eerst een nieuwe reiziger maken en opslaan
String gbdatum = "2000-03-14";
Reiziger sietske = new Reiziger(7, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
rdao.save(sietske);
// Een adres<SUF>
Adres a = new Adres(6, "1234TB", "25A", "HUStraat", "Groningen", 12);
System.out.println("[Test] AdresDAO.save() ");
System.out.println(adressen.size() + " adressen\n");
adao.save(a);
sietske.setAdres(a);
rdao.update(sietske);
adressen = adao.findAll();
System.out.println(adressen.size() + " adressen na de test\n");
//
Adres aa = adao.findByReiziger(sietske);
System.out.println(sietske);
System.out.println("[Test] AdresDAO.findByReiziger() geeft de adres:");
System.out.println(aa);
System.out.println();
System.out.println(adressen.size() + " adressen\n");
System.out.println("[Test] delete(): " + adao.delete(a));
List<Adres> aaa = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende reizigers:");
System.out.println(aaa.size());
System.out.println();
Adres b = new Adres(2, "16e64TB", "voorstraat", "49", "Utrecht", 12);
System.out.println("[Test] update(): " + adao.update(b));
System.out.println(b);
//
closeConnection();
//
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(6, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Voeg aanvullende tests van de ontbrekende CRUD-operaties in.
sietske.setVoorletters("T");
sietske.setTussenvoegsel("aa");
sietske.setAchternaam("Pieter");
System.out.println("Uitgevoerde SQL-query: " + sietske);
System.out.println("Voorletters: " + sietske.getVoorletters());
System.out.println("Tussenvoegsel: " + sietske.getTussenvoegsel());
System.out.println("Achternaam: " + sietske.getAchternaam());
System.out.println("Geboortedatum: " + sietske.getGeboortedatum());
System.out.println("Reiziger ID: " + sietske.getReiziger_id());
System.out.println("[Test] Na de Update met nieuwe naam " + sietske);
if (rdao.update(sietske)) {
System.out.println("[Test] ReizigerDAO.update() gelukt: " + sietske);
} else {
System.out.println("[Test] ReizigerDAO.update() gaat nog niet helemaal goed");
}
System.out.println();
System.out.println("[Test] ReizigerDAO.findById() geeft de volgende reiziger:");
Reiziger gevondenReiziger = rdao.findById(sietske.getReiziger_id());
System.out.println(gevondenReiziger);
System.out.println("[Test] ReizigerDAO.delete() probeert de bovenstaande reiziger te verwijderen...");
if (rdao.delete(gevondenReiziger)) {
System.out.println("[Test] ReizigerDAO.delete() geslaagd, reiziger verwijderd");
} else {
System.out.println("[Test] ReizigerDAO.delete() mislukt");
}
reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers na delete:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
}
private static void closeConnection() throws SQLException {
if (connection != null && !connection.isClosed()) {
connection.close();
}
}
private static void testConnection() throws SQLException {
String query = "SELECT * FROM reiziger;";
PreparedStatement statement = connection.prepareStatement(query);
ResultSet set = statement.executeQuery();
System.out.println("Alle reizigers:");
while (set != null && set.next()) {
System.out.println(" #" + set.getString("reiziger_id") + ": " + set.getString("voorletters") + ". " + set.getString("achternaam") + " (" + set.getString("geboortedatum") + ")");
}
closeConnection();
}
} |
205498_5 | package nl.groep4.kvc.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import nl.groep4.kvc.common.enumeration.Color;
import nl.groep4.kvc.common.enumeration.Direction;
import nl.groep4.kvc.common.enumeration.Point;
import nl.groep4.kvc.common.map.Coordinate;
import nl.groep4.kvc.common.map.Map;
import nl.groep4.kvc.common.map.Street;
import nl.groep4.kvc.common.map.Tile;
import nl.groep4.kvc.common.map.TileLand;
import nl.groep4.kvc.common.map.TileType;
import nl.groep4.kvc.server.model.ServerPlayer;
import nl.groep4.kvc.server.model.map.ServerMap;
public class MapTester {
private Map map;
@Before
public void build() {
map = new ServerMap();
map.createMap();
}
@Test
public void testRelativeTile() {
Tile tile = map.getTile(new Coordinate(0, 0));
Tile foundTile;
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, 2));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 2), foundTile.getPosition());
tile = map.getTile(new Coordinate(-2, -1));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(-2, -2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(-2, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-3, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(-1, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-3, -1), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, -4));
assertNotNull(foundTile);
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertNull(null);
// Kijken of daadwerkelijk een tegel naast de ander zit
// map.getRelativeTile(tile, direction)
}
@Test
public void testTilesCreated() {
int counterFOREST = 0;
int counterMESA = 0;
int counterPLAINS = 0;
int counterMOUNTAIN = 0;
int counterWHEAT = 0;
int counterDESERT = 0;
int counterWATER = 0;
List<Tile> tiles = map.getTiles();
for (int i = 0; i < tiles.size(); i++) {
Tile tile = tiles.get(i);
tile.getType();
switch (tile.getType()) {
case FOREST:
counterFOREST++;
break;
case MESA:
counterMESA++;
break;
case PLAINS:
counterPLAINS++;
break;
case MOUNTAIN:
counterMOUNTAIN++;
break;
case WHEAT:
counterWHEAT++;
break;
case DESERT:
counterDESERT++;
break;
case WATER:
case WATER_TRADE:
case WATER_OPEN_TRADE:
counterWATER++;
break;
default:
break;
}
}
assertEquals(6, counterFOREST);
assertEquals(5, counterMESA);
assertEquals(6, counterPLAINS);
assertEquals(5, counterMOUNTAIN);
assertEquals(6, counterWHEAT);
assertEquals(2, counterDESERT);
assertEquals(22, counterWATER);
Tile tile = map.getTile(0, -4);
assertEquals(TileType.WATER, tile.getType());
Tile tile2 = map.getTile(1, -3);
assertEquals(TileType.WATER, tile2.getType());
Tile tile3 = map.getTile(2, -3);
assertEquals(TileType.WATER, tile3.getType());
Tile tile4 = map.getTile(3, -2);
assertEquals(TileType.WATER, tile4.getType());
Tile tile5 = map.getTile(4, -2);
assertEquals(TileType.WATER, tile5.getType());
Tile tile6 = map.getTile(4, -1);
assertEquals(TileType.WATER, tile6.getType());
Tile tile7 = map.getTile(4, 0);
assertEquals(TileType.WATER, tile7.getType());
Tile tile8 = map.getTile(4, 1);
assertEquals(TileType.WATER, tile8.getType());
Tile tile9 = map.getTile(3, 2);
assertEquals(TileType.WATER, tile9.getType());
Tile tile10 = map.getTile(2, 2);
assertEquals(TileType.WATER, tile10.getType());
Tile tile11 = map.getTile(1, 3);
assertEquals(TileType.WATER, tile11.getType());
Tile tile12 = map.getTile(0, 3);
assertEquals(TileType.WATER, tile12.getType());
Tile tile13 = map.getTile(-1, 3);
assertEquals(TileType.WATER, tile13.getType());
Tile tile14 = map.getTile(-2, 2);
assertEquals(TileType.WATER, tile14.getType());
Tile tile15 = map.getTile(-3, 2);
assertEquals(TileType.WATER, tile15.getType());
Tile tile16 = map.getTile(-4, 1);
assertEquals(TileType.WATER, tile16.getType());
Tile tile17 = map.getTile(-4, 0);
assertEquals(TileType.WATER, tile17.getType());
Tile tile18 = map.getTile(-4, -1);
assertEquals(TileType.WATER, tile18.getType());
Tile tile19 = map.getTile(-4, -2);
assertEquals(TileType.WATER, tile19.getType());
Tile tile20 = map.getTile(-3, -2);
assertEquals(TileType.WATER, tile20.getType());
Tile tile21 = map.getTile(-2, -3);
assertEquals(TileType.WATER, tile21.getType());
Tile tile22 = map.getTile(-1, -3);
assertEquals(TileType.WATER, tile22.getType());
}
// map.getTiles() #
// kijken of de desert op goede plek staat MOET NOG GEFIXED WORDEN WACHT OP
// TIM!
// kijken of er 6forest,6...,6... 5mesa, 5mountain #
// kijken of buitenrand helemaal uit water bestaat #
@Test
public void correctStreets() {
// alle relatieve tiles van de evengetalcentrale tile
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileCenter = map.getTile(new Coordinate(0, -2));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
// Tile testTile = map.getTile(new Coordinate(0, -3));
// assertNotNull(testTile.getStreet(Direction.NORTH));
// de verschillende tiles met elkaar vergelijken
assertNotNull(landtileCenter.getStreet(Direction.NORTH));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_WEST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
// evengetal tiles hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(-1, -2));
landtileSouth = map.getTile(new Coordinate(-1, 0));
landtileCenter = map.getTile(new Coordinate(-1, -1));
landtileNE = map.getTile(new Coordinate(0, -2));
landtileNW = map.getTile(new Coordinate(-2, -2));
landtileSE = map.getTile(new Coordinate(0, -1));
landtileSW = map.getTile(new Coordinate(-2, -1));
// niet evengetal tiles worden hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(3, 0));
landtileSouth = map.getTile(new Coordinate(3, 2));
landtileCenter = map.getTile(new Coordinate(3, 1));
landtileNE = map.getTile(new Coordinate(4, 0));
landtileNW = map.getTile(new Coordinate(2, -0));
landtileSE = map.getTile(new Coordinate(4, 1));
landtileSW = map.getTile(new Coordinate(2, 1));
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
// voor elke street kijken of het 2 tiles heeft
for (Street street : map.getAllStreets()) {
int tilesConnected = 0;
for (Tile tile : street.getConnectedTiles()) {
if (tile != null) {
tilesConnected++;
}
}
assertEquals(2, tilesConnected);
}
}
// Kijken of elke landtegel 6 straten heeft #
// map.getAllStreets() #
// Kijk of Tile x met als buur tile y dezelfde street delen #
@Test
public void correctBuilding() {
// tile.isValidPlace(Point point) om te kijken of de plek wel geschikt
// 1) bij een evengetal tile
Tile evengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_WEST));
// 2) bij een onevengetal tile
Tile OnevengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_WEST));
Tile landtileEven1 = map.getTile(new Coordinate(0, -3));
Tile landtileEven2 = map.getTile(new Coordinate(0, -1));
Tile landtileEven3 = map.getTile(new Coordinate(0, -2));
Tile landtileOnEven1 = map.getTile(new Coordinate(1, -2));
Tile landtileOnEven2 = map.getTile(new Coordinate(-1, -2));
Tile landtileOnEven3 = map.getTile(new Coordinate(1, -1));
Tile landtileOnEven4 = map.getTile(new Coordinate(-1, -1));
// Kijken of elke landtegel 6 buildings heeft
// kijken of elke tile van de evengetallen landtiles een building heeft
// #
assertNotNull(landtileEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.WEST));
assertNotNull(landtileEven1.getBuilding(Point.EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.WEST));
assertNotNull(landtileEven2.getBuilding(Point.EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.WEST));
assertNotNull(landtileEven3.getBuilding(Point.EAST));
// kijken of elke tile van de onvengetallen landtiles een building heeft
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.EAST));
// map.getAllBuidlings()
// Kijk of Tile x met als buur tile y dezelfde building delen #
Tile landtileCentral = map.getTile(new Coordinate(0, -2));
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNorth.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileNE.getBuilding(Point.SOUTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileSE.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSouth.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSouth.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileSW.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileNW.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNorth.getBuilding(Point.SOUTH_WEST));
// Building met coordinaat en kijken of de 3 tiles eromheen kloppen
Tile buildingTile1 = map.getTile(new Coordinate(0, -2));
Tile buildingTile2 = map.getTile(new Coordinate(0, -1));
Tile buildingTile3 = map.getTile(new Coordinate(-1, -1));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile3.getBuilding(Point.EAST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile2.getBuilding(Point.NORTH_WEST), buildingTile1.getBuilding(Point.SOUTH_WEST));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile3.getBuilding(Point.EAST));
// Op een desert moet standaard een rover en op een normale tile niet #
// tile.hasRover() #
TileLand desertTile1 = (TileLand) map.getTile(new Coordinate(0, -2));
TileLand desertTile2 = (TileLand) map.getTile(new Coordinate(0, 1));
TileLand normalTile = (TileLand) map.getTile(new Coordinate(-1, -1));
TileLand normalTile2 = (TileLand) map.getTile(new Coordinate(-2, 0));
TileLand normalTile3 = (TileLand) map.getTile(new Coordinate(-3, -1));
TileLand normalTile4 = (TileLand) map.getTile(new Coordinate(3, -1));
TileLand normalTile5 = (TileLand) map.getTile(new Coordinate(2, 1));
assertTrue(desertTile1.hasRover());
assertTrue(desertTile2.hasRover());
assertTrue(!normalTile.hasRover());
assertTrue(!normalTile2.hasRover());
assertTrue(!normalTile3.hasRover());
assertTrue(!normalTile4.hasRover());
assertTrue(!normalTile5.hasRover());
}
@Test
public void onValidTest() {
ServerPlayer testUser = new ServerPlayer("TEST_PERSOON");
testUser.setColor(Color.BLUE);
Tile north = map.getTile(new Coordinate(0, -1));
Tile center = map.getTile(new Coordinate(0, 0));
Tile east = map.getTile(new Coordinate(1, 0));
north.getBuilding(Point.SOUTH_EAST).setOwner(testUser);
assertTrue(!center.isValidPlace(map, Point.NORTH_EAST));
assertTrue(!center.isValidPlace(map, Point.NORTH_WEST));
assertTrue(!center.isValidPlace(map, Point.EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(center.isValidPlace(map, Point.WEST));
center.getBuilding(Point.NORTH_EAST).setOwner(testUser);
assertTrue(east.isValidPlace(map, Point.NORTH_EAST));
assertTrue(east.isValidPlace(map, Point.EAST));
assertTrue(east.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(!east.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(!east.isValidPlace(map, Point.WEST));
assertTrue(!east.isValidPlace(map, Point.NORTH_WEST));
// Toevoegen derde tile
}
}
| MakerTim/KolonistenVanCatan | KvC-Server/src/test/java/nl/groep4/kvc/server/MapTester.java | 6,231 | // Tile testTile = map.getTile(new Coordinate(0, -3)); | line_comment | nl | package nl.groep4.kvc.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import nl.groep4.kvc.common.enumeration.Color;
import nl.groep4.kvc.common.enumeration.Direction;
import nl.groep4.kvc.common.enumeration.Point;
import nl.groep4.kvc.common.map.Coordinate;
import nl.groep4.kvc.common.map.Map;
import nl.groep4.kvc.common.map.Street;
import nl.groep4.kvc.common.map.Tile;
import nl.groep4.kvc.common.map.TileLand;
import nl.groep4.kvc.common.map.TileType;
import nl.groep4.kvc.server.model.ServerPlayer;
import nl.groep4.kvc.server.model.map.ServerMap;
public class MapTester {
private Map map;
@Before
public void build() {
map = new ServerMap();
map.createMap();
}
@Test
public void testRelativeTile() {
Tile tile = map.getTile(new Coordinate(0, 0));
Tile foundTile;
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, 2));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 2), foundTile.getPosition());
tile = map.getTile(new Coordinate(-2, -1));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(-2, -2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(-2, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-3, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(-1, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-3, -1), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, -4));
assertNotNull(foundTile);
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertNull(null);
// Kijken of daadwerkelijk een tegel naast de ander zit
// map.getRelativeTile(tile, direction)
}
@Test
public void testTilesCreated() {
int counterFOREST = 0;
int counterMESA = 0;
int counterPLAINS = 0;
int counterMOUNTAIN = 0;
int counterWHEAT = 0;
int counterDESERT = 0;
int counterWATER = 0;
List<Tile> tiles = map.getTiles();
for (int i = 0; i < tiles.size(); i++) {
Tile tile = tiles.get(i);
tile.getType();
switch (tile.getType()) {
case FOREST:
counterFOREST++;
break;
case MESA:
counterMESA++;
break;
case PLAINS:
counterPLAINS++;
break;
case MOUNTAIN:
counterMOUNTAIN++;
break;
case WHEAT:
counterWHEAT++;
break;
case DESERT:
counterDESERT++;
break;
case WATER:
case WATER_TRADE:
case WATER_OPEN_TRADE:
counterWATER++;
break;
default:
break;
}
}
assertEquals(6, counterFOREST);
assertEquals(5, counterMESA);
assertEquals(6, counterPLAINS);
assertEquals(5, counterMOUNTAIN);
assertEquals(6, counterWHEAT);
assertEquals(2, counterDESERT);
assertEquals(22, counterWATER);
Tile tile = map.getTile(0, -4);
assertEquals(TileType.WATER, tile.getType());
Tile tile2 = map.getTile(1, -3);
assertEquals(TileType.WATER, tile2.getType());
Tile tile3 = map.getTile(2, -3);
assertEquals(TileType.WATER, tile3.getType());
Tile tile4 = map.getTile(3, -2);
assertEquals(TileType.WATER, tile4.getType());
Tile tile5 = map.getTile(4, -2);
assertEquals(TileType.WATER, tile5.getType());
Tile tile6 = map.getTile(4, -1);
assertEquals(TileType.WATER, tile6.getType());
Tile tile7 = map.getTile(4, 0);
assertEquals(TileType.WATER, tile7.getType());
Tile tile8 = map.getTile(4, 1);
assertEquals(TileType.WATER, tile8.getType());
Tile tile9 = map.getTile(3, 2);
assertEquals(TileType.WATER, tile9.getType());
Tile tile10 = map.getTile(2, 2);
assertEquals(TileType.WATER, tile10.getType());
Tile tile11 = map.getTile(1, 3);
assertEquals(TileType.WATER, tile11.getType());
Tile tile12 = map.getTile(0, 3);
assertEquals(TileType.WATER, tile12.getType());
Tile tile13 = map.getTile(-1, 3);
assertEquals(TileType.WATER, tile13.getType());
Tile tile14 = map.getTile(-2, 2);
assertEquals(TileType.WATER, tile14.getType());
Tile tile15 = map.getTile(-3, 2);
assertEquals(TileType.WATER, tile15.getType());
Tile tile16 = map.getTile(-4, 1);
assertEquals(TileType.WATER, tile16.getType());
Tile tile17 = map.getTile(-4, 0);
assertEquals(TileType.WATER, tile17.getType());
Tile tile18 = map.getTile(-4, -1);
assertEquals(TileType.WATER, tile18.getType());
Tile tile19 = map.getTile(-4, -2);
assertEquals(TileType.WATER, tile19.getType());
Tile tile20 = map.getTile(-3, -2);
assertEquals(TileType.WATER, tile20.getType());
Tile tile21 = map.getTile(-2, -3);
assertEquals(TileType.WATER, tile21.getType());
Tile tile22 = map.getTile(-1, -3);
assertEquals(TileType.WATER, tile22.getType());
}
// map.getTiles() #
// kijken of de desert op goede plek staat MOET NOG GEFIXED WORDEN WACHT OP
// TIM!
// kijken of er 6forest,6...,6... 5mesa, 5mountain #
// kijken of buitenrand helemaal uit water bestaat #
@Test
public void correctStreets() {
// alle relatieve tiles van de evengetalcentrale tile
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileCenter = map.getTile(new Coordinate(0, -2));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
// Tile testTile<SUF>
// assertNotNull(testTile.getStreet(Direction.NORTH));
// de verschillende tiles met elkaar vergelijken
assertNotNull(landtileCenter.getStreet(Direction.NORTH));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_WEST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
// evengetal tiles hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(-1, -2));
landtileSouth = map.getTile(new Coordinate(-1, 0));
landtileCenter = map.getTile(new Coordinate(-1, -1));
landtileNE = map.getTile(new Coordinate(0, -2));
landtileNW = map.getTile(new Coordinate(-2, -2));
landtileSE = map.getTile(new Coordinate(0, -1));
landtileSW = map.getTile(new Coordinate(-2, -1));
// niet evengetal tiles worden hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(3, 0));
landtileSouth = map.getTile(new Coordinate(3, 2));
landtileCenter = map.getTile(new Coordinate(3, 1));
landtileNE = map.getTile(new Coordinate(4, 0));
landtileNW = map.getTile(new Coordinate(2, -0));
landtileSE = map.getTile(new Coordinate(4, 1));
landtileSW = map.getTile(new Coordinate(2, 1));
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
// voor elke street kijken of het 2 tiles heeft
for (Street street : map.getAllStreets()) {
int tilesConnected = 0;
for (Tile tile : street.getConnectedTiles()) {
if (tile != null) {
tilesConnected++;
}
}
assertEquals(2, tilesConnected);
}
}
// Kijken of elke landtegel 6 straten heeft #
// map.getAllStreets() #
// Kijk of Tile x met als buur tile y dezelfde street delen #
@Test
public void correctBuilding() {
// tile.isValidPlace(Point point) om te kijken of de plek wel geschikt
// 1) bij een evengetal tile
Tile evengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_WEST));
// 2) bij een onevengetal tile
Tile OnevengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_WEST));
Tile landtileEven1 = map.getTile(new Coordinate(0, -3));
Tile landtileEven2 = map.getTile(new Coordinate(0, -1));
Tile landtileEven3 = map.getTile(new Coordinate(0, -2));
Tile landtileOnEven1 = map.getTile(new Coordinate(1, -2));
Tile landtileOnEven2 = map.getTile(new Coordinate(-1, -2));
Tile landtileOnEven3 = map.getTile(new Coordinate(1, -1));
Tile landtileOnEven4 = map.getTile(new Coordinate(-1, -1));
// Kijken of elke landtegel 6 buildings heeft
// kijken of elke tile van de evengetallen landtiles een building heeft
// #
assertNotNull(landtileEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.WEST));
assertNotNull(landtileEven1.getBuilding(Point.EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.WEST));
assertNotNull(landtileEven2.getBuilding(Point.EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.WEST));
assertNotNull(landtileEven3.getBuilding(Point.EAST));
// kijken of elke tile van de onvengetallen landtiles een building heeft
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.EAST));
// map.getAllBuidlings()
// Kijk of Tile x met als buur tile y dezelfde building delen #
Tile landtileCentral = map.getTile(new Coordinate(0, -2));
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNorth.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileNE.getBuilding(Point.SOUTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileSE.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSouth.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSouth.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileSW.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileNW.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNorth.getBuilding(Point.SOUTH_WEST));
// Building met coordinaat en kijken of de 3 tiles eromheen kloppen
Tile buildingTile1 = map.getTile(new Coordinate(0, -2));
Tile buildingTile2 = map.getTile(new Coordinate(0, -1));
Tile buildingTile3 = map.getTile(new Coordinate(-1, -1));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile3.getBuilding(Point.EAST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile2.getBuilding(Point.NORTH_WEST), buildingTile1.getBuilding(Point.SOUTH_WEST));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile3.getBuilding(Point.EAST));
// Op een desert moet standaard een rover en op een normale tile niet #
// tile.hasRover() #
TileLand desertTile1 = (TileLand) map.getTile(new Coordinate(0, -2));
TileLand desertTile2 = (TileLand) map.getTile(new Coordinate(0, 1));
TileLand normalTile = (TileLand) map.getTile(new Coordinate(-1, -1));
TileLand normalTile2 = (TileLand) map.getTile(new Coordinate(-2, 0));
TileLand normalTile3 = (TileLand) map.getTile(new Coordinate(-3, -1));
TileLand normalTile4 = (TileLand) map.getTile(new Coordinate(3, -1));
TileLand normalTile5 = (TileLand) map.getTile(new Coordinate(2, 1));
assertTrue(desertTile1.hasRover());
assertTrue(desertTile2.hasRover());
assertTrue(!normalTile.hasRover());
assertTrue(!normalTile2.hasRover());
assertTrue(!normalTile3.hasRover());
assertTrue(!normalTile4.hasRover());
assertTrue(!normalTile5.hasRover());
}
@Test
public void onValidTest() {
ServerPlayer testUser = new ServerPlayer("TEST_PERSOON");
testUser.setColor(Color.BLUE);
Tile north = map.getTile(new Coordinate(0, -1));
Tile center = map.getTile(new Coordinate(0, 0));
Tile east = map.getTile(new Coordinate(1, 0));
north.getBuilding(Point.SOUTH_EAST).setOwner(testUser);
assertTrue(!center.isValidPlace(map, Point.NORTH_EAST));
assertTrue(!center.isValidPlace(map, Point.NORTH_WEST));
assertTrue(!center.isValidPlace(map, Point.EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(center.isValidPlace(map, Point.WEST));
center.getBuilding(Point.NORTH_EAST).setOwner(testUser);
assertTrue(east.isValidPlace(map, Point.NORTH_EAST));
assertTrue(east.isValidPlace(map, Point.EAST));
assertTrue(east.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(!east.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(!east.isValidPlace(map, Point.WEST));
assertTrue(!east.isValidPlace(map, Point.NORTH_WEST));
// Toevoegen derde tile
}
}
|
55863_2 | /*
constantes (public STATIC FINAL)
default methods (public DEFAULT) let op hier wordt het keyword default gebruikt!!! GEEN static, final of abstract
static methods (public STATIC) let op een static interface methode wordt NIET overgeerfd!!! je kan hem alleen op de interface aanroepen niet op de instance van de concrete class
methods (public abstract)
een class kan meerdere interfaces implementeren (implements)
een interface kan overerven van meerdere interfaces (extends)
een interface en zijn methodes kunnen NIET final zijn
een interface zelf heeft default of public
constantes moeten geinitialiseerd zijn
default methods:
override
redeclare
multiple inheritance issue -> override default methode in the first concrete / abstract class
*/
interface Leesplankje {
String eersteWoordje = "aap"; // public static final
//String tweedeWoordje; // constante moet geinitialiseerd zijn ivm final!
default void leesEersteZinnetjeVoor() { System.out.println("aap noot mies"); }
default void leesTweedeZinnetjeVoor() { System.out.println("wim zus jet"); }
static void leesDerdeZinnetjeVoor() { System.out.println("teun vuur gijs"); }
}
interface MielsLeesplankje extends Leesplankje {
default void leesEersteZinnetjeVoor() { System.out.println("aaa bbb ccc"); } // OVERRIDE default method
void leesTweedeZinnetjeVoor(); // REDECLARE default method, public abstract
static void leesDerdeZinnetjeVoor() { System.out.println("ggg hhh iii"); }
}
class Interfaces implements MielsLeesplankje {
//void leesTweedeZinnetjeVoor() { System.out.println("ddd eee fff"); } // LET OP attempting to assign weaker access privileges; was public
public void leesTweedeZinnetjeVoor() { System.out.println("ddd eee fff"); }
public static void main(String args[]) {
System.out.println(Leesplankje.eersteWoordje); // aap
Interfaces i = new Interfaces();
System.out.println(i.eersteWoordje); // aap
i.leesEersteZinnetjeVoor(); // aaa bbb ccc
i.leesTweedeZinnetjeVoor(); // ddd eee fff
// let op static interface methodes worden NIET overgeerfd, methode kan alleen op de Interface worden aangeroepen
//i.leesDerdeZinnetjeVoor(); // compiler error cannot find symbol
Leesplankje.leesDerdeZinnetjeVoor(); // teun vuur gijs
MielsLeesplankje.leesDerdeZinnetjeVoor(); // ggg hhh iii
}
} | mpfdj/oca8-cli | 5. Class Design/Interfaces.java | 644 | //String tweedeWoordje; // constante moet geinitialiseerd zijn ivm final! | line_comment | nl | /*
constantes (public STATIC FINAL)
default methods (public DEFAULT) let op hier wordt het keyword default gebruikt!!! GEEN static, final of abstract
static methods (public STATIC) let op een static interface methode wordt NIET overgeerfd!!! je kan hem alleen op de interface aanroepen niet op de instance van de concrete class
methods (public abstract)
een class kan meerdere interfaces implementeren (implements)
een interface kan overerven van meerdere interfaces (extends)
een interface en zijn methodes kunnen NIET final zijn
een interface zelf heeft default of public
constantes moeten geinitialiseerd zijn
default methods:
override
redeclare
multiple inheritance issue -> override default methode in the first concrete / abstract class
*/
interface Leesplankje {
String eersteWoordje = "aap"; // public static final
//String tweedeWoordje;<SUF>
default void leesEersteZinnetjeVoor() { System.out.println("aap noot mies"); }
default void leesTweedeZinnetjeVoor() { System.out.println("wim zus jet"); }
static void leesDerdeZinnetjeVoor() { System.out.println("teun vuur gijs"); }
}
interface MielsLeesplankje extends Leesplankje {
default void leesEersteZinnetjeVoor() { System.out.println("aaa bbb ccc"); } // OVERRIDE default method
void leesTweedeZinnetjeVoor(); // REDECLARE default method, public abstract
static void leesDerdeZinnetjeVoor() { System.out.println("ggg hhh iii"); }
}
class Interfaces implements MielsLeesplankje {
//void leesTweedeZinnetjeVoor() { System.out.println("ddd eee fff"); } // LET OP attempting to assign weaker access privileges; was public
public void leesTweedeZinnetjeVoor() { System.out.println("ddd eee fff"); }
public static void main(String args[]) {
System.out.println(Leesplankje.eersteWoordje); // aap
Interfaces i = new Interfaces();
System.out.println(i.eersteWoordje); // aap
i.leesEersteZinnetjeVoor(); // aaa bbb ccc
i.leesTweedeZinnetjeVoor(); // ddd eee fff
// let op static interface methodes worden NIET overgeerfd, methode kan alleen op de Interface worden aangeroepen
//i.leesDerdeZinnetjeVoor(); // compiler error cannot find symbol
Leesplankje.leesDerdeZinnetjeVoor(); // teun vuur gijs
MielsLeesplankje.leesDerdeZinnetjeVoor(); // ggg hhh iii
}
} |
99635_10 | package com.example.AppArt.thaliapp.Calendar.Backend;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import com.example.AppArt.thaliapp.R;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Withholds all knowledge of a ThaliaEvent
*
* @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804)
*/
public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable {
private final GregorianCalendar startDate = new GregorianCalendar();
private final GregorianCalendar endDate = new GregorianCalendar();
private final String location;
private final String description;
private final String summary;
private final EventCategory category;
private final int catIcon;
/**
* Initialises the Event object given string input.
*
* @param startDate The starting time of the event in millis
* @param endDate The ending time of the event in millis
* @param location The location of the event
* @param description A large description of the event
* @param summary The event in 3 words or fewer
*/
public ThaliaEvent(Long startDate, Long endDate,
String location, String description, String summary) {
this.startDate.setTimeInMillis(startDate);
this.endDate.setTimeInMillis(endDate);
this.location = location;
this.description = description;
this.summary = summary;
this.category = categoryFinder();
this.catIcon = catIconFinder(category);
}
/*****************************************************************
Methods to help initialise
*****************************************************************/
/**
* Uses the summary and the description of an ThaliaEvent to figure out what
* category it is.
*
* When multiple keywords are found it will use the following order:
* LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT
* (e.g. kinderFEESTjesBORREL -> PARTY)
*
* @return an EventCategory
*/
private EventCategory categoryFinder() {
String eventText = this.summary.concat(this.description);
if (eventText.matches("(?i:.*lezing.*)")) {
return EventCategory.LECTURE;
} else if (eventText.matches("(?i:.*feest.*)") ||
eventText.matches("(?i:.*party.*)")) {
return EventCategory.PARTY;
} else if (eventText.matches("(?i:.*alv.*)")){
return EventCategory.ALV;
} else if (eventText.matches("(?i:.*workshop.*)")) {
return EventCategory.WORKSHOP;
} else if (eventText.matches("(?i:.*borrel.*)")) {
return EventCategory.BORREL;
} else return EventCategory.DEFAULT;
}
/**
* Returns the right drawable according to the category
*
* @param cat the category of this event
* @return A .png file that represents the category of this event
*/
private int catIconFinder(EventCategory cat) {
int catIcon;
switch (cat) {
case ALV:
catIcon = R.drawable.alvicoon;
break;
case BORREL:
catIcon = R.drawable.borrelicoon;
break;
case LECTURE:
catIcon = R.drawable.lezingicoon;
break;
case PARTY:
catIcon = R.drawable.feesticoon;
break;
case WORKSHOP:
catIcon = R.drawable.workshopicoon;
break;
default:
catIcon = R.drawable.overigicoon;
}
return catIcon;
}
/*****************************************************************
Getters for all attributes
*****************************************************************/
public GregorianCalendar getStartDate() {
return startDate;
}
public GregorianCalendar getEndDate() {
return endDate;
}
public String getLocation() {
return location;
}
/**
* A possibly broad description of the ThaliaEvent
* Can contain HTML
* @return possibly very large string
*/
public String getDescription() {
return description;
}
/**
* The ThaliaEvent in less than 5 words
* Can contain HTML
* @return small String
*/
public String getSummary() {
return summary;
}
public EventCategory getCategory() {
return category;
}
public int getCatIcon() {
return catIcon;
}
/**
* Small composition of ThaliaEvent information
* @return summary + "\n" + duration() + "\n" + location
*/
public String makeSynopsis() {
return summary + "\n" + duration() + "\n" + location;
}
/**
* A readable abbreviation of the day
* e.g. di 18 aug
*
* @return dd - dd - mmm
*/
public String getDateString() {
StringBuilder date;
date = new StringBuilder("");
date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()));
date.append(" ");
date.append(this.startDate.get(Calendar.DAY_OF_MONTH));
date.append(" ");
date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()));
return date.toString();
}
/*****************************************************************
Default Methods
*****************************************************************/
/**
* A neat stringformat of the beginning and ending times
*
* @return hh:mm-hh:mm
*/
public String duration() {
StringBuilder sb = new StringBuilder();
sb.append(startDate.get(Calendar.HOUR_OF_DAY));
sb.append(":");
if (startDate.get(Calendar.MINUTE) == 0) {
sb.append("00");
} else {
sb.append(startDate.get(Calendar.MINUTE));
}
sb.append(" - ");
sb.append(endDate.get(Calendar.HOUR_OF_DAY));
sb.append(":");
if (endDate.get(Calendar.MINUTE) == 0) {
sb.append("00");
} else {
sb.append(endDate.get(Calendar.MINUTE));
}
System.out.println("EoF durationfunction: "+sb.toString());
return sb.toString();
}
/**
* Printmethod, useful when you're debugging
*
* @return a string of the event
*/
@Override
public String toString() {
return ("\nstart = " + startDate + ", end = " + endDate
+ "\nlocation = " + location + "\ndescription = " + description
+ "\nsummary = " + summary);
}
/**
* @param another the ThaliaEvent with which you want to compare it
* @return The difference in time between the two
*/
@Override
public int compareTo(@NonNull ThaliaEvent another) {
return startDate.compareTo(another.startDate);
}
/*****************************************************************
Making it a Parcelable, so it can be passed through with an intent
*****************************************************************/
@Override
public int describeContents() {
return 0;
}
/**
* Pretty much all information about this ThaliaEvent object is being
* compressed into a Parcel
*
* @param dest Destination
* @param flags Flags
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(startDate.getTimeInMillis());
dest.writeLong(endDate.getTimeInMillis());
dest.writeString(location);
dest.writeString(description);
dest.writeString(summary);
}
/**
* Reconstructs the ThaliaEvent through a parcel.
*/
public static final Parcelable.Creator<ThaliaEvent> CREATOR
= new Parcelable.Creator<ThaliaEvent>() {
// Parcels work FIFO
public ThaliaEvent createFromParcel(Parcel parcel) {
Long startDate = parcel.readLong();
Long endDate = parcel.readLong();
String location = parcel.readString();
String description = parcel.readString();
String summary = parcel.readString();
return new ThaliaEvent(startDate, endDate, location, description, summary);
}
public ThaliaEvent[] newArray(int size) {
return new ThaliaEvent[size];
}
};
}
| yorickvP/ThaliAppMap | app/src/main/java/com/example/AppArt/thaliapp/Calendar/Backend/ThaliaEvent.java | 2,096 | /*****************************************************************
Default Methods
*****************************************************************/ | block_comment | nl | package com.example.AppArt.thaliapp.Calendar.Backend;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import com.example.AppArt.thaliapp.R;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Withholds all knowledge of a ThaliaEvent
*
* @author Frank Gerlings (s4384873), Lisa Kalse (s4338340), Serena Rietbergen (s4182804)
*/
public class ThaliaEvent implements Comparable<ThaliaEvent>, Parcelable {
private final GregorianCalendar startDate = new GregorianCalendar();
private final GregorianCalendar endDate = new GregorianCalendar();
private final String location;
private final String description;
private final String summary;
private final EventCategory category;
private final int catIcon;
/**
* Initialises the Event object given string input.
*
* @param startDate The starting time of the event in millis
* @param endDate The ending time of the event in millis
* @param location The location of the event
* @param description A large description of the event
* @param summary The event in 3 words or fewer
*/
public ThaliaEvent(Long startDate, Long endDate,
String location, String description, String summary) {
this.startDate.setTimeInMillis(startDate);
this.endDate.setTimeInMillis(endDate);
this.location = location;
this.description = description;
this.summary = summary;
this.category = categoryFinder();
this.catIcon = catIconFinder(category);
}
/*****************************************************************
Methods to help initialise
*****************************************************************/
/**
* Uses the summary and the description of an ThaliaEvent to figure out what
* category it is.
*
* When multiple keywords are found it will use the following order:
* LECTURE > PARTY > ALV > WORKSHOP > BORREL > DEFAULT
* (e.g. kinderFEESTjesBORREL -> PARTY)
*
* @return an EventCategory
*/
private EventCategory categoryFinder() {
String eventText = this.summary.concat(this.description);
if (eventText.matches("(?i:.*lezing.*)")) {
return EventCategory.LECTURE;
} else if (eventText.matches("(?i:.*feest.*)") ||
eventText.matches("(?i:.*party.*)")) {
return EventCategory.PARTY;
} else if (eventText.matches("(?i:.*alv.*)")){
return EventCategory.ALV;
} else if (eventText.matches("(?i:.*workshop.*)")) {
return EventCategory.WORKSHOP;
} else if (eventText.matches("(?i:.*borrel.*)")) {
return EventCategory.BORREL;
} else return EventCategory.DEFAULT;
}
/**
* Returns the right drawable according to the category
*
* @param cat the category of this event
* @return A .png file that represents the category of this event
*/
private int catIconFinder(EventCategory cat) {
int catIcon;
switch (cat) {
case ALV:
catIcon = R.drawable.alvicoon;
break;
case BORREL:
catIcon = R.drawable.borrelicoon;
break;
case LECTURE:
catIcon = R.drawable.lezingicoon;
break;
case PARTY:
catIcon = R.drawable.feesticoon;
break;
case WORKSHOP:
catIcon = R.drawable.workshopicoon;
break;
default:
catIcon = R.drawable.overigicoon;
}
return catIcon;
}
/*****************************************************************
Getters for all attributes
*****************************************************************/
public GregorianCalendar getStartDate() {
return startDate;
}
public GregorianCalendar getEndDate() {
return endDate;
}
public String getLocation() {
return location;
}
/**
* A possibly broad description of the ThaliaEvent
* Can contain HTML
* @return possibly very large string
*/
public String getDescription() {
return description;
}
/**
* The ThaliaEvent in less than 5 words
* Can contain HTML
* @return small String
*/
public String getSummary() {
return summary;
}
public EventCategory getCategory() {
return category;
}
public int getCatIcon() {
return catIcon;
}
/**
* Small composition of ThaliaEvent information
* @return summary + "\n" + duration() + "\n" + location
*/
public String makeSynopsis() {
return summary + "\n" + duration() + "\n" + location;
}
/**
* A readable abbreviation of the day
* e.g. di 18 aug
*
* @return dd - dd - mmm
*/
public String getDateString() {
StringBuilder date;
date = new StringBuilder("");
date.append(this.startDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()));
date.append(" ");
date.append(this.startDate.get(Calendar.DAY_OF_MONTH));
date.append(" ");
date.append(this.startDate.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()));
return date.toString();
}
/*****************************************************************
Default Methods
<SUF>*/
/**
* A neat stringformat of the beginning and ending times
*
* @return hh:mm-hh:mm
*/
public String duration() {
StringBuilder sb = new StringBuilder();
sb.append(startDate.get(Calendar.HOUR_OF_DAY));
sb.append(":");
if (startDate.get(Calendar.MINUTE) == 0) {
sb.append("00");
} else {
sb.append(startDate.get(Calendar.MINUTE));
}
sb.append(" - ");
sb.append(endDate.get(Calendar.HOUR_OF_DAY));
sb.append(":");
if (endDate.get(Calendar.MINUTE) == 0) {
sb.append("00");
} else {
sb.append(endDate.get(Calendar.MINUTE));
}
System.out.println("EoF durationfunction: "+sb.toString());
return sb.toString();
}
/**
* Printmethod, useful when you're debugging
*
* @return a string of the event
*/
@Override
public String toString() {
return ("\nstart = " + startDate + ", end = " + endDate
+ "\nlocation = " + location + "\ndescription = " + description
+ "\nsummary = " + summary);
}
/**
* @param another the ThaliaEvent with which you want to compare it
* @return The difference in time between the two
*/
@Override
public int compareTo(@NonNull ThaliaEvent another) {
return startDate.compareTo(another.startDate);
}
/*****************************************************************
Making it a Parcelable, so it can be passed through with an intent
*****************************************************************/
@Override
public int describeContents() {
return 0;
}
/**
* Pretty much all information about this ThaliaEvent object is being
* compressed into a Parcel
*
* @param dest Destination
* @param flags Flags
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(startDate.getTimeInMillis());
dest.writeLong(endDate.getTimeInMillis());
dest.writeString(location);
dest.writeString(description);
dest.writeString(summary);
}
/**
* Reconstructs the ThaliaEvent through a parcel.
*/
public static final Parcelable.Creator<ThaliaEvent> CREATOR
= new Parcelable.Creator<ThaliaEvent>() {
// Parcels work FIFO
public ThaliaEvent createFromParcel(Parcel parcel) {
Long startDate = parcel.readLong();
Long endDate = parcel.readLong();
String location = parcel.readString();
String description = parcel.readString();
String summary = parcel.readString();
return new ThaliaEvent(startDate, endDate, location, description, summary);
}
public ThaliaEvent[] newArray(int size) {
return new ThaliaEvent[size];
}
};
}
|
101926_0 | package Gui;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import static javafx.scene.control.TabPane.TabClosingPolicy.UNAVAILABLE;
public class GUI extends Application {
private static Planner planner;
public static void main(String[] args) {
planner = new Planner();
planner.init();
launch(GUI.class);
}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Kermis planner");
TabPane tabpane = new TabPane();
// Tab voor Planner
Tab plannerTab = new Tab("Dev");
VBox plannerTabBox = new VBox(10);
Label plannerLabel = new Label("planner page");
Label tempSeedDataButtonLabel = new Label("TEMPORARY button for test data:");
Button tempSeedDataButton = new Button("create test data");
tempSeedDataButton.setOnAction(e -> {
Planner.seedTestData();
});
plannerTabBox.getChildren().addAll(plannerLabel, tempSeedDataButtonLabel, tempSeedDataButton);
plannerTab.setContent(plannerTabBox);
// Tab voor Schedule
Tab scheduleTab = new Tab("Schedule");
scheduleTab.setContent(ScheduleView.createScheduleView(Planner.getSCHEDULE()));
// Tab voor Schedule Items
Tab createScheduleItem = new Tab("Schedule Items");
HBox scheduleItemBox = new HBox();
scheduleItemBox.getChildren().addAll(ScheduleItemCreate.getComponent(), ScheduleItemUpdate.getComponent(), ScheduleItemsOverview.getComponent());
createScheduleItem.setContent(scheduleItemBox);
// Tab voor Attracties
Tab attractionRead = new Tab("Attractions");
HBox AttractionBox = new HBox();
AttractionBox.getChildren().addAll(AttractionCreate.getComponent(), AttractionUpdate.getComponent(), AttractionsOverview.getComponent());
attractionRead.setContent(AttractionBox);
// Tab voor de Simulator
Tab simulator = new Tab("Simulator");
if (planner.getSCHEDULE().getScheduleItems().size() > 0) {
simulator.setContent(Simulator.getComponent());
} else {
simulator.setContent(new Label("No scheduleItems found for the simulation..."));
}
// Voeg alle tabs toe aan de TabPane
tabpane.getTabs().addAll(plannerTab, scheduleTab, createScheduleItem, attractionRead, simulator);
// Sluit het sluiten van tabs uit
tabpane.setTabClosingPolicy(UNAVAILABLE);
Scene scene = new Scene(tabpane, 1200, 600);
stage.setScene(scene);
stage.show();
}
}
| Tiemenbr/KermisPlanner | src/Gui/GUI.java | 676 | // Tab voor Planner | line_comment | nl | package Gui;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import static javafx.scene.control.TabPane.TabClosingPolicy.UNAVAILABLE;
public class GUI extends Application {
private static Planner planner;
public static void main(String[] args) {
planner = new Planner();
planner.init();
launch(GUI.class);
}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Kermis planner");
TabPane tabpane = new TabPane();
// Tab voor<SUF>
Tab plannerTab = new Tab("Dev");
VBox plannerTabBox = new VBox(10);
Label plannerLabel = new Label("planner page");
Label tempSeedDataButtonLabel = new Label("TEMPORARY button for test data:");
Button tempSeedDataButton = new Button("create test data");
tempSeedDataButton.setOnAction(e -> {
Planner.seedTestData();
});
plannerTabBox.getChildren().addAll(plannerLabel, tempSeedDataButtonLabel, tempSeedDataButton);
plannerTab.setContent(plannerTabBox);
// Tab voor Schedule
Tab scheduleTab = new Tab("Schedule");
scheduleTab.setContent(ScheduleView.createScheduleView(Planner.getSCHEDULE()));
// Tab voor Schedule Items
Tab createScheduleItem = new Tab("Schedule Items");
HBox scheduleItemBox = new HBox();
scheduleItemBox.getChildren().addAll(ScheduleItemCreate.getComponent(), ScheduleItemUpdate.getComponent(), ScheduleItemsOverview.getComponent());
createScheduleItem.setContent(scheduleItemBox);
// Tab voor Attracties
Tab attractionRead = new Tab("Attractions");
HBox AttractionBox = new HBox();
AttractionBox.getChildren().addAll(AttractionCreate.getComponent(), AttractionUpdate.getComponent(), AttractionsOverview.getComponent());
attractionRead.setContent(AttractionBox);
// Tab voor de Simulator
Tab simulator = new Tab("Simulator");
if (planner.getSCHEDULE().getScheduleItems().size() > 0) {
simulator.setContent(Simulator.getComponent());
} else {
simulator.setContent(new Label("No scheduleItems found for the simulation..."));
}
// Voeg alle tabs toe aan de TabPane
tabpane.getTabs().addAll(plannerTab, scheduleTab, createScheduleItem, attractionRead, simulator);
// Sluit het sluiten van tabs uit
tabpane.setTabClosingPolicy(UNAVAILABLE);
Scene scene = new Scene(tabpane, 1200, 600);
stage.setScene(scene);
stage.show();
}
}
|
25664_4 | package trucks;
import java.util.Random;
import docks.Dock;
/**
* @author Nico van Ommen - 1030808
* @since 03/28/2020
*/
abstract class BaseTruck extends Thread
{
private String _name;
private int _speed;
private Dock _dock;
protected boolean _thread_finish = false;
private Random _random;
/**
* Constructor
*
* @param name
* @param speed
* @param type
*/
BaseTruck(String name, int speed, Dock dock)
{
this.setTruckName(name);
this.setTruckSpeed(speed);
this.setDock(dock);
this._random = new Random();
}
/**
* Methode voor het zetten van de naam van de truck
*
* @param name
*/
public void setTruckName(String name)
{
this._name = name;
}
/**
* Methode voor het ophalen van de naam van de truck
*
* @return String
*/
public String getTruckName()
{
return this._name;
}
/**
* Methode voor het zetten van de snelheid van de truck
*
* @param speed
*/
public void setTruckSpeed(int speed)
{
this._speed = speed;
}
/**
* Methode voor het ophalen van de truck snelheid
*
* @return int
*/
public int getTruckSpeed()
{
return this._speed;
}
/**
* Methode voor het zetten van een nieuwe dock
*
* @param dock
*/
public void setDock(Dock dock)
{
this._dock = dock;
}
/**
* Methode voor het ophalen van een dock
*
* @return Dock
*/
public Dock getDock()
{
return this._dock;
}
/**
* Methode voor het genereren van een tijd met behulp van de normaal verdeleing
*
* @return
*/
protected int getTiming()
{
int t = (int)Math.round((double)this._random.nextGaussian()*2000+4000);
if (t <= 1000)
{
return 1000;
}
else if (t >= 6000)
{
return 6000;
}
return t;
}
}
| nicoripkip/TINPRO03-3 | src/trucks/BaseTruck.java | 645 | /**
* Methode voor het zetten van de snelheid van de truck
*
* @param speed
*/ | block_comment | nl | package trucks;
import java.util.Random;
import docks.Dock;
/**
* @author Nico van Ommen - 1030808
* @since 03/28/2020
*/
abstract class BaseTruck extends Thread
{
private String _name;
private int _speed;
private Dock _dock;
protected boolean _thread_finish = false;
private Random _random;
/**
* Constructor
*
* @param name
* @param speed
* @param type
*/
BaseTruck(String name, int speed, Dock dock)
{
this.setTruckName(name);
this.setTruckSpeed(speed);
this.setDock(dock);
this._random = new Random();
}
/**
* Methode voor het zetten van de naam van de truck
*
* @param name
*/
public void setTruckName(String name)
{
this._name = name;
}
/**
* Methode voor het ophalen van de naam van de truck
*
* @return String
*/
public String getTruckName()
{
return this._name;
}
/**
* Methode voor het<SUF>*/
public void setTruckSpeed(int speed)
{
this._speed = speed;
}
/**
* Methode voor het ophalen van de truck snelheid
*
* @return int
*/
public int getTruckSpeed()
{
return this._speed;
}
/**
* Methode voor het zetten van een nieuwe dock
*
* @param dock
*/
public void setDock(Dock dock)
{
this._dock = dock;
}
/**
* Methode voor het ophalen van een dock
*
* @return Dock
*/
public Dock getDock()
{
return this._dock;
}
/**
* Methode voor het genereren van een tijd met behulp van de normaal verdeleing
*
* @return
*/
protected int getTiming()
{
int t = (int)Math.round((double)this._random.nextGaussian()*2000+4000);
if (t <= 1000)
{
return 1000;
}
else if (t >= 6000)
{
return 6000;
}
return t;
}
}
|
39976_10 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Level3 extends MyWorld
{
CollisionEngine ce;
Hero hr = new Hero();
public void act(){
super.act();
try{
ce.update();
}
catch(Exception e){
}
}
public Level3()
{
Hero.jumpHeight = -19;
MyWorld.level = 3;
this.setBackground("bglvl3.png");
hr.inLevel = false;
hud();
int[][] map = {
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1},
{111,111,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,217,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,219,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,6,6,6,6,-1,-1,-1,-1,-1,-1,219,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,128,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,81,-1},
{-1,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,111,111,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,80,-1},
{-1,80,-1,-1,243,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,128,128,128,22,-1,-1,-1,-1,22,128,128,128,128,180,180,180,111,111,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,6,6,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,128,128,128,128},
{34,34,34,34,34,34,34,180,180,180,34,34,34,128,128,128,180,180,111,111,111,111,-1,-1,-1,-1,-1,-1,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,34,34,34,34,34,34,178,178,178,34,34,34,34,111,111,178,178,111,111,111,111,272,272,272,272,272,272,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,34,34,34,34,34,34,178,178,178,34,34,34,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,34,34,34,34,34,178,178,178,34,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,34,34,34,34,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,34,34,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
};
// 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);
Enemy enemy1 = new Enemy();
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 97, 1214);
addObject(enemy1, 769, 1214);
addObject(new Jump(), 1233, 1154);
// 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);
ce.addCollidingMover(enemy1);
hr.inLevel = true;
hr.inLevel3 = true;
}
}
| ROCMondriaanTIN/project-greenfoot-game-MoorColin | Level3.java | 7,997 | // Toevoegen van de mover instantie of een extentie hiervan | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Level3 extends MyWorld
{
CollisionEngine ce;
Hero hr = new Hero();
public void act(){
super.act();
try{
ce.update();
}
catch(Exception e){
}
}
public Level3()
{
Hero.jumpHeight = -19;
MyWorld.level = 3;
this.setBackground("bglvl3.png");
hr.inLevel = false;
hud();
int[][] map = {
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,111,34,34,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{111,111,111,34,34,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1},
{111,111,34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,217,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{34,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,219,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,6,6,6,6,-1,-1,-1,-1,-1,-1,219,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,128,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,81,-1},
{-1,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,111,111,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,80,-1},
{-1,80,-1,-1,243,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,128,128,128,128,22,-1,-1,-1,-1,22,128,128,128,128,180,180,180,111,111,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,6,6,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,128,128,128,128},
{34,34,34,34,34,34,34,180,180,180,34,34,34,128,128,128,180,180,111,111,111,111,-1,-1,-1,-1,-1,-1,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,34,34,34,34,34,34,178,178,178,34,34,34,34,111,111,178,178,111,111,111,111,272,272,272,272,272,272,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,34,34,34,34,34,34,178,178,178,34,34,34,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,34,34,34,34,34,178,178,178,34,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,34,34,34,34,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,34,34,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
{111,111,111,111,111,111,111,178,178,178,111,111,111,111,111,111,178,178,111,111,111,111,111,111,111,111,111,111,111,111,111,111,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,178,111,111,111,111},
};
// 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);
Enemy enemy1 = new Enemy();
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 97, 1214);
addObject(enemy1, 769, 1214);
addObject(new Jump(), 1233, 1154);
// 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<SUF>
ce.addCollidingMover(hero);
ce.addCollidingMover(enemy1);
hr.inLevel = true;
hr.inLevel3 = true;
}
}
|
65821_8 | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Geld;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.model.Valuta;
import aimene.doex.bestelling.repository.ProductRepository;
import aimene.doex.bestelling.repository.BestellingRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@RestController
@RequestMapping("/producten")
public class ProductController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public ProductController(ProductRepository productRepository, BestellingRepository bestellingRepository) {
this.productRepository = productRepository;
this.bestellingRepository = bestellingRepository;
}
@GetMapping
public Iterable<Product> findAll() {
return productRepository.findAll();
}
@GetMapping("{id}")
public Product findById(@PathVariable("id") Product product) {
return product;
}
@PatchMapping("{id}/prijs")
public void veranderPrijs(@PathVariable("id") Product product,
@RequestBody Map<String, Object> requestBody) {
/* ******************************************************************** */
// Geef in het sequentiediagram wel expliciet aan dat je het product
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
// (zie voorbeeld in het sequentiediagram)
/* ******************************************************************** */
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
// Je kunt ervan uitgaan dat de nieuwePrijs wordt meegegeven door de
// actor bij aanroep van de methode veranderPrijs van deze controller
Geld nieuwePrijs = new Geld((int) requestBody.get("nieuwe_prijs"), Valuta.EUR);
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze regel in het sequentiediagram aan met een rnote
// (zie voorbeeld in het sequentiediagram)
product.veranderPrijs(nieuwePrijs);
/* ******************************************************************** */
productRepository.save(product);
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
AggregateReference<Product, Integer> productRef =
AggregateReference.to(product.getId());
/* ******************************************************************** */
/* ******************************************************************** */
// Vind alle bestellingen die het product bevatten waarvan de prijs is veranderd
// Dit kan beter met een sql-query, maar dat doen we volgende week
// In het Sequentiediagram kun je ervan uitgaan dat er een methode bestaat
// bestellingRepository.findAllMetProduct(productId) die dit voor je doet;
Iterable<Bestelling> bestellingen = bestellingRepository.findAll();
List<Bestelling> bestellingenMetProduct = StreamSupport.stream(bestellingen.spliterator(), false)
.filter(bestelling -> bestelling.bevatBestellingProduct(productRef))
.collect(Collectors.toList());
/* ******************************************************************** */
/* ******************************************************************** */
// Geef dit in het sequentiediagram aan met een rnote
// Verander de stukprijs van het product in de eerder gevonden bestellingen
bestellingenMetProduct.forEach(bestelling -> bestelling.veranderStukPrijs(productRef, nieuwePrijs));
/* ******************************************************************** */
bestellingRepository.saveAll(bestellingenMetProduct);
}
}
| AIM-ENE/doex-opdracht-3 | oefeningen/les-3/voorbereiding/onderdeel2/bestelling/src/main/java/aimene/doex/bestelling/controller/ProductController.java | 932 | // Geef deze regel in het sequentiediagram aan met een rnote | line_comment | nl | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Geld;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.model.Valuta;
import aimene.doex.bestelling.repository.ProductRepository;
import aimene.doex.bestelling.repository.BestellingRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@RestController
@RequestMapping("/producten")
public class ProductController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public ProductController(ProductRepository productRepository, BestellingRepository bestellingRepository) {
this.productRepository = productRepository;
this.bestellingRepository = bestellingRepository;
}
@GetMapping
public Iterable<Product> findAll() {
return productRepository.findAll();
}
@GetMapping("{id}")
public Product findById(@PathVariable("id") Product product) {
return product;
}
@PatchMapping("{id}/prijs")
public void veranderPrijs(@PathVariable("id") Product product,
@RequestBody Map<String, Object> requestBody) {
/* ******************************************************************** */
// Geef in het sequentiediagram wel expliciet aan dat je het product
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
// (zie voorbeeld in het sequentiediagram)
/* ******************************************************************** */
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
// Je kunt ervan uitgaan dat de nieuwePrijs wordt meegegeven door de
// actor bij aanroep van de methode veranderPrijs van deze controller
Geld nieuwePrijs = new Geld((int) requestBody.get("nieuwe_prijs"), Valuta.EUR);
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze<SUF>
// (zie voorbeeld in het sequentiediagram)
product.veranderPrijs(nieuwePrijs);
/* ******************************************************************** */
productRepository.save(product);
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
AggregateReference<Product, Integer> productRef =
AggregateReference.to(product.getId());
/* ******************************************************************** */
/* ******************************************************************** */
// Vind alle bestellingen die het product bevatten waarvan de prijs is veranderd
// Dit kan beter met een sql-query, maar dat doen we volgende week
// In het Sequentiediagram kun je ervan uitgaan dat er een methode bestaat
// bestellingRepository.findAllMetProduct(productId) die dit voor je doet;
Iterable<Bestelling> bestellingen = bestellingRepository.findAll();
List<Bestelling> bestellingenMetProduct = StreamSupport.stream(bestellingen.spliterator(), false)
.filter(bestelling -> bestelling.bevatBestellingProduct(productRef))
.collect(Collectors.toList());
/* ******************************************************************** */
/* ******************************************************************** */
// Geef dit in het sequentiediagram aan met een rnote
// Verander de stukprijs van het product in de eerder gevonden bestellingen
bestellingenMetProduct.forEach(bestelling -> bestelling.veranderStukPrijs(productRef, nieuwePrijs));
/* ******************************************************************** */
bestellingRepository.saveAll(bestellingenMetProduct);
}
}
|
24928_2 | package Oefeningen;
import org.w3c.dom.ls.LSOutput;
import java.util.ArrayList;
public class Rapport {
private Student student;
private ArrayList<Opleidingsonderdeel> lijst = new ArrayList<>();
public Rapport(Student student) {
this.student = student;
}
public void puntenOpvragen() {
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
double punten = opleidingsonderdeel.getPunten();
}
}
public void afwijking() {
double total = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
total = opleidingsonderdeel.getPunten() - berekenGemiddeldeFunctie();
System.out.println(total);
}
}
public double berekenGemiddeldeFunctie() {
double res = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
res = res + opleidingsonderdeel.getPunten();
}
double gemiddelde = res / lijst.size();
return gemiddelde;
}
public double berekenGemiddelde() {
double bovenGemiddelde = 0;
double onderGemiddelde = 0;
double res = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
res = res + opleidingsonderdeel.getPunten();
}
double gemiddelde = res / lijst.size();
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
if (opleidingsonderdeel.getPunten() > gemiddelde) {
bovenGemiddelde = bovenGemiddelde + 1;
} else {
onderGemiddelde = onderGemiddelde + 1;
}
}
//System.out.println("Aantal vakken boven het gemiddelde = " + bovenGemiddelde);
//System.out.println("Aantal vakken onder het gemiddelde = " + onderGemiddelde);
return gemiddelde;
}
public void voegtoe(Opleidingsonderdeel opleidingsonderdeel) {
this.lijst.add(opleidingsonderdeel);
}
public String overzicht() {
int bovenGemiddelde = 0;
int onderGemiddelde = 0;
int ophetGemiddelde = 0;
double res = 0;
String s = "Puntenoverzicht van" + student.getNaam() + "\n";
for (Opleidingsonderdeel o : this.lijst) {
s += o.getOmschrijving() + " : " + o.getPunten() + "\n";
res = res + o.getPunten();
}
double gemiddelde = res / lijst.size();
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
if (opleidingsonderdeel.getPunten() > gemiddelde) {
bovenGemiddelde = bovenGemiddelde + 1;
} else if ((opleidingsonderdeel.getPunten() > gemiddelde)) {
onderGemiddelde = onderGemiddelde + 1;
} else {
ophetGemiddelde = ophetGemiddelde + 1;
}
}
//System.out.println("Aantal vakken boven het gemiddelde = " + bovenGemiddelde);
//System.out.println("Aantal vakken onder het gemiddelde = " + onderGemiddelde);
//binnen een andere klasse kan je een functie van een andere klasse oproepen.
s += "het gemiddelde van de punten is " + berekenGemiddelde() + "\nAantal vakken boven het gemiddelde: " + bovenGemiddelde + "\nAantal vakken onder het gemiddelde: " + onderGemiddelde;
return s;
}
@Override
public String toString() {
return "Rapport{" +
"student=" + student +
", lijst=" + lijst +
'}';
}
}
| EGSilver/Programming-fundementals | week4/src/Oefeningen/Rapport.java | 984 | //System.out.println("Aantal vakken boven het gemiddelde = " + bovenGemiddelde); | line_comment | nl | package Oefeningen;
import org.w3c.dom.ls.LSOutput;
import java.util.ArrayList;
public class Rapport {
private Student student;
private ArrayList<Opleidingsonderdeel> lijst = new ArrayList<>();
public Rapport(Student student) {
this.student = student;
}
public void puntenOpvragen() {
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
double punten = opleidingsonderdeel.getPunten();
}
}
public void afwijking() {
double total = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
total = opleidingsonderdeel.getPunten() - berekenGemiddeldeFunctie();
System.out.println(total);
}
}
public double berekenGemiddeldeFunctie() {
double res = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
res = res + opleidingsonderdeel.getPunten();
}
double gemiddelde = res / lijst.size();
return gemiddelde;
}
public double berekenGemiddelde() {
double bovenGemiddelde = 0;
double onderGemiddelde = 0;
double res = 0;
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
res = res + opleidingsonderdeel.getPunten();
}
double gemiddelde = res / lijst.size();
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
if (opleidingsonderdeel.getPunten() > gemiddelde) {
bovenGemiddelde = bovenGemiddelde + 1;
} else {
onderGemiddelde = onderGemiddelde + 1;
}
}
//System.out.println("Aantal vakken boven het gemiddelde = " + bovenGemiddelde);
//System.out.println("Aantal vakken onder het gemiddelde = " + onderGemiddelde);
return gemiddelde;
}
public void voegtoe(Opleidingsonderdeel opleidingsonderdeel) {
this.lijst.add(opleidingsonderdeel);
}
public String overzicht() {
int bovenGemiddelde = 0;
int onderGemiddelde = 0;
int ophetGemiddelde = 0;
double res = 0;
String s = "Puntenoverzicht van" + student.getNaam() + "\n";
for (Opleidingsonderdeel o : this.lijst) {
s += o.getOmschrijving() + " : " + o.getPunten() + "\n";
res = res + o.getPunten();
}
double gemiddelde = res / lijst.size();
for (Opleidingsonderdeel opleidingsonderdeel : lijst) {
if (opleidingsonderdeel.getPunten() > gemiddelde) {
bovenGemiddelde = bovenGemiddelde + 1;
} else if ((opleidingsonderdeel.getPunten() > gemiddelde)) {
onderGemiddelde = onderGemiddelde + 1;
} else {
ophetGemiddelde = ophetGemiddelde + 1;
}
}
//System.out.println("Aantal vakken<SUF>
//System.out.println("Aantal vakken onder het gemiddelde = " + onderGemiddelde);
//binnen een andere klasse kan je een functie van een andere klasse oproepen.
s += "het gemiddelde van de punten is " + berekenGemiddelde() + "\nAantal vakken boven het gemiddelde: " + bovenGemiddelde + "\nAantal vakken onder het gemiddelde: " + onderGemiddelde;
return s;
}
@Override
public String toString() {
return "Rapport{" +
"student=" + student +
", lijst=" + lijst +
'}';
}
}
|
120081_0 | package be.ugent.oplossing.model;
import be.ugent.oplossing.show.RubiksReader;
import javafx.scene.paint.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RubiksKubus implements IRubikCube {
private List<Kubusje> kubusjes;
// Alle gegevens voor de 27 kubusjes werden in een excel-bestand ingevuld en bewaard.
// Excel biedt dankzij z'n kolommen een duidelijk overzicht, er kan heel gestructureerd gewerkt
// (en gecontroleerd) worden.
// Inlezen van het bestand werd afgekeken van de gegeven code in de show-map.
// (Moet niet gekend zijn voor op het examen.)
public RubiksKubus() throws FileNotFoundException {
kubusjes = new ArrayList<>();
Scanner sc = new Scanner(new File(Objects.requireNonNull(RubiksReader.class.getResource("kubussen_xyz.csv")).getFile()));
while (sc.hasNext()) {
Scanner sc_ = new Scanner(sc.nextLine());
sc_.useDelimiter(";");
int x = sc_.nextInt();
int y = sc_.nextInt();
int z = sc_.nextInt();
String[] kleuren = new String[6];
for (int i = 0; i < 6; i++) {
kleuren[i] = sc_.next();
}
kubusjes.add(new Kubusje(x, y, z, kleuren));
}
}
// Dit kan je gebruiken om zelf te testen, zolang de view er nog niet is.
// Layout niet handig? Pas zelf aan.
public String toString() {
// kan je later met streams doen
String[] strings = new String[kubusjes.size()];
int i = 0;
for (Kubusje kubus : kubusjes) {
strings[i++] = kubus.toString();
}
return String.join("\n", strings);
}
// Deze methode wordt gebruikt door het showteam om de View te maken.
// Meer is er niet nodig (in tegenstelling tot wat in sprint0 aangekondigd werd,
// dus geen onderscheid tussen zichtbare en onzichtbare vlakjes).
@Override
public List<IFace> getAllFaces() {
return kubusjes.stream().flatMap(e -> Arrays.stream(e.getVlakjes())).collect(Collectors.toList());
}
@Override
public List<IFace> getRotation(Color color, int degree) {
AxisColor axisColor = AxisColor.getAxisColorFromColor(color);
double angle = degree * Math.signum(axisColor.number);
var rotatedFaces = kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number)
.flatMap(e -> e.copyAndRotate(angle, axisColor.axis).stream());
var unRotatedFaces = kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) != axisColor.number)
.flatMap(e -> Arrays.stream(e.getVlakjes()));
return Stream.concat(rotatedFaces, unRotatedFaces).toList();
}
@Override
public void rotate(Color color, boolean clockwise) {
AxisColor axisColor = AxisColor.getAxisColorFromColor(color);
double angle = ((clockwise ? 0 : 1) * 2 - 1) * 90 * Math.signum(axisColor.number);
kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number)
.forEach(e -> e.rotate(angle, axisColor.axis));
}
public List<Kubusje> getKubusjes() {
return kubusjes;
}
}
| Daellhin/UGent-RubicsCube | src/main/java/be/ugent/oplossing/model/RubiksKubus.java | 964 | // Alle gegevens voor de 27 kubusjes werden in een excel-bestand ingevuld en bewaard. | line_comment | nl | package be.ugent.oplossing.model;
import be.ugent.oplossing.show.RubiksReader;
import javafx.scene.paint.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RubiksKubus implements IRubikCube {
private List<Kubusje> kubusjes;
// Alle gegevens<SUF>
// Excel biedt dankzij z'n kolommen een duidelijk overzicht, er kan heel gestructureerd gewerkt
// (en gecontroleerd) worden.
// Inlezen van het bestand werd afgekeken van de gegeven code in de show-map.
// (Moet niet gekend zijn voor op het examen.)
public RubiksKubus() throws FileNotFoundException {
kubusjes = new ArrayList<>();
Scanner sc = new Scanner(new File(Objects.requireNonNull(RubiksReader.class.getResource("kubussen_xyz.csv")).getFile()));
while (sc.hasNext()) {
Scanner sc_ = new Scanner(sc.nextLine());
sc_.useDelimiter(";");
int x = sc_.nextInt();
int y = sc_.nextInt();
int z = sc_.nextInt();
String[] kleuren = new String[6];
for (int i = 0; i < 6; i++) {
kleuren[i] = sc_.next();
}
kubusjes.add(new Kubusje(x, y, z, kleuren));
}
}
// Dit kan je gebruiken om zelf te testen, zolang de view er nog niet is.
// Layout niet handig? Pas zelf aan.
public String toString() {
// kan je later met streams doen
String[] strings = new String[kubusjes.size()];
int i = 0;
for (Kubusje kubus : kubusjes) {
strings[i++] = kubus.toString();
}
return String.join("\n", strings);
}
// Deze methode wordt gebruikt door het showteam om de View te maken.
// Meer is er niet nodig (in tegenstelling tot wat in sprint0 aangekondigd werd,
// dus geen onderscheid tussen zichtbare en onzichtbare vlakjes).
@Override
public List<IFace> getAllFaces() {
return kubusjes.stream().flatMap(e -> Arrays.stream(e.getVlakjes())).collect(Collectors.toList());
}
@Override
public List<IFace> getRotation(Color color, int degree) {
AxisColor axisColor = AxisColor.getAxisColorFromColor(color);
double angle = degree * Math.signum(axisColor.number);
var rotatedFaces = kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number)
.flatMap(e -> e.copyAndRotate(angle, axisColor.axis).stream());
var unRotatedFaces = kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) != axisColor.number)
.flatMap(e -> Arrays.stream(e.getVlakjes()));
return Stream.concat(rotatedFaces, unRotatedFaces).toList();
}
@Override
public void rotate(Color color, boolean clockwise) {
AxisColor axisColor = AxisColor.getAxisColorFromColor(color);
double angle = ((clockwise ? 0 : 1) * 2 - 1) * 90 * Math.signum(axisColor.number);
kubusjes.stream()
.filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number)
.forEach(e -> e.rotate(angle, axisColor.axis));
}
public List<Kubusje> getKubusjes() {
return kubusjes;
}
}
|
72124_17 | package gui.tools;
import robot.*;
import robot.brain.Explorer;
import field.*;
import field.simulation.FieldSimulation;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.text.AttributedCharacterIterator;
import java.util.ConcurrentModificationException;
import java.util.List;
import peno.htttp.PlayerClient;
/*
* Custom canvas klasse om de map van het doolhof
* weer te geven.
*/
public class DrawCanvas extends FieldCanvas{
/**
*
*/
private static final long serialVersionUID = 1L;
private RobotPool robotPool;
private FieldSimulation field;
public DrawCanvas(RobotPool robotPool, String title){
setRobotPool(robotPool);
setTitle(title);
this.setVisible(true);
}
public void setRobotPool(RobotPool robotPool) {
if (robotPool != null) {
this.robotPool = robotPool;
//setField(robotPool.getMainRobot().getField());
}
}
public void setField(FieldSimulation field) {
this.field = field;
}
/*protected void setField(Field field) {
this.field = field;
}*/
// Tekent de map van het doolhof zoals ze op dit moment bekend is.
@Override
public void paint(Graphics g){
createBufferStrategy(2);
if (robotPool != null && robotPool.getMainRobot().isConnectedToGame()) {
if (robotPool.getMainRobot().getField().isMerged()) {
setTitle("Player's View - Merged");
}
try{
//if (robotPool.getMainRobot().getClient().isPlaying()) {
paintTitle(g);
rescale(robotPool.getMainRobot().getField());
paintTiles(g);
paintBorders(g);
paintPos(g);
paintObjects(g);
shortestPath(g);
} catch (ConcurrentModificationException e) {
}
}
}
// TODO add this somewhere else (new canvas?)
/*private void drawLobby(Graphics g) {
PlayerClient client = robotPool.getMainRobot().getClient();
if (client.isPaused()) {
g.drawString("PAUSED", 80, 160);
}
g.drawString("players in lobby:", 20, 20);
int i = 1;
for (String player : client.getPlayers()) {
String drawString = "Player " + i + ": " + player;
g.drawString(drawString, 20, 40 + 20 * i);
i++;
}
}*/
// Tekent de huidige posities op de map. De robots als rechthoek.
private void paintPos(Graphics g){
for (RobotModel currentRobot : robotPool){
//Graphics2D g2 = (Graphics2D)g;
//g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
int x = (int)( currentRobot.getPosition().getPosX()
+ currentRobot.getCurrTile().getPosition().getX() * 40);
int y = (int)( currentRobot.getPosition().getPosY()
+ currentRobot.getCurrTile().getPosition().getY() * 40);
double r = currentRobot.getPosition().getRotationRadian() + (Math.PI/2);
int[] drawXs;
int[] drawYs;
if (currentRobot != robotPool.getMainRobot()){
/*x -= robotPool.getMainRobot().getStartPos().getPosX();
y -= robotPool.getMainRobot().getStartPos().getPosY();*/
TilePosition start = field.getStartPos(robotPool.getMainRobot().getPlayerNr());
TilePosition other = new TilePosition(
currentRobot.getCurrTile().getPosition().getX() - start.getX(),
currentRobot.getCurrTile().getPosition().getY() - start.getY()
);
double rr = field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle();
r -= rr * Math.PI / 180;
int[] newpos = new int[] {(int)other.getX(),(int)other.getY()};
//DebugBuffer.addInfo("pos: " + (r * 180 / Math.PI) + " " + rr);
switch(field.getStartDir(robotPool.getMainRobot().getPlayerNr())) {
case BOTTOM:
newpos = new int[] {-(int)other.getX(),-(int)other.getY()};
break;
case LEFT:
newpos = new int[] {(int)other.getY(),-(int)other.getX()};
break;
case RIGHT:
newpos = new int[] {-(int)other.getY(),(int)other.getX()};
break;
case TOP:
break;
default:
break;
}
x = newpos[0] * 40;
y = newpos[1] * 40;
//DebugBuffer.addInfo("pos: " + x + " " + y);
double[] xs = currentRobot.getCornersX(field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle());
double[] ys = currentRobot.getCornersY(field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle());
drawXs = new int[4];
drawYs = new int[4];
for (int i = 0; i < 4; i++){
drawXs[i] = (int)((getStartX() + (xs[i] * getScale()) + (x * getScale())));
drawYs[i] = (int)((getStartY() - (ys[i] * getScale()) - (y * getScale())));
}
} else {
double[] xs = currentRobot.getCornersX();
double[] ys = currentRobot.getCornersY();
drawXs = new int[4];
drawYs = new int[4];
for (int i = 0; i < 4; i++){
drawXs[i] = (int)((getStartX() + (xs[i] * getScale()) + (x * getScale())));
drawYs[i] = (int)((getStartY() - (ys[i] * getScale()) - (y * getScale())));
}
}
/*System.out.println("paintpos " + x + ", " + y);
System.out.println("startpos " + getStartX() + ", " + getStartY());
System.out.println("getScale() " + getScale() );*/
Polygon robotSurface = new Polygon(drawXs, drawYs, 4);
if (currentRobot == robotPool.getMainRobot()){
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLUE);
}
g.fillPolygon(robotSurface);
// robot heeft object bij.
if (currentRobot.hasBall()){
g.setColor(Color.YELLOW);
g.fillOval((int)(getStartX() + x * getScale()), (int)(getStartY() - y * getScale()), getBorderWidth(), getBorderWidth());
}
g.setColor(Color.BLACK);
g.drawLine((int) ((x * getScale()) + getStartX()), (int) (getStartY() - (y * getScale())), (int) ((getScale() * x) + getStartX() - (getBorderWidth() * Math.cos(r))), (int) (getStartY() - (getScale() * y) - (getBorderWidth() * Math.sin(r))));
}
//current tile
int x = robotPool.getMainRobot().getCurrTile().getPosition().getX();
int y = robotPool.getMainRobot().getCurrTile().getPosition().getY();
g.setColor(Color.ORANGE);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
// teammate current tile
if (robotPool.getMainRobot().hasTeamMate() && robotPool.getMainRobot().getField().isMerged()) {
x = robotPool.getMainRobot().getTeamMate().getCurrTile().getPosition().getX();
y = robotPool.getMainRobot().getTeamMate().getCurrTile().getPosition().getY();
g.setColor(Color.GREEN);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
}
// draw explore tiles
int i = 1;
try {
synchronized (Explorer.getToExplore()) {
for (TilePosition tilePos : Explorer.getToExplore()) {
x = tilePos.getX();
y = tilePos.getY();
g.setColor(Color.CYAN);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
g.drawString(""+i, (getStartX()) + (x * (getTileSize())),(getStartY()) - (y * (getTileSize())));
i++;
}
}
} catch (ConcurrentModificationException e) {
}
// draw robot spotted tiles
for (TilePosition tilePos : robotPool.getMainRobot().getRobotSpottedTiles()) {
x = tilePos.getX();
y = tilePos.getY();
g.setColor(Color.RED);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
}
//ghost
/*if (robotPool.getMainRobot().isSim()){
x = (int) robotPool.getMainRobot().getSimX() - (int) robotPool.getMainRobot().getStartx();
y = (int) robotPool.getMainRobot().getSimY() - (int) robotPool.getMainRobot().getStarty();
double r = robotPool.getMainRobot().getSimAngle() + (Math.PI/2);
g.setColor(Color.CYAN);
g.drawLine((int) ((x * getScale()) + getStartX()), (int) (getStartY() - (y * getScale())), (int) ((getScale() * x) + getStartX() - (getBorderWidth() * Math.cos(r))), (int) (getStartY() - (getScale() * y) - (getBorderWidth() * Math.sin(r))));
g.fillOval((int) ((x * getScale()) + (getStartX() - getHalfBorderWidth())), (int) ((getStartY() - getHalfBorderWidth()) - (y * getScale())), getBorderWidth(), getBorderWidth());
}*/
}
// Tekent alle bekende tegels op de map.
private void paintTiles(Graphics g){
fieldDrawer.drawTiles(g, robotPool.getMainRobot().getField(), this);
}
// Tekent alle bekende muren op de map.
private void paintBorders(Graphics g){
fieldDrawer.drawBorders(g, robotPool.getMainRobot().getField(), this);
}
// tekent de balletjes in het doolhof
private void paintObjects(Graphics g){
fieldDrawer.drawObjects(g, robotPool.getMainRobot().getField(), this);
}
private void shortestPath(Graphics g){
if (robotPool.getMainRobot().getAStarTileList() != null){
g.setColor(Color.CYAN);
List<Tile> list = robotPool.getMainRobot().getAStarTileList();
for (int i = 0; i < list.size()-1; i++){
TilePosition pos1 = list.get(i).getPosition();
TilePosition pos2 = list.get(i+1).getPosition();
int x1 = getStartX() + (pos1.getX() * (getTileSize()));
int y1 = getStartY() - (pos1.getY() * (getTileSize()));
int x2 = getStartX() + (pos2.getX() * (getTileSize()));
int y2 = getStartY() - (pos2.getY() * (getTileSize()));
g.drawLine(x1, y1, x2, y2);
}
}
g.setColor(Color.BLACK);
}
@Override
public void update(Graphics g) {
super.update(g);
}
}
| SamuelLannoy/penocw-teamgeel | penopc/src/gui/tools/DrawCanvas.java | 3,161 | /*if (robotPool.getMainRobot().isSim()){
x = (int) robotPool.getMainRobot().getSimX() - (int) robotPool.getMainRobot().getStartx();
y = (int) robotPool.getMainRobot().getSimY() - (int) robotPool.getMainRobot().getStarty();
double r = robotPool.getMainRobot().getSimAngle() + (Math.PI/2);
g.setColor(Color.CYAN);
g.drawLine((int) ((x * getScale()) + getStartX()), (int) (getStartY() - (y * getScale())), (int) ((getScale() * x) + getStartX() - (getBorderWidth() * Math.cos(r))), (int) (getStartY() - (getScale() * y) - (getBorderWidth() * Math.sin(r))));
g.fillOval((int) ((x * getScale()) + (getStartX() - getHalfBorderWidth())), (int) ((getStartY() - getHalfBorderWidth()) - (y * getScale())), getBorderWidth(), getBorderWidth());
}*/ | block_comment | nl | package gui.tools;
import robot.*;
import robot.brain.Explorer;
import field.*;
import field.simulation.FieldSimulation;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.text.AttributedCharacterIterator;
import java.util.ConcurrentModificationException;
import java.util.List;
import peno.htttp.PlayerClient;
/*
* Custom canvas klasse om de map van het doolhof
* weer te geven.
*/
public class DrawCanvas extends FieldCanvas{
/**
*
*/
private static final long serialVersionUID = 1L;
private RobotPool robotPool;
private FieldSimulation field;
public DrawCanvas(RobotPool robotPool, String title){
setRobotPool(robotPool);
setTitle(title);
this.setVisible(true);
}
public void setRobotPool(RobotPool robotPool) {
if (robotPool != null) {
this.robotPool = robotPool;
//setField(robotPool.getMainRobot().getField());
}
}
public void setField(FieldSimulation field) {
this.field = field;
}
/*protected void setField(Field field) {
this.field = field;
}*/
// Tekent de map van het doolhof zoals ze op dit moment bekend is.
@Override
public void paint(Graphics g){
createBufferStrategy(2);
if (robotPool != null && robotPool.getMainRobot().isConnectedToGame()) {
if (robotPool.getMainRobot().getField().isMerged()) {
setTitle("Player's View - Merged");
}
try{
//if (robotPool.getMainRobot().getClient().isPlaying()) {
paintTitle(g);
rescale(robotPool.getMainRobot().getField());
paintTiles(g);
paintBorders(g);
paintPos(g);
paintObjects(g);
shortestPath(g);
} catch (ConcurrentModificationException e) {
}
}
}
// TODO add this somewhere else (new canvas?)
/*private void drawLobby(Graphics g) {
PlayerClient client = robotPool.getMainRobot().getClient();
if (client.isPaused()) {
g.drawString("PAUSED", 80, 160);
}
g.drawString("players in lobby:", 20, 20);
int i = 1;
for (String player : client.getPlayers()) {
String drawString = "Player " + i + ": " + player;
g.drawString(drawString, 20, 40 + 20 * i);
i++;
}
}*/
// Tekent de huidige posities op de map. De robots als rechthoek.
private void paintPos(Graphics g){
for (RobotModel currentRobot : robotPool){
//Graphics2D g2 = (Graphics2D)g;
//g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
int x = (int)( currentRobot.getPosition().getPosX()
+ currentRobot.getCurrTile().getPosition().getX() * 40);
int y = (int)( currentRobot.getPosition().getPosY()
+ currentRobot.getCurrTile().getPosition().getY() * 40);
double r = currentRobot.getPosition().getRotationRadian() + (Math.PI/2);
int[] drawXs;
int[] drawYs;
if (currentRobot != robotPool.getMainRobot()){
/*x -= robotPool.getMainRobot().getStartPos().getPosX();
y -= robotPool.getMainRobot().getStartPos().getPosY();*/
TilePosition start = field.getStartPos(robotPool.getMainRobot().getPlayerNr());
TilePosition other = new TilePosition(
currentRobot.getCurrTile().getPosition().getX() - start.getX(),
currentRobot.getCurrTile().getPosition().getY() - start.getY()
);
double rr = field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle();
r -= rr * Math.PI / 180;
int[] newpos = new int[] {(int)other.getX(),(int)other.getY()};
//DebugBuffer.addInfo("pos: " + (r * 180 / Math.PI) + " " + rr);
switch(field.getStartDir(robotPool.getMainRobot().getPlayerNr())) {
case BOTTOM:
newpos = new int[] {-(int)other.getX(),-(int)other.getY()};
break;
case LEFT:
newpos = new int[] {(int)other.getY(),-(int)other.getX()};
break;
case RIGHT:
newpos = new int[] {-(int)other.getY(),(int)other.getX()};
break;
case TOP:
break;
default:
break;
}
x = newpos[0] * 40;
y = newpos[1] * 40;
//DebugBuffer.addInfo("pos: " + x + " " + y);
double[] xs = currentRobot.getCornersX(field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle());
double[] ys = currentRobot.getCornersY(field.getStartDir(robotPool.getMainRobot().getPlayerNr()).toAngle());
drawXs = new int[4];
drawYs = new int[4];
for (int i = 0; i < 4; i++){
drawXs[i] = (int)((getStartX() + (xs[i] * getScale()) + (x * getScale())));
drawYs[i] = (int)((getStartY() - (ys[i] * getScale()) - (y * getScale())));
}
} else {
double[] xs = currentRobot.getCornersX();
double[] ys = currentRobot.getCornersY();
drawXs = new int[4];
drawYs = new int[4];
for (int i = 0; i < 4; i++){
drawXs[i] = (int)((getStartX() + (xs[i] * getScale()) + (x * getScale())));
drawYs[i] = (int)((getStartY() - (ys[i] * getScale()) - (y * getScale())));
}
}
/*System.out.println("paintpos " + x + ", " + y);
System.out.println("startpos " + getStartX() + ", " + getStartY());
System.out.println("getScale() " + getScale() );*/
Polygon robotSurface = new Polygon(drawXs, drawYs, 4);
if (currentRobot == robotPool.getMainRobot()){
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLUE);
}
g.fillPolygon(robotSurface);
// robot heeft object bij.
if (currentRobot.hasBall()){
g.setColor(Color.YELLOW);
g.fillOval((int)(getStartX() + x * getScale()), (int)(getStartY() - y * getScale()), getBorderWidth(), getBorderWidth());
}
g.setColor(Color.BLACK);
g.drawLine((int) ((x * getScale()) + getStartX()), (int) (getStartY() - (y * getScale())), (int) ((getScale() * x) + getStartX() - (getBorderWidth() * Math.cos(r))), (int) (getStartY() - (getScale() * y) - (getBorderWidth() * Math.sin(r))));
}
//current tile
int x = robotPool.getMainRobot().getCurrTile().getPosition().getX();
int y = robotPool.getMainRobot().getCurrTile().getPosition().getY();
g.setColor(Color.ORANGE);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
// teammate current tile
if (robotPool.getMainRobot().hasTeamMate() && robotPool.getMainRobot().getField().isMerged()) {
x = robotPool.getMainRobot().getTeamMate().getCurrTile().getPosition().getX();
y = robotPool.getMainRobot().getTeamMate().getCurrTile().getPosition().getY();
g.setColor(Color.GREEN);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
}
// draw explore tiles
int i = 1;
try {
synchronized (Explorer.getToExplore()) {
for (TilePosition tilePos : Explorer.getToExplore()) {
x = tilePos.getX();
y = tilePos.getY();
g.setColor(Color.CYAN);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
g.drawString(""+i, (getStartX()) + (x * (getTileSize())),(getStartY()) - (y * (getTileSize())));
i++;
}
}
} catch (ConcurrentModificationException e) {
}
// draw robot spotted tiles
for (TilePosition tilePos : robotPool.getMainRobot().getRobotSpottedTiles()) {
x = tilePos.getX();
y = tilePos.getY();
g.setColor(Color.RED);
g.drawRect((getStartX() - getHalfTileSize()) + (x * (getTileSize())),(getStartY() - getHalfTileSize()) - (y * (getTileSize())), getTileSize(), getTileSize());
}
//ghost
/*if (robotPool.getMainRobot().isSim()){
<SUF>*/
}
// Tekent alle bekende tegels op de map.
private void paintTiles(Graphics g){
fieldDrawer.drawTiles(g, robotPool.getMainRobot().getField(), this);
}
// Tekent alle bekende muren op de map.
private void paintBorders(Graphics g){
fieldDrawer.drawBorders(g, robotPool.getMainRobot().getField(), this);
}
// tekent de balletjes in het doolhof
private void paintObjects(Graphics g){
fieldDrawer.drawObjects(g, robotPool.getMainRobot().getField(), this);
}
private void shortestPath(Graphics g){
if (robotPool.getMainRobot().getAStarTileList() != null){
g.setColor(Color.CYAN);
List<Tile> list = robotPool.getMainRobot().getAStarTileList();
for (int i = 0; i < list.size()-1; i++){
TilePosition pos1 = list.get(i).getPosition();
TilePosition pos2 = list.get(i+1).getPosition();
int x1 = getStartX() + (pos1.getX() * (getTileSize()));
int y1 = getStartY() - (pos1.getY() * (getTileSize()));
int x2 = getStartX() + (pos2.getX() * (getTileSize()));
int y2 = getStartY() - (pos2.getY() * (getTileSize()));
g.drawLine(x1, y1, x2, y2);
}
}
g.setColor(Color.BLACK);
}
@Override
public void update(Graphics g) {
super.update(g);
}
}
|
78750_18 | package be.fomp.carcassonne.utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import be.fomp.carcassonne.game.objects.AreaType;
import be.fomp.carcassonne.model.Area;
import be.fomp.carcassonne.model.Follower;
import be.fomp.carcassonne.model.Player;
import be.fomp.carcassonne.model.Tile;
import be.fomp.carcassonne.model.Zone;
/**
* Performs scoring calculations by recursively going over the whole map
* @author sven
*
*/
public final class ScoreCalculator {
/**
* - Calculates the score between game rounds
* - Assigns that score to the players
* - Restores the players followers
*
* //TODO another way of calculating scores would be to keep
* track of all followers and iterate over them.
*
* @param rootTile can be any connected tile
*/
public static final void calculateScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateCloisterScore(az); break;
case CITY:
case CITY2: calculateCityScore(az); break;
case ROAD: calculateRoadScore(az); break;
default:break;
}
}
}
// (First Edition, included in the English version) Farm Scoring Rules:
//
// 1. Identify each completed city.
//
// 2. Count the total number of farmers adjacent to the city in all
// adjacent fields. These farmers are said to supply the city.
//
// 3. The player with the most farmers supplying the city earns the 4 points
// (5 if that player also has a pig in an adjacent field).
// If the completed city is besieged, earns 8 points (10 if that player
// also has a pig on that field) instead.
//
// 4. Consider placing a token or a marker of some sort in each scored city;
// this may make it easier to accurately tally the points by identifying the
// cities that have already been scored.
/**
* Calculates the scores at the end of the game
* Assigns it to the players
* Restores the followers
**/
public static final void calculateEndScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
Set<Zone> completedCities = new HashSet<Zone>();
Set<Zone> fields = new HashSet<Zone>();
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(az.getAreaType() == AreaType.CITY || az.getAreaType() == AreaType.CITY2)
if(isComplete(z)) completedCities.add(z);
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateEndCloisterScore(az); break;
case CITY:
case CITY2: calculateEndCityScore(az);
break;
case ROAD: calculateEndRoadScore(az); break;
case FIELD: fields.add(z);
default:break;
}
}
calculateEndFieldScore(fields, completedCities);
}
/**
* A follower was scored so it can be returned to the player
* @param f the follower that was scored
*/
private static void restoreFollower(Follower f){
Player p = f.getOwner();
p.setFollowers(p.getFollowers() + 1);
//Clean up follower from the area
f.setOwner(null);
f.getLocation().removeFollower();
f.setLocation(null);
}
private static final void calculateCloisterScore(Area cloister){
Tile t = cloister.getLocation();
if(!TileUtils.isCompletelySurrounded(t)) return;
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getCloisterScore());
restoreFollower(f);
}
private static final void calculateEndCloisterScore(Area cloister){
Tile t = cloister.getLocation();
int surroundingTiles = TileUtils.countSurroundingTiles(t);
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getEndCloisterScore(surroundingTiles));
restoreFollower(f);
}
/**
* From analysis:
* Stad: Een stad is compleet als hij volledig door muren omringd is.
* De speler met een ridder in de stad scoort 2 punten voor elke tegel
* waarop de stad ligt plus 2 punten voor elk schildje dat in de stad ligt.
*
* Uitzondering: Als de speler een stad vervolledigt dat uit 2 tegels bestaat
* krijgt hij maar 1 punt per tegel plus 1 per schild.
*
* De spelers met de meeste volgers krijgen elk de totale score
* @param city
*/
private static final void calculateCityScore(Area city){
Zone zone = city.getZone();
if(!isComplete(zone)) return; //If the area is not complete, return
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers = 0;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f);
}
private static final void calculateEndCityScore(Area city){
Zone zone = city.getZone();
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getEndCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateRoadScore(Area road) {
Zone zone = road.getZone();
if(!isComplete(zone)) return;
int tileCount = zone.getTiles().size();
int score = Ruleset.getRoadScore(tileCount);
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndRoadScore(Area road) {
Zone zone = road.getZone();
int tileCount = zone.getTiles().size();
int score = Ruleset.getEndRoadScore(tileCount);
int mostFollowers = 1;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndFieldScore(Set<Zone> fields, Set<Zone> cities) {
Set<Follower> checkedFollowers = new HashSet<Follower>();
for(Zone city: cities)
for(Zone field : city.getNeigboringZones())
if(fields.contains(field) && field.hasFollowers()) {
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = field.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + Ruleset.getEndFarmerScore(mostFollowers));
}
checkedFollowers.addAll(followers); //Tag followers for removal
}
for(Follower f : checkedFollowers) restoreFollower(f); //Clean up followers
}
private static final boolean isComplete(Zone z) {
for(Area a : z.getAreas())
{
Area[] border = a.getLocation().getBorder();
Area[] borderConnections = a.getLocation().getBorderConnections();
for(int i=0; i< borderConnections.length; i++)
if(z == border[i].getZone() && borderConnections[i] == null)
return false;
}
return true;
}
private static Map<Player, Integer> countPlayerFollowers(Set<Follower> followers) {
Map<Player, Integer> returnValue = new HashMap<Player, Integer>();
int followerCounter = 1;
for(Follower f: followers) {
Player p = f.getOwner();
if(returnValue.containsKey(p)){
int newCount = returnValue.get(p) + 1;
returnValue.put(p, newCount);
if(followerCounter < newCount) followerCounter = newCount;
}
else
returnValue.put(p, 1);
}
return returnValue;
}
}
| svenmeys/Carcassonne | src/be/fomp/carcassonne/utils/ScoreCalculator.java | 2,998 | //In every zone | line_comment | nl | package be.fomp.carcassonne.utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import be.fomp.carcassonne.game.objects.AreaType;
import be.fomp.carcassonne.model.Area;
import be.fomp.carcassonne.model.Follower;
import be.fomp.carcassonne.model.Player;
import be.fomp.carcassonne.model.Tile;
import be.fomp.carcassonne.model.Zone;
/**
* Performs scoring calculations by recursively going over the whole map
* @author sven
*
*/
public final class ScoreCalculator {
/**
* - Calculates the score between game rounds
* - Assigns that score to the players
* - Restores the players followers
*
* //TODO another way of calculating scores would be to keep
* track of all followers and iterate over them.
*
* @param rootTile can be any connected tile
*/
public static final void calculateScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
for(Zone z : zones) //In every zone
for(Area az : z.getAreas()) //For each area that:
{
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateCloisterScore(az); break;
case CITY:
case CITY2: calculateCityScore(az); break;
case ROAD: calculateRoadScore(az); break;
default:break;
}
}
}
// (First Edition, included in the English version) Farm Scoring Rules:
//
// 1. Identify each completed city.
//
// 2. Count the total number of farmers adjacent to the city in all
// adjacent fields. These farmers are said to supply the city.
//
// 3. The player with the most farmers supplying the city earns the 4 points
// (5 if that player also has a pig in an adjacent field).
// If the completed city is besieged, earns 8 points (10 if that player
// also has a pig on that field) instead.
//
// 4. Consider placing a token or a marker of some sort in each scored city;
// this may make it easier to accurately tally the points by identifying the
// cities that have already been scored.
/**
* Calculates the scores at the end of the game
* Assigns it to the players
* Restores the followers
**/
public static final void calculateEndScores(Tile rootTile){
Set<Area> checkedAreas = new HashSet<Area>();
Zone root = rootTile.getBorder()[0].getZone(); //ROOT ZONE
Set<Zone> zones = TileUtils.fetchAllZones(root, null);
Set<Zone> completedCities = new HashSet<Zone>();
Set<Zone> fields = new HashSet<Zone>();
for(Zone z : zones) //In every<SUF>
for(Area az : z.getAreas()) //For each area that:
{
if(az.getAreaType() == AreaType.CITY || az.getAreaType() == AreaType.CITY2)
if(isComplete(z)) completedCities.add(z);
if(!az.hasFollower()) continue; // - has a follower
if(!checkedAreas.add(az)) continue; // - has not been checked yet
switch(az.getAreaType()){
case CLOISTER: calculateEndCloisterScore(az); break;
case CITY:
case CITY2: calculateEndCityScore(az);
break;
case ROAD: calculateEndRoadScore(az); break;
case FIELD: fields.add(z);
default:break;
}
}
calculateEndFieldScore(fields, completedCities);
}
/**
* A follower was scored so it can be returned to the player
* @param f the follower that was scored
*/
private static void restoreFollower(Follower f){
Player p = f.getOwner();
p.setFollowers(p.getFollowers() + 1);
//Clean up follower from the area
f.setOwner(null);
f.getLocation().removeFollower();
f.setLocation(null);
}
private static final void calculateCloisterScore(Area cloister){
Tile t = cloister.getLocation();
if(!TileUtils.isCompletelySurrounded(t)) return;
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getCloisterScore());
restoreFollower(f);
}
private static final void calculateEndCloisterScore(Area cloister){
Tile t = cloister.getLocation();
int surroundingTiles = TileUtils.countSurroundingTiles(t);
Follower f = cloister.getFollower();
Player p = f.getOwner();
p.setScore(p.getScore() + Ruleset.getEndCloisterScore(surroundingTiles));
restoreFollower(f);
}
/**
* From analysis:
* Stad: Een stad is compleet als hij volledig door muren omringd is.
* De speler met een ridder in de stad scoort 2 punten voor elke tegel
* waarop de stad ligt plus 2 punten voor elk schildje dat in de stad ligt.
*
* Uitzondering: Als de speler een stad vervolledigt dat uit 2 tegels bestaat
* krijgt hij maar 1 punt per tegel plus 1 per schild.
*
* De spelers met de meeste volgers krijgen elk de totale score
* @param city
*/
private static final void calculateCityScore(Area city){
Zone zone = city.getZone();
if(!isComplete(zone)) return; //If the area is not complete, return
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers = 0;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f);
}
private static final void calculateEndCityScore(Area city){
Zone zone = city.getZone();
int score = 0; //Otherwise calculate score
int tileCount = zone.getTiles().size();
int pennantCount = 0;
int mostFollowers;
for(Area a : zone.getAreas())
if(a.getAreaType() == AreaType.CITY2) pennantCount++;
score = Ruleset.getEndCityScore(tileCount, pennantCount);
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateRoadScore(Area road) {
Zone zone = road.getZone();
if(!isComplete(zone)) return;
int tileCount = zone.getTiles().size();
int score = Ruleset.getRoadScore(tileCount);
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndRoadScore(Area road) {
Zone zone = road.getZone();
int tileCount = zone.getTiles().size();
int score = Ruleset.getEndRoadScore(tileCount);
int mostFollowers = 1;
//TODO same as above, put in separate method
Set<Follower> followers = zone.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // only the players with most followers can score
p.setScore(p.getScore() + score);
}
for(Follower f : followers) restoreFollower(f); //Clean up followers
}
private static void calculateEndFieldScore(Set<Zone> fields, Set<Zone> cities) {
Set<Follower> checkedFollowers = new HashSet<Follower>();
for(Zone city: cities)
for(Zone field : city.getNeigboringZones())
if(fields.contains(field) && field.hasFollowers()) {
int mostFollowers;
//TODO same as above, put in separate method
Set<Follower> followers = field.getFollowers();
Map<Player, Integer> playerMap = countPlayerFollowers(followers);
mostFollowers = Collections.max(playerMap.values());
for(Player p : playerMap.keySet()) {
if(playerMap.get(p) != mostFollowers) continue; // pnly the players with most followers can score
p.setScore(p.getScore() + Ruleset.getEndFarmerScore(mostFollowers));
}
checkedFollowers.addAll(followers); //Tag followers for removal
}
for(Follower f : checkedFollowers) restoreFollower(f); //Clean up followers
}
private static final boolean isComplete(Zone z) {
for(Area a : z.getAreas())
{
Area[] border = a.getLocation().getBorder();
Area[] borderConnections = a.getLocation().getBorderConnections();
for(int i=0; i< borderConnections.length; i++)
if(z == border[i].getZone() && borderConnections[i] == null)
return false;
}
return true;
}
private static Map<Player, Integer> countPlayerFollowers(Set<Follower> followers) {
Map<Player, Integer> returnValue = new HashMap<Player, Integer>();
int followerCounter = 1;
for(Follower f: followers) {
Player p = f.getOwner();
if(returnValue.containsKey(p)){
int newCount = returnValue.get(p) + 1;
returnValue.put(p, newCount);
if(followerCounter < newCount) followerCounter = newCount;
}
else
returnValue.put(p, 1);
}
return returnValue;
}
}
|
156945_73 | /*
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.idrsolutions.com
* Help section for developers at http://www.idrsolutions.com/support/
*
* (C) Copyright 1997-2016 IDRsolutions and Contributors.
*
* This file is part of JPedal/JPDF2HTML5
*
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
*
* ---------------
* RhinoParser.java
* ---------------
*/
package org.jpedal.objects.javascript;
import java.util.List;
import java.util.StringTokenizer;
import org.jpedal.objects.Javascript;
import org.jpedal.objects.acroforms.ReturnValues;
import org.jpedal.objects.acroforms.actions.ActionHandler;
import org.jpedal.objects.acroforms.creation.FormFactory;
import org.jpedal.objects.javascript.functions.JSFunction;
import org.jpedal.objects.raw.FormObject;
import org.jpedal.objects.acroforms.AcroRenderer;
import org.jpedal.objects.javascript.defaultactions.DisplayJavascriptActions;
import org.jpedal.objects.javascript.defaultactions.JpedalDefaultJavascript;
import org.jpedal.objects.layers.Layer;
import org.jpedal.objects.layers.PdfLayerList;
import org.jpedal.utils.LogWriter;
import org.jpedal.utils.StringUtils;
import javax.swing.*;
import org.jpedal.objects.raw.PdfDictionary;
public class RhinoParser extends DefaultParser implements ExpressionEngine{
/** version details of our library, so javascript knows what it can do,
* also adds static adobe methods to javascript for execution if called
*/
private static final String viewerSettings = AformDefaultJSscript.getViewerSettings()+
AformDefaultJSscript.getstaticScript();
private org.mozilla.javascript.Context cx;
private org.mozilla.javascript.Scriptable scope;
private String functions="";
/** used to stop the thread that called execute from returning
* before the javascript has been executed on the correct thread.
*/
private boolean javascriptRunning;
private final Javascript JSObj;
public RhinoParser(final Javascript js) {
JSObj = js;
}
/** make sure the contaxt has been exited */
@Override
public void flush() {
if(acro!=null && acro.getFormFactory()!=null){
if (SwingUtilities.isEventDispatchThread()){
flushJS();
}else {
final Runnable doPaintComponent = new Runnable() {
@Override
public void run() {
flushJS();
}
};
try {
SwingUtilities.invokeAndWait(doPaintComponent);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
}
/** should only be called from our Thread code and not by any other access, as it wont work properly */
public void flushJS(){
//clear the stored functions when moving between files
functions="";
// Make sure we exit the current context
if (cx != null){
// The context could be in a different thread,
// we need to check for this and exit in a set way.
try{
org.mozilla.javascript.Context.exit();
// remembering to reset cx to null so that we recreate the contaxt for the next file
cx = null;
}catch(final IllegalStateException e){
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
/** NOT TO BE USED, is a dummy method for HTML only, WILL BE DELETED ONE DAY */
public void setJavaScriptEnded(){
javascriptRunning = false;
}
/**
* store and execute code
*/
public void executeFunctions(final String code, final FormObject ref, final AcroRenderer acro) {
//set to false at end of executeJS method
javascriptRunning=true;
if(acro.getFormFactory().getType()== FormFactory.SWING){
if (SwingUtilities.isEventDispatchThread()){
executeJS( code, ref, acro);
}else {
final Runnable doPaintComponent = new Runnable() {
@Override
public void run() {
executeJS( code, ref, acro);
}
};
try {
SwingUtilities.invokeAndWait(doPaintComponent);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
while(javascriptRunning){
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
}
/** should only be called from our Thread code and not by any other access, as it wont work properly */
public void executeJS(String code, final FormObject ref, final AcroRenderer acro) {
final String defSetCode;
//NOTE - keep everything inside thr try, catch, finally, as the finally tidy's up so that the code will return properly.
try {
//if we have no code dont do anything
if(code.isEmpty() && functions.isEmpty()) {
return;
}
//check if any functions defined in code and save
String func = "";
int index1 = code.indexOf("function ");
while(index1!=-1){//if we have functions
int i = index1+8, bracket=0;
char chr = code.charAt(i);
while(true){//find the whole function
if(chr=='{'){
bracket++;
}
if(chr=='}'){
bracket--;
if(bracket==0) {
break;
}
}
//remember to get next char before looping again
chr = code.charAt(i++);
}
//find beginning of line for start
int indR = code.lastIndexOf('\r', index1);
int indN = code.lastIndexOf('\n', index1);
final int indS = ((indN<indR) ? indR : indN)+1;
//find end of line for end
indR = code.indexOf('\r', i);
if(indR==-1) {
indR = code.length();
}
indN = code.indexOf('\n', i);
if(indN==-1) {
indN = code.length();
}
final int indE = ((indN<indR) ? indN : indR)+1;
//store the function and remove from main code
func += code.substring(indS, indE);
code = code.substring(0,indS)+code.substring(indE);
//remember to check for another function before looping again
index1 = code.indexOf("function ");
}
if(!func.isEmpty()){
addCode(func);
}
code = preParseCode(code);
//code = checkAndAddParentToKids(code,acro);
// Creates and enters a Context. The Context stores information
// about the execution environment of a script.
if(cx==null){
cx = org.mozilla.javascript.Context.enter();
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. Returns
// a scope object that we use in later calls.
scope = cx.initStandardObjects();
// add std objects, ie- access to fields, layers, default functions
addStdObject(acro);
}
// add this formobject to rhino
if(ref!=null){
//if flag true then it will always return a PdfProxy
//PdfProxy proxy = (PdfProxy)acro.getField(ref.getObjectRefAsString()/*TextStreamValue(PdfDictionary.T)*/);
final String name=ref.getTextStreamValue(PdfDictionary.T);
//added to Rhino
// add the current form object by name and by event, as this is the calling object
final Object formObj = org.mozilla.javascript.Context.javaToJS(new PDF2JS(ref), scope );
org.mozilla.javascript.ScriptableObject.putProperty( scope, "event", formObj );
//by its name ( maybe not needed)
if(name!=null) //stops crash on layers/houseplan final
{
org.mozilla.javascript.ScriptableObject.putProperty(scope, name, formObj);
}
}
//execute functions and add them to rhino
//added seperate as allows for easier debugging of main code.
// defSetCode = checkAndAddParentToKids(viewerSettings+functions,acro);
defSetCode = viewerSettings+functions;
cx.evaluateString(scope, defSetCode, "<JS viewer Settings>", 1, null);
// Now evaluate the string we've collected.
cx.evaluateString(scope, code, "<javascript>", 1, null);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}finally{
//sync any changes made in Layers (we need to get as method static at moment)
final PdfLayerList layersObj=acro.getActionHandler().getLayerHandler();
if(layersObj!=null && layersObj.getChangesMade()){
if(Layer.debugLayer) {
System.out.println("changed");
}
try {
//if we call decode page, i'm pritty sure we will recall the layers code, as we would recall all the JS
//hence the infinate loop
acro.getActionHandler().getPDFDecoder().decodePage(-1);
//@fixme
//final org.jpedal.gui.GUIFactory swingGUI=((org.jpedal.examples.viewer.gui.SwingGUI)acro.getActionHandler().getPDFDecoder().getExternalHandler(Options.GUIContainer));
// if(swingGUI!=null) {
// swingGUI.rescanPdfLayers();
//}
//repaint pdf decoder to make sure the layers are repainted
//((org.jpedal.PdfDecoder)acro.getActionHandler().getPDFDecoder()).repaint();//good idea mark
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
//run through all forms and see if they have changed
//acro.updateChangedForms();
//always set the javascript flag to false so that the execute calling thread can resume from its endless loop.
javascriptRunning = false;
}
}
/** replace javascript variables with our own so rhino can easily identify them and pass excution over to us */
private static String preParseCode(String script) {
final String[] searchFor = {"= (\"%.2f\",","this.ADBE"," getField(","\ngetField(","\rgetField(",
"(getField(","this.getField(","this.resetForm(","this.pageNum"," this.getOCGs(","\nthis.getOCGs(",
"\rthis.getOCGs("," getOCGs(","\ngetOCGs(","\rgetOCGs(",".state="};
final String[] replaceWith = {"= util.z(\"%.2f\",","ADBE"," acro.getField(","\nacro.getField(","\racro.getField(",
"(acro.getField(","acro.getField(","acro.resetForm(","acro.pageNum"," layers.getOCGs(","\nlayers.getOCGs(",
"\rlayers.getOCGs("," layers.getOCGs(","\nlayers.getOCGs(","\rlayers.getOCGs(","\rlayers.getOCGs("};
for(int i=0;i<searchFor.length;i++){
script = checkAndReplaceCode(searchFor[i], replaceWith[i], script);
}
//check for printf and put all argumants into an array and call with array
final int indexs = script.indexOf("printf");
printf:
if(indexs!=-1){
final StringBuilder buf = new StringBuilder();
int indexStart = script.lastIndexOf(';', indexs);
final int indextmp = script.lastIndexOf('{',indexs);
if(indexStart==-1 || (indextmp!=-1 && indextmp>indexStart)) {
indexStart = indextmp;
}
buf.append(script.substring(0,indexStart+1));
//find the end of the string
int speech = script.indexOf('\"',indexs);
speech = script.indexOf('\"',speech+1);
while(script.charAt(speech-1)=='\\') {
speech = script.indexOf('\"', speech);
}
//make sure there is an argument ',' after it
final int startArgs = script.indexOf(',',speech);
final int endArgs = script.indexOf(')',startArgs);
//setup arguments string so we can setup in javascript
final String arguments = script.substring(startArgs+1, endArgs);
if(arguments.equals("printfArgs")) {
break printf;
}
final StringTokenizer tok = new StringTokenizer(arguments,", ");
//create array in javascript code
buf.append("var printfArgs=new Array();\n");
//add arguments to the array
int i=0;
while(tok.hasMoreTokens()){
buf.append("printfArgs[");
buf.append(i++);
buf.append("]=");
buf.append(tok.nextToken());
buf.append(";\n");
}
//add printf command with new array as argument
buf.append(script.substring(indexStart+1, startArgs+1));
buf.append("printfArgs");
buf.append(script.substring(endArgs));
script = buf.toString();
}
script = checkAndReplaceCode("event.value=AFMakeNumber(acro.getField(\"sum\").value)(8)","", script);
script = checkAndReplaceCode("calculate = false", "calculate = 0", script);
script = checkAndReplaceCode("calculate = true", "calculate = 1", script);
script = checkAndReplaceCode("calculate=false", "calculate=0", script);
script = checkAndReplaceCode("calculate=true", "calculate=1", script);
return script;
}
// private static String checkAndAddParentToKids(String script, AcroRenderer acro){
//
// String startCode = "acro.getField(\"";
// //find start of GetField statement
// int startIndex = script.indexOf(startCode);
// if(startIndex!=-1){
// int startNameInd = startIndex+15;
// int endNameInd = script.indexOf("\")", startIndex);
// int endIndex = script.indexOf(';', startIndex)+1;
//
// //get the name its calling
// String name = script.substring(startNameInd, endNameInd);
// //if it ends with a . then we have to replace with all kids.
// if(name.endsWith(".")){
//
// //removed by Mark 16042013
// String[] allFieldNames = acro.getChildNames(name);
//
// // add start of script
// StringBuilder buf = new StringBuilder();
// buf.append(script.substring(0,startIndex));
//
// // add modified script with all fieldnames
// for (int j = 0; j < allFieldNames.length; j++) {
// if(j>0)
// buf.append('\n');
// buf.append(startCode);
// buf.append(allFieldNames[j]);
// buf.append(script.substring(endNameInd,endIndex));
// }
//
// // add end of script
// buf.append(script.substring(endIndex,script.length()));
// script = buf.toString();
// }
// }
// return script;
// }
/** replace the searchFor string with the replaceWith string within the code specified */
private static String checkAndReplaceCode(final String searchFor, final String replaceWith,String script) {
final int index = script.indexOf(searchFor);
if(index!=-1){
final StringBuilder buf = new StringBuilder(script.length());
buf.append(script.substring(0, index));
buf.append(replaceWith);
buf.append(checkAndReplaceCode(searchFor, replaceWith, script.substring(index+searchFor.length(),script.length())));
script = buf.toString();
}
return script;
}
/** add the javascript standard execution objects, that acrobat app has defined functions for. */
private void addStdObject(final AcroRenderer acro) {
Object objToJS = org.mozilla.javascript.Context.javaToJS( new JpedalDefaultJavascript(scope,cx), scope );
//util added for jpedal use ONLY
org.mozilla.javascript.ScriptableObject.putProperty( scope, "util", objToJS );
// app added so that methods difined within adobes javascript can be implemented
org.mozilla.javascript.ScriptableObject.putProperty( scope, "app", objToJS );
final Object globalObj = cx.newObject(scope);
//global is added to allow javascript to define and create its own variables
org.mozilla.javascript.ScriptableObject.putProperty( scope, "global", globalObj );
final Object ADBE = cx.newObject(scope);
//global is added to allow javascript to define and create its own variables
org.mozilla.javascript.ScriptableObject.putProperty( scope, "ADBE", ADBE );
objToJS = org.mozilla.javascript.Context.javaToJS( new DisplayJavascriptActions(), scope );
// display adds constant definitions of values
org.mozilla.javascript.ScriptableObject.putProperty( scope, "display", objToJS );
// color adds default constant colors.
org.mozilla.javascript.ScriptableObject.putProperty( scope, "color", objToJS );
// add layers to rhino
final PdfLayerList layerList = acro.getActionHandler().getLayerHandler();
if(layerList!=null){
objToJS = org.mozilla.javascript.Context.javaToJS( layerList, scope );
//not working yet.
org.mozilla.javascript.ScriptableObject.putProperty( scope, "layers", objToJS );//CHRIS @javascript
}
// add a wrapper for accessing the forms etc
objToJS = org.mozilla.javascript.Context.javaToJS( acro, scope );
//acro added to replace 'this' and to allow access to form objects via the acroRenderer
org.mozilla.javascript.ScriptableObject.putProperty( scope, "acro", objToJS );
}
/** add functions to the javascript code to be executed within rhino */
@Override
public int addCode(final String value) {
functions += preParseCode(value);
return 0;
}
/** typeToReturn
* 0 = String,
* 1 = Double,
* -1 = guess
*/
public Object generateJStype(final String textString, final boolean returnAsString){
if(returnAsString){
return cx.newObject(scope, "String", new Object[] { textString });
}else {
if(textString!=null && !textString.isEmpty() && StringUtils.isNumber(textString) &&
!(textString.length()==1 && textString.indexOf('.')!=-1)){//to stop double trying to figure out "."
final Double retNum = Double.valueOf(textString);
return cx.newObject(scope, "Number", new Object[] { retNum });
}else {
return cx.newObject(scope, "String", new Object[] { textString });
}
}
}
/**
* execute javascript and reset forms values
*/
@Override
public int execute(final FormObject form, final int type, final Object code, final int eventType, final char keyPressed) {
int messageCode;
final String js = (String) code;
//convert into args array
final String[] args= JSFunction.convertToArray(js);
final String command=args[0];
if(command.startsWith("AF")) {
messageCode = handleAFCommands(form, command, js, args, eventType, keyPressed);
} else {
executeFunctions(js, form, acro);
messageCode = ActionHandler.VALUESCHANGED;
}
if(type == PdfDictionary.F) {
calcualteEvent();
messageCode = ActionHandler.VALUESCHANGED;
}
return messageCode;
}
private void calcualteEvent() {
// System.out.println("CALC");
final List<FormObject> obs = acro.getCompData().getFormComponents(null, ReturnValues.FORMOBJECTS_FROM_REF, -1);
final Object[] formObjects = obs.toArray();
for(final Object o : formObjects) {
final FormObject formObject = (FormObject) o;
final String ref = formObject.getObjectRefAsString();
final String name = formObject.getTextStreamValue(PdfDictionary.T);
final String command = (String) JSObj.getJavascriptCommand( (name != null ? name : ref), PdfDictionary.C2);
if(command != null) {
// System.out.println(command);
execute(formObject, PdfDictionary.C2, command, ActionHandler.FOCUS_EVENT, ' ');
}
}
}
} | zieglerm/maven-OpenViewerFX-src | OpenViewerFX/src/main/java/org/jpedal/objects/javascript/RhinoParser.java | 5,331 | // for (int j = 0; j < allFieldNames.length; j++) { | line_comment | nl | /*
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.idrsolutions.com
* Help section for developers at http://www.idrsolutions.com/support/
*
* (C) Copyright 1997-2016 IDRsolutions and Contributors.
*
* This file is part of JPedal/JPDF2HTML5
*
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
*
* ---------------
* RhinoParser.java
* ---------------
*/
package org.jpedal.objects.javascript;
import java.util.List;
import java.util.StringTokenizer;
import org.jpedal.objects.Javascript;
import org.jpedal.objects.acroforms.ReturnValues;
import org.jpedal.objects.acroforms.actions.ActionHandler;
import org.jpedal.objects.acroforms.creation.FormFactory;
import org.jpedal.objects.javascript.functions.JSFunction;
import org.jpedal.objects.raw.FormObject;
import org.jpedal.objects.acroforms.AcroRenderer;
import org.jpedal.objects.javascript.defaultactions.DisplayJavascriptActions;
import org.jpedal.objects.javascript.defaultactions.JpedalDefaultJavascript;
import org.jpedal.objects.layers.Layer;
import org.jpedal.objects.layers.PdfLayerList;
import org.jpedal.utils.LogWriter;
import org.jpedal.utils.StringUtils;
import javax.swing.*;
import org.jpedal.objects.raw.PdfDictionary;
public class RhinoParser extends DefaultParser implements ExpressionEngine{
/** version details of our library, so javascript knows what it can do,
* also adds static adobe methods to javascript for execution if called
*/
private static final String viewerSettings = AformDefaultJSscript.getViewerSettings()+
AformDefaultJSscript.getstaticScript();
private org.mozilla.javascript.Context cx;
private org.mozilla.javascript.Scriptable scope;
private String functions="";
/** used to stop the thread that called execute from returning
* before the javascript has been executed on the correct thread.
*/
private boolean javascriptRunning;
private final Javascript JSObj;
public RhinoParser(final Javascript js) {
JSObj = js;
}
/** make sure the contaxt has been exited */
@Override
public void flush() {
if(acro!=null && acro.getFormFactory()!=null){
if (SwingUtilities.isEventDispatchThread()){
flushJS();
}else {
final Runnable doPaintComponent = new Runnable() {
@Override
public void run() {
flushJS();
}
};
try {
SwingUtilities.invokeAndWait(doPaintComponent);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
}
/** should only be called from our Thread code and not by any other access, as it wont work properly */
public void flushJS(){
//clear the stored functions when moving between files
functions="";
// Make sure we exit the current context
if (cx != null){
// The context could be in a different thread,
// we need to check for this and exit in a set way.
try{
org.mozilla.javascript.Context.exit();
// remembering to reset cx to null so that we recreate the contaxt for the next file
cx = null;
}catch(final IllegalStateException e){
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
/** NOT TO BE USED, is a dummy method for HTML only, WILL BE DELETED ONE DAY */
public void setJavaScriptEnded(){
javascriptRunning = false;
}
/**
* store and execute code
*/
public void executeFunctions(final String code, final FormObject ref, final AcroRenderer acro) {
//set to false at end of executeJS method
javascriptRunning=true;
if(acro.getFormFactory().getType()== FormFactory.SWING){
if (SwingUtilities.isEventDispatchThread()){
executeJS( code, ref, acro);
}else {
final Runnable doPaintComponent = new Runnable() {
@Override
public void run() {
executeJS( code, ref, acro);
}
};
try {
SwingUtilities.invokeAndWait(doPaintComponent);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
while(javascriptRunning){
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
}
}
/** should only be called from our Thread code and not by any other access, as it wont work properly */
public void executeJS(String code, final FormObject ref, final AcroRenderer acro) {
final String defSetCode;
//NOTE - keep everything inside thr try, catch, finally, as the finally tidy's up so that the code will return properly.
try {
//if we have no code dont do anything
if(code.isEmpty() && functions.isEmpty()) {
return;
}
//check if any functions defined in code and save
String func = "";
int index1 = code.indexOf("function ");
while(index1!=-1){//if we have functions
int i = index1+8, bracket=0;
char chr = code.charAt(i);
while(true){//find the whole function
if(chr=='{'){
bracket++;
}
if(chr=='}'){
bracket--;
if(bracket==0) {
break;
}
}
//remember to get next char before looping again
chr = code.charAt(i++);
}
//find beginning of line for start
int indR = code.lastIndexOf('\r', index1);
int indN = code.lastIndexOf('\n', index1);
final int indS = ((indN<indR) ? indR : indN)+1;
//find end of line for end
indR = code.indexOf('\r', i);
if(indR==-1) {
indR = code.length();
}
indN = code.indexOf('\n', i);
if(indN==-1) {
indN = code.length();
}
final int indE = ((indN<indR) ? indN : indR)+1;
//store the function and remove from main code
func += code.substring(indS, indE);
code = code.substring(0,indS)+code.substring(indE);
//remember to check for another function before looping again
index1 = code.indexOf("function ");
}
if(!func.isEmpty()){
addCode(func);
}
code = preParseCode(code);
//code = checkAndAddParentToKids(code,acro);
// Creates and enters a Context. The Context stores information
// about the execution environment of a script.
if(cx==null){
cx = org.mozilla.javascript.Context.enter();
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. Returns
// a scope object that we use in later calls.
scope = cx.initStandardObjects();
// add std objects, ie- access to fields, layers, default functions
addStdObject(acro);
}
// add this formobject to rhino
if(ref!=null){
//if flag true then it will always return a PdfProxy
//PdfProxy proxy = (PdfProxy)acro.getField(ref.getObjectRefAsString()/*TextStreamValue(PdfDictionary.T)*/);
final String name=ref.getTextStreamValue(PdfDictionary.T);
//added to Rhino
// add the current form object by name and by event, as this is the calling object
final Object formObj = org.mozilla.javascript.Context.javaToJS(new PDF2JS(ref), scope );
org.mozilla.javascript.ScriptableObject.putProperty( scope, "event", formObj );
//by its name ( maybe not needed)
if(name!=null) //stops crash on layers/houseplan final
{
org.mozilla.javascript.ScriptableObject.putProperty(scope, name, formObj);
}
}
//execute functions and add them to rhino
//added seperate as allows for easier debugging of main code.
// defSetCode = checkAndAddParentToKids(viewerSettings+functions,acro);
defSetCode = viewerSettings+functions;
cx.evaluateString(scope, defSetCode, "<JS viewer Settings>", 1, null);
// Now evaluate the string we've collected.
cx.evaluateString(scope, code, "<javascript>", 1, null);
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}finally{
//sync any changes made in Layers (we need to get as method static at moment)
final PdfLayerList layersObj=acro.getActionHandler().getLayerHandler();
if(layersObj!=null && layersObj.getChangesMade()){
if(Layer.debugLayer) {
System.out.println("changed");
}
try {
//if we call decode page, i'm pritty sure we will recall the layers code, as we would recall all the JS
//hence the infinate loop
acro.getActionHandler().getPDFDecoder().decodePage(-1);
//@fixme
//final org.jpedal.gui.GUIFactory swingGUI=((org.jpedal.examples.viewer.gui.SwingGUI)acro.getActionHandler().getPDFDecoder().getExternalHandler(Options.GUIContainer));
// if(swingGUI!=null) {
// swingGUI.rescanPdfLayers();
//}
//repaint pdf decoder to make sure the layers are repainted
//((org.jpedal.PdfDecoder)acro.getActionHandler().getPDFDecoder()).repaint();//good idea mark
} catch (final Exception e) {
LogWriter.writeLog("Exception: " + e.getMessage());
}
}
//run through all forms and see if they have changed
//acro.updateChangedForms();
//always set the javascript flag to false so that the execute calling thread can resume from its endless loop.
javascriptRunning = false;
}
}
/** replace javascript variables with our own so rhino can easily identify them and pass excution over to us */
private static String preParseCode(String script) {
final String[] searchFor = {"= (\"%.2f\",","this.ADBE"," getField(","\ngetField(","\rgetField(",
"(getField(","this.getField(","this.resetForm(","this.pageNum"," this.getOCGs(","\nthis.getOCGs(",
"\rthis.getOCGs("," getOCGs(","\ngetOCGs(","\rgetOCGs(",".state="};
final String[] replaceWith = {"= util.z(\"%.2f\",","ADBE"," acro.getField(","\nacro.getField(","\racro.getField(",
"(acro.getField(","acro.getField(","acro.resetForm(","acro.pageNum"," layers.getOCGs(","\nlayers.getOCGs(",
"\rlayers.getOCGs("," layers.getOCGs(","\nlayers.getOCGs(","\rlayers.getOCGs(","\rlayers.getOCGs("};
for(int i=0;i<searchFor.length;i++){
script = checkAndReplaceCode(searchFor[i], replaceWith[i], script);
}
//check for printf and put all argumants into an array and call with array
final int indexs = script.indexOf("printf");
printf:
if(indexs!=-1){
final StringBuilder buf = new StringBuilder();
int indexStart = script.lastIndexOf(';', indexs);
final int indextmp = script.lastIndexOf('{',indexs);
if(indexStart==-1 || (indextmp!=-1 && indextmp>indexStart)) {
indexStart = indextmp;
}
buf.append(script.substring(0,indexStart+1));
//find the end of the string
int speech = script.indexOf('\"',indexs);
speech = script.indexOf('\"',speech+1);
while(script.charAt(speech-1)=='\\') {
speech = script.indexOf('\"', speech);
}
//make sure there is an argument ',' after it
final int startArgs = script.indexOf(',',speech);
final int endArgs = script.indexOf(')',startArgs);
//setup arguments string so we can setup in javascript
final String arguments = script.substring(startArgs+1, endArgs);
if(arguments.equals("printfArgs")) {
break printf;
}
final StringTokenizer tok = new StringTokenizer(arguments,", ");
//create array in javascript code
buf.append("var printfArgs=new Array();\n");
//add arguments to the array
int i=0;
while(tok.hasMoreTokens()){
buf.append("printfArgs[");
buf.append(i++);
buf.append("]=");
buf.append(tok.nextToken());
buf.append(";\n");
}
//add printf command with new array as argument
buf.append(script.substring(indexStart+1, startArgs+1));
buf.append("printfArgs");
buf.append(script.substring(endArgs));
script = buf.toString();
}
script = checkAndReplaceCode("event.value=AFMakeNumber(acro.getField(\"sum\").value)(8)","", script);
script = checkAndReplaceCode("calculate = false", "calculate = 0", script);
script = checkAndReplaceCode("calculate = true", "calculate = 1", script);
script = checkAndReplaceCode("calculate=false", "calculate=0", script);
script = checkAndReplaceCode("calculate=true", "calculate=1", script);
return script;
}
// private static String checkAndAddParentToKids(String script, AcroRenderer acro){
//
// String startCode = "acro.getField(\"";
// //find start of GetField statement
// int startIndex = script.indexOf(startCode);
// if(startIndex!=-1){
// int startNameInd = startIndex+15;
// int endNameInd = script.indexOf("\")", startIndex);
// int endIndex = script.indexOf(';', startIndex)+1;
//
// //get the name its calling
// String name = script.substring(startNameInd, endNameInd);
// //if it ends with a . then we have to replace with all kids.
// if(name.endsWith(".")){
//
// //removed by Mark 16042013
// String[] allFieldNames = acro.getChildNames(name);
//
// // add start of script
// StringBuilder buf = new StringBuilder();
// buf.append(script.substring(0,startIndex));
//
// // add modified script with all fieldnames
// for (int<SUF>
// if(j>0)
// buf.append('\n');
// buf.append(startCode);
// buf.append(allFieldNames[j]);
// buf.append(script.substring(endNameInd,endIndex));
// }
//
// // add end of script
// buf.append(script.substring(endIndex,script.length()));
// script = buf.toString();
// }
// }
// return script;
// }
/** replace the searchFor string with the replaceWith string within the code specified */
private static String checkAndReplaceCode(final String searchFor, final String replaceWith,String script) {
final int index = script.indexOf(searchFor);
if(index!=-1){
final StringBuilder buf = new StringBuilder(script.length());
buf.append(script.substring(0, index));
buf.append(replaceWith);
buf.append(checkAndReplaceCode(searchFor, replaceWith, script.substring(index+searchFor.length(),script.length())));
script = buf.toString();
}
return script;
}
/** add the javascript standard execution objects, that acrobat app has defined functions for. */
private void addStdObject(final AcroRenderer acro) {
Object objToJS = org.mozilla.javascript.Context.javaToJS( new JpedalDefaultJavascript(scope,cx), scope );
//util added for jpedal use ONLY
org.mozilla.javascript.ScriptableObject.putProperty( scope, "util", objToJS );
// app added so that methods difined within adobes javascript can be implemented
org.mozilla.javascript.ScriptableObject.putProperty( scope, "app", objToJS );
final Object globalObj = cx.newObject(scope);
//global is added to allow javascript to define and create its own variables
org.mozilla.javascript.ScriptableObject.putProperty( scope, "global", globalObj );
final Object ADBE = cx.newObject(scope);
//global is added to allow javascript to define and create its own variables
org.mozilla.javascript.ScriptableObject.putProperty( scope, "ADBE", ADBE );
objToJS = org.mozilla.javascript.Context.javaToJS( new DisplayJavascriptActions(), scope );
// display adds constant definitions of values
org.mozilla.javascript.ScriptableObject.putProperty( scope, "display", objToJS );
// color adds default constant colors.
org.mozilla.javascript.ScriptableObject.putProperty( scope, "color", objToJS );
// add layers to rhino
final PdfLayerList layerList = acro.getActionHandler().getLayerHandler();
if(layerList!=null){
objToJS = org.mozilla.javascript.Context.javaToJS( layerList, scope );
//not working yet.
org.mozilla.javascript.ScriptableObject.putProperty( scope, "layers", objToJS );//CHRIS @javascript
}
// add a wrapper for accessing the forms etc
objToJS = org.mozilla.javascript.Context.javaToJS( acro, scope );
//acro added to replace 'this' and to allow access to form objects via the acroRenderer
org.mozilla.javascript.ScriptableObject.putProperty( scope, "acro", objToJS );
}
/** add functions to the javascript code to be executed within rhino */
@Override
public int addCode(final String value) {
functions += preParseCode(value);
return 0;
}
/** typeToReturn
* 0 = String,
* 1 = Double,
* -1 = guess
*/
public Object generateJStype(final String textString, final boolean returnAsString){
if(returnAsString){
return cx.newObject(scope, "String", new Object[] { textString });
}else {
if(textString!=null && !textString.isEmpty() && StringUtils.isNumber(textString) &&
!(textString.length()==1 && textString.indexOf('.')!=-1)){//to stop double trying to figure out "."
final Double retNum = Double.valueOf(textString);
return cx.newObject(scope, "Number", new Object[] { retNum });
}else {
return cx.newObject(scope, "String", new Object[] { textString });
}
}
}
/**
* execute javascript and reset forms values
*/
@Override
public int execute(final FormObject form, final int type, final Object code, final int eventType, final char keyPressed) {
int messageCode;
final String js = (String) code;
//convert into args array
final String[] args= JSFunction.convertToArray(js);
final String command=args[0];
if(command.startsWith("AF")) {
messageCode = handleAFCommands(form, command, js, args, eventType, keyPressed);
} else {
executeFunctions(js, form, acro);
messageCode = ActionHandler.VALUESCHANGED;
}
if(type == PdfDictionary.F) {
calcualteEvent();
messageCode = ActionHandler.VALUESCHANGED;
}
return messageCode;
}
private void calcualteEvent() {
// System.out.println("CALC");
final List<FormObject> obs = acro.getCompData().getFormComponents(null, ReturnValues.FORMOBJECTS_FROM_REF, -1);
final Object[] formObjects = obs.toArray();
for(final Object o : formObjects) {
final FormObject formObject = (FormObject) o;
final String ref = formObject.getObjectRefAsString();
final String name = formObject.getTextStreamValue(PdfDictionary.T);
final String command = (String) JSObj.getJavascriptCommand( (name != null ? name : ref), PdfDictionary.C2);
if(command != null) {
// System.out.println(command);
execute(formObject, PdfDictionary.C2, command, ActionHandler.FOCUS_EVENT, ' ');
}
}
}
} |
58855_16 | package be.intecbrussel;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class Opdrachten {
public static void main(String[] args) {
System.out.println("---- Opdracht 1 - Random integers ----" + "\n");
// - Maak een Random generator en vraag verschillende integers op.
// - Zorg ervoor dat je alleen maar getallen kunt genereren tussen 0 en 99.
// - Maak nu een applicatie die maar 6 getallen opvraagt.
Random random = new Random();
int maxRandomNum = 0;
while (maxRandomNum < 6) {
int randomNumber = random.nextInt(100);
maxRandomNum++;
System.out.println("Random number: " + randomNumber + "\n");
}
// Opdracht 2
// Zelfstudie
System.out.println("---- Opdracht 3 ----" + "\n");
// - Maak een nieuwe Scanner die een String opvraagt.
Scanner scanner = new Scanner(System.in);
System.out.println("Schrijf een word!");
String answer1 = scanner.nextLine().toLowerCase();
// - druk de tekst af in grote letters
String upperCase = answer1.toUpperCase();
System.out.println("Grote letters: " + upperCase + "\n");
// - druk de tekst af in kleine letters
String lowerCase = answer1.toLowerCase();
System.out.println("Kleine letters: " + lowerCase + "\n");
// - Vervang alle ‘e’ door ‘u’
String replacedLetters = answer1.replaceAll("e", "u");
if (answer1.contains("e")) {
System.out.println("Alle letters 'e' vervangen door 'u' = " + replacedLetters + "\n");
} else {
System.out.println("Geen letters (e) gevonden in het word " + answer1 + "\n");
}
// - Druk af hoeveel keer de letter ‘r’ in je String voorkomt
int count = 0;
for (int i = 0; i < answer1.length(); i++ ) {
if (answer1.charAt(i) == 'r') {
count++;
}
}
if (answer1.contains("r")) {
System.out.println("De letter r is " + count + " keer voor gekomen bij het word " + answer1.toLowerCase() + "." + "\n");
} else {
System.out.println("Geen letters (r) gevonden in het word " + answer1 + "\n");
}
// - Maak twee strings en vergelijk ze met elkaar met een String methode.
String string1 = "Tekst";
String string2 = "tekst";
boolean comparison = string1.equalsIgnoreCase(string2);
if (comparison) {
System.out.println("Het word " + string1 + " is gelijk aan het word " + string2 + "\n");
} else {
System.out.println("Het word " + string1 + " is niet gelijk aan aan het word " + string2 + "\n");
}
// - Vergelijk twee Strings alfabetisch, en druk ze allebei af. De String die eerst alfabetisch komt, moet eerst afgedrukt worden.
String string3 = "zebra";
String string4 = "aap";
int firstCodePoint = string3.codePointAt(0);
int secondCodePoint = string4.codePointAt(0);
System.out.println("Strings op alfabetisch volgorde -> 1ste manier " + "\n");
if (firstCodePoint < secondCodePoint) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// Of
int compareResult = string3.compareToIgnoreCase(string4);
System.out.println("Strings op alfabetisch volgorde -> 2de manier " + "\n");
if (compareResult < 0) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// - Maak een string met extra spaties vooraan en achteraan. Druk de string dan af zonder de spaties.
String string5 = " Hello, my name is Gabriel ";
System.out.println("String met spaties: " + "\n" + string5 + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.strip() + " 'met strip()'" + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.trim() + " 'met trim()'" + "\n");
System.out.println("---- Opdracht 4 ----" + "\n");
// - Maak een programma dat twee Strings opvraagt met StringBuilder
System.out.println("Schrijf eerste string");
String input1 = scanner.nextLine();
System.out.println("Schrijf tweede string");
String input2 = scanner.nextLine();
StringBuilder sb1 = new StringBuilder(input1);
StringBuilder sb2 = new StringBuilder(input2);
// - Voeg extra tekst toe aan de eerste StringBuilder
sb1.append(" -> extra text");
System.out.println("1ste StringBuilder met extra tekst: " + sb1 + "\n");
// - Draai de tekst van de 2de StringBuilder om
sb2.reverse();
System.out.println("Tekst van 2de StringBuilder omgedraaid: " + sb2 + "\n");
// - Verwijder alle spaties van de eerste StringBuilder
int i = 0;
while (i < sb1.length()) {
if (sb1.charAt(i) == ' ') {
sb1.deleteCharAt(i);
} else {
i++;
}
}
System.out.println("1ste StringBuilder zonder spaties -> " + sb1 + "\n");
// - Verdubbel iedere letter 't' in de tweede StringBuilder
i = 0;
while (i < sb2.length()) {
if (sb2.charAt(i) == 't') {
sb2.insert(i + 1, 't');
i += 2;
} else {
i++;
}
}
System.out.println("2de StringBuilder met verdubbelde 't': " + sb2 + "\n");
// - Verwijder bij de tweede StringBuilder 2 worden
int firstSpace = sb2.indexOf(" ");
int secondSpace = sb2.indexOf(" ", firstSpace + 1);
sb2.delete(0, secondSpace + 1);
System.out.println("2de StringBuilder zonder 2 woorden: " + sb2 + "\n");
System.out.println("---- Opdracht - 5 ----" + "\n");
// - Maak een programma dat de eenheid ‘meter’ omzet naar de eenheid ‘voet’.
// Toon de waarden van 1 meter tot en met 20 meter (je doet telkens +0.5meter).
// Je mag maar twee cijfers na de komma hebben, en alle getallen moeten mooi naast elkaar gaan.
// Je gaat hier formatting voor moeten gebruiken.
for (double meter = 1.0; meter <= 20.0; meter += 0.5) {
double feet = meter * 3.28;
System.out.println(String.format("%,.2f", meter) + " meter" + " = " + String.format("%,.2f", feet) + " feet" + "\n");
}
}
}
| Gabe-Alvess/OopOpdracht | src/be/intecbrussel/Opdrachten.java | 1,864 | // - Verwijder bij de tweede StringBuilder 2 worden | line_comment | nl | package be.intecbrussel;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class Opdrachten {
public static void main(String[] args) {
System.out.println("---- Opdracht 1 - Random integers ----" + "\n");
// - Maak een Random generator en vraag verschillende integers op.
// - Zorg ervoor dat je alleen maar getallen kunt genereren tussen 0 en 99.
// - Maak nu een applicatie die maar 6 getallen opvraagt.
Random random = new Random();
int maxRandomNum = 0;
while (maxRandomNum < 6) {
int randomNumber = random.nextInt(100);
maxRandomNum++;
System.out.println("Random number: " + randomNumber + "\n");
}
// Opdracht 2
// Zelfstudie
System.out.println("---- Opdracht 3 ----" + "\n");
// - Maak een nieuwe Scanner die een String opvraagt.
Scanner scanner = new Scanner(System.in);
System.out.println("Schrijf een word!");
String answer1 = scanner.nextLine().toLowerCase();
// - druk de tekst af in grote letters
String upperCase = answer1.toUpperCase();
System.out.println("Grote letters: " + upperCase + "\n");
// - druk de tekst af in kleine letters
String lowerCase = answer1.toLowerCase();
System.out.println("Kleine letters: " + lowerCase + "\n");
// - Vervang alle ‘e’ door ‘u’
String replacedLetters = answer1.replaceAll("e", "u");
if (answer1.contains("e")) {
System.out.println("Alle letters 'e' vervangen door 'u' = " + replacedLetters + "\n");
} else {
System.out.println("Geen letters (e) gevonden in het word " + answer1 + "\n");
}
// - Druk af hoeveel keer de letter ‘r’ in je String voorkomt
int count = 0;
for (int i = 0; i < answer1.length(); i++ ) {
if (answer1.charAt(i) == 'r') {
count++;
}
}
if (answer1.contains("r")) {
System.out.println("De letter r is " + count + " keer voor gekomen bij het word " + answer1.toLowerCase() + "." + "\n");
} else {
System.out.println("Geen letters (r) gevonden in het word " + answer1 + "\n");
}
// - Maak twee strings en vergelijk ze met elkaar met een String methode.
String string1 = "Tekst";
String string2 = "tekst";
boolean comparison = string1.equalsIgnoreCase(string2);
if (comparison) {
System.out.println("Het word " + string1 + " is gelijk aan het word " + string2 + "\n");
} else {
System.out.println("Het word " + string1 + " is niet gelijk aan aan het word " + string2 + "\n");
}
// - Vergelijk twee Strings alfabetisch, en druk ze allebei af. De String die eerst alfabetisch komt, moet eerst afgedrukt worden.
String string3 = "zebra";
String string4 = "aap";
int firstCodePoint = string3.codePointAt(0);
int secondCodePoint = string4.codePointAt(0);
System.out.println("Strings op alfabetisch volgorde -> 1ste manier " + "\n");
if (firstCodePoint < secondCodePoint) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// Of
int compareResult = string3.compareToIgnoreCase(string4);
System.out.println("Strings op alfabetisch volgorde -> 2de manier " + "\n");
if (compareResult < 0) {
System.out.println(string3 + "\n" + string4 + "\n");
} else {
System.out.println(string4 + "\n" + string3 + "\n");
}
// - Maak een string met extra spaties vooraan en achteraan. Druk de string dan af zonder de spaties.
String string5 = " Hello, my name is Gabriel ";
System.out.println("String met spaties: " + "\n" + string5 + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.strip() + " 'met strip()'" + "\n");
System.out.println("String zonder spaties: " + "\n" + string5.trim() + " 'met trim()'" + "\n");
System.out.println("---- Opdracht 4 ----" + "\n");
// - Maak een programma dat twee Strings opvraagt met StringBuilder
System.out.println("Schrijf eerste string");
String input1 = scanner.nextLine();
System.out.println("Schrijf tweede string");
String input2 = scanner.nextLine();
StringBuilder sb1 = new StringBuilder(input1);
StringBuilder sb2 = new StringBuilder(input2);
// - Voeg extra tekst toe aan de eerste StringBuilder
sb1.append(" -> extra text");
System.out.println("1ste StringBuilder met extra tekst: " + sb1 + "\n");
// - Draai de tekst van de 2de StringBuilder om
sb2.reverse();
System.out.println("Tekst van 2de StringBuilder omgedraaid: " + sb2 + "\n");
// - Verwijder alle spaties van de eerste StringBuilder
int i = 0;
while (i < sb1.length()) {
if (sb1.charAt(i) == ' ') {
sb1.deleteCharAt(i);
} else {
i++;
}
}
System.out.println("1ste StringBuilder zonder spaties -> " + sb1 + "\n");
// - Verdubbel iedere letter 't' in de tweede StringBuilder
i = 0;
while (i < sb2.length()) {
if (sb2.charAt(i) == 't') {
sb2.insert(i + 1, 't');
i += 2;
} else {
i++;
}
}
System.out.println("2de StringBuilder met verdubbelde 't': " + sb2 + "\n");
// - Verwijder<SUF>
int firstSpace = sb2.indexOf(" ");
int secondSpace = sb2.indexOf(" ", firstSpace + 1);
sb2.delete(0, secondSpace + 1);
System.out.println("2de StringBuilder zonder 2 woorden: " + sb2 + "\n");
System.out.println("---- Opdracht - 5 ----" + "\n");
// - Maak een programma dat de eenheid ‘meter’ omzet naar de eenheid ‘voet’.
// Toon de waarden van 1 meter tot en met 20 meter (je doet telkens +0.5meter).
// Je mag maar twee cijfers na de komma hebben, en alle getallen moeten mooi naast elkaar gaan.
// Je gaat hier formatting voor moeten gebruiken.
for (double meter = 1.0; meter <= 20.0; meter += 0.5) {
double feet = meter * 3.28;
System.out.println(String.format("%,.2f", meter) + " meter" + " = " + String.format("%,.2f", feet) + " feet" + "\n");
}
}
}
|
184904_9 | /*******************************************************************************
* 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.ofbiz.entity.serialize;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilObject;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* XmlSerializer class. This class is deprecated - new code should use the
* Java object marshalling/unmarshalling methods in <code>UtilXml.java</code>.
*
*/
public class XmlSerializer {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static WeakReference<DateFormat> simpleDateFormatter;
public static String serialize(Object object) throws SerializeException, FileNotFoundException, IOException {
Document document = UtilXml.makeEmptyXmlDocument("ofbiz-ser");
Element rootElement = document.getDocumentElement();
rootElement.appendChild(serializeSingle(object, document));
return UtilXml.writeXmlDocument(document);
}
/** Deserialize a Java object from an XML string. <p>This method should be used with caution.
* If the XML string contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param content the content
* @param delegator the delegator
* @return return a deserialized object from XML string
* @throws SerializeException
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static Object deserialize(String content, Delegator delegator)
throws SerializeException, SAXException, ParserConfigurationException, IOException {
// readXmlDocument with false second parameter to disable validation
Document document = UtilXml.readXmlDocument(content, false);
if (document != null) {
if (!"ofbiz-ser".equals(document.getDocumentElement().getTagName())) {
return UtilXml.fromXml(content);
}
return deserialize(document, delegator);
} else {
Debug.logWarning("Serialized document came back null", module);
return null;
}
}
/** Deserialize a Java object from a DOM <code>Document</code>.
* <p>This method should be used with caution. If the DOM <code>Document</code>
* contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param document the document
* @param delegator the delegator
* @return returns a deserialized object from a DOM document
* @throws SerializeException
*/
public static Object deserialize(Document document, Delegator delegator) throws SerializeException {
Element rootElement = document.getDocumentElement();
// find the first element below the root element, that should be the object
Node curChild = rootElement.getFirstChild();
while (curChild != null && curChild.getNodeType() != Node.ELEMENT_NODE) {
curChild = curChild.getNextSibling();
}
if (curChild == null) {
return null;
}
return deserializeSingle((Element) curChild, delegator);
}
public static Element serializeSingle(Object object, Document document) throws SerializeException {
if (document == null) return null;
if (object == null) return makeElement("null", object, document);
// - Standard Objects -
if (object instanceof String) {
return makeElement("std-String", object, document);
} else if (object instanceof Integer) {
return makeElement("std-Integer", object, document);
} else if (object instanceof Long) {
return makeElement("std-Long", object, document);
} else if (object instanceof Float) {
return makeElement("std-Float", object, document);
} else if (object instanceof Double) {
return makeElement("std-Double", object, document);
} else if (object instanceof Boolean) {
return makeElement("std-Boolean", object, document);
} else if (object instanceof Locale) {
return makeElement("std-Locale", object, document);
} else if (object instanceof BigDecimal) {
String stringValue = ((BigDecimal) object).setScale(10, BigDecimal.ROUND_HALF_UP).toString();
return makeElement("std-BigDecimal", stringValue, document);
// - SQL Objects -
} else if (object instanceof java.sql.Timestamp) {
String stringValue = object.toString().replace(' ', 'T');
return makeElement("sql-Timestamp", stringValue, document);
} else if (object instanceof java.sql.Date) {
return makeElement("sql-Date", object, document);
} else if (object instanceof java.sql.Time) {
return makeElement("sql-Time", object, document);
} else if (object instanceof java.util.Date) {
// NOTE: make sure this is AFTER the java.sql date/time objects since they inherit from java.util.Date
DateFormat formatter = getDateFormat();
String stringValue = null;
synchronized (formatter) {
stringValue = formatter.format((java.util.Date) object);
}
return makeElement("std-Date", stringValue, document);
// return makeElement("std-Date", object, document);
} else if (object instanceof Collection<?>) {
// - Collections -
String elementName = null;
// these ARE order sensitive; for instance Stack extends Vector, so if Vector were first we would lose the stack part
if (object instanceof ArrayList<?>) {
elementName = "col-ArrayList";
} else if (object instanceof LinkedList<?>) {
elementName = "col-LinkedList";
} else if (object instanceof Stack<?>) {
elementName = "col-Stack";
} else if (object instanceof Vector<?>) {
elementName = "col-Vector";
} else if (object instanceof TreeSet<?>) {
elementName = "col-TreeSet";
} else if (object instanceof HashSet<?>) {
elementName = "col-HashSet";
} else {
// no specific type found, do general Collection, will deserialize as LinkedList
elementName = "col-Collection";
}
// if (elementName == null) return serializeCustom(object, document);
Collection<?> value = UtilGenerics.cast(object);
Element element = document.createElement(elementName);
Iterator<?> iter = value.iterator();
while (iter.hasNext()) {
element.appendChild(serializeSingle(iter.next(), document));
}
return element;
} else if (object instanceof GenericPK) {
// Do GenericEntity objects as a special case, use std XML import/export routines
GenericPK value = (GenericPK) object;
return value.makeXmlElement(document, "eepk-");
} else if (object instanceof GenericValue) {
GenericValue value = (GenericValue) object;
return value.makeXmlElement(document, "eeval-");
} else if (object instanceof Map<?, ?>) {
// - Maps -
String elementName = null;
// these ARE order sensitive; for instance Properties extends Hashtable, so if Hashtable were first we would lose the Properties part
if (object instanceof HashMap<?, ?>) {
elementName = "map-HashMap";
} else if (object instanceof Properties) {
elementName = "map-Properties";
} else if (object instanceof Hashtable<?, ?>) {
elementName = "map-Hashtable";
} else if (object instanceof WeakHashMap<?, ?>) {
elementName = "map-WeakHashMap";
} else if (object instanceof TreeMap<?, ?>) {
elementName = "map-TreeMap";
} else {
// serialize as a simple Map implementation if nothing else applies, these will deserialize as a HashMap
elementName = "map-Map";
}
Element element = document.createElement(elementName);
Map<?,?> value = UtilGenerics.cast(object);
Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
while (iter.hasNext()) {
Map.Entry<?,?> entry = iter.next();
Element entryElement = document.createElement("map-Entry");
element.appendChild(entryElement);
Element key = document.createElement("map-Key");
entryElement.appendChild(key);
key.appendChild(serializeSingle(entry.getKey(), document));
Element mapValue = document.createElement("map-Value");
entryElement.appendChild(mapValue);
mapValue.appendChild(serializeSingle(entry.getValue(), document));
}
return element;
}
return serializeCustom(object, document);
}
public static Element serializeCustom(Object object, Document document) throws SerializeException {
if (object instanceof Serializable) {
byte[] objBytes = UtilObject.getBytes(object);
if (objBytes == null) {
throw new SerializeException("Unable to serialize object; null byte array returned");
} else {
String byteHex = StringUtil.toHexString(objBytes);
Element element = document.createElement("cus-obj");
// this is hex encoded so does not need to be in a CDATA block
element.appendChild(document.createTextNode(byteHex));
return element;
}
} else {
throw new SerializeException("Cannot serialize object of class " + object.getClass().getName());
}
}
public static Element makeElement(String elementName, Object value, Document document) {
if (value == null) {
Element element = document.createElement("null");
element.setAttribute("xsi:nil", "true");
// I tried to put the schema in the envelope header (in createAndSendSOAPResponse)
// resEnv.declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null);
// But it gets prefixed and that does not work. So adding in each instance
element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
return element;
}
Element element = document.createElement(elementName);
element.setAttribute("value", value.toString());
return element;
}
public static Object deserializeSingle(Element element, Delegator delegator) throws SerializeException {
String tagName = element.getLocalName();
if (tagName.equals("null")) return null;
if (tagName.startsWith("std-")) {
// - Standard Objects -
if ("std-String".equals(tagName)) {
return element.getAttribute("value");
} else if ("std-Integer".equals(tagName)) {
String valStr = element.getAttribute("value");
return Integer.valueOf(valStr);
} else if ("std-Long".equals(tagName)) {
String valStr = element.getAttribute("value");
return Long.valueOf(valStr);
} else if ("std-Float".equals(tagName)) {
String valStr = element.getAttribute("value");
return Float.valueOf(valStr);
} else if ("std-Double".equals(tagName)) {
String valStr = element.getAttribute("value");
return Double.valueOf(valStr);
} else if ("std-BigDecimal".equals(tagName)) {
String valStr = element.getAttribute("value");
return new BigDecimal(valStr);
} else if ("std-Boolean".equals(tagName)) {
String valStr = element.getAttribute("value");
return Boolean.valueOf(valStr);
} else if ("std-Locale".equals(tagName)) {
String valStr = element.getAttribute("value");
return UtilMisc.parseLocale(valStr);
} else if ("std-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
DateFormat formatter = getDateFormat();
java.util.Date value = null;
try {
synchronized (formatter) {
value = formatter.parse(valStr);
}
} catch (ParseException e) {
throw new SerializeException("Could not parse date String: " + valStr, e);
}
return value;
}
} else if (tagName.startsWith("sql-")) {
// - SQL Objects -
if ("sql-Timestamp".equals(tagName)) {
String valStr = element.getAttribute("value");
/*
* sql-Timestamp is defined as xsd:dateTime in ModelService.getTypes(),
* so try to parse the value as xsd:dateTime first.
* Fallback is java.sql.Timestamp because it has been this way all the time.
*/
try {
Calendar cal = DatatypeConverter.parseDate(valStr);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
catch (Exception e) {
Debug.logWarning("sql-Timestamp does not conform to XML Schema definition, try java.sql.Timestamp format", module);
return java.sql.Timestamp.valueOf(valStr);
}
} else if ("sql-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Date.valueOf(valStr);
} else if ("sql-Time".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Time.valueOf(valStr);
}
} else if (tagName.startsWith("col-")) {
// - Collections -
Collection<Object> value = null;
if ("col-ArrayList".equals(tagName)) {
value = new ArrayList<Object>();
} else if ("col-LinkedList".equals(tagName)) {
value = new LinkedList<Object>();
} else if ("col-Stack".equals(tagName)) {
value = new Stack<Object>();
} else if ("col-Vector".equals(tagName)) {
value = new Vector<Object>();
} else if ("col-TreeSet".equals(tagName)) {
value = new TreeSet<Object>();
} else if ("col-HashSet".equals(tagName)) {
value = new HashSet<Object>();
} else if ("col-Collection".equals(tagName)) {
value = new LinkedList<Object>();
}
if (value == null) {
return deserializeCustom(element);
} else {
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
value.add(deserializeSingle((Element) curChild, delegator));
}
curChild = curChild.getNextSibling();
}
return value;
}
} else if (tagName.startsWith("map-")) {
// - Maps -
Map<Object, Object> value = null;
if ("map-HashMap".equals(tagName)) {
value = new HashMap<Object, Object>();
} else if ("map-Properties".equals(tagName)) {
value = new Properties();
} else if ("map-Hashtable".equals(tagName)) {
value = new Hashtable<Object, Object>();
} else if ("map-WeakHashMap".equals(tagName)) {
value = new WeakHashMap<Object, Object>();
} else if ("map-TreeMap".equals(tagName)) {
value = new TreeMap<Object, Object>();
} else if ("map-Map".equals(tagName)) {
value = new HashMap<Object, Object>();
}
if (value == null) {
return deserializeCustom(element);
} else {
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) curChild;
if ("map-Entry".equals(curElement.getLocalName())) {
Element mapKeyElement = UtilXml.firstChildElement(curElement, "map-Key");
Element keyElement = null;
Node tempNode = mapKeyElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
keyElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (keyElement == null) throw new SerializeException("Could not find an element under the map-Key");
Element mapValueElement = UtilXml.firstChildElement(curElement, "map-Value");
Element valueElement = null;
tempNode = mapValueElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
valueElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (valueElement == null) throw new SerializeException("Could not find an element under the map-Value");
value.put(deserializeSingle(keyElement, delegator), deserializeSingle(valueElement, delegator));
}
}
curChild = curChild.getNextSibling();
}
return value;
}
} else if (tagName.startsWith("eepk-")) {
return delegator.makePK(element);
} else if (tagName.startsWith("eeval-")) {
return delegator.makeValue(element);
}
return deserializeCustom(element);
}
public static Object deserializeCustom(Element element) throws SerializeException {
String tagName = element.getLocalName();
if ("cus-obj".equals(tagName)) {
String value = UtilXml.elementValue(element);
if (value != null) {
byte[] valueBytes = StringUtil.fromHexString(value);
if (valueBytes != null) {
Object obj = UtilObject.getObject(valueBytes);
if (obj != null) {
return obj;
}
}
}
throw new SerializeException("Problem deserializing object from byte array + " + element.getLocalName());
} else {
throw new SerializeException("Cannot deserialize element named " + element.getLocalName());
}
}
/**
* Returns the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
* This format is NOT used to format any of the java.sql subtypes of java.util.Date.
* A <code>WeakReference</code> is used to maintain a reference to the DateFormat object
* so that it can be created and garbage collected as needed.
*
* @return the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
*/
private static DateFormat getDateFormat() {
DateFormat formatter = null;
if (simpleDateFormatter != null) {
formatter = simpleDateFormatter.get();
}
if (formatter == null) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
simpleDateFormatter = new WeakReference<DateFormat>(formatter);
}
return formatter;
}
}
| eric-erki/scipio-erp | framework/entity/src/org/ofbiz/entity/serialize/XmlSerializer.java | 5,015 | // return makeElement("std-Date", object, document); | 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.ofbiz.entity.serialize;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilObject;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* XmlSerializer class. This class is deprecated - new code should use the
* Java object marshalling/unmarshalling methods in <code>UtilXml.java</code>.
*
*/
public class XmlSerializer {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static WeakReference<DateFormat> simpleDateFormatter;
public static String serialize(Object object) throws SerializeException, FileNotFoundException, IOException {
Document document = UtilXml.makeEmptyXmlDocument("ofbiz-ser");
Element rootElement = document.getDocumentElement();
rootElement.appendChild(serializeSingle(object, document));
return UtilXml.writeXmlDocument(document);
}
/** Deserialize a Java object from an XML string. <p>This method should be used with caution.
* If the XML string contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param content the content
* @param delegator the delegator
* @return return a deserialized object from XML string
* @throws SerializeException
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static Object deserialize(String content, Delegator delegator)
throws SerializeException, SAXException, ParserConfigurationException, IOException {
// readXmlDocument with false second parameter to disable validation
Document document = UtilXml.readXmlDocument(content, false);
if (document != null) {
if (!"ofbiz-ser".equals(document.getDocumentElement().getTagName())) {
return UtilXml.fromXml(content);
}
return deserialize(document, delegator);
} else {
Debug.logWarning("Serialized document came back null", module);
return null;
}
}
/** Deserialize a Java object from a DOM <code>Document</code>.
* <p>This method should be used with caution. If the DOM <code>Document</code>
* contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param document the document
* @param delegator the delegator
* @return returns a deserialized object from a DOM document
* @throws SerializeException
*/
public static Object deserialize(Document document, Delegator delegator) throws SerializeException {
Element rootElement = document.getDocumentElement();
// find the first element below the root element, that should be the object
Node curChild = rootElement.getFirstChild();
while (curChild != null && curChild.getNodeType() != Node.ELEMENT_NODE) {
curChild = curChild.getNextSibling();
}
if (curChild == null) {
return null;
}
return deserializeSingle((Element) curChild, delegator);
}
public static Element serializeSingle(Object object, Document document) throws SerializeException {
if (document == null) return null;
if (object == null) return makeElement("null", object, document);
// - Standard Objects -
if (object instanceof String) {
return makeElement("std-String", object, document);
} else if (object instanceof Integer) {
return makeElement("std-Integer", object, document);
} else if (object instanceof Long) {
return makeElement("std-Long", object, document);
} else if (object instanceof Float) {
return makeElement("std-Float", object, document);
} else if (object instanceof Double) {
return makeElement("std-Double", object, document);
} else if (object instanceof Boolean) {
return makeElement("std-Boolean", object, document);
} else if (object instanceof Locale) {
return makeElement("std-Locale", object, document);
} else if (object instanceof BigDecimal) {
String stringValue = ((BigDecimal) object).setScale(10, BigDecimal.ROUND_HALF_UP).toString();
return makeElement("std-BigDecimal", stringValue, document);
// - SQL Objects -
} else if (object instanceof java.sql.Timestamp) {
String stringValue = object.toString().replace(' ', 'T');
return makeElement("sql-Timestamp", stringValue, document);
} else if (object instanceof java.sql.Date) {
return makeElement("sql-Date", object, document);
} else if (object instanceof java.sql.Time) {
return makeElement("sql-Time", object, document);
} else if (object instanceof java.util.Date) {
// NOTE: make sure this is AFTER the java.sql date/time objects since they inherit from java.util.Date
DateFormat formatter = getDateFormat();
String stringValue = null;
synchronized (formatter) {
stringValue = formatter.format((java.util.Date) object);
}
return makeElement("std-Date", stringValue, document);
// return makeElement("std-Date",<SUF>
} else if (object instanceof Collection<?>) {
// - Collections -
String elementName = null;
// these ARE order sensitive; for instance Stack extends Vector, so if Vector were first we would lose the stack part
if (object instanceof ArrayList<?>) {
elementName = "col-ArrayList";
} else if (object instanceof LinkedList<?>) {
elementName = "col-LinkedList";
} else if (object instanceof Stack<?>) {
elementName = "col-Stack";
} else if (object instanceof Vector<?>) {
elementName = "col-Vector";
} else if (object instanceof TreeSet<?>) {
elementName = "col-TreeSet";
} else if (object instanceof HashSet<?>) {
elementName = "col-HashSet";
} else {
// no specific type found, do general Collection, will deserialize as LinkedList
elementName = "col-Collection";
}
// if (elementName == null) return serializeCustom(object, document);
Collection<?> value = UtilGenerics.cast(object);
Element element = document.createElement(elementName);
Iterator<?> iter = value.iterator();
while (iter.hasNext()) {
element.appendChild(serializeSingle(iter.next(), document));
}
return element;
} else if (object instanceof GenericPK) {
// Do GenericEntity objects as a special case, use std XML import/export routines
GenericPK value = (GenericPK) object;
return value.makeXmlElement(document, "eepk-");
} else if (object instanceof GenericValue) {
GenericValue value = (GenericValue) object;
return value.makeXmlElement(document, "eeval-");
} else if (object instanceof Map<?, ?>) {
// - Maps -
String elementName = null;
// these ARE order sensitive; for instance Properties extends Hashtable, so if Hashtable were first we would lose the Properties part
if (object instanceof HashMap<?, ?>) {
elementName = "map-HashMap";
} else if (object instanceof Properties) {
elementName = "map-Properties";
} else if (object instanceof Hashtable<?, ?>) {
elementName = "map-Hashtable";
} else if (object instanceof WeakHashMap<?, ?>) {
elementName = "map-WeakHashMap";
} else if (object instanceof TreeMap<?, ?>) {
elementName = "map-TreeMap";
} else {
// serialize as a simple Map implementation if nothing else applies, these will deserialize as a HashMap
elementName = "map-Map";
}
Element element = document.createElement(elementName);
Map<?,?> value = UtilGenerics.cast(object);
Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
while (iter.hasNext()) {
Map.Entry<?,?> entry = iter.next();
Element entryElement = document.createElement("map-Entry");
element.appendChild(entryElement);
Element key = document.createElement("map-Key");
entryElement.appendChild(key);
key.appendChild(serializeSingle(entry.getKey(), document));
Element mapValue = document.createElement("map-Value");
entryElement.appendChild(mapValue);
mapValue.appendChild(serializeSingle(entry.getValue(), document));
}
return element;
}
return serializeCustom(object, document);
}
public static Element serializeCustom(Object object, Document document) throws SerializeException {
if (object instanceof Serializable) {
byte[] objBytes = UtilObject.getBytes(object);
if (objBytes == null) {
throw new SerializeException("Unable to serialize object; null byte array returned");
} else {
String byteHex = StringUtil.toHexString(objBytes);
Element element = document.createElement("cus-obj");
// this is hex encoded so does not need to be in a CDATA block
element.appendChild(document.createTextNode(byteHex));
return element;
}
} else {
throw new SerializeException("Cannot serialize object of class " + object.getClass().getName());
}
}
public static Element makeElement(String elementName, Object value, Document document) {
if (value == null) {
Element element = document.createElement("null");
element.setAttribute("xsi:nil", "true");
// I tried to put the schema in the envelope header (in createAndSendSOAPResponse)
// resEnv.declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null);
// But it gets prefixed and that does not work. So adding in each instance
element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
return element;
}
Element element = document.createElement(elementName);
element.setAttribute("value", value.toString());
return element;
}
public static Object deserializeSingle(Element element, Delegator delegator) throws SerializeException {
String tagName = element.getLocalName();
if (tagName.equals("null")) return null;
if (tagName.startsWith("std-")) {
// - Standard Objects -
if ("std-String".equals(tagName)) {
return element.getAttribute("value");
} else if ("std-Integer".equals(tagName)) {
String valStr = element.getAttribute("value");
return Integer.valueOf(valStr);
} else if ("std-Long".equals(tagName)) {
String valStr = element.getAttribute("value");
return Long.valueOf(valStr);
} else if ("std-Float".equals(tagName)) {
String valStr = element.getAttribute("value");
return Float.valueOf(valStr);
} else if ("std-Double".equals(tagName)) {
String valStr = element.getAttribute("value");
return Double.valueOf(valStr);
} else if ("std-BigDecimal".equals(tagName)) {
String valStr = element.getAttribute("value");
return new BigDecimal(valStr);
} else if ("std-Boolean".equals(tagName)) {
String valStr = element.getAttribute("value");
return Boolean.valueOf(valStr);
} else if ("std-Locale".equals(tagName)) {
String valStr = element.getAttribute("value");
return UtilMisc.parseLocale(valStr);
} else if ("std-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
DateFormat formatter = getDateFormat();
java.util.Date value = null;
try {
synchronized (formatter) {
value = formatter.parse(valStr);
}
} catch (ParseException e) {
throw new SerializeException("Could not parse date String: " + valStr, e);
}
return value;
}
} else if (tagName.startsWith("sql-")) {
// - SQL Objects -
if ("sql-Timestamp".equals(tagName)) {
String valStr = element.getAttribute("value");
/*
* sql-Timestamp is defined as xsd:dateTime in ModelService.getTypes(),
* so try to parse the value as xsd:dateTime first.
* Fallback is java.sql.Timestamp because it has been this way all the time.
*/
try {
Calendar cal = DatatypeConverter.parseDate(valStr);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
catch (Exception e) {
Debug.logWarning("sql-Timestamp does not conform to XML Schema definition, try java.sql.Timestamp format", module);
return java.sql.Timestamp.valueOf(valStr);
}
} else if ("sql-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Date.valueOf(valStr);
} else if ("sql-Time".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Time.valueOf(valStr);
}
} else if (tagName.startsWith("col-")) {
// - Collections -
Collection<Object> value = null;
if ("col-ArrayList".equals(tagName)) {
value = new ArrayList<Object>();
} else if ("col-LinkedList".equals(tagName)) {
value = new LinkedList<Object>();
} else if ("col-Stack".equals(tagName)) {
value = new Stack<Object>();
} else if ("col-Vector".equals(tagName)) {
value = new Vector<Object>();
} else if ("col-TreeSet".equals(tagName)) {
value = new TreeSet<Object>();
} else if ("col-HashSet".equals(tagName)) {
value = new HashSet<Object>();
} else if ("col-Collection".equals(tagName)) {
value = new LinkedList<Object>();
}
if (value == null) {
return deserializeCustom(element);
} else {
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
value.add(deserializeSingle((Element) curChild, delegator));
}
curChild = curChild.getNextSibling();
}
return value;
}
} else if (tagName.startsWith("map-")) {
// - Maps -
Map<Object, Object> value = null;
if ("map-HashMap".equals(tagName)) {
value = new HashMap<Object, Object>();
} else if ("map-Properties".equals(tagName)) {
value = new Properties();
} else if ("map-Hashtable".equals(tagName)) {
value = new Hashtable<Object, Object>();
} else if ("map-WeakHashMap".equals(tagName)) {
value = new WeakHashMap<Object, Object>();
} else if ("map-TreeMap".equals(tagName)) {
value = new TreeMap<Object, Object>();
} else if ("map-Map".equals(tagName)) {
value = new HashMap<Object, Object>();
}
if (value == null) {
return deserializeCustom(element);
} else {
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) curChild;
if ("map-Entry".equals(curElement.getLocalName())) {
Element mapKeyElement = UtilXml.firstChildElement(curElement, "map-Key");
Element keyElement = null;
Node tempNode = mapKeyElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
keyElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (keyElement == null) throw new SerializeException("Could not find an element under the map-Key");
Element mapValueElement = UtilXml.firstChildElement(curElement, "map-Value");
Element valueElement = null;
tempNode = mapValueElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
valueElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (valueElement == null) throw new SerializeException("Could not find an element under the map-Value");
value.put(deserializeSingle(keyElement, delegator), deserializeSingle(valueElement, delegator));
}
}
curChild = curChild.getNextSibling();
}
return value;
}
} else if (tagName.startsWith("eepk-")) {
return delegator.makePK(element);
} else if (tagName.startsWith("eeval-")) {
return delegator.makeValue(element);
}
return deserializeCustom(element);
}
public static Object deserializeCustom(Element element) throws SerializeException {
String tagName = element.getLocalName();
if ("cus-obj".equals(tagName)) {
String value = UtilXml.elementValue(element);
if (value != null) {
byte[] valueBytes = StringUtil.fromHexString(value);
if (valueBytes != null) {
Object obj = UtilObject.getObject(valueBytes);
if (obj != null) {
return obj;
}
}
}
throw new SerializeException("Problem deserializing object from byte array + " + element.getLocalName());
} else {
throw new SerializeException("Cannot deserialize element named " + element.getLocalName());
}
}
/**
* Returns the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
* This format is NOT used to format any of the java.sql subtypes of java.util.Date.
* A <code>WeakReference</code> is used to maintain a reference to the DateFormat object
* so that it can be created and garbage collected as needed.
*
* @return the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
*/
private static DateFormat getDateFormat() {
DateFormat formatter = null;
if (simpleDateFormatter != null) {
formatter = simpleDateFormatter.get();
}
if (formatter == null) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
simpleDateFormatter = new WeakReference<DateFormat>(formatter);
}
return formatter;
}
}
|
75836_3 | package nl.avans.android.todos.presentation;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import nl.avans.android.todos.R;
import nl.avans.android.todos.domain.ToDo;
import nl.avans.android.todos.domain.ToDoAdapter;
import nl.avans.android.todos.service.ToDoRequest;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
AdapterView.OnItemClickListener,
ToDoRequest.ToDoListener {
// Logging tag
public final String TAG = this.getClass().getSimpleName();
// The name for communicating Intents extras
public final static String TODO_DATA = "TODOS";
// A request code for returning data from Intent - is supposed to be unique.
public static final int MY_REQUEST_CODE = 1234;
// UI Elements
private ListView listViewToDos;
private BaseAdapter todoAdapter;
private ArrayList<ToDo> toDos = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We kijken hier eerst of de gebruiker nog een geldig token heeft.
// Het token is opgeslagen in SharedPreferences.
// Mocht er geen token zijn, of het token is expired, dan moeten we
// eerst opnieuw inloggen.
if(tokenAvailable()){
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent newToDo = new Intent(getApplicationContext(), ToDoEditActivity.class);
// We receive a ToDo object to be stored via the API.
startActivityForResult( newToDo, MY_REQUEST_CODE );
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
listViewToDos = (ListView) findViewById(R.id.listViewToDos);
listViewToDos.setOnItemClickListener(this);
todoAdapter = new ToDoAdapter(this, getLayoutInflater(), toDos);
listViewToDos.setAdapter(todoAdapter);
//
// We hebben een token. Je zou eerst nog kunnen valideren dat het token nog
// geldig is; dat doen we nu niet.
// Vul de lijst met ToDos
//
Log.d(TAG, "Token gevonden - ToDos ophalen!");
getToDos();
} else {
//
// Blijkbaar was er geen token - eerst inloggen dus
//
Log.d(TAG, "Geen token gevonden - inloggen dus");
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(login);
// Sluit de huidige activity. Dat voorkomt dat de gebuiker via de
// back-button zonder inloggen terugkeert naar het homescreen.
finish();
}
}
/**
* Aangeroepen door terugkerende Intents. Maakt het mogelijk om data
* terug te ontvangen van een Intent.
*
* @param requestCode
* @param resultCode
* @param pData
*/
protected void onActivityResult(int requestCode, int resultCode, Intent pData)
{
if ( requestCode == MY_REQUEST_CODE )
{
Log.v( TAG, "onActivityResult OK" );
if (resultCode == Activity.RESULT_OK )
{
final ToDo newToDo = (ToDo) pData.getSerializableExtra(TODO_DATA);
Log.v( TAG, "Retrieved Value newToDo is " + newToDo);
// We need to save our new ToDo
postTodo(newToDo);
}
}
}
/**
* Check of een token in localstorage is opgeslagen. We checken niet de geldigheid -
* alleen of het token bestaat.
*
* @return
*/
private boolean tokenAvailable() {
boolean result = false;
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String token = sharedPref.getString(getString(R.string.saved_token), "dummy default token");
if (token != null && !token.equals("dummy default token")) {
result = true;
}
return result;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(settings);
return true;
} else if(id == R.id.action_logout){
// Logout - remove token from local settings and navigate to login screen.
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.remove(getString(R.string.saved_token));
editor.commit();
// Empty the homescreen
toDos.clear();
todoAdapter.notifyDataSetChanged();
// Navigate to login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(login);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "Position " + position + " is geselecteerd");
ToDo toDo = toDos.get(position);
Intent intent = new Intent(getApplicationContext(), ToDoDetailActivity.class);
intent.putExtra(TODO_DATA, toDo);
startActivity(intent);
}
/**
* Callback function - handle an ArrayList of ToDos
*
* @param toDoArrayList
*/
@Override
public void onToDosAvailable(ArrayList<ToDo> toDoArrayList) {
Log.i(TAG, "We hebben " + toDoArrayList.size() + " items in de lijst");
toDos.clear();
for(int i = 0; i < toDoArrayList.size(); i++) {
toDos.add(toDoArrayList.get(i));
}
todoAdapter.notifyDataSetChanged();
}
/**
* Callback function - handle a single ToDo
*
* @param todo
*/
@Override
public void onToDoAvailable(ToDo todo) {
toDos.add(todo);
todoAdapter.notifyDataSetChanged();
}
/**
* Callback function
*
* @param message
*/
@Override
public void onToDosError(String message) {
Log.e(TAG, message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
/**
* Start the activity to GET all ToDos from the server.
*/
private void getToDos(){
ToDoRequest request = new ToDoRequest(getApplicationContext(), this);
request.handleGetAllToDos();
}
/**
* Start the activity to POST a new ToDo to the server.
*/
private void postTodo(ToDo todo){
ToDoRequest request = new ToDoRequest(getApplicationContext(), this);
request.handlePostToDo(todo);
}
}
| avansinformatica/android-todolist | app/src/main/java/nl/avans/android/todos/presentation/MainActivity.java | 2,419 | // Het token is opgeslagen in SharedPreferences. | line_comment | nl | package nl.avans.android.todos.presentation;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import nl.avans.android.todos.R;
import nl.avans.android.todos.domain.ToDo;
import nl.avans.android.todos.domain.ToDoAdapter;
import nl.avans.android.todos.service.ToDoRequest;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
AdapterView.OnItemClickListener,
ToDoRequest.ToDoListener {
// Logging tag
public final String TAG = this.getClass().getSimpleName();
// The name for communicating Intents extras
public final static String TODO_DATA = "TODOS";
// A request code for returning data from Intent - is supposed to be unique.
public static final int MY_REQUEST_CODE = 1234;
// UI Elements
private ListView listViewToDos;
private BaseAdapter todoAdapter;
private ArrayList<ToDo> toDos = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We kijken hier eerst of de gebruiker nog een geldig token heeft.
// Het token<SUF>
// Mocht er geen token zijn, of het token is expired, dan moeten we
// eerst opnieuw inloggen.
if(tokenAvailable()){
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent newToDo = new Intent(getApplicationContext(), ToDoEditActivity.class);
// We receive a ToDo object to be stored via the API.
startActivityForResult( newToDo, MY_REQUEST_CODE );
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
listViewToDos = (ListView) findViewById(R.id.listViewToDos);
listViewToDos.setOnItemClickListener(this);
todoAdapter = new ToDoAdapter(this, getLayoutInflater(), toDos);
listViewToDos.setAdapter(todoAdapter);
//
// We hebben een token. Je zou eerst nog kunnen valideren dat het token nog
// geldig is; dat doen we nu niet.
// Vul de lijst met ToDos
//
Log.d(TAG, "Token gevonden - ToDos ophalen!");
getToDos();
} else {
//
// Blijkbaar was er geen token - eerst inloggen dus
//
Log.d(TAG, "Geen token gevonden - inloggen dus");
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(login);
// Sluit de huidige activity. Dat voorkomt dat de gebuiker via de
// back-button zonder inloggen terugkeert naar het homescreen.
finish();
}
}
/**
* Aangeroepen door terugkerende Intents. Maakt het mogelijk om data
* terug te ontvangen van een Intent.
*
* @param requestCode
* @param resultCode
* @param pData
*/
protected void onActivityResult(int requestCode, int resultCode, Intent pData)
{
if ( requestCode == MY_REQUEST_CODE )
{
Log.v( TAG, "onActivityResult OK" );
if (resultCode == Activity.RESULT_OK )
{
final ToDo newToDo = (ToDo) pData.getSerializableExtra(TODO_DATA);
Log.v( TAG, "Retrieved Value newToDo is " + newToDo);
// We need to save our new ToDo
postTodo(newToDo);
}
}
}
/**
* Check of een token in localstorage is opgeslagen. We checken niet de geldigheid -
* alleen of het token bestaat.
*
* @return
*/
private boolean tokenAvailable() {
boolean result = false;
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String token = sharedPref.getString(getString(R.string.saved_token), "dummy default token");
if (token != null && !token.equals("dummy default token")) {
result = true;
}
return result;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(settings);
return true;
} else if(id == R.id.action_logout){
// Logout - remove token from local settings and navigate to login screen.
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.remove(getString(R.string.saved_token));
editor.commit();
// Empty the homescreen
toDos.clear();
todoAdapter.notifyDataSetChanged();
// Navigate to login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(login);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "Position " + position + " is geselecteerd");
ToDo toDo = toDos.get(position);
Intent intent = new Intent(getApplicationContext(), ToDoDetailActivity.class);
intent.putExtra(TODO_DATA, toDo);
startActivity(intent);
}
/**
* Callback function - handle an ArrayList of ToDos
*
* @param toDoArrayList
*/
@Override
public void onToDosAvailable(ArrayList<ToDo> toDoArrayList) {
Log.i(TAG, "We hebben " + toDoArrayList.size() + " items in de lijst");
toDos.clear();
for(int i = 0; i < toDoArrayList.size(); i++) {
toDos.add(toDoArrayList.get(i));
}
todoAdapter.notifyDataSetChanged();
}
/**
* Callback function - handle a single ToDo
*
* @param todo
*/
@Override
public void onToDoAvailable(ToDo todo) {
toDos.add(todo);
todoAdapter.notifyDataSetChanged();
}
/**
* Callback function
*
* @param message
*/
@Override
public void onToDosError(String message) {
Log.e(TAG, message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
/**
* Start the activity to GET all ToDos from the server.
*/
private void getToDos(){
ToDoRequest request = new ToDoRequest(getApplicationContext(), this);
request.handleGetAllToDos();
}
/**
* Start the activity to POST a new ToDo to the server.
*/
private void postTodo(ToDo todo){
ToDoRequest request = new ToDoRequest(getApplicationContext(), this);
request.handlePostToDo(todo);
}
}
|
18318_46 | package novi.basics;
import static novi.basics.Main.PLAYERINPUT;
public class TicTacToe {
// atributen: (lijst) waaruit de game classe uit bestaat
private final int drawCount;
private final Field[] board;
private int maxRounds;
private int chosenfield;
private int chosenindex;
private final Player player1;
private final Player player2;
private Player activePlayer;
// constructor: in de constructor methode krijgen alle attributen een waarde
public TicTacToe(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;
// opslaan hoeveel keer er gelijk spel is geweest
drawCount = 0;
// token van de actieve speler opslaan
//char activePlayerToken = player1.getToken();
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(); huiswerk
// 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(); huiswerk
// 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);
//player.score += 10;
// het nieuwe speelbord tonen
printBoard(); //huiswerk
// 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
//changePlayer(); huiswerk
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
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");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// als het veld niet bestaat
else {
// het maximale 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
}
// vragen of de spelers nog een keer willen spelen
//1: nog een keer spelen
//2: van spelers wisselen
//3: afsluiten
// speler keuze opslaan
// bij keuze 1: terug naar het maken van het bord
// bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen
// bij keuze 3: het spel en de applicatie helemaal afsluiten
}
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-SunshineSummerville | src/novi/basics/TicTacToe.java | 1,279 | // als we het tweede veld geprint hebben of het vijfde veld geprint hebben | line_comment | nl | package novi.basics;
import static novi.basics.Main.PLAYERINPUT;
public class TicTacToe {
// atributen: (lijst) waaruit de game classe uit bestaat
private final int drawCount;
private final Field[] board;
private int maxRounds;
private int chosenfield;
private int chosenindex;
private final Player player1;
private final Player player2;
private Player activePlayer;
// constructor: in de constructor methode krijgen alle attributen een waarde
public TicTacToe(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;
// opslaan hoeveel keer er gelijk spel is geweest
drawCount = 0;
// token van de actieve speler opslaan
//char activePlayerToken = player1.getToken();
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(); huiswerk
// 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(); huiswerk
// 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);
//player.score += 10;
// het nieuwe speelbord tonen
printBoard(); //huiswerk
// 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
//changePlayer(); huiswerk
// de beurt doorgeven aan de volgende speler (van speler wisselen)
// als de actieve speler, speler 1 is:
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");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// als het veld niet bestaat
else {
// het maximale 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
}
// vragen of de spelers nog een keer willen spelen
//1: nog een keer spelen
//2: van spelers wisselen
//3: afsluiten
// speler keuze opslaan
// bij keuze 1: terug naar het maken van het bord
// bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen
// bij keuze 3: het spel en de applicatie helemaal afsluiten
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex].getToken() + " ");
// als we<SUF>
// dan gaan we naar de volgende regel
if (fieldIndex == 2 || fieldIndex == 5) {
System.out.println();
}
}
System.out.println();
}
} |
56970_3 | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk
* verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring
* van inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19");
private final int key;
private DocumentType(final String value) {
this.key = toKey(value);
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
final int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: "
+ encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
final DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
| Corilus/commons-eid | commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java | 1,074 | /**
* Bewijs van inschrijving in het vreemdelingenregister
*/ | block_comment | nl | /*
* Commons eID Project.
* Copyright (C) 2008-2013 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.commons.eid.consumer;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"),
KIDS_CARD("6"),
BOOTSTRAP_CARD("7"),
HABILITATION_CARD("8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk
* verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving<SUF>*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring
* van inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19");
private final int key;
private DocumentType(final String value) {
this.key = toKey(value);
}
private int toKey(final String value) {
final char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
final char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(final byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
final int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: "
+ encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(final byte[] value) {
final int key = DocumentType.toKey(value);
final DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(final byte[] documentTypeValue) {
return Integer.toString(DocumentType.toKey(documentTypeValue));
}
}
|
66346_2 | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import de.willuhn.boot.BootLoader;
import de.willuhn.boot.Bootable;
import de.willuhn.boot.SkipServiceException;
import de.willuhn.jameica.search.SearchProvider;
import de.willuhn.jameica.search.SearchResult;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Settings;
import de.willuhn.logging.Logger;
/**
* Service zur Initialisierung der Suchmaschine.
*/
public class SearchService implements Bootable
{
private ArrayList<SearchProvider> providers = null;
private static Settings settings = new Settings(SearchService.class);
/**
* @see de.willuhn.boot.Bootable#depends()
*/
public Class[] depends()
{
return new Class[]{PluginService.class};
}
/**
* @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable)
*/
public void init(BootLoader loader, Bootable caller) throws SkipServiceException
{
this.providers = new ArrayList<SearchProvider>();
try
{
Logger.info("looking for search providers");
Class[] providers = Application.getClassLoader().getClassFinder().findImplementors(SearchProvider.class);
BeanService beanService = Application.getBootLoader().getBootable(BeanService.class);
int count = 0;
for (int i=0;i<providers.length;++i)
{
try
{
SearchProvider p = (SearchProvider) beanService.get(providers[i]);
Logger.debug(" " + p.getName());
this.providers.add(p);
count++;
}
catch (Throwable t)
{
Logger.error("unable to load search provider " + providers[i].getName(),t);
}
}
Collections.sort(this.providers,new Comparator<SearchProvider>() {
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(SearchProvider o1, SearchProvider o2)
{
return o1.getName().compareTo(o2.getName());
}
});
Logger.info("loaded " + count + " search providers");
}
catch (ClassNotFoundException ne)
{
Logger.info("no search providers found");
}
}
/**
* @see de.willuhn.boot.Bootable#shutdown()
*/
public void shutdown()
{
this.providers = null;
}
/**
* Fuehrt eine Suche ueber die Such-Provider durch.
* Aus Perfomanz-Gruenden beginnt die Suche nicht sofort
* sondern erst, wenn die SearchResults vom Aufrufer ausgewertet werden.
* @param text der Suchbegriff.
* @return das Suchergebnis.
* Jedes SearchResult enthaelt die Suchergebnisse fuer einen Provider.
*/
public List<SearchResult> search(String text)
{
List<SearchResult> result = new ArrayList<SearchResult>();
// Suche ohne Suchbegriff gibts nicht
if (text == null || text.length() == 0)
return result;
Logger.debug("searching for " + text);
for (int i=0;i<this.providers.size();++i)
{
SearchProvider p = this.providers.get(i);
// Checken, ob der SearchProvider von der Suche ausgeschlossen wurde
if (!isEnabled(p))
continue;
result.add(new SearchResult(p,text));
}
Logger.debug("search completed");
return result;
}
/**
* Liefert eine Liste der SerchProvider.
* @return Liste der SearchProvider. Nie <code>null</code> sondern
* hoechstens eine leere Liste.
*/
public SearchProvider[] getSearchProviders()
{
if (this.providers == null)
return new SearchProvider[0];
return this.providers.toArray(new SearchProvider[this.providers.size()]);
}
/**
* Aktiviert oder deaktiviert die Suche in einem einzelnen Searchprovider.
* @param provider der Provider.
* @param enabled false, wenn die Suche in dem Provider deaktiviert werden soll, sonst true.
*/
public void setEnabled(SearchProvider provider,boolean enabled)
{
if (provider == null)
return;
settings.setAttribute(provider.getClass().getName() + ".enabled",enabled);
}
/**
* Prueft, ob der angegebene Search-Provider aktiviert ist.
* @param provider Search-Provider.
* @return true, wenn er aktiv ist, sonst false.
*/
public boolean isEnabled(SearchProvider provider)
{
if (provider == null)
return false;
return settings.getBoolean(provider.getClass().getName() + ".enabled",true);
}
}
/**********************************************************************
* $Log: SearchService.java,v $
* Revision 1.8 2011/08/30 16:02:23 willuhn
* @N Alle restlichen Stellen, in denen Instanzen via Class#newInstance erzeugt wurden, gegen BeanService ersetzt. Damit kann jetzt quasi ueberall Dependency-Injection verwendet werden, wo Jameica selbst die Instanzen erzeugt
*
* Revision 1.7 2010-11-03 15:28:31 willuhn
* @N Ergebnisliste getypt
*
* Revision 1.6 2008/09/03 23:32:14 willuhn
* @C Suchergebnis nicht mehr als View sondern als Snapin am unteren Rand anzeigen. Dann kann man durch die Elemente klicken, ohne das Suchergebnis zu verlassen
*
* Revision 1.5 2008/09/03 11:14:20 willuhn
* @N Suchfeld anzeigen
* @N Such-Optionen
*
* Revision 1.4 2008/09/03 08:41:17 willuhn
* @R Namen der Searchprovider in Level DEBUG loggen
*
* Revision 1.3 2008/09/03 00:11:43 willuhn
* @N Erste Version eine funktionsfaehigen Suche - zur Zeit in Navigation.java deaktiviert
*
* Revision 1.2 2008/08/31 23:07:10 willuhn
* @N Erster GUI-Code fuer die Suche
*
* Revision 1.1 2008/08/31 14:08:45 willuhn
* @N Erster Code fuer eine jameica-interne Suchmaschine
*
**********************************************************************/
| jspricke/jameica | src/de/willuhn/jameica/services/SearchService.java | 1,775 | /**
* @see de.willuhn.boot.Bootable#depends()
*/ | block_comment | nl | /**********************************************************************
*
* Copyright (c) 2004 Olaf Willuhn
* All rights reserved.
*
* This software is copyrighted work licensed under the terms of the
* Jameica License. Please consult the file "LICENSE" for details.
*
**********************************************************************/
package de.willuhn.jameica.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import de.willuhn.boot.BootLoader;
import de.willuhn.boot.Bootable;
import de.willuhn.boot.SkipServiceException;
import de.willuhn.jameica.search.SearchProvider;
import de.willuhn.jameica.search.SearchResult;
import de.willuhn.jameica.system.Application;
import de.willuhn.jameica.system.Settings;
import de.willuhn.logging.Logger;
/**
* Service zur Initialisierung der Suchmaschine.
*/
public class SearchService implements Bootable
{
private ArrayList<SearchProvider> providers = null;
private static Settings settings = new Settings(SearchService.class);
/**
* @see de.willuhn.boot.Bootable#depends()
<SUF>*/
public Class[] depends()
{
return new Class[]{PluginService.class};
}
/**
* @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable)
*/
public void init(BootLoader loader, Bootable caller) throws SkipServiceException
{
this.providers = new ArrayList<SearchProvider>();
try
{
Logger.info("looking for search providers");
Class[] providers = Application.getClassLoader().getClassFinder().findImplementors(SearchProvider.class);
BeanService beanService = Application.getBootLoader().getBootable(BeanService.class);
int count = 0;
for (int i=0;i<providers.length;++i)
{
try
{
SearchProvider p = (SearchProvider) beanService.get(providers[i]);
Logger.debug(" " + p.getName());
this.providers.add(p);
count++;
}
catch (Throwable t)
{
Logger.error("unable to load search provider " + providers[i].getName(),t);
}
}
Collections.sort(this.providers,new Comparator<SearchProvider>() {
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(SearchProvider o1, SearchProvider o2)
{
return o1.getName().compareTo(o2.getName());
}
});
Logger.info("loaded " + count + " search providers");
}
catch (ClassNotFoundException ne)
{
Logger.info("no search providers found");
}
}
/**
* @see de.willuhn.boot.Bootable#shutdown()
*/
public void shutdown()
{
this.providers = null;
}
/**
* Fuehrt eine Suche ueber die Such-Provider durch.
* Aus Perfomanz-Gruenden beginnt die Suche nicht sofort
* sondern erst, wenn die SearchResults vom Aufrufer ausgewertet werden.
* @param text der Suchbegriff.
* @return das Suchergebnis.
* Jedes SearchResult enthaelt die Suchergebnisse fuer einen Provider.
*/
public List<SearchResult> search(String text)
{
List<SearchResult> result = new ArrayList<SearchResult>();
// Suche ohne Suchbegriff gibts nicht
if (text == null || text.length() == 0)
return result;
Logger.debug("searching for " + text);
for (int i=0;i<this.providers.size();++i)
{
SearchProvider p = this.providers.get(i);
// Checken, ob der SearchProvider von der Suche ausgeschlossen wurde
if (!isEnabled(p))
continue;
result.add(new SearchResult(p,text));
}
Logger.debug("search completed");
return result;
}
/**
* Liefert eine Liste der SerchProvider.
* @return Liste der SearchProvider. Nie <code>null</code> sondern
* hoechstens eine leere Liste.
*/
public SearchProvider[] getSearchProviders()
{
if (this.providers == null)
return new SearchProvider[0];
return this.providers.toArray(new SearchProvider[this.providers.size()]);
}
/**
* Aktiviert oder deaktiviert die Suche in einem einzelnen Searchprovider.
* @param provider der Provider.
* @param enabled false, wenn die Suche in dem Provider deaktiviert werden soll, sonst true.
*/
public void setEnabled(SearchProvider provider,boolean enabled)
{
if (provider == null)
return;
settings.setAttribute(provider.getClass().getName() + ".enabled",enabled);
}
/**
* Prueft, ob der angegebene Search-Provider aktiviert ist.
* @param provider Search-Provider.
* @return true, wenn er aktiv ist, sonst false.
*/
public boolean isEnabled(SearchProvider provider)
{
if (provider == null)
return false;
return settings.getBoolean(provider.getClass().getName() + ".enabled",true);
}
}
/**********************************************************************
* $Log: SearchService.java,v $
* Revision 1.8 2011/08/30 16:02:23 willuhn
* @N Alle restlichen Stellen, in denen Instanzen via Class#newInstance erzeugt wurden, gegen BeanService ersetzt. Damit kann jetzt quasi ueberall Dependency-Injection verwendet werden, wo Jameica selbst die Instanzen erzeugt
*
* Revision 1.7 2010-11-03 15:28:31 willuhn
* @N Ergebnisliste getypt
*
* Revision 1.6 2008/09/03 23:32:14 willuhn
* @C Suchergebnis nicht mehr als View sondern als Snapin am unteren Rand anzeigen. Dann kann man durch die Elemente klicken, ohne das Suchergebnis zu verlassen
*
* Revision 1.5 2008/09/03 11:14:20 willuhn
* @N Suchfeld anzeigen
* @N Such-Optionen
*
* Revision 1.4 2008/09/03 08:41:17 willuhn
* @R Namen der Searchprovider in Level DEBUG loggen
*
* Revision 1.3 2008/09/03 00:11:43 willuhn
* @N Erste Version eine funktionsfaehigen Suche - zur Zeit in Navigation.java deaktiviert
*
* Revision 1.2 2008/08/31 23:07:10 willuhn
* @N Erster GUI-Code fuer die Suche
*
* Revision 1.1 2008/08/31 14:08:45 willuhn
* @N Erster Code fuer eine jameica-interne Suchmaschine
*
**********************************************************************/
|
59329_6 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für SimpleFieldType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="SimpleFieldType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}displayName" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}SimpleFieldExtension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SimpleFieldType", propOrder = {
"displayName",
"simpleFieldExtension"
})
public class SimpleFieldType {
protected String displayName;
@XmlElement(name = "SimpleFieldExtension")
protected List<Object> simpleFieldExtension;
@XmlAttribute(name = "type")
protected String type;
@XmlAttribute(name = "name")
protected String name;
/**
* Ruft den Wert der displayName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDisplayName() {
return displayName;
}
/**
* Legt den Wert der displayName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDisplayName(String value) {
this.displayName = value;
}
public boolean isSetDisplayName() {
return (this.displayName!= null);
}
/**
* Gets the value of the simpleFieldExtension property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the simpleFieldExtension property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSimpleFieldExtension().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getSimpleFieldExtension() {
if (simpleFieldExtension == null) {
simpleFieldExtension = new ArrayList<Object>();
}
return this.simpleFieldExtension;
}
public boolean isSetSimpleFieldExtension() {
return ((this.simpleFieldExtension!= null)&&(!this.simpleFieldExtension.isEmpty()));
}
public void unsetSimpleFieldExtension() {
this.simpleFieldExtension = null;
}
/**
* Ruft den Wert der type-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Legt den Wert der type-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
public boolean isSetType() {
return (this.type!= null);
}
/**
* Ruft den Wert der name-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Legt den Wert der name-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
public boolean isSetName() {
return (this.name!= null);
}
public void setSimpleFieldExtension(List<Object> value) {
this.simpleFieldExtension = value;
}
}
| 3dcitydb/importer-exporter | impexp-vis-plugin/src-gen/main/java/net/opengis/kml/_2/SimpleFieldType.java | 1,415 | /**
* Legt den Wert der displayName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/ | block_comment | nl | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für SimpleFieldType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="SimpleFieldType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}displayName" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}SimpleFieldExtension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SimpleFieldType", propOrder = {
"displayName",
"simpleFieldExtension"
})
public class SimpleFieldType {
protected String displayName;
@XmlElement(name = "SimpleFieldExtension")
protected List<Object> simpleFieldExtension;
@XmlAttribute(name = "type")
protected String type;
@XmlAttribute(name = "name")
protected String name;
/**
* Ruft den Wert der displayName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDisplayName() {
return displayName;
}
/**
* Legt den Wert<SUF>*/
public void setDisplayName(String value) {
this.displayName = value;
}
public boolean isSetDisplayName() {
return (this.displayName!= null);
}
/**
* Gets the value of the simpleFieldExtension property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the simpleFieldExtension property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSimpleFieldExtension().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getSimpleFieldExtension() {
if (simpleFieldExtension == null) {
simpleFieldExtension = new ArrayList<Object>();
}
return this.simpleFieldExtension;
}
public boolean isSetSimpleFieldExtension() {
return ((this.simpleFieldExtension!= null)&&(!this.simpleFieldExtension.isEmpty()));
}
public void unsetSimpleFieldExtension() {
this.simpleFieldExtension = null;
}
/**
* Ruft den Wert der type-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Legt den Wert der type-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
public boolean isSetType() {
return (this.type!= null);
}
/**
* Ruft den Wert der name-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Legt den Wert der name-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
public boolean isSetName() {
return (this.name!= null);
}
public void setSimpleFieldExtension(List<Object> value) {
this.simpleFieldExtension = value;
}
}
|
12223_0 | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import utils.Kleur;
public class Spel {
private FicheRepository ficheRepo;
private OntwikkelingskaartRepository niveau1;
private OntwikkelingskaartRepository niveau2;
private OntwikkelingskaartRepository niveau3;
private EdeleRepository edeleRepo;
private List<Speler> spelers;
private Speler huidigeSpeler;
public static final int MIN_AANTAL_SPELERS = 2;
private static final int AANTAL_PRESTIGEPUNTEN_WIN = 15;
// Beurtteller
private int beurt;
public Spel(List<Speler> spelers) {
int aantalSpelers = spelers.size();
setSpelers(spelers);
setFicheRepository(aantalSpelers);
setEdeleRepository(aantalSpelers);
huidigeSpeler = spelers.get(0);
niveau1 = new OntwikkelingskaartRepository(1);
niveau2 = new OntwikkelingskaartRepository(2);
niveau3 = new OntwikkelingskaartRepository(3);
this.beurt = 0;
}
public List<Speler> getSpelers() {
return spelers;
}
private void setSpelers(List<Speler> spelers) {
if (spelers == null) {
throw new IllegalArgumentException("geenSpelers");
}
if (spelers.size() < MIN_AANTAL_SPELERS) {
throw new IllegalArgumentException("minAantalSpelers");
}
this.spelers = spelers;
}
public int[] getFiches() {
return ficheRepo.getFiches();
}
private void setFicheRepository(int aantalSpelers) {
// aantal fiches voor elke edelsteen bepalen a.d.h.v. het aantal spelers
int aantalFiches = switch (aantalSpelers) {
case 2 -> 4;
case 3 -> 5;
case 4 -> 7;
default -> throw new IllegalArgumentException("aantalSpelersError");
};
int lengte = Kleur.values().length;
int[] edelstenen = new int[lengte];
// het aantal fiches voor elke edelsteen gelijkstellen aan het eerder bepaalde
// aantal
for (int i = 0; i < lengte; i++) {
edelstenen[i] = aantalFiches;
}
ficheRepo = new FicheRepository(edelstenen);
}
public List<Edele> getEdelen() {
return edeleRepo.getEdelen();
}
public void setEdeleRepository(int aantalSpelers) {
// aantal edelen van het spel bepalen a.d.h.v. het aantal spelers
int aantalEdelen = switch (aantalSpelers) {
case 2 -> 3;
case 3 -> 4;
case 4 -> 5;
default -> 3;
};
this.edeleRepo = new EdeleRepository(aantalEdelen);
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3.getOntwikkelingskaarten();
}
public boolean isEindeSpel() {
// als de huidige speler geen startspeler is wilt dat zeggen dat er nog een
// ronde bezig is en kan er nog geen winnaar zijn
if (!huidigeSpeler.isStartSpeler()) {
return false;
}
// spelers overlopen en checken of één van de spelers 15 of meer prestigepunten
// heeft
for (Speler s : spelers) {
if (s.getPrestigePunten() >= AANTAL_PRESTIGEPUNTEN_WIN) {
return true;
}
}
return false;
}
private int geefIndexSpelerAanDeBeurt() {
return beurt % spelers.size();
}
public Speler geefSpeler(Speler speler) {
for (Speler s : spelers) {
if (s.equals(speler)) {
return s;
}
}
return null;
}
/**
* @return een lijst met de winnaars van het spel
* dit kan er maar 1 zijn maar het kunnen ook meerdere spelers zijn
*/
public List<Speler> geefWinnaars() {
// als het spel nog niet gedaan is kunnen er nog geen winnaars zijn
if (!isEindeSpel()) {
return null;
}
// copy maken van de spelers list
List<Speler> spelersCopy = new ArrayList<>(spelers);
// copy sorteren aan de hand van WinnaarComparator, deze sorteert op
// prestigepunten van groot naar klein en aantal ontwikkelingskaarten van klein
// naar groot
Collections.sort(spelersCopy, new WinnaarComparator());
// eerste speler in de gesorteerde copu eruit halen en gelijkstellen aan de
// mogelijkeWinaar variabele
Speler winnaar = spelersCopy.remove(0);
List<Speler> winnaars = new ArrayList<>();
winnaars.add(winnaar);
int aantalOntwikkelingskaartenWinnaar = winnaar.getOntwikkelingskaarten().size();
int index = 0;
Speler volgendeSpeler = spelersCopy.get(index);
// kijken of er nog winnaars zijn door de overige speler af te lopen en te
// kijken of ze even veel prestigepunten en even weinig ontwikkelingskaarten
// hebben
while (volgendeSpeler.getPrestigePunten() == winnaar.getPrestigePunten()
&& volgendeSpeler.getOntwikkelingskaarten().size() == aantalOntwikkelingskaartenWinnaar) {
winnaars.add(volgendeSpeler);
if (index + 1 < spelersCopy.size()) {
volgendeSpeler = spelersCopy.get(++index);
} else {
volgendeSpeler = new Speler("test", 2002);
}
}
return winnaars;
}
/**
* Voegt 2 fiches van dezelfde kleur toe aan de fiches van de speler
* en neem 2 fiches van die kleur weg bij het spel.
* @param kleur geeft aan welke kleur de 2 fiches zijn die de speler moet krijgen en weggenomen moeten worden bij het spel
*/
public void neemTweeDezelfdeFiches(int kleur) {
// als er minder dan 4 fiches van de opgegeven kleur in het spel zitten dan
// mogen er geen 2 dezelfde fiches van die kleur genomen worden
if (ficheRepo.geefAantal(kleur) < 4) {
throw new IllegalArgumentException("teweinigEdfiches");
}
// contoleren of de speler niet meer dan 10 fiches heeft als hij er 2 bijneemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + 2);
// fiches wegnemen van het spel
ficheRepo.neemFichesWeg(kleur, 2);
// fiches toevoegen bij de speler
huidigeSpeler.voegFichesToe(kleur, 2);
beurt++;
}
public void neemVerschillendeFiches(List<Integer> kleuren) {
// het aantal genomen fiches mag maximaal 3 zijn
if (kleuren.size() > 3) {
throw new IllegalArgumentException("teveelEdfiches");
}
// er mogen geen duplicate fiches bijzitten
if (kleuren.size() > new HashSet<>(kleuren).size()) {
throw new IllegalArgumentException("dubbeleFiches");
}
// controleren of de speler niet meer dan 10 fiches heeft als hij het aantal
// geselecteerde fiches neemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + kleuren.size());
// elk geselecteerd fiche toevoegen bij de speler en wegnemen bij het spel
for (int kleur : kleuren) {
ficheRepo.neemFichesWeg(kleur, 1);
huidigeSpeler.voegFichesToe(kleur, 1);
}
beurt++;
}
private void controleerAantalFichesSpeler(int aantal) {
// een speler mag niet meer dan 10 fiches in bezit hebben
if (aantal > 10) {
throw new IllegalArgumentException("maxEdelfiches");
}
}
private Ontwikkelingskaart geefOntwikkelingskaart(int id, int niveau) {
List<Ontwikkelingskaart> kaarten = geefNiveau(niveau);
for (Ontwikkelingskaart o : kaarten) {
if (o.getId() == id) {
return o;
}
}
return null;
}
public List<Integer> koopOntwikkelingskaart(int id, int niveau) {
Ontwikkelingskaart o = geefOntwikkelingskaart(id, niveau);
List<Ontwikkelingskaart> ontwikkelingskaartenSpeler = huidigeSpeler.getOntwikkelingskaarten();
int[] fichesSpeler = huidigeSpeler.getFiches();
int[] fichesEnBonussenSpeler = Arrays.copyOf(fichesSpeler, fichesSpeler.length);
int[] vereisteFiches = o.getVereisteFiches();
int[] wegTeHalen = Arrays.copyOf(vereisteFiches, vereisteFiches.length);
// bonussen toevoegen aan fiches en aftrekken van de weg te halen fiches
for (Ontwikkelingskaart kaart : ontwikkelingskaartenSpeler) {
int bonus = Kleur.valueOf(kaart.getBonus().toUpperCase()).ordinal();
fichesEnBonussenSpeler[bonus]++;
if (wegTeHalen[bonus] > 0) {
wegTeHalen[bonus]--;
}
}
// kijken of speler genoeg fiches heeft om kaart te kopen
for (int i = 0; i < fichesEnBonussenSpeler.length; i++) {
if (fichesEnBonussenSpeler[i] < vereisteFiches[i]) {
throw new IllegalArgumentException("teWeinigFichesError");
}
}
// fiches weghalen bij speler en toevoegen aan spel
for (int i = 0; i < wegTeHalen.length; i++) {
int aantal = wegTeHalen[i];
huidigeSpeler.neemFichesWeg(i, aantal);
ficheRepo.voegFichesToe(i, aantal);
}
geefNiveau(niveau).remove(o);
huidigeSpeler.voegOntwikkelingskaartToe(o);
// bepaal of er koopbare edelen zijn na een ontwikkelingskaart kopen
return geefIDsKoopbareEdelen(); // TODO Opgelet: zorg ervoor dat de beurtteller na deze methode verhoogt.
}
private List<Integer> geefIDsKoopbareEdelen() {
List<Integer> idsKoopbareEdelen = new ArrayList<>();
for (Edele e : edeleRepo.getEdelen()) {
if (controleerEdeleIsKoopbaar(e)) {
idsKoopbareEdelen.add(e.getId());
}
}
return idsKoopbareEdelen;
}
public void koopEdele(int id) {
Edele e = geefEdele(id);
// controlleren of de speler genoeg bonussen heeft om de edele te kopen
if (!controleerEdeleIsKoopbaar(e)) {
throw new IllegalArgumentException("teWeinigBonussenError");
}
// edele verwijderen bij spel en toevoegen bij de huidige speler
edeleRepo.verwijderEdele(e);
huidigeSpeler.voegEdeleToe(e);
}
private Edele geefEdele(int id) {
for (Edele e : edeleRepo.getEdelen()) {
if (e.getId() == id) {
return e;
}
}
return null;
}
private boolean controleerEdeleIsKoopbaar(Edele e) {
int[] bonussenSpeler = huidigeSpeler.berekenBonussen();
int[] vereisteBonussenEdele = e.getVereisteBonussen();
// kijken of de huidige speler de edele kan kopen
for (int i = 0; i < bonussenSpeler.length; i++) {
if (bonussenSpeler[i] < vereisteBonussenEdele[i]) {
return false;
}
}
return true;
}
private List<Ontwikkelingskaart> geefNiveau(int niveau) {
return switch (niveau) {
case 1 -> niveau1.getOntwikkelingskaarten();
case 2 -> niveau2.getOntwikkelingskaarten();
case 3 -> niveau3.getOntwikkelingskaarten();
default -> null;
};
}
public void verhoogBeurtTeller() {
beurt++;
}
public void setHuidigeSpeler() {
huidigeSpeler = spelers.get(geefIndexSpelerAanDeBeurt());
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public boolean isAanDeBeurt(String gebruikersnaam, int geboortedatum) {
Speler s = geefSpeler(new Speler(gebruikersnaam, geboortedatum));
return huidigeSpeler.equals(s);
}
// methode om de spelers aan het begin van het spel al ontwikkelingskaarten te
// geven
public void preload() {
for (Speler s : spelers) {
neemKaarten(s, niveau1, 5);
neemKaarten(s, niveau2, 3);
// neemKaarten(s, niveau3, 1);
}
}
private void neemKaarten(Speler s, OntwikkelingskaartRepository ontwikklingskaartRepo, int aantal) {
for (int i = 0; i < aantal; i++) {
Ontwikkelingskaart kaart = ontwikklingskaartRepo.geefOntwikkelingskaart(i);
ontwikklingskaartRepo.verwijderOntwikkelingskaart(kaart);
s.voegOntwikkelingskaartToe(kaart);
}
}
// methode die alle ontwikkelingskaarten uit het spel retourneert
public List<Ontwikkelingskaart> geefAlleOntwikkelingskaarten() {
List<Ontwikkelingskaart> alleOntwikkelingskaarten = geefNiveau2En3();
for (Ontwikkelingskaart o : niveau1.getOntwikkelingskaarten()) {
alleOntwikkelingskaarten.add(o);
}
return alleOntwikkelingskaarten;
}
public List<Ontwikkelingskaart> geefNiveau2En3() {
List<Ontwikkelingskaart> kaarten = new ArrayList<>();
for (Ontwikkelingskaart o : niveau2.getOntwikkelingskaarten()) {
kaarten.add(o);
}
for (Ontwikkelingskaart o : niveau3.getOntwikkelingskaarten()) {
kaarten.add(o);
}
return kaarten;
}
// methode om het nemen van een Edele te testen
public void geefGenoegKaartenOmEdelenTeKopen() {
Speler s = spelers.get(0);
int[] aantallen = new int[5];
List<Ontwikkelingskaart> kaarten = geefAlleOntwikkelingskaarten();
Collections.shuffle(kaarten);
int i = 0;
while (s.getOntwikkelingskaarten().size() < 20) {
Ontwikkelingskaart o = kaarten.get(i++);
int bonus = Kleur.valueOf(o.getBonus().toUpperCase()).ordinal();
if (aantallen[bonus] < 4) {
s.voegOntwikkelingskaartToe(o);
}
aantallen[bonus]++;
}
}
private void geef15Prestigepunten(int index) {
Speler s = spelers.get(index);
int i = 0;
List<Ontwikkelingskaart> kaarten = geefNiveau2En3();
while (s.getPrestigePunten() != 15) {
Ontwikkelingskaart o = kaarten.get(i++);
if (s.getPrestigePunten() + o.getPrestigepunten() <= 15) {
s.voegOntwikkelingskaartToe(o);
}
}
}
public void maakWinnaars() {
geef15Prestigepunten(0);
geef15Prestigepunten(1);
}
}
| JulesGoubert/splendor | src/domein/Spel.java | 4,151 | // aantal fiches voor elke edelsteen bepalen a.d.h.v. het aantal spelers | line_comment | nl | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import utils.Kleur;
public class Spel {
private FicheRepository ficheRepo;
private OntwikkelingskaartRepository niveau1;
private OntwikkelingskaartRepository niveau2;
private OntwikkelingskaartRepository niveau3;
private EdeleRepository edeleRepo;
private List<Speler> spelers;
private Speler huidigeSpeler;
public static final int MIN_AANTAL_SPELERS = 2;
private static final int AANTAL_PRESTIGEPUNTEN_WIN = 15;
// Beurtteller
private int beurt;
public Spel(List<Speler> spelers) {
int aantalSpelers = spelers.size();
setSpelers(spelers);
setFicheRepository(aantalSpelers);
setEdeleRepository(aantalSpelers);
huidigeSpeler = spelers.get(0);
niveau1 = new OntwikkelingskaartRepository(1);
niveau2 = new OntwikkelingskaartRepository(2);
niveau3 = new OntwikkelingskaartRepository(3);
this.beurt = 0;
}
public List<Speler> getSpelers() {
return spelers;
}
private void setSpelers(List<Speler> spelers) {
if (spelers == null) {
throw new IllegalArgumentException("geenSpelers");
}
if (spelers.size() < MIN_AANTAL_SPELERS) {
throw new IllegalArgumentException("minAantalSpelers");
}
this.spelers = spelers;
}
public int[] getFiches() {
return ficheRepo.getFiches();
}
private void setFicheRepository(int aantalSpelers) {
// aantal fiches<SUF>
int aantalFiches = switch (aantalSpelers) {
case 2 -> 4;
case 3 -> 5;
case 4 -> 7;
default -> throw new IllegalArgumentException("aantalSpelersError");
};
int lengte = Kleur.values().length;
int[] edelstenen = new int[lengte];
// het aantal fiches voor elke edelsteen gelijkstellen aan het eerder bepaalde
// aantal
for (int i = 0; i < lengte; i++) {
edelstenen[i] = aantalFiches;
}
ficheRepo = new FicheRepository(edelstenen);
}
public List<Edele> getEdelen() {
return edeleRepo.getEdelen();
}
public void setEdeleRepository(int aantalSpelers) {
// aantal edelen van het spel bepalen a.d.h.v. het aantal spelers
int aantalEdelen = switch (aantalSpelers) {
case 2 -> 3;
case 3 -> 4;
case 4 -> 5;
default -> 3;
};
this.edeleRepo = new EdeleRepository(aantalEdelen);
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3.getOntwikkelingskaarten();
}
public boolean isEindeSpel() {
// als de huidige speler geen startspeler is wilt dat zeggen dat er nog een
// ronde bezig is en kan er nog geen winnaar zijn
if (!huidigeSpeler.isStartSpeler()) {
return false;
}
// spelers overlopen en checken of één van de spelers 15 of meer prestigepunten
// heeft
for (Speler s : spelers) {
if (s.getPrestigePunten() >= AANTAL_PRESTIGEPUNTEN_WIN) {
return true;
}
}
return false;
}
private int geefIndexSpelerAanDeBeurt() {
return beurt % spelers.size();
}
public Speler geefSpeler(Speler speler) {
for (Speler s : spelers) {
if (s.equals(speler)) {
return s;
}
}
return null;
}
/**
* @return een lijst met de winnaars van het spel
* dit kan er maar 1 zijn maar het kunnen ook meerdere spelers zijn
*/
public List<Speler> geefWinnaars() {
// als het spel nog niet gedaan is kunnen er nog geen winnaars zijn
if (!isEindeSpel()) {
return null;
}
// copy maken van de spelers list
List<Speler> spelersCopy = new ArrayList<>(spelers);
// copy sorteren aan de hand van WinnaarComparator, deze sorteert op
// prestigepunten van groot naar klein en aantal ontwikkelingskaarten van klein
// naar groot
Collections.sort(spelersCopy, new WinnaarComparator());
// eerste speler in de gesorteerde copu eruit halen en gelijkstellen aan de
// mogelijkeWinaar variabele
Speler winnaar = spelersCopy.remove(0);
List<Speler> winnaars = new ArrayList<>();
winnaars.add(winnaar);
int aantalOntwikkelingskaartenWinnaar = winnaar.getOntwikkelingskaarten().size();
int index = 0;
Speler volgendeSpeler = spelersCopy.get(index);
// kijken of er nog winnaars zijn door de overige speler af te lopen en te
// kijken of ze even veel prestigepunten en even weinig ontwikkelingskaarten
// hebben
while (volgendeSpeler.getPrestigePunten() == winnaar.getPrestigePunten()
&& volgendeSpeler.getOntwikkelingskaarten().size() == aantalOntwikkelingskaartenWinnaar) {
winnaars.add(volgendeSpeler);
if (index + 1 < spelersCopy.size()) {
volgendeSpeler = spelersCopy.get(++index);
} else {
volgendeSpeler = new Speler("test", 2002);
}
}
return winnaars;
}
/**
* Voegt 2 fiches van dezelfde kleur toe aan de fiches van de speler
* en neem 2 fiches van die kleur weg bij het spel.
* @param kleur geeft aan welke kleur de 2 fiches zijn die de speler moet krijgen en weggenomen moeten worden bij het spel
*/
public void neemTweeDezelfdeFiches(int kleur) {
// als er minder dan 4 fiches van de opgegeven kleur in het spel zitten dan
// mogen er geen 2 dezelfde fiches van die kleur genomen worden
if (ficheRepo.geefAantal(kleur) < 4) {
throw new IllegalArgumentException("teweinigEdfiches");
}
// contoleren of de speler niet meer dan 10 fiches heeft als hij er 2 bijneemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + 2);
// fiches wegnemen van het spel
ficheRepo.neemFichesWeg(kleur, 2);
// fiches toevoegen bij de speler
huidigeSpeler.voegFichesToe(kleur, 2);
beurt++;
}
public void neemVerschillendeFiches(List<Integer> kleuren) {
// het aantal genomen fiches mag maximaal 3 zijn
if (kleuren.size() > 3) {
throw new IllegalArgumentException("teveelEdfiches");
}
// er mogen geen duplicate fiches bijzitten
if (kleuren.size() > new HashSet<>(kleuren).size()) {
throw new IllegalArgumentException("dubbeleFiches");
}
// controleren of de speler niet meer dan 10 fiches heeft als hij het aantal
// geselecteerde fiches neemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + kleuren.size());
// elk geselecteerd fiche toevoegen bij de speler en wegnemen bij het spel
for (int kleur : kleuren) {
ficheRepo.neemFichesWeg(kleur, 1);
huidigeSpeler.voegFichesToe(kleur, 1);
}
beurt++;
}
private void controleerAantalFichesSpeler(int aantal) {
// een speler mag niet meer dan 10 fiches in bezit hebben
if (aantal > 10) {
throw new IllegalArgumentException("maxEdelfiches");
}
}
private Ontwikkelingskaart geefOntwikkelingskaart(int id, int niveau) {
List<Ontwikkelingskaart> kaarten = geefNiveau(niveau);
for (Ontwikkelingskaart o : kaarten) {
if (o.getId() == id) {
return o;
}
}
return null;
}
public List<Integer> koopOntwikkelingskaart(int id, int niveau) {
Ontwikkelingskaart o = geefOntwikkelingskaart(id, niveau);
List<Ontwikkelingskaart> ontwikkelingskaartenSpeler = huidigeSpeler.getOntwikkelingskaarten();
int[] fichesSpeler = huidigeSpeler.getFiches();
int[] fichesEnBonussenSpeler = Arrays.copyOf(fichesSpeler, fichesSpeler.length);
int[] vereisteFiches = o.getVereisteFiches();
int[] wegTeHalen = Arrays.copyOf(vereisteFiches, vereisteFiches.length);
// bonussen toevoegen aan fiches en aftrekken van de weg te halen fiches
for (Ontwikkelingskaart kaart : ontwikkelingskaartenSpeler) {
int bonus = Kleur.valueOf(kaart.getBonus().toUpperCase()).ordinal();
fichesEnBonussenSpeler[bonus]++;
if (wegTeHalen[bonus] > 0) {
wegTeHalen[bonus]--;
}
}
// kijken of speler genoeg fiches heeft om kaart te kopen
for (int i = 0; i < fichesEnBonussenSpeler.length; i++) {
if (fichesEnBonussenSpeler[i] < vereisteFiches[i]) {
throw new IllegalArgumentException("teWeinigFichesError");
}
}
// fiches weghalen bij speler en toevoegen aan spel
for (int i = 0; i < wegTeHalen.length; i++) {
int aantal = wegTeHalen[i];
huidigeSpeler.neemFichesWeg(i, aantal);
ficheRepo.voegFichesToe(i, aantal);
}
geefNiveau(niveau).remove(o);
huidigeSpeler.voegOntwikkelingskaartToe(o);
// bepaal of er koopbare edelen zijn na een ontwikkelingskaart kopen
return geefIDsKoopbareEdelen(); // TODO Opgelet: zorg ervoor dat de beurtteller na deze methode verhoogt.
}
private List<Integer> geefIDsKoopbareEdelen() {
List<Integer> idsKoopbareEdelen = new ArrayList<>();
for (Edele e : edeleRepo.getEdelen()) {
if (controleerEdeleIsKoopbaar(e)) {
idsKoopbareEdelen.add(e.getId());
}
}
return idsKoopbareEdelen;
}
public void koopEdele(int id) {
Edele e = geefEdele(id);
// controlleren of de speler genoeg bonussen heeft om de edele te kopen
if (!controleerEdeleIsKoopbaar(e)) {
throw new IllegalArgumentException("teWeinigBonussenError");
}
// edele verwijderen bij spel en toevoegen bij de huidige speler
edeleRepo.verwijderEdele(e);
huidigeSpeler.voegEdeleToe(e);
}
private Edele geefEdele(int id) {
for (Edele e : edeleRepo.getEdelen()) {
if (e.getId() == id) {
return e;
}
}
return null;
}
private boolean controleerEdeleIsKoopbaar(Edele e) {
int[] bonussenSpeler = huidigeSpeler.berekenBonussen();
int[] vereisteBonussenEdele = e.getVereisteBonussen();
// kijken of de huidige speler de edele kan kopen
for (int i = 0; i < bonussenSpeler.length; i++) {
if (bonussenSpeler[i] < vereisteBonussenEdele[i]) {
return false;
}
}
return true;
}
private List<Ontwikkelingskaart> geefNiveau(int niveau) {
return switch (niveau) {
case 1 -> niveau1.getOntwikkelingskaarten();
case 2 -> niveau2.getOntwikkelingskaarten();
case 3 -> niveau3.getOntwikkelingskaarten();
default -> null;
};
}
public void verhoogBeurtTeller() {
beurt++;
}
public void setHuidigeSpeler() {
huidigeSpeler = spelers.get(geefIndexSpelerAanDeBeurt());
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public boolean isAanDeBeurt(String gebruikersnaam, int geboortedatum) {
Speler s = geefSpeler(new Speler(gebruikersnaam, geboortedatum));
return huidigeSpeler.equals(s);
}
// methode om de spelers aan het begin van het spel al ontwikkelingskaarten te
// geven
public void preload() {
for (Speler s : spelers) {
neemKaarten(s, niveau1, 5);
neemKaarten(s, niveau2, 3);
// neemKaarten(s, niveau3, 1);
}
}
private void neemKaarten(Speler s, OntwikkelingskaartRepository ontwikklingskaartRepo, int aantal) {
for (int i = 0; i < aantal; i++) {
Ontwikkelingskaart kaart = ontwikklingskaartRepo.geefOntwikkelingskaart(i);
ontwikklingskaartRepo.verwijderOntwikkelingskaart(kaart);
s.voegOntwikkelingskaartToe(kaart);
}
}
// methode die alle ontwikkelingskaarten uit het spel retourneert
public List<Ontwikkelingskaart> geefAlleOntwikkelingskaarten() {
List<Ontwikkelingskaart> alleOntwikkelingskaarten = geefNiveau2En3();
for (Ontwikkelingskaart o : niveau1.getOntwikkelingskaarten()) {
alleOntwikkelingskaarten.add(o);
}
return alleOntwikkelingskaarten;
}
public List<Ontwikkelingskaart> geefNiveau2En3() {
List<Ontwikkelingskaart> kaarten = new ArrayList<>();
for (Ontwikkelingskaart o : niveau2.getOntwikkelingskaarten()) {
kaarten.add(o);
}
for (Ontwikkelingskaart o : niveau3.getOntwikkelingskaarten()) {
kaarten.add(o);
}
return kaarten;
}
// methode om het nemen van een Edele te testen
public void geefGenoegKaartenOmEdelenTeKopen() {
Speler s = spelers.get(0);
int[] aantallen = new int[5];
List<Ontwikkelingskaart> kaarten = geefAlleOntwikkelingskaarten();
Collections.shuffle(kaarten);
int i = 0;
while (s.getOntwikkelingskaarten().size() < 20) {
Ontwikkelingskaart o = kaarten.get(i++);
int bonus = Kleur.valueOf(o.getBonus().toUpperCase()).ordinal();
if (aantallen[bonus] < 4) {
s.voegOntwikkelingskaartToe(o);
}
aantallen[bonus]++;
}
}
private void geef15Prestigepunten(int index) {
Speler s = spelers.get(index);
int i = 0;
List<Ontwikkelingskaart> kaarten = geefNiveau2En3();
while (s.getPrestigePunten() != 15) {
Ontwikkelingskaart o = kaarten.get(i++);
if (s.getPrestigePunten() + o.getPrestigepunten() <= 15) {
s.voegOntwikkelingskaartToe(o);
}
}
}
public void maakWinnaars() {
geef15Prestigepunten(0);
geef15Prestigepunten(1);
}
}
|
36878_41 | package be.ugent.intec.ibcn.dbase.tooling.editor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import org.eclipse.bpmn2.Collaboration;
import org.eclipse.bpmn2.EndEvent;
import org.eclipse.bpmn2.ExclusiveGateway;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.FlowNode;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.GatewayDirection;
import org.eclipse.bpmn2.MessageFlow;
import org.eclipse.bpmn2.ParallelGateway;
import org.eclipse.bpmn2.Participant;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.bpmn2.StartEvent;
import org.eclipse.bpmn2.impl.StartEventImpl;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
class CollaborationHelper {
static List<Process> processes;
static List<MessageFlow> messageFlows;
static Map<FlowNode, MessageFlow> sending;
static Map<FlowNode, MessageFlow> receiving;
// //
static Map<Process, List<TimeObject>> processVectors;
static Map<FlowNode, TimeObject> flowNodeTimeObject;
static Map<FlowNode, List<TimeObject>> flowNodeTimeVectors;
// //
//
static Map<Process, Stack<FlowNode>> gateways;
//
public static boolean validate(Collaboration original,
Collaboration collaboration) {
// messageflows --> sending/receiving
messageFlows = collaboration.getMessageFlows();
sending = new HashMap<FlowNode, MessageFlow>();
receiving = new HashMap<FlowNode, MessageFlow>();
for (MessageFlow messageFlow : messageFlows) {
FlowNode source = (FlowNode) messageFlow.getSourceRef();
FlowNode target = (FlowNode) messageFlow.getTargetRef();
sending.put(source, messageFlow);
receiving.put(target, messageFlow);
}
processes = new ArrayList<Process>();
for (Participant participant : collaboration.getParticipants()) {
processes.add(participant.getProcessRef());
}
// //
processVectors = new HashMap<Process, List<TimeObject>>();
gateways = new HashMap<Process, Stack<FlowNode>>();
for (Process process : processes) {
List<TimeObject> vector = new ArrayList<TimeObject>();
for (int i = 0; i < processes.size(); i++) {
vector.add(new TimeObject());
}
processVectors.put(process, vector);
gateways.put(process, new Stack<FlowNode>());
}
// //
// start pointers per process
// assign time objects
List<FlowNode> pointers = new ArrayList<FlowNode>();
flowNodeTimeObject = new HashMap<FlowNode, TimeObject>();
flowNodeTimeVectors = new HashMap<FlowNode, List<TimeObject>>();
for (Process process : processes) {
if (process != null) {
List<FlowElement> flowElements = process.getFlowElements();
for (FlowElement flowElement : flowElements) {
if (flowElement instanceof StartEvent) {
pointers.add((FlowNode) flowElement);
// //
int i = processes.indexOf(process);
TimeObject timeObject = processVectors.get(process)
.get(i);
flowNodeTimeObject.put((FlowNode) flowElement,
TimeObject.clone(timeObject));
List<TimeObject> timeVector = processVectors.get(process);
flowNodeTimeVectors.put((FlowNode) flowElement, TimeObject.clone(timeVector));
printTimeObject((FlowNode) flowElement);
printTimeVector((FlowNode) flowElement);
// //
}
}
}
}
// move pointers and set vector clocks per node
while (pointers.size() != 0) {
// move pointers as long as they are not sending or receiving and
// not on gateway (diverging/converging)
// while incrementing vector clocks per node
List<FlowNode> updatedPointers = new ArrayList<FlowNode>();
for (FlowNode pointer : pointers) {
while (pointer != null && hasNext(pointer)
&& !isReceiving(pointer) && !isSending(pointer)
&& !isConverging(pointer) && !isDiverging(pointer)) {
// // Hold current time
TimeObject timeObject = flowNodeTimeObject.get(pointer);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
// //
pointer = moveNext(pointer);
if (pointer != null && !isConverging(pointer)) {
// // Assign to next flow element
TimeObject to = TimeObject.clone(timeObject);
List<TimeObject> tv = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer, to);
flowNodeTimeVectors.put(pointer, tv);
printTimeObject(pointer);
printTimeVector(pointer);
// //
if (!(pointer instanceof StartEvent
|| pointer instanceof EndEvent
|| pointer instanceof Gateway
|| isSending(pointer) || isReceiving(pointer))) {
// // increment if not startevent or gateway
to.increment();
tv.get(processes.indexOf(pointer.eContainer())).increment();
printTimeObject(pointer);
printTimeVector(pointer);
}
}
}
if (pointer != null) {
updatedPointers.add(pointer);
}
}
pointers = updatedPointers;
// validate messageflows + fork/join
List<FlowNode> updatedPointers2 = new ArrayList<FlowNode>();
for (FlowNode pointer : pointers) {
if (isSending(pointer) || isReceiving(pointer)) {
// validate messageflow
FlowNode sendingNode = null;
FlowNode receivingNode = null;
if (isSending(pointer)) {
sendingNode = pointer;
receivingNode = (FlowNode) sending.get(pointer)
.getTargetRef();
} else if (isReceiving(pointer)) {
receivingNode = pointer;
sendingNode = (FlowNode) receiving.get(pointer)
.getSourceRef();
}
boolean sendingNodeReached = false;
boolean receivingNodeReached = false;
for (FlowNode ptr : pointers) {
if (ptr.equals(sendingNode)) {
sendingNodeReached = true;
}
if (ptr.equals(receivingNode)) {
receivingNodeReached = true;
}
}
if (sendingNodeReached == true
&& receivingNodeReached == true) {
// check valid
boolean valid = validateMessageFlow(sendingNode, receivingNode);
if (!valid) {
//return false;
}
// increment clocks
flowNodeTimeObject.get(sendingNode).increment();
flowNodeTimeVectors.get(sendingNode).get(processes.indexOf(sendingNode.eContainer())).increment();
printTimeObject(sendingNode);
printTimeVector(sendingNode);
flowNodeTimeObject.get(receivingNode).increment();
flowNodeTimeVectors.get(receivingNode).get(processes.indexOf(receivingNode.eContainer())).increment();
// update receiving process knowledge about sending
// process
List<TimeObject> receivingNodeTimeVector = flowNodeTimeVectors.get(receivingNode);
List<TimeObject> sendingNodeTimeVector = flowNodeTimeVectors.get(sendingNode);
TimeObject.supremumVectorClock(receivingNodeTimeVector, sendingNodeTimeVector);
printTimeObject(receivingNode);
printTimeVector(receivingNode);
// move both pointers
List<FlowNode> nodes = new ArrayList<FlowNode>();
nodes.add(sendingNode);
nodes.add(receivingNode);
for (FlowNode pointer1 : nodes) {
// // Hold current time
TimeObject timeObject = flowNodeTimeObject.get(pointer1);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer1);
// //
pointer1 = moveNext(pointer1);
if (pointer1 != null && !isConverging(pointer1)) {
// // Assign to next flow element
TimeObject to = TimeObject.clone(timeObject);
List<TimeObject> tv = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer1, to);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// //
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not start/end event,
// gateway or receiving or sending
to.increment();
tv.get(processes.indexOf(pointer1.eContainer())).increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
}
updatedPointers2.add(pointer1);
}
// remove sending+receiving (when checking counterpart,
// no need to fix messageflow twice)
sending.remove(sendingNode);
receiving.remove(receivingNode);
} else {
// keep waiting
updatedPointers2.add(pointer);
}
} else if (isConverging(pointer)) {
// join (indien nog niet gebeurt (geen timeobject voor
// gateway)
if (!flowNodeTimeObject.containsKey(pointer)) {
// pas als paden volledig behandeld zijn.
// evenveel pointers wijzen naar gateway, als er
// inkomende paden zijn.
int aantal = 0;
for (FlowNode ptr : pointers) {
if (ptr.getId().equals(pointer.getId())) {
aantal++;
}
}
List<SequenceFlow> incoming = pointer.getIncoming();
if (aantal == incoming.size()) {
// kijken als parallel zijn
FlowNode firstGateway = gateways.get(pointer.eContainer()).pop();
System.out.println(firstGateway.getName() + " - " + pointer.getName());
// first elements
List<FlowNode> firstNodes = new ArrayList<FlowNode>();
getFirstNodes(firstGateway, firstNodes);
// last elements
List<FlowNode> lastNodes = new ArrayList<FlowNode>();
getLastNodes(pointer, lastNodes);
// compare
boolean parallel = false;
for(FlowNode n1 : firstNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
int k1 = timeVectorN1.get(processes.indexOf(n1.eContainer())).getK();
for(FlowNode n2 : lastNodes){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
int k2 = timeVectorN2.get(processes.indexOf(n2.eContainer())).getK();
// if zelfde k-waarde
if(k1 != k2){
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
for(FlowNode n1 : firstNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
for(FlowNode n2 : firstNodes){
if(!n1.equals(n2)){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
for(FlowNode n1 : lastNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
for(FlowNode n2 : lastNodes){
if(!n1.equals(n2)){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
// //
List<TimeObject> timeObjects = new ArrayList<TimeObject>();
List<List<TimeObject>> timeVectors = new ArrayList<List<TimeObject>>();
for (SequenceFlow sequenceFlow : incoming) {
FlowNode node = sequenceFlow.getSourceRef();
if (flowNodeTimeObject.containsKey(node)) {
TimeObject timeObject = flowNodeTimeObject.get(node);
timeObjects.add(timeObject);
}
if (flowNodeTimeVectors.containsKey(node)){
List<TimeObject> timeVector = flowNodeTimeVectors.get(node);
timeVectors.add(timeVector);
}
}
TimeObject newTime = TimeObject.supremum(timeObjects);
List<TimeObject> newTimeVector = new ArrayList<TimeObject>();
int huidig = processes.indexOf(pointer.eContainer());
for(int i=0; i<processes.size(); i++){
if(i == huidig){
newTimeVector.add(i, newTime);
}else{
// grootste TimeObject van alle inkomende verbindingen hun TimeVector
TimeObject greatestTimeObject = new TimeObject();
for(List<TimeObject> vector : timeVectors){
TimeObject to = TimeObject.clone(vector.get(i));
while(to.getParent() != null){
to = to.getParent();
}
/*if(greatestTimeObject.lessOrEqualThan(to)){
greatestTimeObject = to;
}*/
TimeObject.sup(greatestTimeObject, to);
}
newTimeVector.add(i, greatestTimeObject);
}
}
// //
// set timeObject on gateway (prevents checking
// gateway twice)
TimeObject to = TimeObject.clone(newTime);
List<TimeObject> tv = TimeObject.clone(newTimeVector);
flowNodeTimeObject.put(pointer, to);
flowNodeTimeVectors.put(pointer, tv);
printTimeObject(pointer);
printTimeVector(pointer);
// move pointer
FlowNode pointer1 = pointer.getOutgoing().get(0).getTargetRef();
// set pointer
flowNodeTimeObject.put(pointer1, to);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// increment if not startevent or gateway
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not startevent or gateway
to.increment();
tv.get(processes.indexOf(pointer1.eContainer())).increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
updatedPointers2.add(pointer1);
} else {
// keep waiting
updatedPointers2.add(pointer);
}
}
} else if (isDiverging(pointer)) {
// fork
gateways.get(pointer.eContainer()).push(pointer);
// //
TimeObject timeObject = flowNodeTimeObject.get(pointer);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
List<SequenceFlow> outgoing = pointer.getOutgoing();
List<TimeObject> tos = new ArrayList<TimeObject>();
for (int i = 0; i < outgoing.size(); i++){
TimeObject to = timeObject.addTimeObject();
tos.add(to);
}
TimeObject newTimeObject = TimeObject.clone(tos.get(0).getParent());
List<TimeObject> newTimeVector = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer, newTimeObject);
newTimeVector.set(processes.indexOf(pointer.eContainer()), newTimeObject);
flowNodeTimeVectors.put(pointer, newTimeVector);
printTimeObject(pointer);
printTimeVector(pointer);
for (int i = 0; i < outgoing.size(); i++) {
// hold current time object
TimeObject to = TimeObject.clone(tos.get(i));
// move pointer
FlowNode pointer1 = outgoing.get(i).getTargetRef();
// set pointer (if not converging gateway)
if (!isConverging(pointer1)) {
TimeObject toc = TimeObject.clone(to);
List<TimeObject> tv = TimeObject.clone(newTimeVector);
TimeObject tocc = TimeObject.clone(toc);
tv.set(processes.indexOf(pointer.eContainer()), tocc);
flowNodeTimeObject.put(pointer1, toc);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// increment if not startevent or gateway
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not startevent or gateway
toc.increment();
tocc.increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
}
updatedPointers2.add(pointer1);
}
// //
}
}
pointers = updatedPointers2;
}
// saveCollaboration(original, collaboration);
// printTimeVectors();
return true;
}
private static void getLastNodes(FlowNode node, List<FlowNode> nodes) {
if(isConverging(node)){
List<SequenceFlow> incoming = node.getIncoming();
for(SequenceFlow sf : incoming){
FlowNode node1 = sf.getSourceRef();
getLastNodes(node1, nodes);
}
}else{
nodes.add(node);
}
}
private static void getFirstNodes(FlowNode firstGateway,
List<FlowNode> firstNodes) {
if(isDiverging(firstGateway)){
List<SequenceFlow> outgoing = firstGateway.getOutgoing();
for(SequenceFlow sf : outgoing){
FlowNode node = sf.getTargetRef();
getFirstNodes(node, firstNodes);
}
}else{
firstNodes.add(firstGateway);
}
}
private static void printTimeVectors() {
// TODO Auto-generated method stub
Iterator it = flowNodeTimeVectors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<FlowNode, List<TimeObject>> pair = (Entry<FlowNode, List<TimeObject>>)it.next();
printTimeVector(pair.getKey());
it.remove(); // avoids a ConcurrentModificationException
}
}
private static void printTimeVector(FlowNode pointer) {
// change name
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
String output = pointer.getName();
output += "\t";
for(TimeObject timeObject : timeVector){
while (timeObject.getParent() != null) {
timeObject = timeObject.getParent();
}
output += timeObject.toString();
}
System.out.println(output);
}
private static void printTimeObject(FlowNode pointer) {
// change name
/*TimeObject timeObject = flowNodeTimeObject.get(pointer);
while (timeObject.getParent() != null) {
timeObject = timeObject.getParent();
}
//pointer.setName(timeObject.toString());
System.out.println(pointer.getName() + "\t" + timeObject);*/
// //
}
private static void saveCollaboration(Collaboration original,
Collaboration collaboration) {
original.getParticipants()
.get(0)
.setProcessRef(
collaboration.getParticipants().get(0).getProcessRef());
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("key", new XMIResourceFactoryImpl());
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(URI
.createFileURI("C:\\Users\\janseeuw\\Documents\\"
+ original.hashCode() + ".bpmn"));
resource.getContents().add(original.eContainer().eContainer());
try {
resource.save(Collections.EMPTY_MAP);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static boolean isSending(FlowNode node) {
return sending.containsKey(node);
}
private static boolean isReceiving(FlowNode node) {
return receiving.containsKey(node);
}
private static boolean isConverging(FlowNode node) {
if (node instanceof Gateway) {
Gateway gateway = (Gateway) node;
return gateway instanceof ParallelGateway
&& gateway.getGatewayDirection() == GatewayDirection.CONVERGING;
} else {
return false;
}
}
private static boolean isDiverging(FlowNode node) {
if (node instanceof Gateway) {
Gateway gateway = (Gateway) node;
return gateway instanceof ParallelGateway
&& gateway.getGatewayDirection() == GatewayDirection.DIVERGING;
} else {
return false;
}
}
private static boolean hasNext(FlowNode node) {
List<SequenceFlow> taskOutgoing = node.getOutgoing();
return taskOutgoing.size() != 0;
}
private static FlowNode moveNext(FlowNode node) {
List<SequenceFlow> taskOutgoing = node.getOutgoing();
if (taskOutgoing.size() != 0) {
// follow (first) sequenceflow
node = taskOutgoing.get(0).getTargetRef();
} else {
// op het einde
node = null;
}
return node;
}
private static boolean validateMessageFlow(FlowNode sendingNode,
FlowNode receivingNode) {
List<TimeObject> sendingNodeTimeVector = flowNodeTimeVectors.get(sendingNode);
List<TimeObject> receivingNodeTimeVector = flowNodeTimeVectors.get(receivingNode);
Process receivingProcess = (Process) receivingNode.eContainer();
int index = processes.indexOf(receivingProcess);
Process sendingProcess = (Process) sendingNode.eContainer();
// clone omdat we aanpassingen gaan doen
TimeObject sendingNodeTimeObject = TimeObject.clone(sendingNodeTimeVector.get(index));
TimeObject receivingNodeTimeObject = TimeObject.clone(receivingNodeTimeVector.get(index));
// op zelfde niveau brengen
if(sendingNodeTimeObject.getDepth() < receivingNodeTimeObject.getDepth()){
while(sendingNodeTimeObject.getDepth() != receivingNodeTimeObject.getDepth()){
receivingNodeTimeObject = TimeObject.supremum(receivingNodeTimeObject.getParent().getTimeObjects());
}
}else if(sendingNodeTimeObject.getDepth() > receivingNodeTimeObject.getDepth()){
while(sendingNodeTimeObject.getDepth() != receivingNodeTimeObject.getDepth()){
sendingNodeTimeObject = TimeObject.supremum(sendingNodeTimeObject.getParent().getTimeObjects());
}
}
return sendingNodeTimeObject.getI() == receivingNodeTimeObject.getI();
}
}
| janseeuw/BPMN2-modeler | be.ugent.intec.ibcn.dbase.tooling/src/be/ugent/intec/ibcn/dbase/tooling/editor/CollaborationHelper.java | 6,401 | // op zelfde niveau brengen | line_comment | nl | package be.ugent.intec.ibcn.dbase.tooling.editor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import org.eclipse.bpmn2.Collaboration;
import org.eclipse.bpmn2.EndEvent;
import org.eclipse.bpmn2.ExclusiveGateway;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.FlowNode;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.GatewayDirection;
import org.eclipse.bpmn2.MessageFlow;
import org.eclipse.bpmn2.ParallelGateway;
import org.eclipse.bpmn2.Participant;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.bpmn2.StartEvent;
import org.eclipse.bpmn2.impl.StartEventImpl;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
class CollaborationHelper {
static List<Process> processes;
static List<MessageFlow> messageFlows;
static Map<FlowNode, MessageFlow> sending;
static Map<FlowNode, MessageFlow> receiving;
// //
static Map<Process, List<TimeObject>> processVectors;
static Map<FlowNode, TimeObject> flowNodeTimeObject;
static Map<FlowNode, List<TimeObject>> flowNodeTimeVectors;
// //
//
static Map<Process, Stack<FlowNode>> gateways;
//
public static boolean validate(Collaboration original,
Collaboration collaboration) {
// messageflows --> sending/receiving
messageFlows = collaboration.getMessageFlows();
sending = new HashMap<FlowNode, MessageFlow>();
receiving = new HashMap<FlowNode, MessageFlow>();
for (MessageFlow messageFlow : messageFlows) {
FlowNode source = (FlowNode) messageFlow.getSourceRef();
FlowNode target = (FlowNode) messageFlow.getTargetRef();
sending.put(source, messageFlow);
receiving.put(target, messageFlow);
}
processes = new ArrayList<Process>();
for (Participant participant : collaboration.getParticipants()) {
processes.add(participant.getProcessRef());
}
// //
processVectors = new HashMap<Process, List<TimeObject>>();
gateways = new HashMap<Process, Stack<FlowNode>>();
for (Process process : processes) {
List<TimeObject> vector = new ArrayList<TimeObject>();
for (int i = 0; i < processes.size(); i++) {
vector.add(new TimeObject());
}
processVectors.put(process, vector);
gateways.put(process, new Stack<FlowNode>());
}
// //
// start pointers per process
// assign time objects
List<FlowNode> pointers = new ArrayList<FlowNode>();
flowNodeTimeObject = new HashMap<FlowNode, TimeObject>();
flowNodeTimeVectors = new HashMap<FlowNode, List<TimeObject>>();
for (Process process : processes) {
if (process != null) {
List<FlowElement> flowElements = process.getFlowElements();
for (FlowElement flowElement : flowElements) {
if (flowElement instanceof StartEvent) {
pointers.add((FlowNode) flowElement);
// //
int i = processes.indexOf(process);
TimeObject timeObject = processVectors.get(process)
.get(i);
flowNodeTimeObject.put((FlowNode) flowElement,
TimeObject.clone(timeObject));
List<TimeObject> timeVector = processVectors.get(process);
flowNodeTimeVectors.put((FlowNode) flowElement, TimeObject.clone(timeVector));
printTimeObject((FlowNode) flowElement);
printTimeVector((FlowNode) flowElement);
// //
}
}
}
}
// move pointers and set vector clocks per node
while (pointers.size() != 0) {
// move pointers as long as they are not sending or receiving and
// not on gateway (diverging/converging)
// while incrementing vector clocks per node
List<FlowNode> updatedPointers = new ArrayList<FlowNode>();
for (FlowNode pointer : pointers) {
while (pointer != null && hasNext(pointer)
&& !isReceiving(pointer) && !isSending(pointer)
&& !isConverging(pointer) && !isDiverging(pointer)) {
// // Hold current time
TimeObject timeObject = flowNodeTimeObject.get(pointer);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
// //
pointer = moveNext(pointer);
if (pointer != null && !isConverging(pointer)) {
// // Assign to next flow element
TimeObject to = TimeObject.clone(timeObject);
List<TimeObject> tv = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer, to);
flowNodeTimeVectors.put(pointer, tv);
printTimeObject(pointer);
printTimeVector(pointer);
// //
if (!(pointer instanceof StartEvent
|| pointer instanceof EndEvent
|| pointer instanceof Gateway
|| isSending(pointer) || isReceiving(pointer))) {
// // increment if not startevent or gateway
to.increment();
tv.get(processes.indexOf(pointer.eContainer())).increment();
printTimeObject(pointer);
printTimeVector(pointer);
}
}
}
if (pointer != null) {
updatedPointers.add(pointer);
}
}
pointers = updatedPointers;
// validate messageflows + fork/join
List<FlowNode> updatedPointers2 = new ArrayList<FlowNode>();
for (FlowNode pointer : pointers) {
if (isSending(pointer) || isReceiving(pointer)) {
// validate messageflow
FlowNode sendingNode = null;
FlowNode receivingNode = null;
if (isSending(pointer)) {
sendingNode = pointer;
receivingNode = (FlowNode) sending.get(pointer)
.getTargetRef();
} else if (isReceiving(pointer)) {
receivingNode = pointer;
sendingNode = (FlowNode) receiving.get(pointer)
.getSourceRef();
}
boolean sendingNodeReached = false;
boolean receivingNodeReached = false;
for (FlowNode ptr : pointers) {
if (ptr.equals(sendingNode)) {
sendingNodeReached = true;
}
if (ptr.equals(receivingNode)) {
receivingNodeReached = true;
}
}
if (sendingNodeReached == true
&& receivingNodeReached == true) {
// check valid
boolean valid = validateMessageFlow(sendingNode, receivingNode);
if (!valid) {
//return false;
}
// increment clocks
flowNodeTimeObject.get(sendingNode).increment();
flowNodeTimeVectors.get(sendingNode).get(processes.indexOf(sendingNode.eContainer())).increment();
printTimeObject(sendingNode);
printTimeVector(sendingNode);
flowNodeTimeObject.get(receivingNode).increment();
flowNodeTimeVectors.get(receivingNode).get(processes.indexOf(receivingNode.eContainer())).increment();
// update receiving process knowledge about sending
// process
List<TimeObject> receivingNodeTimeVector = flowNodeTimeVectors.get(receivingNode);
List<TimeObject> sendingNodeTimeVector = flowNodeTimeVectors.get(sendingNode);
TimeObject.supremumVectorClock(receivingNodeTimeVector, sendingNodeTimeVector);
printTimeObject(receivingNode);
printTimeVector(receivingNode);
// move both pointers
List<FlowNode> nodes = new ArrayList<FlowNode>();
nodes.add(sendingNode);
nodes.add(receivingNode);
for (FlowNode pointer1 : nodes) {
// // Hold current time
TimeObject timeObject = flowNodeTimeObject.get(pointer1);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer1);
// //
pointer1 = moveNext(pointer1);
if (pointer1 != null && !isConverging(pointer1)) {
// // Assign to next flow element
TimeObject to = TimeObject.clone(timeObject);
List<TimeObject> tv = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer1, to);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// //
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not start/end event,
// gateway or receiving or sending
to.increment();
tv.get(processes.indexOf(pointer1.eContainer())).increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
}
updatedPointers2.add(pointer1);
}
// remove sending+receiving (when checking counterpart,
// no need to fix messageflow twice)
sending.remove(sendingNode);
receiving.remove(receivingNode);
} else {
// keep waiting
updatedPointers2.add(pointer);
}
} else if (isConverging(pointer)) {
// join (indien nog niet gebeurt (geen timeobject voor
// gateway)
if (!flowNodeTimeObject.containsKey(pointer)) {
// pas als paden volledig behandeld zijn.
// evenveel pointers wijzen naar gateway, als er
// inkomende paden zijn.
int aantal = 0;
for (FlowNode ptr : pointers) {
if (ptr.getId().equals(pointer.getId())) {
aantal++;
}
}
List<SequenceFlow> incoming = pointer.getIncoming();
if (aantal == incoming.size()) {
// kijken als parallel zijn
FlowNode firstGateway = gateways.get(pointer.eContainer()).pop();
System.out.println(firstGateway.getName() + " - " + pointer.getName());
// first elements
List<FlowNode> firstNodes = new ArrayList<FlowNode>();
getFirstNodes(firstGateway, firstNodes);
// last elements
List<FlowNode> lastNodes = new ArrayList<FlowNode>();
getLastNodes(pointer, lastNodes);
// compare
boolean parallel = false;
for(FlowNode n1 : firstNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
int k1 = timeVectorN1.get(processes.indexOf(n1.eContainer())).getK();
for(FlowNode n2 : lastNodes){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
int k2 = timeVectorN2.get(processes.indexOf(n2.eContainer())).getK();
// if zelfde k-waarde
if(k1 != k2){
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
for(FlowNode n1 : firstNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
for(FlowNode n2 : firstNodes){
if(!n1.equals(n2)){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
for(FlowNode n1 : lastNodes){
List<TimeObject> timeVectorN1 = flowNodeTimeVectors.get(n1);
for(FlowNode n2 : lastNodes){
if(!n1.equals(n2)){
List<TimeObject> timeVectorN2 = flowNodeTimeVectors.get(n2);
System.out.println(n1.getName() + " " + TimeObject.printTimeVector(timeVectorN1) + " || " + n2.getName() + " " + TimeObject.printTimeVector(timeVectorN2) );
for(int i=0; i<processes.size(); i++){
TimeObject to1 = TimeObject.clone(timeVectorN1.get(i));
while(to1.getParent() != null){
to1 = to1.getParent();
}
TimeObject to2 = TimeObject.clone(timeVectorN2.get(i));
while(to2.getParent() != null){
to2 = to2.getParent();
}
if(to1.isParallel(to2)){
parallel = true;
}
}
if(!parallel){
return false;
}
}
}
}
// //
List<TimeObject> timeObjects = new ArrayList<TimeObject>();
List<List<TimeObject>> timeVectors = new ArrayList<List<TimeObject>>();
for (SequenceFlow sequenceFlow : incoming) {
FlowNode node = sequenceFlow.getSourceRef();
if (flowNodeTimeObject.containsKey(node)) {
TimeObject timeObject = flowNodeTimeObject.get(node);
timeObjects.add(timeObject);
}
if (flowNodeTimeVectors.containsKey(node)){
List<TimeObject> timeVector = flowNodeTimeVectors.get(node);
timeVectors.add(timeVector);
}
}
TimeObject newTime = TimeObject.supremum(timeObjects);
List<TimeObject> newTimeVector = new ArrayList<TimeObject>();
int huidig = processes.indexOf(pointer.eContainer());
for(int i=0; i<processes.size(); i++){
if(i == huidig){
newTimeVector.add(i, newTime);
}else{
// grootste TimeObject van alle inkomende verbindingen hun TimeVector
TimeObject greatestTimeObject = new TimeObject();
for(List<TimeObject> vector : timeVectors){
TimeObject to = TimeObject.clone(vector.get(i));
while(to.getParent() != null){
to = to.getParent();
}
/*if(greatestTimeObject.lessOrEqualThan(to)){
greatestTimeObject = to;
}*/
TimeObject.sup(greatestTimeObject, to);
}
newTimeVector.add(i, greatestTimeObject);
}
}
// //
// set timeObject on gateway (prevents checking
// gateway twice)
TimeObject to = TimeObject.clone(newTime);
List<TimeObject> tv = TimeObject.clone(newTimeVector);
flowNodeTimeObject.put(pointer, to);
flowNodeTimeVectors.put(pointer, tv);
printTimeObject(pointer);
printTimeVector(pointer);
// move pointer
FlowNode pointer1 = pointer.getOutgoing().get(0).getTargetRef();
// set pointer
flowNodeTimeObject.put(pointer1, to);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// increment if not startevent or gateway
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not startevent or gateway
to.increment();
tv.get(processes.indexOf(pointer1.eContainer())).increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
updatedPointers2.add(pointer1);
} else {
// keep waiting
updatedPointers2.add(pointer);
}
}
} else if (isDiverging(pointer)) {
// fork
gateways.get(pointer.eContainer()).push(pointer);
// //
TimeObject timeObject = flowNodeTimeObject.get(pointer);
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
List<SequenceFlow> outgoing = pointer.getOutgoing();
List<TimeObject> tos = new ArrayList<TimeObject>();
for (int i = 0; i < outgoing.size(); i++){
TimeObject to = timeObject.addTimeObject();
tos.add(to);
}
TimeObject newTimeObject = TimeObject.clone(tos.get(0).getParent());
List<TimeObject> newTimeVector = TimeObject.clone(timeVector);
flowNodeTimeObject.put(pointer, newTimeObject);
newTimeVector.set(processes.indexOf(pointer.eContainer()), newTimeObject);
flowNodeTimeVectors.put(pointer, newTimeVector);
printTimeObject(pointer);
printTimeVector(pointer);
for (int i = 0; i < outgoing.size(); i++) {
// hold current time object
TimeObject to = TimeObject.clone(tos.get(i));
// move pointer
FlowNode pointer1 = outgoing.get(i).getTargetRef();
// set pointer (if not converging gateway)
if (!isConverging(pointer1)) {
TimeObject toc = TimeObject.clone(to);
List<TimeObject> tv = TimeObject.clone(newTimeVector);
TimeObject tocc = TimeObject.clone(toc);
tv.set(processes.indexOf(pointer.eContainer()), tocc);
flowNodeTimeObject.put(pointer1, toc);
flowNodeTimeVectors.put(pointer1, tv);
printTimeObject(pointer1);
printTimeVector(pointer1);
// increment if not startevent or gateway
if (!(pointer1 instanceof StartEvent
|| pointer1 instanceof EndEvent
|| pointer1 instanceof Gateway
|| isSending(pointer1) || isReceiving(pointer1))) {
// // increment if not startevent or gateway
toc.increment();
tocc.increment();
printTimeObject(pointer1);
printTimeVector(pointer1);
}
}
updatedPointers2.add(pointer1);
}
// //
}
}
pointers = updatedPointers2;
}
// saveCollaboration(original, collaboration);
// printTimeVectors();
return true;
}
private static void getLastNodes(FlowNode node, List<FlowNode> nodes) {
if(isConverging(node)){
List<SequenceFlow> incoming = node.getIncoming();
for(SequenceFlow sf : incoming){
FlowNode node1 = sf.getSourceRef();
getLastNodes(node1, nodes);
}
}else{
nodes.add(node);
}
}
private static void getFirstNodes(FlowNode firstGateway,
List<FlowNode> firstNodes) {
if(isDiverging(firstGateway)){
List<SequenceFlow> outgoing = firstGateway.getOutgoing();
for(SequenceFlow sf : outgoing){
FlowNode node = sf.getTargetRef();
getFirstNodes(node, firstNodes);
}
}else{
firstNodes.add(firstGateway);
}
}
private static void printTimeVectors() {
// TODO Auto-generated method stub
Iterator it = flowNodeTimeVectors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<FlowNode, List<TimeObject>> pair = (Entry<FlowNode, List<TimeObject>>)it.next();
printTimeVector(pair.getKey());
it.remove(); // avoids a ConcurrentModificationException
}
}
private static void printTimeVector(FlowNode pointer) {
// change name
List<TimeObject> timeVector = flowNodeTimeVectors.get(pointer);
String output = pointer.getName();
output += "\t";
for(TimeObject timeObject : timeVector){
while (timeObject.getParent() != null) {
timeObject = timeObject.getParent();
}
output += timeObject.toString();
}
System.out.println(output);
}
private static void printTimeObject(FlowNode pointer) {
// change name
/*TimeObject timeObject = flowNodeTimeObject.get(pointer);
while (timeObject.getParent() != null) {
timeObject = timeObject.getParent();
}
//pointer.setName(timeObject.toString());
System.out.println(pointer.getName() + "\t" + timeObject);*/
// //
}
private static void saveCollaboration(Collaboration original,
Collaboration collaboration) {
original.getParticipants()
.get(0)
.setProcessRef(
collaboration.getParticipants().get(0).getProcessRef());
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("key", new XMIResourceFactoryImpl());
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(URI
.createFileURI("C:\\Users\\janseeuw\\Documents\\"
+ original.hashCode() + ".bpmn"));
resource.getContents().add(original.eContainer().eContainer());
try {
resource.save(Collections.EMPTY_MAP);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static boolean isSending(FlowNode node) {
return sending.containsKey(node);
}
private static boolean isReceiving(FlowNode node) {
return receiving.containsKey(node);
}
private static boolean isConverging(FlowNode node) {
if (node instanceof Gateway) {
Gateway gateway = (Gateway) node;
return gateway instanceof ParallelGateway
&& gateway.getGatewayDirection() == GatewayDirection.CONVERGING;
} else {
return false;
}
}
private static boolean isDiverging(FlowNode node) {
if (node instanceof Gateway) {
Gateway gateway = (Gateway) node;
return gateway instanceof ParallelGateway
&& gateway.getGatewayDirection() == GatewayDirection.DIVERGING;
} else {
return false;
}
}
private static boolean hasNext(FlowNode node) {
List<SequenceFlow> taskOutgoing = node.getOutgoing();
return taskOutgoing.size() != 0;
}
private static FlowNode moveNext(FlowNode node) {
List<SequenceFlow> taskOutgoing = node.getOutgoing();
if (taskOutgoing.size() != 0) {
// follow (first) sequenceflow
node = taskOutgoing.get(0).getTargetRef();
} else {
// op het einde
node = null;
}
return node;
}
private static boolean validateMessageFlow(FlowNode sendingNode,
FlowNode receivingNode) {
List<TimeObject> sendingNodeTimeVector = flowNodeTimeVectors.get(sendingNode);
List<TimeObject> receivingNodeTimeVector = flowNodeTimeVectors.get(receivingNode);
Process receivingProcess = (Process) receivingNode.eContainer();
int index = processes.indexOf(receivingProcess);
Process sendingProcess = (Process) sendingNode.eContainer();
// clone omdat we aanpassingen gaan doen
TimeObject sendingNodeTimeObject = TimeObject.clone(sendingNodeTimeVector.get(index));
TimeObject receivingNodeTimeObject = TimeObject.clone(receivingNodeTimeVector.get(index));
// op zelfde<SUF>
if(sendingNodeTimeObject.getDepth() < receivingNodeTimeObject.getDepth()){
while(sendingNodeTimeObject.getDepth() != receivingNodeTimeObject.getDepth()){
receivingNodeTimeObject = TimeObject.supremum(receivingNodeTimeObject.getParent().getTimeObjects());
}
}else if(sendingNodeTimeObject.getDepth() > receivingNodeTimeObject.getDepth()){
while(sendingNodeTimeObject.getDepth() != receivingNodeTimeObject.getDepth()){
sendingNodeTimeObject = TimeObject.supremum(sendingNodeTimeObject.getParent().getTimeObjects());
}
}
return sendingNodeTimeObject.getI() == receivingNodeTimeObject.getI();
}
}
|
162572_0 | package Src;
public class Main {
//main method in mijn main class maken!
//short cut just type main to have line below
//int is without "" string is with "eats " (bijvoorbeeld)
//initialialiseren in main
public static void main(String[] args) {
// ElectricPokemon Picka = new ElectricPokemon("fireup",1,3,"fire","fireballs","vuuuuw","kaaaboemmmm","flash flash");
// Picka.eats(" fireballs");
//// Picka.getLevel("+1");
//// Picka.setLightup(Picka.getElectricity());
WaterPokemon Chocin = new WaterPokemon ("Chocin", 5, "40", "water", "fish", "brieeey");
System.out.println( Chocin.eats());
Chocin.setSwim(Chocin.isSwim());
Chocin.speaks("brieeeuj");
}
}
| Majda-Mech/Java-Pokemon-Application | Src/Main.java | 219 | //main method in mijn main class maken! | line_comment | nl | package Src;
public class Main {
//main method<SUF>
//short cut just type main to have line below
//int is without "" string is with "eats " (bijvoorbeeld)
//initialialiseren in main
public static void main(String[] args) {
// ElectricPokemon Picka = new ElectricPokemon("fireup",1,3,"fire","fireballs","vuuuuw","kaaaboemmmm","flash flash");
// Picka.eats(" fireballs");
//// Picka.getLevel("+1");
//// Picka.setLightup(Picka.getElectricity());
WaterPokemon Chocin = new WaterPokemon ("Chocin", 5, "40", "water", "fish", "brieeey");
System.out.println( Chocin.eats());
Chocin.setSwim(Chocin.isSwim());
Chocin.speaks("brieeeuj");
}
}
|
46809_4 | package User;
import MixingProxy.MixingProxy;
import Registrar.Registrar;
import javafx.scene.paint.Color;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Scanner;
public class UserImpl extends UnicastRemoteObject implements User {
private Registrar registrar;
private MixingProxy mixingProxy;
private Color colorAfterQrScan;
private String phone;
private String name;
private String QRCode;
private String metInfectedPerson;
private ArrayList<byte[]> userTokens;
private ArrayList<String> userLogs = new ArrayList<>();
private byte[] currentToken;
public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException {
this.name = name;
this.phone = phone;
this.registrar = registrar;
this.userTokens = new ArrayList<>();
this.mixingProxy = mixingProxy;
}
// Interface methods
@Override
public String getPhone() throws RemoteException {
return phone;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException {
// New daily tokens
this.userTokens.clear();
this.userTokens.addAll(newUserTokens);
// Check if critical tokens are in logs
ArrayList<String> logs = readLogs();
ArrayList<String> informedUserTokens = new ArrayList<>();
if(!criticalTokens.isEmpty()){
boolean informed = false;
for(String[] sCt: criticalTokens ){
String criticalUserToken = sCt[0];
LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]);
LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]);
for(int i=0; i<logs.size(); i++) {
String logFromString = logs.get(i).split("\\^")[0];
LocalDateTime logFrom = LocalDateTime.parse(logFromString);
String QR = logs.get(i).split("\\^")[1];
String userToken = logs.get(i).split("\\^")[2];
i++;
String logUntilString = logs.get(i).split("\\^")[0];
LocalDateTime logUntil = LocalDateTime.parse(logUntilString);
if (criticalUserToken.equals(userToken) &&
!logUntil.isBefore(timeFrom) &&
!logFrom.isAfter(timeUntil)) {
System.out.println("Je bent in contact gekomen met een positief getest persoon");
informedUserTokens.add(userToken);
informed = true;
break;
}
}
if(informed){
break;
}
}
mixingProxy.informedTokens(informedUserTokens);
}
}
@Override
public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
// User Token
this.currentToken = userTokens.get(0);
//tijd
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
//qr code loggen
this.QRCode = qr;
userLogs.add(ldt + "^" + qr + "^" + currentToken);
System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken);
writeToLogFile(ldt, qr, currentToken);
//h value van qr code splitten om door te sturen in capsule
String h = qr.substring(qr.lastIndexOf("|") + 1);
boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken);
// Gebruikte token verwijderen
userTokens.remove(0);
//symbool toekennen indien jusite qr code scan
//op basis van business nummer een kleur toekennen
String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|'));
generateColor(businessNumber);
if(validityToken){
return "ok | " + ldt;
}
else return "not ok" + ldt;
}
@Override
public String leaveCatering(UserImpl user, String qr) throws RemoteException {
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
userLogs.add(ldt + "^" + qr);
writeToLogFile(ldt, qr, currentToken);
String h = qr.substring(qr.lastIndexOf("|") + 1);
mixingProxy.retrieveExitCapsule(ld, h, currentToken);
return "Successfully left catering";
}
public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){
String phoneForLog = phone.replace(" ", "_");
try {
File logFile = new File("logs/log_" + phoneForLog + ".txt");
if (!logFile.exists()){
logFile.createNewFile();
}
FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true);
logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken));
logFW.write("\n");
logFW.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void generateColor(String b){
switch (b) {
case "1":
this.colorAfterQrScan = Color.BLUE;
break;
case "2":
this.colorAfterQrScan = Color.GREEN;
break;
case "3":
this.colorAfterQrScan = Color.RED;
break;
case "4":
this.colorAfterQrScan = Color.ORANGE;
break;
default: this.colorAfterQrScan = Color.BLACK;
}
}
public Color getColorAfterQrScan() {
return colorAfterQrScan;
}
public ArrayList<String> readLogs(){
String phoneForLog = phone.replace(" ", "_");
ArrayList<String> logs = new ArrayList<>();
try {
File userLog = new File("logs/log_" + phoneForLog + ".txt");
if (!userLog.exists()){
userLog.createNewFile();
}
Scanner userLogReader = new Scanner(userLog);
while (userLogReader.hasNextLine()) {
logs.add(userLogReader.nextLine());
}
userLogReader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return logs;
}
//Setters en getters
public ArrayList<byte[]> getUserTokens() {
return userTokens;
}
}
| MartijnVanderschelden/ProjectDistributedSystems2 | src/User/UserImpl.java | 1,737 | // Gebruikte token verwijderen | line_comment | nl | package User;
import MixingProxy.MixingProxy;
import Registrar.Registrar;
import javafx.scene.paint.Color;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Scanner;
public class UserImpl extends UnicastRemoteObject implements User {
private Registrar registrar;
private MixingProxy mixingProxy;
private Color colorAfterQrScan;
private String phone;
private String name;
private String QRCode;
private String metInfectedPerson;
private ArrayList<byte[]> userTokens;
private ArrayList<String> userLogs = new ArrayList<>();
private byte[] currentToken;
public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException {
this.name = name;
this.phone = phone;
this.registrar = registrar;
this.userTokens = new ArrayList<>();
this.mixingProxy = mixingProxy;
}
// Interface methods
@Override
public String getPhone() throws RemoteException {
return phone;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException {
// New daily tokens
this.userTokens.clear();
this.userTokens.addAll(newUserTokens);
// Check if critical tokens are in logs
ArrayList<String> logs = readLogs();
ArrayList<String> informedUserTokens = new ArrayList<>();
if(!criticalTokens.isEmpty()){
boolean informed = false;
for(String[] sCt: criticalTokens ){
String criticalUserToken = sCt[0];
LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]);
LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]);
for(int i=0; i<logs.size(); i++) {
String logFromString = logs.get(i).split("\\^")[0];
LocalDateTime logFrom = LocalDateTime.parse(logFromString);
String QR = logs.get(i).split("\\^")[1];
String userToken = logs.get(i).split("\\^")[2];
i++;
String logUntilString = logs.get(i).split("\\^")[0];
LocalDateTime logUntil = LocalDateTime.parse(logUntilString);
if (criticalUserToken.equals(userToken) &&
!logUntil.isBefore(timeFrom) &&
!logFrom.isAfter(timeUntil)) {
System.out.println("Je bent in contact gekomen met een positief getest persoon");
informedUserTokens.add(userToken);
informed = true;
break;
}
}
if(informed){
break;
}
}
mixingProxy.informedTokens(informedUserTokens);
}
}
@Override
public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
// User Token
this.currentToken = userTokens.get(0);
//tijd
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
//qr code loggen
this.QRCode = qr;
userLogs.add(ldt + "^" + qr + "^" + currentToken);
System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken);
writeToLogFile(ldt, qr, currentToken);
//h value van qr code splitten om door te sturen in capsule
String h = qr.substring(qr.lastIndexOf("|") + 1);
boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken);
// Gebruikte token<SUF>
userTokens.remove(0);
//symbool toekennen indien jusite qr code scan
//op basis van business nummer een kleur toekennen
String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|'));
generateColor(businessNumber);
if(validityToken){
return "ok | " + ldt;
}
else return "not ok" + ldt;
}
@Override
public String leaveCatering(UserImpl user, String qr) throws RemoteException {
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
userLogs.add(ldt + "^" + qr);
writeToLogFile(ldt, qr, currentToken);
String h = qr.substring(qr.lastIndexOf("|") + 1);
mixingProxy.retrieveExitCapsule(ld, h, currentToken);
return "Successfully left catering";
}
public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){
String phoneForLog = phone.replace(" ", "_");
try {
File logFile = new File("logs/log_" + phoneForLog + ".txt");
if (!logFile.exists()){
logFile.createNewFile();
}
FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true);
logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken));
logFW.write("\n");
logFW.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void generateColor(String b){
switch (b) {
case "1":
this.colorAfterQrScan = Color.BLUE;
break;
case "2":
this.colorAfterQrScan = Color.GREEN;
break;
case "3":
this.colorAfterQrScan = Color.RED;
break;
case "4":
this.colorAfterQrScan = Color.ORANGE;
break;
default: this.colorAfterQrScan = Color.BLACK;
}
}
public Color getColorAfterQrScan() {
return colorAfterQrScan;
}
public ArrayList<String> readLogs(){
String phoneForLog = phone.replace(" ", "_");
ArrayList<String> logs = new ArrayList<>();
try {
File userLog = new File("logs/log_" + phoneForLog + ".txt");
if (!userLog.exists()){
userLog.createNewFile();
}
Scanner userLogReader = new Scanner(userLog);
while (userLogReader.hasNextLine()) {
logs.add(userLogReader.nextLine());
}
userLogReader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return logs;
}
//Setters en getters
public ArrayList<byte[]> getUserTokens() {
return userTokens;
}
}
|
47858_2 | /*******************************************************************************
* 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 atd.database;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
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.util.ArrayList;
import java.util.Properties;
import atd.domein.Privilege;
import atd.domein.StatusDB;
import atd.domein.User;
/**
* @author Martijn
*
* TODO: Heel veel code kan hieruit weg TODO: Auth moet veilig zijn (MD5 + SALT)
*
*/
public class UsersDAO {
private static Connection con = null;
private static Statement st = null;
private static ResultSet rs = null;
private static Properties prop = new Properties();
private static InputStream config = null;
private static final String CONFIG_URL = "http://localhost:8080/ATD-WEBSITE/config/database.properties";
/**
* Maakt nieuwe User gebruiker aan in host
*
* @param usrIn
* Ingegeven user
* @param password
* Wachtwoord word niet opgeslagen in User object
* @return
*/
public static StatusDB setUser(User usrIn, String password) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
int priv = 3;
if (usrIn.getPriv() == Privilege.ADMIN) {
priv = 1;
} else if (usrIn.getPriv() == Privilege.MONTEUR) {
priv = 2;
}
String query = "INSERT INTO Users(username, naam, priv, password) VALUES(?, ?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, usrIn.getUsername());
preparedStmt.setString(2, usrIn.getNaam());
preparedStmt.setInt(3, priv);
preparedStmt.setString(4, password);
preparedStmt.execute();
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
return StatusDB.INCORRECT;
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return StatusDB.UNKOWN;
}
/**
* Geeft User object terug met gegeven id
*
* @param id
* host user ID
* @return User
* @throws SQLException
*/
public static User getUser(int id) throws SQLException {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE id='" + id + "'");
if (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
return new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv);
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
/**
* Geeft alle Users in de host terug als ArrayList
*
* @return ArrayList<User>
* @throws SQLException
*/
public static ArrayList<User> getAllUsers() throws SQLException {
ArrayList<User> allUsers = new ArrayList<>();
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users");
while (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
allUsers.add(new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv));
}
return allUsers;
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
/**
* Hiermee kun je eigen SQLQueries uitvoeren. Wordt voornamelijk gebruikt in host.java
*
* @param input
* Rauwe SQL query, geen ; invoeren!
* @return boolean
*/
public static boolean userExist(int id) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE id='" + id + "'");
if (rs.next()) {
if (rs.getString(1).equals(null)) {
return false;
}
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return true;
}
/**
* Controleert gebruikerswachtwoord met host, return als goed is true
*
* @param username
* @param password
* @return boolean
*/
public static boolean authUser(String username, String password) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT password FROM Users WHERE username='" + username + "'");
if (rs.next()) {
if (rs.getString(1).equals(password)) {
return true;
}
} else {
return false;
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return false;
}
/**
* Zoek gebruiker in host en return User object
*
* @param username
* Gebruikernaam gebruiker
* @param fullName
* Volledige naam gebruiker
* @return
*/
public static User searchUser(String username) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE username='" + username + "'");
if (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
return new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv);
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
}
| gitter-badger/Thema-Opdracht-Web | ATD-WEBSITE/src/atd/database/UsersDAO.java | 2,833 | /**
* Maakt nieuwe User gebruiker aan in host
*
* @param usrIn
* Ingegeven user
* @param password
* Wachtwoord word niet opgeslagen in User object
* @return
*/ | block_comment | nl | /*******************************************************************************
* 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 atd.database;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
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.util.ArrayList;
import java.util.Properties;
import atd.domein.Privilege;
import atd.domein.StatusDB;
import atd.domein.User;
/**
* @author Martijn
*
* TODO: Heel veel code kan hieruit weg TODO: Auth moet veilig zijn (MD5 + SALT)
*
*/
public class UsersDAO {
private static Connection con = null;
private static Statement st = null;
private static ResultSet rs = null;
private static Properties prop = new Properties();
private static InputStream config = null;
private static final String CONFIG_URL = "http://localhost:8080/ATD-WEBSITE/config/database.properties";
/**
* Maakt nieuwe User<SUF>*/
public static StatusDB setUser(User usrIn, String password) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
int priv = 3;
if (usrIn.getPriv() == Privilege.ADMIN) {
priv = 1;
} else if (usrIn.getPriv() == Privilege.MONTEUR) {
priv = 2;
}
String query = "INSERT INTO Users(username, naam, priv, password) VALUES(?, ?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, usrIn.getUsername());
preparedStmt.setString(2, usrIn.getNaam());
preparedStmt.setInt(3, priv);
preparedStmt.setString(4, password);
preparedStmt.execute();
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
return StatusDB.INCORRECT;
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return StatusDB.UNKOWN;
}
/**
* Geeft User object terug met gegeven id
*
* @param id
* host user ID
* @return User
* @throws SQLException
*/
public static User getUser(int id) throws SQLException {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE id='" + id + "'");
if (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
return new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv);
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
/**
* Geeft alle Users in de host terug als ArrayList
*
* @return ArrayList<User>
* @throws SQLException
*/
public static ArrayList<User> getAllUsers() throws SQLException {
ArrayList<User> allUsers = new ArrayList<>();
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users");
while (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
allUsers.add(new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv));
}
return allUsers;
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
/**
* Hiermee kun je eigen SQLQueries uitvoeren. Wordt voornamelijk gebruikt in host.java
*
* @param input
* Rauwe SQL query, geen ; invoeren!
* @return boolean
*/
public static boolean userExist(int id) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE id='" + id + "'");
if (rs.next()) {
if (rs.getString(1).equals(null)) {
return false;
}
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return true;
}
/**
* Controleert gebruikerswachtwoord met host, return als goed is true
*
* @param username
* @param password
* @return boolean
*/
public static boolean authUser(String username, String password) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT password FROM Users WHERE username='" + username + "'");
if (rs.next()) {
if (rs.getString(1).equals(password)) {
return true;
}
} else {
return false;
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return false;
}
/**
* Zoek gebruiker in host en return User object
*
* @param username
* Gebruikernaam gebruiker
* @param fullName
* Volledige naam gebruiker
* @return
*/
public static User searchUser(String username) {
try {
config = new URL(CONFIG_URL).openStream();
prop.load(config);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://" + prop.getProperty("host") + ":3306/" + prop.getProperty("database"), prop.getProperty("dbuser"), prop.getProperty("dbpassword"));
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM Users WHERE username='" + username + "'");
if (rs.next()) {
Privilege priv = Privilege.KLANT;
switch (rs.getInt(4)) {
case 1:
priv = Privilege.ADMIN;
break;
case 2:
priv = Privilege.MONTEUR;
break;
case 3:
priv = Privilege.KLANT;
}
return new User(rs.getInt(1), rs.getString(2), rs.getString(3), priv);
}
} catch (SQLException | IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return null;
}
}
|
117221_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van de Pol
*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken / info inwinnen.
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() , null);
tempFile.delete();
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
| B3Partners/datastorelinker | datastorelinker/src/main/java/nl/b3p/datastorelinker/gui/stripes/FileAction.java | 7,219 | // Voorbeelden bekijken / info inwinnen. | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.datastorelinker.gui.stripes;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import net.sf.json.JSONArray;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesRequestWrapper;
import net.sourceforge.stripes.util.Log;
import nl.b3p.commons.jpa.JpaUtilServlet;
import nl.b3p.commons.stripes.Transactional;
import nl.b3p.datastorelinker.entity.Inout;
import nl.b3p.datastorelinker.entity.Organization;
import nl.b3p.datastorelinker.json.ArraySuccessMessage;
import nl.b3p.datastorelinker.json.JSONResolution;
import nl.b3p.datastorelinker.json.ProgressMessage;
import nl.b3p.datastorelinker.json.UploaderStatus;
import nl.b3p.datastorelinker.uploadprogress.UploadProgressListener;
import nl.b3p.datastorelinker.util.DefaultErrorResolution;
import nl.b3p.datastorelinker.util.Dir;
import nl.b3p.datastorelinker.util.DirContent;
import org.hibernate.Session;
/**
*
* @author Erik van de Pol
*/
@Transactional
public class FileAction extends DefaultAction {
private final static Log log = Log.getInstance(FileAction.class);
protected final static String SHAPE_EXT = ".shp";
protected final static String ZIP_EXT = ".zip";
protected final static String PRETTY_DIR_SEPARATOR = "/";
protected final static String[] ALLOWED_CONTENT_TYPES = {
""
};
private final static String CREATE_JSP = "/WEB-INF/jsp/main/file/create.jsp";
private final static String LIST_JSP = "/WEB-INF/jsp/main/file/list.jsp";
private final static String WRAPPER_JSP = "/WEB-INF/jsp/main/file/filetreeWrapper.jsp";
private final static String ADMIN_JSP = "/WEB-INF/jsp/management/fileAdmin.jsp";
private final static String DIRCONTENTS_JSP = "/WEB-INF/jsp/main/file/filetreeConnector.jsp";
private DirContent dirContent;
private FileBean filedata;
private UploaderStatus uploaderStatus;
private String dir;
private String expandTo;
private String selectedFilePath;
private String selectedFilePaths;
private boolean adminPage = false;
public Resolution listDir() {
log.debug("Directory requested: " + dir);
log.debug("expandTo: " + expandTo);
Boolean expandDir = Boolean.valueOf(getContext().getServletContext().getInitParameter("expandAllDirsDirectly"));
File directory = null;
if (dir != null) {
// wordt dit niet gewoon goed geregeld met user privileges?
// De tomcat user kan in *nix niet naar de root / parent dir?
// Voorbeelden bekijken<SUF>
if (dir.contains("..")) {
log.error("Possible hack attempt; Dir requested: " + dir);
return null;
}
directory = getFileFromPPFileName(dir);
} else {
directory = getOrganizationUploadDir();
}
if (expandDir) {
dirContent = getDirContent(directory, null,expandDir);
} else if (expandTo == null) {
dirContent = getDirContent(directory, null,expandDir);
} else {
selectedFilePath = expandTo.trim().replace("\n", "").replace("\r", "");
log.debug("selectedFilePath/expandTo: " + selectedFilePath);
List<String> subDirList = new LinkedList<String>();
File currentDirFile = getFileFromPPFileName(selectedFilePath);
while (!currentDirFile.getAbsolutePath().equals(directory.getAbsolutePath())) {
subDirList.add(0, currentDirFile.getName());
currentDirFile = currentDirFile.getParentFile();
}
dirContent = getDirContent(directory, subDirList,expandDir);
}
//log.debug("dirs: " + directories.size());
//log.debug("files: " + files.size());
return new ForwardResolution(DIRCONTENTS_JSP);
}
protected DirContent getDirContent(File directory, List<String> subDirList, Boolean expandDirs) {
DirContent dc = new DirContent();
File[] dirs = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
});
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory();
}
});
List<Dir> dirsList = new ArrayList<Dir>();
if (dirs != null) {
for (File dir : dirs) {
Dir newDir = new Dir();
newDir.setName(dir.getName());
newDir.setPath(getFileNameRelativeToUploadDirPP(dir));
dirsList.add(newDir);
}
}
List<nl.b3p.datastorelinker.util.File> filesList = new ArrayList<nl.b3p.datastorelinker.util.File>();
if (files != null) {
for (File file : files) {
nl.b3p.datastorelinker.util.File newFile = new nl.b3p.datastorelinker.util.File();
newFile.setName(file.getName());
newFile.setPath(getFileNameRelativeToUploadDirPP(file));
filesList.add(newFile);
}
}
Collections.sort(dirsList, new DirExtensionComparator());
Collections.sort(filesList, new FileExtensionComparator());
dc.setDirs(dirsList);
dc.setFiles(filesList);
filterOutFilesToHide(dc);
if (expandDirs) {
for (Dir subDir : dc.getDirs()) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, null,expandDirs));
}
} else if (subDirList != null && subDirList.size() > 0) {
String subDirString = subDirList.remove(0);
for (Dir subDir : dc.getDirs()) {
if (subDir.getName().equals(subDirString)) {
File followSubDir = getFileFromPPFileName(subDir.getPath());
subDir.setContent(getDirContent(followSubDir, subDirList,expandDirs));
break;
}
}
}
return dc;
}
protected void filterOutFilesToHide(DirContent dc) {
filterOutShapeExtraFiles(dc);
}
protected void filterOutShapeExtraFiles(DirContent dc) {
List<String> shapeNames = new ArrayList<String>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().endsWith(SHAPE_EXT)) {
shapeNames.add(file.getName().substring(0, file.getName().length() - SHAPE_EXT.length()));
}
}
for (String shapeName : shapeNames) {
List<nl.b3p.datastorelinker.util.File> toBeIgnoredFiles = new ArrayList<nl.b3p.datastorelinker.util.File>();
for (nl.b3p.datastorelinker.util.File file : dc.getFiles()) {
if (file.getName().startsWith(shapeName) && !file.getName().endsWith(SHAPE_EXT)) {
toBeIgnoredFiles.add(file);
}
}
for (nl.b3p.datastorelinker.util.File file : toBeIgnoredFiles) {
dc.getFiles().remove(file);
}
}
}
public Resolution admin() {
list();
return new ForwardResolution(ADMIN_JSP);
}
public Resolution list() {
return new ForwardResolution(LIST_JSP);
}
public Resolution deleteCheck() {
log.debug(selectedFilePaths);
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
try {
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String pathToDelete = (String) filePathObj;
String relativePathToDelete = pathToDelete.replace(PRETTY_DIR_SEPARATOR, File.separator);
File fileToDelete = new File(getUploadDirectoryIOFile(), relativePathToDelete);
List<LocalizableMessage> deleteMessages = deleteCheckImpl(fileToDelete);
messages.addAll(deleteMessages);
}
} catch (IOException ioex) {
log.error(ioex);
// Still needed?
// if anything goes wrong here something is wrong with the uploadDir.
}
if (messages.isEmpty()) {
return new JSONResolution(new ArraySuccessMessage(true));
} else {
JSONArray jsonArray = new JSONArray();
for (LocalizableMessage m : messages) {
jsonArray.element(m.getMessage(getContext().getLocale()));
}
return new JSONResolution(new ArraySuccessMessage(false, jsonArray));
}
}
private List<LocalizableMessage> deleteCheckImpl(File fileToDelete) throws IOException {
List<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
if (fileToDelete.isDirectory()) {
for (File fileInDir : fileToDelete.listFiles()) {
messages.addAll(deleteCheckImpl(fileInDir));
}
} else {
String ppFileName = getFileNameRelativeToUploadDirPP(fileToDelete);
List<Inout> inouts = getDependingInouts(fileToDelete);
if (inouts != null && !inouts.isEmpty()) {
for (Inout inout : inouts) {
if (inout.getType() == Inout.Type.INPUT) {
messages.add(new LocalizableMessage("file.inuseInput", ppFileName, inout.getName()));
if (inout.getInputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getInputProcessList()) {
messages.add(new LocalizableMessage("input.inuse", inout.getName(), process.getName()));
}
}
} else { // output
messages.add(new LocalizableMessage("file.inuseOutput", ppFileName, inout.getName()));
if (inout.getOutputProcessList() != null) {
for (nl.b3p.datastorelinker.entity.Process process : inout.getOutputProcessList()) {
messages.add(new LocalizableMessage("output.inuse", inout.getName(), process.getName()));
}
}
}
}
}
}
return messages;
}
private List<Inout> getDependingInouts(File file) throws IOException {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
List<Inout> inouts = session.createQuery("from Inout where file = :file").setParameter("file", file.getAbsolutePath()).list();
return inouts;
}
private File getFileFromPPFileName(String fileName) {
return getFileFromPPFileName(fileName, getContext());
}
private String getFileNameFromPPFileName(String fileName) {
File file = getFileFromPPFileName(fileName);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
private static File getFileFromPPFileName(String fileName, ActionBeanContext context) {
String subPath = fileName.replace(PRETTY_DIR_SEPARATOR, File.separator);
return new File(getUploadDirectoryIOFile(context), subPath);
}
public static String getFileNameFromPPFileName(String fileName, ActionBeanContext context) {
File file = getFileFromPPFileName(fileName, context);
if (file == null) {
return null;
} else {
return file.getAbsolutePath();
}
}
// Pretty printed version of getFileNameRelativeToUploadDir(File file).
// This name is uniform on all systems where the server runs (*nix or Windows).
public static String getFileNameRelativeToUploadDirPP(String file, ActionBeanContext context) {
return getFileNameRelativeToUploadDirPP(new File(file), context);
}
private String getFileNameRelativeToUploadDirPP(File file) {
return getFileNameRelativeToUploadDirPP(file, getContext());
}
private static String getFileNameRelativeToUploadDirPP(File file, ActionBeanContext context) {
String name = getFileNameRelativeToUploadDir(file, context);
if (name == null) {
return null;
} else {
return name.replace(File.separator, PRETTY_DIR_SEPARATOR);
}
}
private String getFileNameRelativeToUploadDir(File file) {
return getFileNameRelativeToUploadDir(file, getContext());
}
private static String getFileNameRelativeToUploadDir(File file, ActionBeanContext context) {
String absName = file.getAbsolutePath();
String uploadDir = getUploadDirectory(context);
if (uploadDir == null || !absName.startsWith(uploadDir)) {
return null;
} else {
return absName.substring(getUploadDirectory(context).length());
}
}
public Resolution delete() {
log.debug(selectedFilePaths);
JSONArray selectedFilePathsJSON = JSONArray.fromObject(selectedFilePaths);
for (Object filePathObj : selectedFilePathsJSON) {
String filePath = (String) filePathObj;
deleteImpl(getFileFromPPFileName(filePath));
}
return list();
}
protected void deleteImpl(File file) {
if (file != null) {
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
// file could already be deleted if an ancestor directory was also deleted in the same request.
if (!file.isDirectory() && file.exists()) {
boolean deleteSuccess = file.delete();
if (!deleteSuccess) {
log.error("Failed to delete file: " + file.getAbsolutePath());
}
}
try {
List<Inout> inouts = getDependingInouts(file);
for (Inout inout : inouts) {
session.delete(inout);
}
} catch (IOException ioex) {
log.error(ioex);
}
deleteExtraShapeFilesInSameDir(file);
deleteDirIfDir(file);
}
}
private void deleteExtraShapeFilesInSameDir(final File file) {
if (!file.isDirectory() && file.getName().endsWith(SHAPE_EXT)) {
final String fileBaseName = file.getName().substring(0, file.getName().length() - SHAPE_EXT.length());
File currentDir = file.getParentFile();
log.debug("currentDir == " + currentDir);
if (currentDir != null && currentDir.exists()) {
File[] extraShapeFilesInDir = currentDir.listFiles(new FileFilter() {
public boolean accept(File extraFile) {
return extraFile.getName().startsWith(fileBaseName)
&& extraFile.getName().length() == file.getName().length();
}
});
for (File extraShapeFile : extraShapeFilesInDir) {
if (!extraShapeFile.isDirectory()) {
deleteImpl(extraShapeFile);
}
}
}
}
}
protected void deleteDirIfDir(File dir) {
// Does this still apply?
// can be null if we tried to delete a directory first and then
// one or more (recursively) deleted files within it.
if (dir != null && dir.isDirectory() && dir.exists()) {
for (File fileInDir : dir.listFiles()) {
deleteImpl(fileInDir);
}
// dir must be empty when deleting it
boolean deleteDirSuccess = dir.delete();
if (!deleteDirSuccess) {
log.error("Failed to delete dir: " + dir.getAbsolutePath() + "; This could happen if the dir was not empty at the time of deletion. This should not happen.");
}
}
}
@DontValidate
public Resolution create() {
return new ForwardResolution(CREATE_JSP);
}
public Resolution createComplete() {
//return list();
return new ForwardResolution(WRAPPER_JSP);
}
@SuppressWarnings("unused")
@Before(stages = LifecycleStage.BindingAndValidation)
private void rehydrate() {
StripesRequestWrapper req = StripesRequestWrapper.findStripesWrapper(getContext().getRequest());
try {
if (req.isMultipart()) {
filedata = req.getFileParameterValue("uploader");
} /*else if (req.getParameter("status") != null) {
log.debug("req.getParameter('status'): " + req.getParameter("status"));
JSONObject jsonObject = JSONObject.fromObject(req.getParameter("status"));
uploaderStatus = (UploaderStatus) JSONObject.toBean(jsonObject, UploaderStatus.class);
}*/
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@DefaultHandler
public Resolution upload() {
if (filedata != null) {
log.debug("Filedata: " + filedata.getFileName());
try {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdirs();
}
if (isZipFile(filedata.getFileName())) {
File tempFile = File.createTempFile(filedata.getFileName() , null);
tempFile.delete();
filedata.save(tempFile);
File zipDir = new File(getOrganizationUploadString(), getZipName(filedata.getFileName()));
extractZip(tempFile, zipDir);
} else {
File destinationFile = new File(dirFile, filedata.getFileName());
filedata.save(destinationFile);
log.info("Saved file " + destinationFile.getAbsolutePath() + ", Successfully!");
selectedFilePath = getFileNameRelativeToUploadDirPP(destinationFile);
log.debug("selectedFilePath: " + selectedFilePath);
}
} catch (IOException e) {
String errorMsg = e.getMessage();
log.error("Error while writing file: " + filedata.getFileName() + " :: " + errorMsg);
return new DefaultErrorResolution(errorMsg);
}
return createComplete();
}
return new DefaultErrorResolution("An unknown error has occurred!");
}
public Resolution uploadProgress() {
int progress;
UploadProgressListener listener = (UploadProgressListener) getContext().getRequest().getSession().getAttribute(UploadProgressListener.class.toString());
if (listener != null) {
progress = (int) (listener.getProgress() * 100);
} else {
progress = 100;
}
return new JSONResolution(new ProgressMessage(progress));
}
/**
* Extract a zip tempfile to a directory. The tempfile will be deleted by
* this method.
*
* @param tempFile The zip file to extract. This tempfile will be deleted by
* this method.
* @param zipDir Directory to extract files into
* @throws IOException
*/
private void extractZip(File tempFile, File zipDir) throws IOException {
if (!tempFile.exists()) {
return;
}
if (!zipDir.exists()) {
zipDir.mkdirs();
}
byte[] buffer = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry = null;
try {
zipinputstream = new ZipInputStream(new FileInputStream(tempFile));
while ((zipentry = zipinputstream.getNextEntry()) != null) {
log.debug("extractZip zipentry name: " + zipentry.getName());
File newFile = new File(zipDir, zipentry.getName());
if (zipentry.isDirectory()) {
// ZipInputStream does not work recursively
// files within this directory will be encountered as a later zipEntry
newFile.mkdirs();
} else if (isZipFile(zipentry.getName())) {
// If the zipfile is in a subdir of the zip,
// we have to extract the filename without the dir.
// It seems the zip-implementation of java always uses "/"
// as file separator in a zip. Even on a windows system.
int lastIndexOfFileSeparator = zipentry.getName().lastIndexOf("/");
String zipName = null;
if (lastIndexOfFileSeparator < 0) {
zipName = zipentry.getName().substring(0);
} else {
zipName = zipentry.getName().substring(lastIndexOfFileSeparator + 1);
}
File tempZipFile = File.createTempFile(zipName + ".", null);
File newZipDir = new File(zipDir, getZipName(zipentry.getName()));
copyZipEntryTo(zipinputstream, tempZipFile, buffer);
extractZip(tempZipFile, newZipDir);
} else {
// TODO: is valid file in zip (delete newFile if necessary)
copyZipEntryTo(zipinputstream, newFile, buffer);
}
zipinputstream.closeEntry();
}
} catch (IOException ioex) {
if (zipentry == null) {
throw ioex;
} else {
throw new IOException(ioex.getMessage()
+ "\nProcessing zip entry: " + zipentry.getName());
}
} finally {
if (zipinputstream != null) {
zipinputstream.close();
}
boolean deleteSuccess = tempFile.delete();
/*if (!deleteSuccess)
log.warn("Could not delete: " + tempFile.getAbsolutePath());*/
}
}
private void copyZipEntryTo(ZipInputStream zipinputstream, File newFile, byte[] buffer) throws IOException {
FileOutputStream fileoutputstream = null;
try {
fileoutputstream = new FileOutputStream(newFile);
int n;
while ((n = zipinputstream.read(buffer)) > -1) {
fileoutputstream.write(buffer, 0, n);
}
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
}
}
public Resolution check() {
if (uploaderStatus != null) {
File dirFile = getOrganizationUploadDir();
if (!dirFile.exists()) {
dirFile.mkdir();
}
File tempFile = new File(dirFile, uploaderStatus.getFname());
log.debug(tempFile.getAbsolutePath());
log.debug(tempFile.getPath());
log.debug("check fpath: ");
if (uploaderStatus.getFpath() != null) {
log.debug(uploaderStatus.getFpath());
}
// TODO: check ook op andere dingen, size enzo. Dit blijft natuurlijk alleen maar een convenience check. Heeft niets met safety te maken.
Map resultMap = new HashMap();
// TODO: exists check is niet goed
if (tempFile.exists()) {
uploaderStatus.setErrtype("exists");
}
if (isZipFile(tempFile) && zipFileToDirFile(tempFile, new File(getOrganizationUploadString())).exists()) {
uploaderStatus.setErrtype("exists");
} else {
uploaderStatus.setErrtype("none");
}
resultMap.put("0", uploaderStatus);
return new JSONResolution(resultMap);
}
return new JSONResolution(false);
}
private boolean isZipFile(String fileName) {
return fileName.toLowerCase().endsWith(ZIP_EXT);
}
private boolean isZipFile(File file) {
return isZipFile(file.getName());
}
private String getZipName(String zipFileName) {
return zipFileName.substring(0, zipFileName.length() - ZIP_EXT.length());
}
private String getZipName(File zipFile) {
return getZipName(zipFile.getName());
}
private File zipFileToDirFile(File zipFile, File parent) {
return new File(parent, getZipName(zipFile));
}
private String getUploadDirectory() {
return getUploadDirectory(getContext());
}
public static String getUploadDirectory(ActionBeanContext context) {
return getUploadDirectoryIOFile(context).getAbsolutePath();
}
private File getUploadDirectoryIOFile() {
return getUploadDirectoryIOFile(getContext());
}
public static File getUploadDirectoryIOFile(ActionBeanContext context) {
return new File(context.getServletContext().getInitParameter("uploadDirectory"));
}
public DirContent getDirContent() {
return dirContent;
}
public void setDirContent(DirContent dirContent) {
this.dirContent = dirContent;
}
public String getExpandTo() {
return expandTo;
}
public void setExpandTo(String expandTo) {
this.expandTo = expandTo;
}
public String getSelectedFilePaths() {
return selectedFilePaths;
}
public void setSelectedFilePaths(String selectedFilePaths) {
this.selectedFilePaths = selectedFilePaths;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSelectedFilePath() {
return selectedFilePath;
}
public void setSelectedFilePath(String selectedFilePath) {
this.selectedFilePath = selectedFilePath;
}
public boolean getAdminPage() {
return adminPage;
}
public void setAdminPage(boolean adminPage) {
this.adminPage = adminPage;
}
public File getOrganizationUploadDir() {
if (isUserAdmin()) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory"));
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
return new File(getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath());
}
return null;
}
public String getOrganizationUploadString() {
String uploadPath = null;
if (isUserAdmin()) {
return getContext().getServletContext().getInitParameter("uploadDirectory");
}
EntityManager em = JpaUtilServlet.getThreadEntityManager();
Session session = (Session) em.getDelegate();
Organization org = (Organization) session.createQuery("from Organization where id = :id")
.setParameter("id", getUserOrganiztionId())
.uniqueResult();
if (org != null) {
uploadPath = getContext().getServletContext().getInitParameter("uploadDirectory") + File.separator + org.getUploadPath();
}
return uploadPath;
}
// <editor-fold defaultstate="collapsed" desc="Comparison methods for file/dir sorting">
private int compareExtensions(String s1, String s2) {
// the +1 is to avoid including the '.' in the extension and to avoid exceptions
// EDIT:
// We first need to make sure that either both files or neither file
// has an extension (otherwise we'll end up comparing the extension of one
// to the start of the other, or else throwing an exception)
final int s1Dot = s1.lastIndexOf('.');
final int s2Dot = s2.lastIndexOf('.');
if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
s1 = s1.substring(s1Dot + 1);
s2 = s2.substring(s2Dot + 1);
return s1.compareTo(s2);
} else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
return -1;
} else { // only s1 has an extension, so s1 goes second
return 1;
}
}
private class DirExtensionComparator implements Comparator<Dir> {
@Override
public int compare(Dir d1, Dir d2) {
String s1 = d1.getName();
String s2 = d2.getName();
return compareExtensions(s1, s2);
}
}
private class FileExtensionComparator implements Comparator<nl.b3p.datastorelinker.util.File> {
@Override
public int compare(nl.b3p.datastorelinker.util.File f1, nl.b3p.datastorelinker.util.File f2) {
String s1 = f1.getName();
String s2 = f2.getName();
return compareExtensions(s1, s2);
}
}
// </editor-fold>
}
|
22688_0 | package com.mybaggage.models;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Het doel van deze class is om een WHERE query dynamisch op te bouwen, zo kan je namelijk de Where query overzichtelijk en simpel houden.
*
* @author Mitchell Gordon (500775386)
*/
public abstract class WhereQueryBuilder<T> {
public final int QUERY_VOORBEREIDING_LIMIET = 1;
public ArrayList<WhereQueryBuilder> whereConditions;
public String veld;
public Object waarde;
public WhereQueryBuilder() {
}
public WhereQueryBuilder(String field, Object txtValue) {
this.veld = field;
this.waarde = txtValue;
}
protected void prepareWhereQueryCondities(T formulier) {
whereConditions = new ArrayList<>();
}
protected String buildWhereQuery(String query, T formulier) {
return query;
}
public void setWhereQueryWaardes(PreparedStatement statement) throws SQLException {
}
}
| vriesr032/MyBaggage | src/main/java/com/mybaggage/models/WhereQueryBuilder.java | 281 | /**
* Het doel van deze class is om een WHERE query dynamisch op te bouwen, zo kan je namelijk de Where query overzichtelijk en simpel houden.
*
* @author Mitchell Gordon (500775386)
*/ | block_comment | nl | package com.mybaggage.models;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Het doel van<SUF>*/
public abstract class WhereQueryBuilder<T> {
public final int QUERY_VOORBEREIDING_LIMIET = 1;
public ArrayList<WhereQueryBuilder> whereConditions;
public String veld;
public Object waarde;
public WhereQueryBuilder() {
}
public WhereQueryBuilder(String field, Object txtValue) {
this.veld = field;
this.waarde = txtValue;
}
protected void prepareWhereQueryCondities(T formulier) {
whereConditions = new ArrayList<>();
}
protected String buildWhereQuery(String query, T formulier) {
return query;
}
public void setWhereQueryWaardes(PreparedStatement statement) throws SQLException {
}
}
|
96577_13 | package tup;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BranchAndBound {
private Problem problem;
private int bestDistance = Integer.MAX_VALUE;
public int[][] bestSolution;
private int[] numberOfUniqueVenuesVisited;
private boolean[][] visited;
private LowerBound lowerBound;
private long nNodes = 0;
private long startTime = System.currentTimeMillis();
private int m = 0;
public BranchAndBound(Problem problem) throws InterruptedException {
this.problem = problem;
bestSolution = new int[problem.nUmpires][problem.nRounds];
numberOfUniqueVenuesVisited = new int[problem.nUmpires];
visited = new boolean[problem.nUmpires][problem.nTeams];
// init arrays
for (int i = 0; i < problem.nUmpires; i++) {
numberOfUniqueVenuesVisited[i] = 0;
for (int j = 0; j < problem.nTeams; j++) {
visited[i][j] = false;
}
}
// Start lower bound calculation in a separate thread
lowerBound = new LowerBound(problem);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
long StartTime = System.currentTimeMillis();
try {
lowerBound.solve();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Lower bound calculation time: " + (System.currentTimeMillis() - StartTime) / 1000.0 + "s");
});
executor.shutdown();
}
public void solve() throws InterruptedException {
startTime = System.currentTimeMillis();
int[][] path = new int[problem.nUmpires][problem.nRounds];
// Wijs in de eerste ronde elke scheidsrechter willekeurig toe aan een wedstrijd
int umpire = 0;
for (int team = 0; team < problem.nTeams; team++) {
if (problem.opponents[0][team] < 0) {
path[umpire][0] = -problem.opponents[0][team];
numberOfUniqueVenuesVisited[umpire]++;
visited[umpire++][-problem.opponents[0][team] - 1] = true;
}
}
// Voer het branch-and-bound algoritme uit vanaf de tweede ronde
this.branchAndBound(path, 0, 1, 0);
this.lowerBound.shutdown = true;
System.out.println("Best solution: ");
printPath(bestSolution);
System.out.println("Distance: " + bestDistance);
System.out.println("Number of nodes: " + nNodes);
System.out.println("Time: " + (System.currentTimeMillis() - startTime) / 1_000.0 + "s");
}
private void branchAndBound(int[][] path, int umpire, int round, int currentCost) throws InterruptedException {
if (round == this.problem.nRounds) {
// Constructed a full feasible path
if (currentCost < bestDistance) {
// The constructed path is better than the current best path! :)
System.out.println("New BEST solution found in " + (System.currentTimeMillis() - startTime) / 60_000.0 + " min with cost " + currentCost + "! :)");
//printPath(path);
// Copy solution
bestDistance = currentCost;
for (int _umpire = 0; _umpire < this.problem.nUmpires; _umpire++) {
System.arraycopy(path[_umpire], 0, bestSolution[_umpire], 0, this.problem.nRounds);
}
}
return;
}
List<Integer> feasibleAllocations = problem.getValidAllocations(path, umpire, round);
if (!feasibleAllocations.isEmpty()) {
for (Integer allocation : feasibleAllocations) {
// int[][] subgraph = generateSubgraph(path, round, allocation);
// if (subgraph != null) {
// int m = solveMatchingProblem(subgraph);
// }
path[umpire][round] = allocation;
boolean firstVisit = !visited[umpire][allocation - 1];
if (firstVisit) {
visited[umpire][allocation - 1] = true;
numberOfUniqueVenuesVisited[umpire]++;
}
int prevHomeTeam = path[umpire][round - 1];
int extraCost = this.problem.dist[prevHomeTeam - 1][allocation - 1];
//if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] < problem.nRounds - round && currentCost + extraCost + lowerBound.getLowerBound(round) < bestDistance) {
if (!canPrune(path, umpire, round, allocation, currentCost + extraCost)) {
nNodes++;
if (umpire == this.problem.nUmpires - 1) {
this.branchAndBound(path, 0, round + 1, currentCost + extraCost);
}
else this.branchAndBound(path, umpire + 1, round, currentCost + extraCost);
}
// Backtrack
path[umpire][round] = 0;
if (firstVisit) {
visited[umpire][allocation - 1] = false;
numberOfUniqueVenuesVisited[umpire]--;
}
}
}
}
private int solveMatchingProblem(int[][] subgraph){
Hungarian hungarian = new Hungarian();
hungarian.assignmentProblem(subgraph);
int[] solution = hungarian.xy;
int cost = 0;
for (int i = 0; i < solution.length; i++) {
cost += subgraph[i][solution[i]];
}
return cost;
}
private int[][] generateSubgraph(int[][] assignments, int round, int allocation) {
List<Integer> visitedTeams = new ArrayList<>();//aantal teams gevisited in deze ronde
List<Integer> previousTeams = new ArrayList<>();//teams visited in de vorige ronde
List<Integer> currentRoundTeams = new ArrayList<>();//overige nog te bezoeken teams in deze ronde
for (int i = 0; i < problem.nUmpires; i++) {
if (assignments[i][round] == 0) {
} else {
visitedTeams.add(assignments[i][round]);
}
}
// System.out.println("Generating subgraph for round " + round +1);
if (visitedTeams.isEmpty()) {
return null;
}
for (int i = visitedTeams.size(); i < problem.nUmpires; i++) {
previousTeams.add(assignments[i][round-1]);
}
for (int i = 0; i < problem.nTeams; i++) {
if (problem.opponents[round][i] < 0) {
int homeTeam = -problem.opponents[round][i];
int awayTeam = i + 1;
if (!visitedTeams.contains(homeTeam) && !visitedTeams.contains(awayTeam) && homeTeam != allocation) {
currentRoundTeams.add(homeTeam);
}
}
}
int size = Math.max(previousTeams.size(), currentRoundTeams.size());
int[][] subgraph = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i < previousTeams.size() && j < currentRoundTeams.size()) {
// Vul de kosten in voor de werkelijke teams
subgraph[i][j] = problem.dist[previousTeams.get(i)-1][currentRoundTeams.get(j)-1];
} else {
// Vul de kosten in voor de dummy-knopen
subgraph[i][j] = Integer.MAX_VALUE;
}
}
}
return subgraph;
}
private boolean canPrune(int[][] path, int umpire, int round, int allocation, int currentCost) throws InterruptedException {
// Controleer of het team al is toegewezen in deze ronde
// for (int i = 0; i < umpire; i++) {
// if (path[i][round] == allocation) {
// return true;
// }
// }
if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] >= problem.nRounds - round) return true;
double lb = this.lowerBound.getLowerBound(round);
if (currentCost + lb >= bestDistance) {
//System.out.println("Pruned op LB");
return true;
}
int[][] subgraph = generateSubgraph(path, round, allocation);
if (subgraph != null && currentCost + lb + lowerBound.getLowerBound(round, round+1) >= bestDistance) {
m = solveMatchingProblem(subgraph);
//System.out.println("Matching cost: " + m);
if (currentCost + lowerBound.getLowerBound(round) + m >= bestDistance) {
//System.out.println("Pruned op matching");
return true;
}
}
return false;
}
private void printPath(int[][] path) {
System.out.println("-------------------------------------------------------------------------------------");
System.out.println(Arrays.deepToString(path));
}
} | Jonas-VN/TUP | src/tup/BranchAndBound.java | 2,297 | // Vul de kosten in voor de werkelijke teams | line_comment | nl | package tup;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BranchAndBound {
private Problem problem;
private int bestDistance = Integer.MAX_VALUE;
public int[][] bestSolution;
private int[] numberOfUniqueVenuesVisited;
private boolean[][] visited;
private LowerBound lowerBound;
private long nNodes = 0;
private long startTime = System.currentTimeMillis();
private int m = 0;
public BranchAndBound(Problem problem) throws InterruptedException {
this.problem = problem;
bestSolution = new int[problem.nUmpires][problem.nRounds];
numberOfUniqueVenuesVisited = new int[problem.nUmpires];
visited = new boolean[problem.nUmpires][problem.nTeams];
// init arrays
for (int i = 0; i < problem.nUmpires; i++) {
numberOfUniqueVenuesVisited[i] = 0;
for (int j = 0; j < problem.nTeams; j++) {
visited[i][j] = false;
}
}
// Start lower bound calculation in a separate thread
lowerBound = new LowerBound(problem);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
long StartTime = System.currentTimeMillis();
try {
lowerBound.solve();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Lower bound calculation time: " + (System.currentTimeMillis() - StartTime) / 1000.0 + "s");
});
executor.shutdown();
}
public void solve() throws InterruptedException {
startTime = System.currentTimeMillis();
int[][] path = new int[problem.nUmpires][problem.nRounds];
// Wijs in de eerste ronde elke scheidsrechter willekeurig toe aan een wedstrijd
int umpire = 0;
for (int team = 0; team < problem.nTeams; team++) {
if (problem.opponents[0][team] < 0) {
path[umpire][0] = -problem.opponents[0][team];
numberOfUniqueVenuesVisited[umpire]++;
visited[umpire++][-problem.opponents[0][team] - 1] = true;
}
}
// Voer het branch-and-bound algoritme uit vanaf de tweede ronde
this.branchAndBound(path, 0, 1, 0);
this.lowerBound.shutdown = true;
System.out.println("Best solution: ");
printPath(bestSolution);
System.out.println("Distance: " + bestDistance);
System.out.println("Number of nodes: " + nNodes);
System.out.println("Time: " + (System.currentTimeMillis() - startTime) / 1_000.0 + "s");
}
private void branchAndBound(int[][] path, int umpire, int round, int currentCost) throws InterruptedException {
if (round == this.problem.nRounds) {
// Constructed a full feasible path
if (currentCost < bestDistance) {
// The constructed path is better than the current best path! :)
System.out.println("New BEST solution found in " + (System.currentTimeMillis() - startTime) / 60_000.0 + " min with cost " + currentCost + "! :)");
//printPath(path);
// Copy solution
bestDistance = currentCost;
for (int _umpire = 0; _umpire < this.problem.nUmpires; _umpire++) {
System.arraycopy(path[_umpire], 0, bestSolution[_umpire], 0, this.problem.nRounds);
}
}
return;
}
List<Integer> feasibleAllocations = problem.getValidAllocations(path, umpire, round);
if (!feasibleAllocations.isEmpty()) {
for (Integer allocation : feasibleAllocations) {
// int[][] subgraph = generateSubgraph(path, round, allocation);
// if (subgraph != null) {
// int m = solveMatchingProblem(subgraph);
// }
path[umpire][round] = allocation;
boolean firstVisit = !visited[umpire][allocation - 1];
if (firstVisit) {
visited[umpire][allocation - 1] = true;
numberOfUniqueVenuesVisited[umpire]++;
}
int prevHomeTeam = path[umpire][round - 1];
int extraCost = this.problem.dist[prevHomeTeam - 1][allocation - 1];
//if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] < problem.nRounds - round && currentCost + extraCost + lowerBound.getLowerBound(round) < bestDistance) {
if (!canPrune(path, umpire, round, allocation, currentCost + extraCost)) {
nNodes++;
if (umpire == this.problem.nUmpires - 1) {
this.branchAndBound(path, 0, round + 1, currentCost + extraCost);
}
else this.branchAndBound(path, umpire + 1, round, currentCost + extraCost);
}
// Backtrack
path[umpire][round] = 0;
if (firstVisit) {
visited[umpire][allocation - 1] = false;
numberOfUniqueVenuesVisited[umpire]--;
}
}
}
}
private int solveMatchingProblem(int[][] subgraph){
Hungarian hungarian = new Hungarian();
hungarian.assignmentProblem(subgraph);
int[] solution = hungarian.xy;
int cost = 0;
for (int i = 0; i < solution.length; i++) {
cost += subgraph[i][solution[i]];
}
return cost;
}
private int[][] generateSubgraph(int[][] assignments, int round, int allocation) {
List<Integer> visitedTeams = new ArrayList<>();//aantal teams gevisited in deze ronde
List<Integer> previousTeams = new ArrayList<>();//teams visited in de vorige ronde
List<Integer> currentRoundTeams = new ArrayList<>();//overige nog te bezoeken teams in deze ronde
for (int i = 0; i < problem.nUmpires; i++) {
if (assignments[i][round] == 0) {
} else {
visitedTeams.add(assignments[i][round]);
}
}
// System.out.println("Generating subgraph for round " + round +1);
if (visitedTeams.isEmpty()) {
return null;
}
for (int i = visitedTeams.size(); i < problem.nUmpires; i++) {
previousTeams.add(assignments[i][round-1]);
}
for (int i = 0; i < problem.nTeams; i++) {
if (problem.opponents[round][i] < 0) {
int homeTeam = -problem.opponents[round][i];
int awayTeam = i + 1;
if (!visitedTeams.contains(homeTeam) && !visitedTeams.contains(awayTeam) && homeTeam != allocation) {
currentRoundTeams.add(homeTeam);
}
}
}
int size = Math.max(previousTeams.size(), currentRoundTeams.size());
int[][] subgraph = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i < previousTeams.size() && j < currentRoundTeams.size()) {
// Vul de<SUF>
subgraph[i][j] = problem.dist[previousTeams.get(i)-1][currentRoundTeams.get(j)-1];
} else {
// Vul de kosten in voor de dummy-knopen
subgraph[i][j] = Integer.MAX_VALUE;
}
}
}
return subgraph;
}
private boolean canPrune(int[][] path, int umpire, int round, int allocation, int currentCost) throws InterruptedException {
// Controleer of het team al is toegewezen in deze ronde
// for (int i = 0; i < umpire; i++) {
// if (path[i][round] == allocation) {
// return true;
// }
// }
if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] >= problem.nRounds - round) return true;
double lb = this.lowerBound.getLowerBound(round);
if (currentCost + lb >= bestDistance) {
//System.out.println("Pruned op LB");
return true;
}
int[][] subgraph = generateSubgraph(path, round, allocation);
if (subgraph != null && currentCost + lb + lowerBound.getLowerBound(round, round+1) >= bestDistance) {
m = solveMatchingProblem(subgraph);
//System.out.println("Matching cost: " + m);
if (currentCost + lowerBound.getLowerBound(round) + m >= bestDistance) {
//System.out.println("Pruned op matching");
return true;
}
}
return false;
}
private void printPath(int[][] path) {
System.out.println("-------------------------------------------------------------------------------------");
System.out.println(Arrays.deepToString(path));
}
} |
14938_0 | import java.util.Scanner;
public class Les2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Wat is jouw naam? ");
String name = scanner.nextLine();
System.out.println("Halllo " + name);
//rekenregels in Java
//Dezelfde als bij ons in de normale wiskunde, dus boeit niet echt.
}
}
| iljo-dp/OLOD | Hoofdstuk1/src/Les2.java | 111 | //rekenregels in Java | line_comment | nl | import java.util.Scanner;
public class Les2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Wat is jouw naam? ");
String name = scanner.nextLine();
System.out.println("Halllo " + name);
//rekenregels in<SUF>
//Dezelfde als bij ons in de normale wiskunde, dus boeit niet echt.
}
}
|
18201_13 | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
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'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- 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");
// 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] != player1.getToken() && board[chosenIndex] != player2.getToken()) {
// wanneer de speler een token op het bord kan plaatsen
// de token van de actieve speler op het gekozen veld plaatsen
board[chosenIndex] = activePlayer.getToken();
//player.score += 10;
// 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:
if (activePlayer == player1) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// 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");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex] + " ");
// 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();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} | hogeschoolnovi/tic-tac-toe-vurgill | src/novi/basics/Game.java | 1,579 | // de token van de actieve speler op het gekozen veld plaatsen | line_comment | nl | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] board;
private int maxRounds;
private Player player1;
private Player player2;
private int drawCount;
private Player activePlayer;
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'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- 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");
// 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] != player1.getToken() && board[chosenIndex] != player2.getToken()) {
// wanneer de speler een token op het bord kan plaatsen
// de token<SUF>
board[chosenIndex] = activePlayer.getToken();
//player.score += 10;
// 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:
if (activePlayer == player1) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //of al bezet is
else {
maxRounds++;
System.out.println("this field is not available, choose another");
}
//versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField
/*if(board[chosenIndex] != '1' + chosenIndex) {
board[chosenIndex] = activePlayerToken;
}*/
}
// 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");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) {
System.out.print(board[fieldIndex] + " ");
// 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();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} |
69153_0 | package com.hiddevanleeuwen.amazighapp;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
DatabaseReference algemeen,woorden;
private RecyclerView recyclerView;
Context x;
ItemAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Reference naar woorden database
woorden = FirebaseDatabase.getInstance().getReference("woorden");
x = getApplicationContext();
//Klaarzetten recyclerview
recyclerView = findViewById(R.id.recycler1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// bouwen van de dataquery
FirebaseRecyclerOptions<Woord> options
= new FirebaseRecyclerOptions.Builder<Woord>()
.setQuery(woorden, Woord.class)
.build();
// bouwen van de adapter met query
adapter = new ItemAdapter(options, x);
// koppelen van de adapter
recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
public void playSound(View view) throws IOException {
TextView textView = findViewById(R.id.tvAudiopath);
String Url = textView.getText().toString();
//Toast.makeText(this, Url, Toast.LENGTH_SHORT).show();
// initializing media player
MediaPlayer mediaPlayer = new MediaPlayer();
// below line is use to set the audio
// stream type for our media player.
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// below line is use to set our
// url to our media player.
try {
mediaPlayer.setDataSource(Url);
// below line is use to prepare
// and start our media player.
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
// below line is use to display a toast message.
Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
}
} | hrobben/Android_vertaal_app | app/src/main/java/com/hiddevanleeuwen/amazighapp/MainActivity.java | 650 | //Reference naar woorden database | line_comment | nl | package com.hiddevanleeuwen.amazighapp;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
DatabaseReference algemeen,woorden;
private RecyclerView recyclerView;
Context x;
ItemAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Reference naar<SUF>
woorden = FirebaseDatabase.getInstance().getReference("woorden");
x = getApplicationContext();
//Klaarzetten recyclerview
recyclerView = findViewById(R.id.recycler1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// bouwen van de dataquery
FirebaseRecyclerOptions<Woord> options
= new FirebaseRecyclerOptions.Builder<Woord>()
.setQuery(woorden, Woord.class)
.build();
// bouwen van de adapter met query
adapter = new ItemAdapter(options, x);
// koppelen van de adapter
recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
public void playSound(View view) throws IOException {
TextView textView = findViewById(R.id.tvAudiopath);
String Url = textView.getText().toString();
//Toast.makeText(this, Url, Toast.LENGTH_SHORT).show();
// initializing media player
MediaPlayer mediaPlayer = new MediaPlayer();
// below line is use to set the audio
// stream type for our media player.
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// below line is use to set our
// url to our media player.
try {
mediaPlayer.setDataSource(Url);
// below line is use to prepare
// and start our media player.
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
// below line is use to display a toast message.
Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
}
} |
19094_19 | /**
* Title: KWS<p>
* Description: Your description<p>
* Copyright: Copyright (c) 1999<p>
* Company: UZLeuven<p>
* adapted for non UZL-use by
*
* @author Bart Decuypere
* @author Romain Reniers
* @version
*/
package uz.emv.sam.v1;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Converter voor JAVA types. Bevat enkel statische utility methodes.
*/
public class JavaTypeConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaTypeConverter.class);
private static final Pattern READABLE_DATE_FORMAT_PATTERN = Pattern.compile(
"^(\\d{1,2})[ -](\\d{1,2})[ -](\\d{4})(?: {1,2}(\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:([\\.:])(\\d{1,3}))?)?)?$");
private static final Pattern READABLE_TIME_FORMAT_PATTERN = Pattern.compile(
"^(?:(\\d{1,2})[ -](\\d{1,2})[ -](\\d{4}) {1,2})?(?:(\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:([\\.:])(\\d{1,3}))?)?)?$");
private static final Map<Class, Class> PRIMITIVE_TO_WRAPPER_MAPPING;
static {
PRIMITIVE_TO_WRAPPER_MAPPING = new HashMap<Class, Class>();
PRIMITIVE_TO_WRAPPER_MAPPING.put(Boolean.TYPE, Boolean.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Character.TYPE, Character.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Byte.TYPE, Byte.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Short.TYPE, Short.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Integer.TYPE, Integer.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Long.TYPE, Long.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Float.TYPE, Float.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Double.TYPE, Double.class);
}
/**
* Omwille van performantie zullen we bijhoden welke 'convertTo'-methode we moeten gebruiken
* voor een combinatie van result/value class.
*/
private static Map<Pair<Class, Class>, Method> methodCache = new HashMap<Pair<Class, Class>, Method>();
/**
* Geen constructor nodig, hier zijn enkel statische methodes.
*/
private JavaTypeConverter() {
}
/**
* Converts a value to the given class. If conversion does not succeed, this is only
* written to System.out and null is returned.
*
* @param c the resulting class
* @param value the value to be converted
* @return the converted value or null if the conversion fails.
*/
public static <T> T convertValueSilent(Class<T> c, Object value) {
try {
return convertValue(c, value);
} catch (Exception e) {
return null;
}
}
/**
* Converts a value to the given class.
*
* @param c the resulting class
* @param value the value to be converted
* @return the converted value
* @throws Exception if the value could not be converted
*/
public static <T> T convertValue(Class<T> c, Object value) throws Exception {
if (value == null) {
return null;
}
// In all cases we convert an empty string to the 'null' value on the database.
if (value instanceof String && ((String) value).isEmpty()) {
return null;
}
//noinspection unchecked
c = convertToWrapperClass(c);
Class clazz = value.getClass();
if (c.equals(clazz) || c.isInstance(value)) {
//noinspection unchecked
return (T) value;
}
// kijk in de cache of we reeds deze combinatie van result/value class geconverteerd hebben.
Pair<Class, Class> cacheKey = Pair.of((Class) c, clazz);
Method m = methodCache.get(cacheKey);
if (m == null) {
// find the correct converter method
String suffix = c.getName().substring(c.getName().lastIndexOf('.') + 1);
if ("[B".equals(suffix)) {
suffix = "ByteArray";
}
// deze loop eindigt ofwel met een gevonden methode, ofwel door een NoSuchMethodException te throwen
while (m == null) {
try {
m = JavaTypeConverter.class.getMethod("convertTo" + suffix, clazz);
methodCache.put(cacheKey, m);
} catch (NoSuchMethodException nsme) {
// opnieuw proberen met superclass
clazz = clazz.getSuperclass();
if (clazz == null) {
LOGGER.error("Return Class: {}", c);
LOGGER.error("No such conversion exists: JavaTypeConverter.convertTo{}({} {})", suffix, value.getClass(), value);
throw nsme;
}
}
}
}
try {
//noinspection unchecked
return (T) m.invoke(null, value);
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof Exception) {
//noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException
throw (Exception) cause;
}
throw ite;
}
}
/**
* Converteer een primitieve klasse naar zijn overeenkomstige wrapper klasse.
*/
public static Class convertToWrapperClass(Class primitiveClass) {
Class result = PRIMITIVE_TO_WRAPPER_MAPPING.get(primitiveClass);
return result == null ? primitiveClass : result;
}
/**
* Converts a Date value to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Date value) {
if (value == null) {
return null;
} else {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
return dateFormat.format(value);
}
}
/**
* Converts a Calendar value to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Calendar value) {
if (value == null) {
return null;
} else {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
return dateFormat.format(value.getTime());
}
}
/**
* Converts a Boolean to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Boolean value) {
if (value == null) {
return null;
} else {
if (value.booleanValue()) {
return "1";
} else {
return "0";
}
}
}
/**
* Converts an object to a String
*
* @param value the object
* @return the converted value
*/
public static String convertToString(Object value) {
if (value == null) {
return null;
} else if (value instanceof String) {
return (String) value;
} else {
return value.toString();
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(Number value) {
if (value == null) {
return null;
} else if (value instanceof Integer) {
return (Integer) value;
} else {
return value.intValue();
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(String value) {
while (true) {
if (value == null || value.isEmpty()) {
return null;
} else {
// bugfix:
// * <jdk1.7: Integer.parseInt("+5") throws Exception
// * >=jdk1.7: Integer.parseInt("+5") == 5
if (value.startsWith("+") && value.length() > 1 && Character.isDigit(value.charAt(1))) {
value = value.substring(1);
continue;
}
return Integer.valueOf(value);
}
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(Boolean value) {
if (value == null) {
return null;
} else {
return value.booleanValue() ? 1 : 0;
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(Number value) {
if (value == null) {
return null;
} else if (value instanceof Long) {
return (Long) value;
} else {
return value.longValue();
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
// bugfix:
// * <jdk1.7: Integer.parseInt("+5") throws Exception
// * >=jdk1.7: Integer.parseInt("+5") == 5
if (value.startsWith("+") && value.length() > 1 && Character.isDigit(value.charAt(1))) {
return Long.valueOf(value.substring(1));
}
return Long.valueOf(value);
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(Boolean value) {
if (value == null) {
return null;
} else {
return value.booleanValue() ? 1L : 0L;
}
}
/**
* Converts a value to the BigDecimal type
*
* @param value the value
* @return the converted value
*/
public static BigDecimal convertToBigDecimal(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return new BigDecimal(value.replace(',', '.'));
}
}
/**
* Converts a value to the BigDecimal type
*
* @param value the value
* @return the converted value
*/
public static BigDecimal convertToBigDecimal(Number value) {
if (value == null) {
return null;
} else if (value instanceof BigDecimal) {
return (BigDecimal) value;
} else if (value instanceof Long || value instanceof Integer) {
return BigDecimal.valueOf(value.longValue());
} else {
return BigDecimal.valueOf(value.doubleValue());
}
}
/**
* Converts a value to the Short type
*
* @param value the value
* @return the converted value
*/
public static Short convertToShort(Number value) {
if (value == null) {
return null;
} else if (value instanceof Short) {
return (Short) value;
} else {
return value.shortValue();
}
}
/**
* Converts a value to the Short type
*
* @param value the value
* @return the converted value
*/
public static Short convertToShort(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Short.valueOf(value);
}
}
/**
* Converts a value to the Byte type
*
* @param value the value
* @return the converted value
*/
public static Byte convertToByte(Number value) {
if (value == null) {
return null;
} else if (value instanceof Byte) {
return (Byte) value;
} else {
return value.byteValue();
}
}
/**
* Converts a value to the Byte type
*
* @param value the value
* @return the converted value
*/
public static Byte convertToByte(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Byte.valueOf(value);
}
}
/**
* Converts a value to the Float type
*
* @param value the value
* @return the converted value
*/
public static Float convertToFloat(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Float.valueOf(value.replace(',', '.'));
}
}
/**
* Converts a value to the Float type
*
* @param value the value
* @return the converted value
*/
public static Float convertToFloat(Number value) {
if (value == null) {
return null;
} else if (value instanceof Float) {
return (Float) value;
} else {
return value.floatValue();
}
}
/**
* Converts a value to the Double type
*
* @param value the value
* @return the converted value
*/
public static Double convertToDouble(String value) {
if (value == null || value.trim().isEmpty()) {
return null;
} else {
return Double.valueOf(value.replace(',', '.'));
}
}
/**
* Converts a value to the Double type
*
* @param value the value
* @return the converted value
*/
public static Double convertToDouble(Number value) {
if (value == null) {
return null;
} else if (value instanceof Double) {
return (Double) value;
} else {
return value.doubleValue();
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(String value) {
if (value == null) {
return null;
} else {
if ("1".equals(value)) {
return Boolean.TRUE;
} else if ("0".equals(value)) {
return Boolean.FALSE;
} else {
return Boolean.valueOf(value);
}
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Number value) {
if (value == null) {
return null;
} else {
return Boolean.valueOf(value.intValue() == 1);
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value to convert
* @param booleanIfNull the return value if null
* @return the converted value
*/
public static Boolean convertToBoolean(Object value, Boolean booleanIfNull) {
if (value == null) {
return booleanIfNull;
}
if (value instanceof String) {
return convertToBoolean((String) value);
} else if (value instanceof Float) {
return convertToBoolean((Float) value);
} else if (value instanceof Double) {
return convertToBoolean((Double) value);
} else if (value instanceof Number) {
return convertToBoolean((Number) value);
}
throw new IllegalArgumentException("JavaTypeConverter: convert to " + value + " is not supported!");
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Float value) {
if (value == null) {
return null;
} else {
//noinspection FloatingPointEquality
return Boolean.valueOf(value.floatValue() == 1.0f);
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Double value) {
if (value == null) {
return null;
} else {
//noinspection FloatingPointEquality
return Boolean.valueOf(value.doubleValue() == 1.0d);
}
}
/**
* Converts a value to the Date type
*
* @param value the value
* @return the converted value
*/
public static Date convertToDate(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_DATE_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int day;
final int month;
final int year;
final int hour;
final int min;
final int sec;
int ms;
day = Integer.parseInt(matcher.group(1));
month = Integer.parseInt(matcher.group(2));
year = Integer.parseInt(matcher.group(3));
if (matcher.group(4) != null) {
hour = Integer.parseInt(matcher.group(4));
} else {
hour = 0;
}
if (matcher.group(5) != null) {
min = Integer.parseInt(matcher.group(5));
} else {
min = 0;
}
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
boolean valid;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
valid = (day <= 31);
break;
case 4:
case 6:
case 9:
case 11:
valid = (day <= 30);
break;
case 2:
final boolean leap = cal.isLeapYear(year);
valid = (leap && day <= 29 || !leap && day <= 28);
break;
default:
valid = false;
break;
}
valid = valid
&& (day >= 1)
&& (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
// The month value must be 0-based. e.g., 0 for January.
// noinspection MagicConstant
cal.set(year, month - 1, day, hour, min, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
return cal.getTime();
}
}
/**
* Converts a time to the Date type
*
* @param value the time
* @return the converted value
*/
public static Date convertToDate(Long value) {
if (value == null) {
return null;
} else {
return new Date(value.longValue());
}
}
/**
* Converts a value to the Date type
*
* @param value the value
* @return the converted value
*/
public static Date convertToDate(Calendar value) {
if (value == null) {
return null;
} else {
return value.getTime();
}
}
/**
* Converts a value to the Calendar type
*
* @param value the value
* @return the converted value
*/
public static Calendar convertToCalendar(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(convertToDate(value));
return cal;
}
}
/**
* Converts a value to the Calendar type
*
* @param value the value
* @return the converted value
*/
public static Calendar convertToCalendar(Date value) {
if (value == null) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(value);
return cal;
}
}
/**
* Converts a time to the Calendar type
*
* @param value the time
* @return the converted value
*/
public static Calendar convertToCalendar(Long value) {
if (value == null) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(value.longValue()));
return cal;
}
}
/**
* Converts a value to the Timestamp type
*
* @param value the value
* @return the converted value
*/
public static Timestamp convertToTimestamp(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_DATE_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int day;
final int month;
final int year;
final int hour;
final int min;
final int sec;
int ms;
day = Integer.parseInt(matcher.group(1));
month = Integer.parseInt(matcher.group(2));
year = Integer.parseInt(matcher.group(3));
if (matcher.group(4) != null) {
hour = Integer.parseInt(matcher.group(4));
} else {
hour = 0;
}
if (matcher.group(5) != null) {
min = Integer.parseInt(matcher.group(5));
} else {
min = 0;
}
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
boolean valid;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
valid = (day <= 31);
break;
case 4:
case 6:
case 9:
case 11:
valid = (day <= 30);
break;
case 2:
final boolean leap = cal.isLeapYear(year);
valid = (leap && day <= 29 || !leap && day <= 28);
break;
default:
valid = false;
break;
}
valid = valid
&& (day >= 1)
&& (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
// The month value must be 0-based. e.g., 0 for January.
// noinspection MagicConstant
cal.set(year, month - 1, day, hour, min, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
Date date = cal.getTime();
return new Timestamp(date.getTime());
}
}
/**
* Converts a Date to the Timestamp type
*
* @param value the Date
* @return the converted value
*/
public static Timestamp convertToTimestamp(Date value) {
if (value == null) {
return null;
} else if (value instanceof Timestamp) {
return (Timestamp) value;
} else {
return new Timestamp(value.getTime());
}
}
/**
* Converts a Calendar to the Timestamp type
*
* @param value the Date
* @return the converted value
*/
public static Timestamp convertToTimestamp(Calendar value) {
if (value == null) {
return null;
} else {
return new Timestamp(value.getTime().getTime());
}
}
public static Time convertToTime(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_TIME_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int hour;
final int min;
final int sec;
int ms;
hour = Integer.parseInt(matcher.group(4));
min = Integer.parseInt(matcher.group(5));
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
cal.clear();
boolean valid = (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
return new Time(cal.getTimeInMillis());
}
}
public static Time convertToTime(Date value) {
if (value == null) {
return null;
} else if (value instanceof Time) {
return (Time) value;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.clear(Calendar.YEAR);
calendar.clear(Calendar.MONTH);
calendar.clear(Calendar.DATE);
return new Time(calendar.getTimeInMillis());
}
}
/**
* Converts a time to the Timestamp type
*
* @param value the time
* @return the converted value
*/
public static Timestamp convertToTimestamp(Long value) {
if (value == null) {
return null;
} else {
return new Timestamp(value.longValue());
}
}
/**
* Converts a value to a URL.
*
* @param value the value
* @return the converted value
* @throws MalformedURLException if the value couldn't be converted
*/
public static URL convertToURL(String value) throws MalformedURLException {
if (value == null) {
return null;
} else {
return new URL(value);
}
}
/**
* Converts a hexadecimal string (12a2bc0d) to the byte[] type
*
* @param value the hexadecimal string
* @return the converted value
*/
@Nullable
public static byte[] convertToByteArray(String value) {
if (value == null) {
return null;
} else {
final int len = value.length() / 2;
final byte[] res = new byte[len];
for (int i = 0; i < len; i++) {
// System.out.println("Hex: "+hex.substring(i*2, (i+1)*2) + " Byte: "+
// (byte) Integer.parseInt(hex.substring(i*2, (i+1)*2), 16));
res[i] = (byte) Integer.parseInt(value.substring(i * 2, (i + 1) * 2), 16);
}
return res;
}
}
public static UUID convertToUUID(Object value) {
if (value == null) {
return null;
} else {
return UUID.fromString((String) value);
}
}
}
| imec-int/ritme | Sam/src/uz/emv/sam/v1/JavaTypeConverter.java | 7,779 | // * >=jdk1.7: Integer.parseInt("+5") == 5 | line_comment | nl | /**
* Title: KWS<p>
* Description: Your description<p>
* Copyright: Copyright (c) 1999<p>
* Company: UZLeuven<p>
* adapted for non UZL-use by
*
* @author Bart Decuypere
* @author Romain Reniers
* @version
*/
package uz.emv.sam.v1;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Converter voor JAVA types. Bevat enkel statische utility methodes.
*/
public class JavaTypeConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaTypeConverter.class);
private static final Pattern READABLE_DATE_FORMAT_PATTERN = Pattern.compile(
"^(\\d{1,2})[ -](\\d{1,2})[ -](\\d{4})(?: {1,2}(\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:([\\.:])(\\d{1,3}))?)?)?$");
private static final Pattern READABLE_TIME_FORMAT_PATTERN = Pattern.compile(
"^(?:(\\d{1,2})[ -](\\d{1,2})[ -](\\d{4}) {1,2})?(?:(\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:([\\.:])(\\d{1,3}))?)?)?$");
private static final Map<Class, Class> PRIMITIVE_TO_WRAPPER_MAPPING;
static {
PRIMITIVE_TO_WRAPPER_MAPPING = new HashMap<Class, Class>();
PRIMITIVE_TO_WRAPPER_MAPPING.put(Boolean.TYPE, Boolean.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Character.TYPE, Character.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Byte.TYPE, Byte.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Short.TYPE, Short.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Integer.TYPE, Integer.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Long.TYPE, Long.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Float.TYPE, Float.class);
PRIMITIVE_TO_WRAPPER_MAPPING.put(Double.TYPE, Double.class);
}
/**
* Omwille van performantie zullen we bijhoden welke 'convertTo'-methode we moeten gebruiken
* voor een combinatie van result/value class.
*/
private static Map<Pair<Class, Class>, Method> methodCache = new HashMap<Pair<Class, Class>, Method>();
/**
* Geen constructor nodig, hier zijn enkel statische methodes.
*/
private JavaTypeConverter() {
}
/**
* Converts a value to the given class. If conversion does not succeed, this is only
* written to System.out and null is returned.
*
* @param c the resulting class
* @param value the value to be converted
* @return the converted value or null if the conversion fails.
*/
public static <T> T convertValueSilent(Class<T> c, Object value) {
try {
return convertValue(c, value);
} catch (Exception e) {
return null;
}
}
/**
* Converts a value to the given class.
*
* @param c the resulting class
* @param value the value to be converted
* @return the converted value
* @throws Exception if the value could not be converted
*/
public static <T> T convertValue(Class<T> c, Object value) throws Exception {
if (value == null) {
return null;
}
// In all cases we convert an empty string to the 'null' value on the database.
if (value instanceof String && ((String) value).isEmpty()) {
return null;
}
//noinspection unchecked
c = convertToWrapperClass(c);
Class clazz = value.getClass();
if (c.equals(clazz) || c.isInstance(value)) {
//noinspection unchecked
return (T) value;
}
// kijk in de cache of we reeds deze combinatie van result/value class geconverteerd hebben.
Pair<Class, Class> cacheKey = Pair.of((Class) c, clazz);
Method m = methodCache.get(cacheKey);
if (m == null) {
// find the correct converter method
String suffix = c.getName().substring(c.getName().lastIndexOf('.') + 1);
if ("[B".equals(suffix)) {
suffix = "ByteArray";
}
// deze loop eindigt ofwel met een gevonden methode, ofwel door een NoSuchMethodException te throwen
while (m == null) {
try {
m = JavaTypeConverter.class.getMethod("convertTo" + suffix, clazz);
methodCache.put(cacheKey, m);
} catch (NoSuchMethodException nsme) {
// opnieuw proberen met superclass
clazz = clazz.getSuperclass();
if (clazz == null) {
LOGGER.error("Return Class: {}", c);
LOGGER.error("No such conversion exists: JavaTypeConverter.convertTo{}({} {})", suffix, value.getClass(), value);
throw nsme;
}
}
}
}
try {
//noinspection unchecked
return (T) m.invoke(null, value);
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof Exception) {
//noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException
throw (Exception) cause;
}
throw ite;
}
}
/**
* Converteer een primitieve klasse naar zijn overeenkomstige wrapper klasse.
*/
public static Class convertToWrapperClass(Class primitiveClass) {
Class result = PRIMITIVE_TO_WRAPPER_MAPPING.get(primitiveClass);
return result == null ? primitiveClass : result;
}
/**
* Converts a Date value to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Date value) {
if (value == null) {
return null;
} else {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
return dateFormat.format(value);
}
}
/**
* Converts a Calendar value to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Calendar value) {
if (value == null) {
return null;
} else {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
return dateFormat.format(value.getTime());
}
}
/**
* Converts a Boolean to the String type
*
* @param value the value
* @return the converted value
*/
public static String convertToString(Boolean value) {
if (value == null) {
return null;
} else {
if (value.booleanValue()) {
return "1";
} else {
return "0";
}
}
}
/**
* Converts an object to a String
*
* @param value the object
* @return the converted value
*/
public static String convertToString(Object value) {
if (value == null) {
return null;
} else if (value instanceof String) {
return (String) value;
} else {
return value.toString();
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(Number value) {
if (value == null) {
return null;
} else if (value instanceof Integer) {
return (Integer) value;
} else {
return value.intValue();
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(String value) {
while (true) {
if (value == null || value.isEmpty()) {
return null;
} else {
// bugfix:
// * <jdk1.7: Integer.parseInt("+5") throws Exception
// * >=jdk1.7: Integer.parseInt("+5")<SUF>
if (value.startsWith("+") && value.length() > 1 && Character.isDigit(value.charAt(1))) {
value = value.substring(1);
continue;
}
return Integer.valueOf(value);
}
}
}
/**
* Converts a value to the Integer type
*
* @param value the value
* @return the converted value
*/
public static Integer convertToInteger(Boolean value) {
if (value == null) {
return null;
} else {
return value.booleanValue() ? 1 : 0;
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(Number value) {
if (value == null) {
return null;
} else if (value instanceof Long) {
return (Long) value;
} else {
return value.longValue();
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
// bugfix:
// * <jdk1.7: Integer.parseInt("+5") throws Exception
// * >=jdk1.7: Integer.parseInt("+5") == 5
if (value.startsWith("+") && value.length() > 1 && Character.isDigit(value.charAt(1))) {
return Long.valueOf(value.substring(1));
}
return Long.valueOf(value);
}
}
/**
* Converts a value to the Long type
*
* @param value the value
* @return the converted value
*/
public static Long convertToLong(Boolean value) {
if (value == null) {
return null;
} else {
return value.booleanValue() ? 1L : 0L;
}
}
/**
* Converts a value to the BigDecimal type
*
* @param value the value
* @return the converted value
*/
public static BigDecimal convertToBigDecimal(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return new BigDecimal(value.replace(',', '.'));
}
}
/**
* Converts a value to the BigDecimal type
*
* @param value the value
* @return the converted value
*/
public static BigDecimal convertToBigDecimal(Number value) {
if (value == null) {
return null;
} else if (value instanceof BigDecimal) {
return (BigDecimal) value;
} else if (value instanceof Long || value instanceof Integer) {
return BigDecimal.valueOf(value.longValue());
} else {
return BigDecimal.valueOf(value.doubleValue());
}
}
/**
* Converts a value to the Short type
*
* @param value the value
* @return the converted value
*/
public static Short convertToShort(Number value) {
if (value == null) {
return null;
} else if (value instanceof Short) {
return (Short) value;
} else {
return value.shortValue();
}
}
/**
* Converts a value to the Short type
*
* @param value the value
* @return the converted value
*/
public static Short convertToShort(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Short.valueOf(value);
}
}
/**
* Converts a value to the Byte type
*
* @param value the value
* @return the converted value
*/
public static Byte convertToByte(Number value) {
if (value == null) {
return null;
} else if (value instanceof Byte) {
return (Byte) value;
} else {
return value.byteValue();
}
}
/**
* Converts a value to the Byte type
*
* @param value the value
* @return the converted value
*/
public static Byte convertToByte(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Byte.valueOf(value);
}
}
/**
* Converts a value to the Float type
*
* @param value the value
* @return the converted value
*/
public static Float convertToFloat(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
return Float.valueOf(value.replace(',', '.'));
}
}
/**
* Converts a value to the Float type
*
* @param value the value
* @return the converted value
*/
public static Float convertToFloat(Number value) {
if (value == null) {
return null;
} else if (value instanceof Float) {
return (Float) value;
} else {
return value.floatValue();
}
}
/**
* Converts a value to the Double type
*
* @param value the value
* @return the converted value
*/
public static Double convertToDouble(String value) {
if (value == null || value.trim().isEmpty()) {
return null;
} else {
return Double.valueOf(value.replace(',', '.'));
}
}
/**
* Converts a value to the Double type
*
* @param value the value
* @return the converted value
*/
public static Double convertToDouble(Number value) {
if (value == null) {
return null;
} else if (value instanceof Double) {
return (Double) value;
} else {
return value.doubleValue();
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(String value) {
if (value == null) {
return null;
} else {
if ("1".equals(value)) {
return Boolean.TRUE;
} else if ("0".equals(value)) {
return Boolean.FALSE;
} else {
return Boolean.valueOf(value);
}
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Number value) {
if (value == null) {
return null;
} else {
return Boolean.valueOf(value.intValue() == 1);
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value to convert
* @param booleanIfNull the return value if null
* @return the converted value
*/
public static Boolean convertToBoolean(Object value, Boolean booleanIfNull) {
if (value == null) {
return booleanIfNull;
}
if (value instanceof String) {
return convertToBoolean((String) value);
} else if (value instanceof Float) {
return convertToBoolean((Float) value);
} else if (value instanceof Double) {
return convertToBoolean((Double) value);
} else if (value instanceof Number) {
return convertToBoolean((Number) value);
}
throw new IllegalArgumentException("JavaTypeConverter: convert to " + value + " is not supported!");
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Float value) {
if (value == null) {
return null;
} else {
//noinspection FloatingPointEquality
return Boolean.valueOf(value.floatValue() == 1.0f);
}
}
/**
* Converts a value to the Boolean type
*
* @param value the value
* @return the converted value
*/
public static Boolean convertToBoolean(Double value) {
if (value == null) {
return null;
} else {
//noinspection FloatingPointEquality
return Boolean.valueOf(value.doubleValue() == 1.0d);
}
}
/**
* Converts a value to the Date type
*
* @param value the value
* @return the converted value
*/
public static Date convertToDate(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_DATE_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int day;
final int month;
final int year;
final int hour;
final int min;
final int sec;
int ms;
day = Integer.parseInt(matcher.group(1));
month = Integer.parseInt(matcher.group(2));
year = Integer.parseInt(matcher.group(3));
if (matcher.group(4) != null) {
hour = Integer.parseInt(matcher.group(4));
} else {
hour = 0;
}
if (matcher.group(5) != null) {
min = Integer.parseInt(matcher.group(5));
} else {
min = 0;
}
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
boolean valid;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
valid = (day <= 31);
break;
case 4:
case 6:
case 9:
case 11:
valid = (day <= 30);
break;
case 2:
final boolean leap = cal.isLeapYear(year);
valid = (leap && day <= 29 || !leap && day <= 28);
break;
default:
valid = false;
break;
}
valid = valid
&& (day >= 1)
&& (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
// The month value must be 0-based. e.g., 0 for January.
// noinspection MagicConstant
cal.set(year, month - 1, day, hour, min, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
return cal.getTime();
}
}
/**
* Converts a time to the Date type
*
* @param value the time
* @return the converted value
*/
public static Date convertToDate(Long value) {
if (value == null) {
return null;
} else {
return new Date(value.longValue());
}
}
/**
* Converts a value to the Date type
*
* @param value the value
* @return the converted value
*/
public static Date convertToDate(Calendar value) {
if (value == null) {
return null;
} else {
return value.getTime();
}
}
/**
* Converts a value to the Calendar type
*
* @param value the value
* @return the converted value
*/
public static Calendar convertToCalendar(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(convertToDate(value));
return cal;
}
}
/**
* Converts a value to the Calendar type
*
* @param value the value
* @return the converted value
*/
public static Calendar convertToCalendar(Date value) {
if (value == null) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(value);
return cal;
}
}
/**
* Converts a time to the Calendar type
*
* @param value the time
* @return the converted value
*/
public static Calendar convertToCalendar(Long value) {
if (value == null) {
return null;
} else {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(value.longValue()));
return cal;
}
}
/**
* Converts a value to the Timestamp type
*
* @param value the value
* @return the converted value
*/
public static Timestamp convertToTimestamp(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_DATE_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int day;
final int month;
final int year;
final int hour;
final int min;
final int sec;
int ms;
day = Integer.parseInt(matcher.group(1));
month = Integer.parseInt(matcher.group(2));
year = Integer.parseInt(matcher.group(3));
if (matcher.group(4) != null) {
hour = Integer.parseInt(matcher.group(4));
} else {
hour = 0;
}
if (matcher.group(5) != null) {
min = Integer.parseInt(matcher.group(5));
} else {
min = 0;
}
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
boolean valid;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
valid = (day <= 31);
break;
case 4:
case 6:
case 9:
case 11:
valid = (day <= 30);
break;
case 2:
final boolean leap = cal.isLeapYear(year);
valid = (leap && day <= 29 || !leap && day <= 28);
break;
default:
valid = false;
break;
}
valid = valid
&& (day >= 1)
&& (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
// The month value must be 0-based. e.g., 0 for January.
// noinspection MagicConstant
cal.set(year, month - 1, day, hour, min, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
Date date = cal.getTime();
return new Timestamp(date.getTime());
}
}
/**
* Converts a Date to the Timestamp type
*
* @param value the Date
* @return the converted value
*/
public static Timestamp convertToTimestamp(Date value) {
if (value == null) {
return null;
} else if (value instanceof Timestamp) {
return (Timestamp) value;
} else {
return new Timestamp(value.getTime());
}
}
/**
* Converts a Calendar to the Timestamp type
*
* @param value the Date
* @return the converted value
*/
public static Timestamp convertToTimestamp(Calendar value) {
if (value == null) {
return null;
} else {
return new Timestamp(value.getTime().getTime());
}
}
public static Time convertToTime(String value) {
if (value == null || value.isEmpty()) {
return null;
} else {
final String trimmedValue = value.trim();
final Matcher matcher = READABLE_TIME_FORMAT_PATTERN.matcher(trimmedValue);
if (!matcher.matches() || matcher.groupCount() < 8) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
final int hour;
final int min;
final int sec;
int ms;
hour = Integer.parseInt(matcher.group(4));
min = Integer.parseInt(matcher.group(5));
if (matcher.group(6) != null) {
sec = Integer.parseInt(matcher.group(6));
} else {
sec = 0;
}
if (matcher.group(8) != null) {
ms = Integer.parseInt(matcher.group(8));
// Indien milliseconden voorafgegaan door een punt, dan nullen achteraan toevoegen i.p.v. vooraan !
if (".".equals(matcher.group(7))) {
ms = Integer.parseInt((matcher.group(8) + "000").substring(0, 3));
}
} else {
ms = 0;
}
final GregorianCalendar cal = new GregorianCalendar();
cal.clear();
boolean valid = (hour >= 0 && hour <= 23)
&& (min >= 0 && min <= 59)
&& (sec >= 0 && sec <= 59)
&& (ms >= 0 && ms <= 999);
if (!valid) {
throw new IllegalArgumentException("Illegal date format (dd-mm-yyyy hh:mm:ss): " + value);
}
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
cal.set(Calendar.SECOND, sec);
cal.set(Calendar.MILLISECOND, ms);
// The method getTime() will validate all the fields !
return new Time(cal.getTimeInMillis());
}
}
public static Time convertToTime(Date value) {
if (value == null) {
return null;
} else if (value instanceof Time) {
return (Time) value;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.clear(Calendar.YEAR);
calendar.clear(Calendar.MONTH);
calendar.clear(Calendar.DATE);
return new Time(calendar.getTimeInMillis());
}
}
/**
* Converts a time to the Timestamp type
*
* @param value the time
* @return the converted value
*/
public static Timestamp convertToTimestamp(Long value) {
if (value == null) {
return null;
} else {
return new Timestamp(value.longValue());
}
}
/**
* Converts a value to a URL.
*
* @param value the value
* @return the converted value
* @throws MalformedURLException if the value couldn't be converted
*/
public static URL convertToURL(String value) throws MalformedURLException {
if (value == null) {
return null;
} else {
return new URL(value);
}
}
/**
* Converts a hexadecimal string (12a2bc0d) to the byte[] type
*
* @param value the hexadecimal string
* @return the converted value
*/
@Nullable
public static byte[] convertToByteArray(String value) {
if (value == null) {
return null;
} else {
final int len = value.length() / 2;
final byte[] res = new byte[len];
for (int i = 0; i < len; i++) {
// System.out.println("Hex: "+hex.substring(i*2, (i+1)*2) + " Byte: "+
// (byte) Integer.parseInt(hex.substring(i*2, (i+1)*2), 16));
res[i] = (byte) Integer.parseInt(value.substring(i * 2, (i + 1) * 2), 16);
}
return res;
}
}
public static UUID convertToUUID(Object value) {
if (value == null) {
return null;
} else {
return UUID.fromString((String) value);
}
}
}
|
10968_17 | package sleutelbarricade;
/**
*
* @author Crhis Bruijn, Ruben Buijck, Gijs de Lange
*/
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Poppetje extends JFrame implements KeyListener {
//initialiseren van de benodigde variabelen.
private static int cordX = 0;
private static int cordY = 0;
private static int oldCordX = 0;
private static int oldCordY = 0;
private static int sleutel;
private static ImageIcon player = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje.png")); //Het plaatje waarop het poppetje naar beneden kijkt.
private static ImageIcon player1 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje1.png")); //Het plaatje waarop het poppetje naar rechts kijkt.
private static ImageIcon player2 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje2.png")); //Het plaatje waarop het poppetje naar boven kijkt.
private static ImageIcon player3 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje3.png")); //Het plaatje waarop het poppetje naar links kijkt.
private static JLabel poppetje = new JLabel();
private static int win = 0;
// het plaatje van poppetje plaatsen op het JFrame.
public Poppetje() {
cordX = 0;
cordY = 0;
oldCordX = 0;
oldCordY = 0;
poppetje.setIcon(player);
poppetje.setBounds(0, 0, 64, 64);
add(poppetje);
setFocusable(true);
addKeyListener(this);
}
//getters en setters
public static void setSleutel(int sleutel) {
Poppetje.sleutel = sleutel;
}
public static int getSleutel() {
return sleutel;
}
public static int getCordX() {
return cordX;
}
public static void setCordX(int cordX) {
Poppetje.cordX = cordX;
}
public static int getCordY() {
return cordY;
}
public static void setCordY(int cordY) {
Poppetje.cordY = cordY;
}
public static void setOldCordX(int oldCordX) {
Poppetje.oldCordX = oldCordX;
}
public static void setOldCordY(int oldCordY) {
Poppetje.oldCordY = oldCordY;
}
// zorgen dat het poppetje kan bewegen ever het veld.
public void bewegen(int x, int y) {
// kijken bij Level of hij daarheen mag bewegen.
boolean check = Level.checkMovement(x, y, sleutel, win);
if (check == true) {
poppetje.setIcon(player);
poppetje.setBounds(x * 64, y * 64, 64, 64);
oldCordX = x;
oldCordY = y;
add(poppetje);
} else {
//als hij niet naar het nieuwe coördinaat toe kan worden de coördinaten weer het oude.
cordX = oldCordX;
cordY = oldCordY;
}
//als hij op het laatste veld is melden dat hij gewonnen heeft.
if (x == 9 && y == 9) {
win();
}
}
public void win() {
win++;
// na 3 keer winnen word er verteld dat hij het spel gewonnen heeft en word de speler terug gebracht bij het menu en worden alle waardens hersteld.
if (win == 3) {
JOptionPane.showMessageDialog(this, "U heeft dit spel gewonnen!");
dispose();
spelStart s = new spelStart();
s.setVisible(true);
win = 0;
} else {
JOptionPane.showMessageDialog(this, "U heeft dit level gewonnen!");
sleutel = 0;
oldCordX = 0;
oldCordY = 0;
cordX = 0;
cordY = 0;
Level.generateLevel(win);
}
}
// het kijken of er iemand op de pijltjes toetsen drukt.
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
//een tegel naar rechts met pijltje naar rechts
case KeyEvent.VK_RIGHT: {
cordX += 1;
bewegen(cordX, cordY);
poppetje.setIcon(player1);
}
break;
//een tegel naar links met pijltje naar links
case KeyEvent.VK_LEFT: {
cordX -= 1;
// het nieuwe coördinaat versturen.
bewegen(cordX, cordY);
// poppetje naar de nieuwe laten wijzen.
poppetje.setIcon(player3);
}
break;
//een tegel omlaag met het pijltje omlaag
case KeyEvent.VK_DOWN: {
cordY += 1;
bewegen(cordX, cordY);
poppetje.setIcon(player);
}
break;
//een tegel omhoog met het pijltje omhoog
case KeyEvent.VK_UP: {
cordY -= 1;
bewegen(cordX, cordY);
poppetje.setIcon(player2);
}
break;
}
}
//als een knop ingedrukt wordt
public void keyTyped(KeyEvent ke) {
}
//als een knop lostgelaten wordt
public void keyReleased(KeyEvent ke) {
}
}
| gijsdl/Sleutelbarricade | src/sleutelbarricade/Poppetje.java | 1,491 | // poppetje naar de nieuwe laten wijzen. | line_comment | nl | package sleutelbarricade;
/**
*
* @author Crhis Bruijn, Ruben Buijck, Gijs de Lange
*/
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Poppetje extends JFrame implements KeyListener {
//initialiseren van de benodigde variabelen.
private static int cordX = 0;
private static int cordY = 0;
private static int oldCordX = 0;
private static int oldCordY = 0;
private static int sleutel;
private static ImageIcon player = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje.png")); //Het plaatje waarop het poppetje naar beneden kijkt.
private static ImageIcon player1 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje1.png")); //Het plaatje waarop het poppetje naar rechts kijkt.
private static ImageIcon player2 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje2.png")); //Het plaatje waarop het poppetje naar boven kijkt.
private static ImageIcon player3 = new javax.swing.ImageIcon(Poppetje.class.getResource("/sleutelbarricade/pics/poppetje3.png")); //Het plaatje waarop het poppetje naar links kijkt.
private static JLabel poppetje = new JLabel();
private static int win = 0;
// het plaatje van poppetje plaatsen op het JFrame.
public Poppetje() {
cordX = 0;
cordY = 0;
oldCordX = 0;
oldCordY = 0;
poppetje.setIcon(player);
poppetje.setBounds(0, 0, 64, 64);
add(poppetje);
setFocusable(true);
addKeyListener(this);
}
//getters en setters
public static void setSleutel(int sleutel) {
Poppetje.sleutel = sleutel;
}
public static int getSleutel() {
return sleutel;
}
public static int getCordX() {
return cordX;
}
public static void setCordX(int cordX) {
Poppetje.cordX = cordX;
}
public static int getCordY() {
return cordY;
}
public static void setCordY(int cordY) {
Poppetje.cordY = cordY;
}
public static void setOldCordX(int oldCordX) {
Poppetje.oldCordX = oldCordX;
}
public static void setOldCordY(int oldCordY) {
Poppetje.oldCordY = oldCordY;
}
// zorgen dat het poppetje kan bewegen ever het veld.
public void bewegen(int x, int y) {
// kijken bij Level of hij daarheen mag bewegen.
boolean check = Level.checkMovement(x, y, sleutel, win);
if (check == true) {
poppetje.setIcon(player);
poppetje.setBounds(x * 64, y * 64, 64, 64);
oldCordX = x;
oldCordY = y;
add(poppetje);
} else {
//als hij niet naar het nieuwe coördinaat toe kan worden de coördinaten weer het oude.
cordX = oldCordX;
cordY = oldCordY;
}
//als hij op het laatste veld is melden dat hij gewonnen heeft.
if (x == 9 && y == 9) {
win();
}
}
public void win() {
win++;
// na 3 keer winnen word er verteld dat hij het spel gewonnen heeft en word de speler terug gebracht bij het menu en worden alle waardens hersteld.
if (win == 3) {
JOptionPane.showMessageDialog(this, "U heeft dit spel gewonnen!");
dispose();
spelStart s = new spelStart();
s.setVisible(true);
win = 0;
} else {
JOptionPane.showMessageDialog(this, "U heeft dit level gewonnen!");
sleutel = 0;
oldCordX = 0;
oldCordY = 0;
cordX = 0;
cordY = 0;
Level.generateLevel(win);
}
}
// het kijken of er iemand op de pijltjes toetsen drukt.
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
//een tegel naar rechts met pijltje naar rechts
case KeyEvent.VK_RIGHT: {
cordX += 1;
bewegen(cordX, cordY);
poppetje.setIcon(player1);
}
break;
//een tegel naar links met pijltje naar links
case KeyEvent.VK_LEFT: {
cordX -= 1;
// het nieuwe coördinaat versturen.
bewegen(cordX, cordY);
// poppetje naar<SUF>
poppetje.setIcon(player3);
}
break;
//een tegel omlaag met het pijltje omlaag
case KeyEvent.VK_DOWN: {
cordY += 1;
bewegen(cordX, cordY);
poppetje.setIcon(player);
}
break;
//een tegel omhoog met het pijltje omhoog
case KeyEvent.VK_UP: {
cordY -= 1;
bewegen(cordX, cordY);
poppetje.setIcon(player2);
}
break;
}
}
//als een knop ingedrukt wordt
public void keyTyped(KeyEvent ke) {
}
//als een knop lostgelaten wordt
public void keyReleased(KeyEvent ke) {
}
}
|
200271_30 | import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class WebScrape {
public static String getDef(String word) {
String url = "https://www.dwds.de/?q="+word+"&from=wb";
// String url = "https://www.dwds.de/?q=Bauch&from=wb";
String groundWord = "";
try {
final Document document = Jsoup.connect(url).get();
// for (Element element : document.select("div.bedeutungsuebersicht")) {
// if (element.select("ol"))
// }
//word and info
ArrayList<String> allInfos = new ArrayList<>();
for (Element infos : document.select("span.dwdswb-ft-blocktext")) {
allInfos.add(infos.text());
// System.out.println(infos.text()+";");
}
String[] infos = allInfos.get(0).split(" ");
String pofs = infos[0];
String shpofs = "";
if (pofs.equals("Adjektiv")) {
shpofs = "a. ";
} else if (pofs.equals("Substantiv")) {
// shpofs = "s";
if (infos[1].equals("(Neutrum)")) {
shpofs = "das ";
} else if (infos[1].equals("(Femininum)")) {
shpofs = "die ";
} else if (infos[1].equals("(Maskulinum)")) {
shpofs = "der ";
} else if (infos[1].equals("(Femininum,") && infos[2].equals("Maskulinum)")) {
shpofs = "die-der ";
} else if (infos[1].equals("(Maskulinum,") && infos[2].equals("Femininum)")) {
shpofs = "der-die ";
} else if (infos[1].equals("(Neutrum,") && infos[2].equals("Maskulinum)")) {
shpofs = "das-der ";
} else if (infos[1].equals("(Neutrum,") && infos[2].equals("Femininum)")) {
shpofs = "das-die ";
}
} else if (pofs.equals("Verb")) {
shpofs = "v. ";
} else if (pofs.equals("Konjunktion")) {
shpofs = "c. ";
} else if (pofs.equals("Adverb")) {
shpofs = "av. ";
} else if (pofs.equals("Präposition")) {
shpofs = "p. ";
} else if (pofs.equals("partizipiales")) {
shpofs = "pa. ";
} else {
shpofs = pofs+". ";
}
// System.out.print(shpofs); //wasprinting
GlobalVar.Bedeutung += shpofs;
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByTag("b")) {
allWords.add(words.text());
// System.out.println(words.text());
}
// System.out.print(allWords.get(0)+": "); //wasprinting
GlobalVar.Bedeutung += allWords.get(0)+": ";
groundWord = allWords.get(0);
//defs
ArrayList<String> allDefs = new ArrayList<>();
for (Element defs : document.getElementsByTag("ol")) {
allDefs.add(defs.text());
// System.out.println(defs.text()+";");
}
//adds synonym where there would be otherwise nothing
for (Element defs : document.getElementsByClass("dwdswb-verweise")) {
allDefs.add(defs.text());
}
boolean wasEmpty = false;
if (allDefs.isEmpty()) {
for (Element defs : document.getElementsByClass("dwdswb-lesart-def")) {
allDefs.add(defs.text());
// System.out.println(defs.text()+";");
}
wasEmpty = true;
}
// if (allDefs.isEmpty()) {
// System.out.println("ASNOHEUSNATODESU");
// for (Element element : document.select("div.bedeutungsuebersicht")) {
// allDefs.add(element.text());
// }
// wasEmpty = true;
// }
ArrayList<String> allExSentences = new ArrayList<>();
// //the sentences at the bottom
// for (Element exSens : document.getElementsByClass("dwds-gb-list")) {
// allExSentences.add(exSens.text());
// }
// String firstExSens = null;
// try {
// String[] exSens = allExSentences.get(0).split("(?<=[a-z]\\.)");
// firstExSens = exSens[0];
// } catch (Exception e) {
// firstExSens = null;
// }
//the example of the first def
for (Element exSens : document.getElementsByClass("dwdswb-kompetenzbeispiel")) {
allExSentences.add(exSens.text());
}
String firstExSens = null;
try {
firstExSens = allExSentences.get(0)+";\n"+allExSentences.get(1);
} catch (Exception e) {
try {
firstExSens = allExSentences.get(0);
} catch (Exception f) {
firstExSens = null;
}
}
// System.out.println(allDefs.get(1));
String[] splitDefs = {};
if (wasEmpty) {
splitDefs = allDefs.get(0).split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))");
} else {
String longString = allDefs.get(1);
// longString = longString.trim().replaceAll("\\s{2,}", " ");
longString = longString.replace("⟨","{");
longString = longString.replace("⟩","}");
longString = longString.replace("[bildlich] ...", "");
longString = longString.replace("[übertragen] ...", "");
longString = longString.replace("[salopp] ...", "");
longString = longString.replace("[gehoben] ...", "");
longString = longString.replace("[salopp, übertragen] ...", "");
longString = longString.replace("[gehoben, übertragen] ...", "");
longString = longString.replace("[papierdeutsch] ...", "");
longString = longString.replace(" umgangssprachlich ", " [umgangssprachlich] ");
longString = longString.replace(" bildlich ", " [bildlich] ");
longString = longString.replace(" salopp ", " [salopp] ");
longString = longString.replace(" gehoben ", " [gehoben] ");
longString = longString.replace(" veraltend ", " [veraltend] ");
longString = longString.replace(" dichterisch ", " [dichterisch] ");
longString = longString.replace("[umgangssprachlich] ...", "");
longString = longString.replace(" salopp, abwertend ", " [salopp, abwertend] ");
longString = longString.replace("landschaftlich ", "[landschaftlich ] ");
longString = longString.replaceAll("[a-z]\\)\\s[...]", "");
longString = longString.replace("häufig im Partizip I", "");
longString = longString.replace("oft im Partizip II", "");
longString = longString.replace("(1)", "(erste bedeutung)");
longString = longString.replace("(2)", "(zweite Bedeutung)");
longString = longString.replace("(3)", "(dritte Bedeutung)");
longString = longString.trim().replaceAll("\\s{2,}", " ");
longString = longString.replace(". [", ".|["); //to skip the regex splitting
longString = longString.replace(". {", ".|{");
longString = longString.replace("} [", "}|[");
longString = longString.replace("] {", "]|{");
longString = longString.replace(") {", ")|{");
longString = longString.replace(") [", ")|[");
splitDefs = longString.split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))|\\s(?=\\[)|\\s(?=\\{)|\\s(?=II.)|\\s(?=●)");
// splitDefs = longString.split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))|[a-zA-Z]\\s(?=\\[)|[a-zA-Z]\\s(?=\\{)");
}
// splitDefs = defs.text().split("(?<=[b)])");
// splitDefs = defs.text().split("(?<=\\s^[0-9])");
for (String aDef : splitDefs) {
String firstchar = String.valueOf(aDef.charAt(0));
// String lastchar = String.valueOf(aDef.charAt(aDef.length()-1));
if(aDef.endsWith(" ")) {
aDef= aDef.substring(0, aDef.length() - 1); //deletes characters that are not spaces
if(aDef.endsWith(" ")) {
aDef= aDef.substring(0, aDef.length() - 1); //second time
}
}
aDef = aDef.replace(".|[", ". ["); //to skip the regex splitting
aDef = aDef.replace(".|{", ". {");
aDef = aDef.replace("}|[", "} [");
aDef = aDef.replace("]|{", "] {");
aDef = aDef.replace(")|{", ") {");
aDef = aDef.replace(")|[", ") [");
// aDef = aDef.replace("⟨","{");
// aDef = aDef.replace("⟩","}");
// aDef = aDef.replace("[bildlich] ...", "");
// aDef = aDef.replace("[übertragen] ...", "");
// aDef = aDef.replace("[salopp] ...", "");
// aDef = aDef.replace("[gehoben] ...", "");
// aDef = aDef.replace("[salopp, übertragen] ...", "");
// aDef = aDef.replace("[papierdeutsch] ...", "");
// aDef = aDef.replace(" umgangssprachlich ", " [umgangssprachlich] ");
// aDef = aDef.replace(" bildlich ", " [bildlich] ");
// aDef = aDef.replace(" salopp ", " [salopp] ");
// aDef = aDef.replace(" gehoben ", " [gehoben] ");
// aDef = aDef.replace("[umgangssprachlich] ...", "");
if (firstchar.equals("1") || firstchar.equals("2") || firstchar.equals("3") || firstchar.equals("4") ||
firstchar.equals("5") || firstchar.equals("6") || firstchar.equals("7") || firstchar.equals("8") ||
firstchar.equals("9") || firstchar.equals("I") || Arrays.asList(splitDefs).indexOf(aDef) == 0) { //I added Arrays.asList on 2021.01.01
// System.out.println(""+aDef+";"); //wasprinting
GlobalVar.Bedeutung += ""+aDef+";\n";
} else if(aDef.equalsIgnoreCase(" ")||aDef.equalsIgnoreCase("")||aDef.equalsIgnoreCase(" ") ||
aDef.equalsIgnoreCase("bildlich") || aDef.equalsIgnoreCase("2. ") || aDef.equalsIgnoreCase("3. ")) {
} else {
// System.out.println(" "+aDef+";"); //wasprinting
GlobalVar.Bedeutung += " "+aDef+";\n";
}
// System.out.println(" "+aDef);
}
//Example Sentence at the end
if (firstExSens != null && firstExSens.length() != 0) {
// System.out.println("\nz.B.: " + firstExSens); //wasprinting
GlobalVar.Bedeutung += "\nz.B.: " + firstExSens;
}
// System.out.println(document.outerHtml());
// if (allDefs.isEmpty()) {
// System.out.println("n/a\n");
// }
} catch (Exception ex) {
// ex.printStackTrace();
try {
final Document document = Jsoup.connect(url).get();
//defs
ArrayList<String> allDefs = new ArrayList<>();
for (Element defs : document.getElementsByClass("dwdswb-lesart-def")) {
allDefs.add(defs.text());
}
for (String wordss : allDefs) {
// System.out.println(wordss); //wasprinting
wordss = wordss.replace("⟨","{");
wordss = wordss.replace("⟩","} ");
wordss = wordss.replace("[bildlich] ...", "");
wordss = wordss.replace("[übertragen] ...", "");
wordss = wordss.replace("[salopp] ...", "");
wordss = wordss.replace("[gehoben] ...", "");
wordss = wordss.replace("[salopp, übertragen] ...", "");
wordss = wordss.replace("[gehoben, übertragen] ...", "");
wordss = wordss.replace("[papierdeutsch] ...", "");
wordss = wordss.replace("umgangssprachlich ", "[umgangssprachlich] ");
wordss = wordss.replace("bildlich ", "[bildlich] ");
wordss = wordss.replace("salopp ", "[salopp] ");
wordss = wordss.replace("gehoben ", "[gehoben] ");
wordss = wordss.replace("veraltend ", "[veraltend] ");
wordss = wordss.replace("dichterisch ", "[dichterisch] ");
wordss = wordss.replace("salopp, abwertend ", "[salopp, abwertend] ");
wordss = wordss.replace("landschaftlich ", "[landschaftlich ] ");
wordss = wordss.replace("[umgangssprachlich] ...", "");
wordss = wordss.replaceAll("[a-z]\\)\\s[...]", "");
wordss = wordss.replace("häufig im Partizip I", "");
wordss = wordss.replace("oft im Partizip II", "");
wordss = wordss.replace("(1)", "(erste bedeutung)");
wordss = wordss.replace("(2)", "(zweite Bedeutung)");
wordss = wordss.replace("(3)", "(dritte Bedeutung)");
if (allDefs.indexOf(wordss) != allDefs.size()-1 && allDefs.size() != 1) {
GlobalVar.Bedeutung += wordss + ";\n";
} else {
GlobalVar.Bedeutung += wordss + ";";
}
}
// System.out.println(allDefs.get(1));
} catch (Exception ex1) {
// ex.printStackTrace();
// System.out.println("{Keine Wortdefinitionen}"); //wasprinting
GlobalVar.Bedeutung += "{Keine Wortdefinitionen}";
}
}
return groundWord;
}
public static String getGroundWord(String word) throws IOException {
String groundWord = null;
try {
//looks at ground word to see if word is already added
String url = "https://www.dwds.de/?q="+word+"&from=wb";
final Document document = Jsoup.connect(url).get();
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByTag("b")) {
allWords.add(words.text());
}
groundWord = allWords.get(0);
} catch (Exception e) {
// try {
// //captitalize the first character
// word = word.substring(0, 1).toUpperCase() + word.substring(1);
// //looks at ground word to see if word is already added
// String url = "https://www.dwds.de/?q="+word+"&from=wb";
// final Document document = Jsoup.connect(url).get();
//
// ArrayList<String> allWords = new ArrayList<>();
// for (Element words : document.getElementsByTag("b")) {
// allWords.add(words.text());
// }
//
// } catch (Exception f) {
// groundWord = "aoeu";
// }
groundWord = "aoeu"; //for me to know that there is no ground word found
}
if (groundWord == null) { //sometimes the website doesn't react
groundWord = "aoeu";
}
return groundWord;
}
public static String getFrequency(String baseWord) throws IOException {
if (baseWord != null) {
//change ä to ae
baseWord = baseWord.replace("ä", "ae");
baseWord = baseWord.replace("ö", "oe");
baseWord = baseWord.replace("ü", "ue");
try {
String url = "https://www.duden.de/rechtschreibung/" + baseWord;
final Document document = Jsoup.connect(url).get();
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByClass("shaft")) {
allWords.add(words.text());
}
if (allWords.size() != 0) {
if (allWords.get(0).equals("▒▒▒▒▒")) { //very frequent
// System.out.print("★★★★★");
return "★★★★★";
} else if (allWords.get(0).equals("▒░░░░")) {
// System.out.print("★");
return "★";
} else if (allWords.get(0).equals("▒▒░░░")) {
// System.out.print("★★");
return "★★";
} else if (allWords.get(0).equals("▒▒▒░░")) {
// System.out.print("★★★");
return "★★★";
} else if (allWords.get(0).equals("▒▒▒▒░")) {
// System.out.print("★★★★");
return "★★★★";
} else { //very unfrequent
// System.out.print("");
return " ";
}
} else {
return " ";
}
} catch (Exception e) {
return "";
}
}
return "";
}
}
| amiothenes/1T-Sentence-Miner | src/WebScrape.java | 4,766 | // aDef = aDef.replace("[gehoben] ...", "");
| line_comment | nl | import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class WebScrape {
public static String getDef(String word) {
String url = "https://www.dwds.de/?q="+word+"&from=wb";
// String url = "https://www.dwds.de/?q=Bauch&from=wb";
String groundWord = "";
try {
final Document document = Jsoup.connect(url).get();
// for (Element element : document.select("div.bedeutungsuebersicht")) {
// if (element.select("ol"))
// }
//word and info
ArrayList<String> allInfos = new ArrayList<>();
for (Element infos : document.select("span.dwdswb-ft-blocktext")) {
allInfos.add(infos.text());
// System.out.println(infos.text()+";");
}
String[] infos = allInfos.get(0).split(" ");
String pofs = infos[0];
String shpofs = "";
if (pofs.equals("Adjektiv")) {
shpofs = "a. ";
} else if (pofs.equals("Substantiv")) {
// shpofs = "s";
if (infos[1].equals("(Neutrum)")) {
shpofs = "das ";
} else if (infos[1].equals("(Femininum)")) {
shpofs = "die ";
} else if (infos[1].equals("(Maskulinum)")) {
shpofs = "der ";
} else if (infos[1].equals("(Femininum,") && infos[2].equals("Maskulinum)")) {
shpofs = "die-der ";
} else if (infos[1].equals("(Maskulinum,") && infos[2].equals("Femininum)")) {
shpofs = "der-die ";
} else if (infos[1].equals("(Neutrum,") && infos[2].equals("Maskulinum)")) {
shpofs = "das-der ";
} else if (infos[1].equals("(Neutrum,") && infos[2].equals("Femininum)")) {
shpofs = "das-die ";
}
} else if (pofs.equals("Verb")) {
shpofs = "v. ";
} else if (pofs.equals("Konjunktion")) {
shpofs = "c. ";
} else if (pofs.equals("Adverb")) {
shpofs = "av. ";
} else if (pofs.equals("Präposition")) {
shpofs = "p. ";
} else if (pofs.equals("partizipiales")) {
shpofs = "pa. ";
} else {
shpofs = pofs+". ";
}
// System.out.print(shpofs); //wasprinting
GlobalVar.Bedeutung += shpofs;
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByTag("b")) {
allWords.add(words.text());
// System.out.println(words.text());
}
// System.out.print(allWords.get(0)+": "); //wasprinting
GlobalVar.Bedeutung += allWords.get(0)+": ";
groundWord = allWords.get(0);
//defs
ArrayList<String> allDefs = new ArrayList<>();
for (Element defs : document.getElementsByTag("ol")) {
allDefs.add(defs.text());
// System.out.println(defs.text()+";");
}
//adds synonym where there would be otherwise nothing
for (Element defs : document.getElementsByClass("dwdswb-verweise")) {
allDefs.add(defs.text());
}
boolean wasEmpty = false;
if (allDefs.isEmpty()) {
for (Element defs : document.getElementsByClass("dwdswb-lesart-def")) {
allDefs.add(defs.text());
// System.out.println(defs.text()+";");
}
wasEmpty = true;
}
// if (allDefs.isEmpty()) {
// System.out.println("ASNOHEUSNATODESU");
// for (Element element : document.select("div.bedeutungsuebersicht")) {
// allDefs.add(element.text());
// }
// wasEmpty = true;
// }
ArrayList<String> allExSentences = new ArrayList<>();
// //the sentences at the bottom
// for (Element exSens : document.getElementsByClass("dwds-gb-list")) {
// allExSentences.add(exSens.text());
// }
// String firstExSens = null;
// try {
// String[] exSens = allExSentences.get(0).split("(?<=[a-z]\\.)");
// firstExSens = exSens[0];
// } catch (Exception e) {
// firstExSens = null;
// }
//the example of the first def
for (Element exSens : document.getElementsByClass("dwdswb-kompetenzbeispiel")) {
allExSentences.add(exSens.text());
}
String firstExSens = null;
try {
firstExSens = allExSentences.get(0)+";\n"+allExSentences.get(1);
} catch (Exception e) {
try {
firstExSens = allExSentences.get(0);
} catch (Exception f) {
firstExSens = null;
}
}
// System.out.println(allDefs.get(1));
String[] splitDefs = {};
if (wasEmpty) {
splitDefs = allDefs.get(0).split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))");
} else {
String longString = allDefs.get(1);
// longString = longString.trim().replaceAll("\\s{2,}", " ");
longString = longString.replace("⟨","{");
longString = longString.replace("⟩","}");
longString = longString.replace("[bildlich] ...", "");
longString = longString.replace("[übertragen] ...", "");
longString = longString.replace("[salopp] ...", "");
longString = longString.replace("[gehoben] ...", "");
longString = longString.replace("[salopp, übertragen] ...", "");
longString = longString.replace("[gehoben, übertragen] ...", "");
longString = longString.replace("[papierdeutsch] ...", "");
longString = longString.replace(" umgangssprachlich ", " [umgangssprachlich] ");
longString = longString.replace(" bildlich ", " [bildlich] ");
longString = longString.replace(" salopp ", " [salopp] ");
longString = longString.replace(" gehoben ", " [gehoben] ");
longString = longString.replace(" veraltend ", " [veraltend] ");
longString = longString.replace(" dichterisch ", " [dichterisch] ");
longString = longString.replace("[umgangssprachlich] ...", "");
longString = longString.replace(" salopp, abwertend ", " [salopp, abwertend] ");
longString = longString.replace("landschaftlich ", "[landschaftlich ] ");
longString = longString.replaceAll("[a-z]\\)\\s[...]", "");
longString = longString.replace("häufig im Partizip I", "");
longString = longString.replace("oft im Partizip II", "");
longString = longString.replace("(1)", "(erste bedeutung)");
longString = longString.replace("(2)", "(zweite Bedeutung)");
longString = longString.replace("(3)", "(dritte Bedeutung)");
longString = longString.trim().replaceAll("\\s{2,}", " ");
longString = longString.replace(". [", ".|["); //to skip the regex splitting
longString = longString.replace(". {", ".|{");
longString = longString.replace("} [", "}|[");
longString = longString.replace("] {", "]|{");
longString = longString.replace(") {", ")|{");
longString = longString.replace(") [", ")|[");
splitDefs = longString.split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))|\\s(?=\\[)|\\s(?=\\{)|\\s(?=II.)|\\s(?=●)");
// splitDefs = longString.split("(?=[1-9])|\\s(?=a\\))|\\s(?=b\\))|\\s(?=c\\))|\\s(?=d\\))|\\s(?=e\\))|[a-zA-Z]\\s(?=\\[)|[a-zA-Z]\\s(?=\\{)");
}
// splitDefs = defs.text().split("(?<=[b)])");
// splitDefs = defs.text().split("(?<=\\s^[0-9])");
for (String aDef : splitDefs) {
String firstchar = String.valueOf(aDef.charAt(0));
// String lastchar = String.valueOf(aDef.charAt(aDef.length()-1));
if(aDef.endsWith(" ")) {
aDef= aDef.substring(0, aDef.length() - 1); //deletes characters that are not spaces
if(aDef.endsWith(" ")) {
aDef= aDef.substring(0, aDef.length() - 1); //second time
}
}
aDef = aDef.replace(".|[", ". ["); //to skip the regex splitting
aDef = aDef.replace(".|{", ". {");
aDef = aDef.replace("}|[", "} [");
aDef = aDef.replace("]|{", "] {");
aDef = aDef.replace(")|{", ") {");
aDef = aDef.replace(")|[", ") [");
// aDef = aDef.replace("⟨","{");
// aDef = aDef.replace("⟩","}");
// aDef = aDef.replace("[bildlich] ...", "");
// aDef = aDef.replace("[übertragen] ...", "");
// aDef = aDef.replace("[salopp] ...", "");
// aDef =<SUF>
// aDef = aDef.replace("[salopp, übertragen] ...", "");
// aDef = aDef.replace("[papierdeutsch] ...", "");
// aDef = aDef.replace(" umgangssprachlich ", " [umgangssprachlich] ");
// aDef = aDef.replace(" bildlich ", " [bildlich] ");
// aDef = aDef.replace(" salopp ", " [salopp] ");
// aDef = aDef.replace(" gehoben ", " [gehoben] ");
// aDef = aDef.replace("[umgangssprachlich] ...", "");
if (firstchar.equals("1") || firstchar.equals("2") || firstchar.equals("3") || firstchar.equals("4") ||
firstchar.equals("5") || firstchar.equals("6") || firstchar.equals("7") || firstchar.equals("8") ||
firstchar.equals("9") || firstchar.equals("I") || Arrays.asList(splitDefs).indexOf(aDef) == 0) { //I added Arrays.asList on 2021.01.01
// System.out.println(""+aDef+";"); //wasprinting
GlobalVar.Bedeutung += ""+aDef+";\n";
} else if(aDef.equalsIgnoreCase(" ")||aDef.equalsIgnoreCase("")||aDef.equalsIgnoreCase(" ") ||
aDef.equalsIgnoreCase("bildlich") || aDef.equalsIgnoreCase("2. ") || aDef.equalsIgnoreCase("3. ")) {
} else {
// System.out.println(" "+aDef+";"); //wasprinting
GlobalVar.Bedeutung += " "+aDef+";\n";
}
// System.out.println(" "+aDef);
}
//Example Sentence at the end
if (firstExSens != null && firstExSens.length() != 0) {
// System.out.println("\nz.B.: " + firstExSens); //wasprinting
GlobalVar.Bedeutung += "\nz.B.: " + firstExSens;
}
// System.out.println(document.outerHtml());
// if (allDefs.isEmpty()) {
// System.out.println("n/a\n");
// }
} catch (Exception ex) {
// ex.printStackTrace();
try {
final Document document = Jsoup.connect(url).get();
//defs
ArrayList<String> allDefs = new ArrayList<>();
for (Element defs : document.getElementsByClass("dwdswb-lesart-def")) {
allDefs.add(defs.text());
}
for (String wordss : allDefs) {
// System.out.println(wordss); //wasprinting
wordss = wordss.replace("⟨","{");
wordss = wordss.replace("⟩","} ");
wordss = wordss.replace("[bildlich] ...", "");
wordss = wordss.replace("[übertragen] ...", "");
wordss = wordss.replace("[salopp] ...", "");
wordss = wordss.replace("[gehoben] ...", "");
wordss = wordss.replace("[salopp, übertragen] ...", "");
wordss = wordss.replace("[gehoben, übertragen] ...", "");
wordss = wordss.replace("[papierdeutsch] ...", "");
wordss = wordss.replace("umgangssprachlich ", "[umgangssprachlich] ");
wordss = wordss.replace("bildlich ", "[bildlich] ");
wordss = wordss.replace("salopp ", "[salopp] ");
wordss = wordss.replace("gehoben ", "[gehoben] ");
wordss = wordss.replace("veraltend ", "[veraltend] ");
wordss = wordss.replace("dichterisch ", "[dichterisch] ");
wordss = wordss.replace("salopp, abwertend ", "[salopp, abwertend] ");
wordss = wordss.replace("landschaftlich ", "[landschaftlich ] ");
wordss = wordss.replace("[umgangssprachlich] ...", "");
wordss = wordss.replaceAll("[a-z]\\)\\s[...]", "");
wordss = wordss.replace("häufig im Partizip I", "");
wordss = wordss.replace("oft im Partizip II", "");
wordss = wordss.replace("(1)", "(erste bedeutung)");
wordss = wordss.replace("(2)", "(zweite Bedeutung)");
wordss = wordss.replace("(3)", "(dritte Bedeutung)");
if (allDefs.indexOf(wordss) != allDefs.size()-1 && allDefs.size() != 1) {
GlobalVar.Bedeutung += wordss + ";\n";
} else {
GlobalVar.Bedeutung += wordss + ";";
}
}
// System.out.println(allDefs.get(1));
} catch (Exception ex1) {
// ex.printStackTrace();
// System.out.println("{Keine Wortdefinitionen}"); //wasprinting
GlobalVar.Bedeutung += "{Keine Wortdefinitionen}";
}
}
return groundWord;
}
public static String getGroundWord(String word) throws IOException {
String groundWord = null;
try {
//looks at ground word to see if word is already added
String url = "https://www.dwds.de/?q="+word+"&from=wb";
final Document document = Jsoup.connect(url).get();
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByTag("b")) {
allWords.add(words.text());
}
groundWord = allWords.get(0);
} catch (Exception e) {
// try {
// //captitalize the first character
// word = word.substring(0, 1).toUpperCase() + word.substring(1);
// //looks at ground word to see if word is already added
// String url = "https://www.dwds.de/?q="+word+"&from=wb";
// final Document document = Jsoup.connect(url).get();
//
// ArrayList<String> allWords = new ArrayList<>();
// for (Element words : document.getElementsByTag("b")) {
// allWords.add(words.text());
// }
//
// } catch (Exception f) {
// groundWord = "aoeu";
// }
groundWord = "aoeu"; //for me to know that there is no ground word found
}
if (groundWord == null) { //sometimes the website doesn't react
groundWord = "aoeu";
}
return groundWord;
}
public static String getFrequency(String baseWord) throws IOException {
if (baseWord != null) {
//change ä to ae
baseWord = baseWord.replace("ä", "ae");
baseWord = baseWord.replace("ö", "oe");
baseWord = baseWord.replace("ü", "ue");
try {
String url = "https://www.duden.de/rechtschreibung/" + baseWord;
final Document document = Jsoup.connect(url).get();
ArrayList<String> allWords = new ArrayList<>();
for (Element words : document.getElementsByClass("shaft")) {
allWords.add(words.text());
}
if (allWords.size() != 0) {
if (allWords.get(0).equals("▒▒▒▒▒")) { //very frequent
// System.out.print("★★★★★");
return "★★★★★";
} else if (allWords.get(0).equals("▒░░░░")) {
// System.out.print("★");
return "★";
} else if (allWords.get(0).equals("▒▒░░░")) {
// System.out.print("★★");
return "★★";
} else if (allWords.get(0).equals("▒▒▒░░")) {
// System.out.print("★★★");
return "★★★";
} else if (allWords.get(0).equals("▒▒▒▒░")) {
// System.out.print("★★★★");
return "★★★★";
} else { //very unfrequent
// System.out.print("");
return " ";
}
} else {
return " ";
}
} catch (Exception e) {
return "";
}
}
return "";
}
}
|