file_id
stringlengths
5
10
content
stringlengths
110
36.3k
repo
stringlengths
7
108
path
stringlengths
8
198
token_length
int64
37
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
62
36.3k
41733_2
/* * SpeechTendancyToken.java * Copyright 2003 (C) Devon Jones <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package plugin.exporttokens.deprecated; import pcgen.core.display.CharacterDisplay; import pcgen.io.ExportHandler; import pcgen.io.exporttoken.AbstractExportToken; /** * SPEECHTENDANCY token for export */ public class SpeechTendancyToken extends AbstractExportToken { /** * @see pcgen.io.exporttoken.Token#getTokenName() */ @Override public String getTokenName() { return "SPEECHTENDENCY"; } //TODO: Move this to a token that has all of the descriptive stuff about a character /** * @see AbstractExportToken#getToken(String, CharacterDisplay, ExportHandler) */ @Override public String getToken(String tokenSource, CharacterDisplay display, ExportHandler eh) { return display.getSpeechTendency(); } }
romen/pcgen
code/src/java/plugin/exporttokens/deprecated/SpeechTendancyToken.java
464
/** * @see pcgen.io.exporttoken.Token#getTokenName() */
block_comment
nl
/* * SpeechTendancyToken.java * Copyright 2003 (C) Devon Jones <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package plugin.exporttokens.deprecated; import pcgen.core.display.CharacterDisplay; import pcgen.io.ExportHandler; import pcgen.io.exporttoken.AbstractExportToken; /** * SPEECHTENDANCY token for export */ public class SpeechTendancyToken extends AbstractExportToken { /** * @see pcgen.io.exporttoken.Token#getTokenName() <SUF>*/ @Override public String getTokenName() { return "SPEECHTENDENCY"; } //TODO: Move this to a token that has all of the descriptive stuff about a character /** * @see AbstractExportToken#getToken(String, CharacterDisplay, ExportHandler) */ @Override public String getToken(String tokenSource, CharacterDisplay display, ExportHandler eh) { return display.getSpeechTendency(); } }
168062_2
package com.keemerz.klaverjas.repository; import com.keemerz.klaverjas.domain.Credentials; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class CredentialsRepository { private static final List<Credentials> CREDENTIALS = new ArrayList<>(); public static final String DEFAULT_PASSWORD = "bier"; static { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // for now, actual security is of no importance. // What matters is that the logged in user has a Principal, which is required for individual web sockets to work :) CREDENTIALS.add(new Credentials("user1", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user2", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user3", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user4", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("martin", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("alex", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("ronald", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("eelco", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("robert", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("rommert", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("toon", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("jasper", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("yoran", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("paul", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("joris", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("frank", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("janthijs", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("anton", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("edzo", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("marc", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("sander", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("mitchell", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("jonathan", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("niek", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("stefan", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("ties", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("hans", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("mark", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("matthijs", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("sidney", encoder.encode(DEFAULT_PASSWORD))); // maatjes van Ties CREDENTIALS.add(new Credentials("rogier", encoder.encode(DEFAULT_PASSWORD))); // maatjes van Ties } public Credentials getCredentials(String userId) { return CREDENTIALS.stream() .filter(credentials -> credentials.getUserId().equals(userId)) .findFirst() .orElseThrow(IllegalArgumentException::new); } }
rommertdebruijn/klaverjas
src/main/java/com/keemerz/klaverjas/repository/CredentialsRepository.java
1,121
// maatjes van Ties
line_comment
nl
package com.keemerz.klaverjas.repository; import com.keemerz.klaverjas.domain.Credentials; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class CredentialsRepository { private static final List<Credentials> CREDENTIALS = new ArrayList<>(); public static final String DEFAULT_PASSWORD = "bier"; static { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // for now, actual security is of no importance. // What matters is that the logged in user has a Principal, which is required for individual web sockets to work :) CREDENTIALS.add(new Credentials("user1", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user2", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user3", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("user4", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("martin", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("alex", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("ronald", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("eelco", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("robert", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("rommert", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("toon", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("jasper", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("yoran", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("paul", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("joris", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("frank", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("janthijs", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("anton", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("edzo", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("marc", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("sander", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("mitchell", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("jonathan", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("niek", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("stefan", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("ties", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("hans", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("mark", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("matthijs", encoder.encode(DEFAULT_PASSWORD))); CREDENTIALS.add(new Credentials("sidney", encoder.encode(DEFAULT_PASSWORD))); // maatjes van<SUF> CREDENTIALS.add(new Credentials("rogier", encoder.encode(DEFAULT_PASSWORD))); // maatjes van Ties } public Credentials getCredentials(String userId) { return CREDENTIALS.stream() .filter(credentials -> credentials.getUserId().equals(userId)) .findFirst() .orElseThrow(IllegalArgumentException::new); } }
116167_2
/* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import ender.CurioInfo; public class Item extends Widget implements DTarget { static Coord shoff = new Coord(1, 3); static final Pattern patt = Pattern.compile("quality (\\d+) ", Pattern.CASE_INSENSITIVE); static Map<Integer, Tex> qmap; static Resource missing = Resource.load("gfx/invobjs/missing"); static Color outcol = new Color(0, 0, 0, 255); static Color clrWater = new Color(24, 116, 205); static Color clrWine = new Color(139, 71, 137); static Color clrHoney = new Color(238, 173, 14); boolean dm = false; public int q, q2; boolean hq; Coord doff; public String tooltip; int num = -1; Indir<Resource> res; Tex sh; public Color olcol = null; Tex mask = null; int meter = 0; String curioStr = null; public static int idCounter = 0; // new public int id = 0; // new static { Widget.addtype("item", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { int res = (Integer) args[0]; int q = (Integer) args[1]; int num = -1; String tooltip = null; int ca = 3; Coord drag = null; if ((Integer) args[2] != 0) drag = (Coord) args[ca++]; if (args.length > ca) tooltip = (String) args[ca++]; if ((tooltip != null) && tooltip.equals("")) tooltip = null; if (args.length > ca) num = (Integer) args[ca++]; Item item = new Item(c, res, q, parent, drag, num); item.settip(tooltip); return (item); } }); missing.loadwait(); qmap = new HashMap<Integer, Tex>(); } public void settip(String t) { tooltip = t; q2 = -1; if (tooltip != null) { try { Matcher m = patt.matcher(tooltip); while (m.find()) { q2 = Integer.parseInt(m.group(1)); } } catch (IllegalStateException e) { System.out.println(e.getMessage()); } } calcFEP(); calcCurio(); shorttip = longtip = null; } private void fixsize() { if (res.get() != null) { Tex tex = res.get().layer(Resource.imgc).tex(); sz = tex.sz().add(shoff); } else { sz = new Coord(30, 30); } } public void draw(GOut g) { final Resource ttres; if (res.get() == null) { sh = null; sz = new Coord(30, 30); g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz); ttres = missing; } else { Tex tex = res.get().layer(Resource.imgc).tex(); fixsize(); if (dm) { g.chcolor(255, 255, 255, 128); g.image(tex, Coord.z); g.chcolor(); } else { if(res.get().basename().equals("silkmoth") && tooltip != null && tooltip.contains("Female")) g.chcolor(255, 124, 195, 255); g.image(tex, Coord.z); g.chcolor(); } if (num >= 0) { // g.chcolor(Color.WHITE); // g.atext(Integer.toString(num), new Coord(0, 30), 0, 1); g.aimage(getqtex(num), Coord.z, 0, 0); } if (meter > 0) { double a = ((double) meter) / 100.0; int r = (int) ((1 - a) * 255); int gr = (int) (a * 255); int b = 0; g.chcolor(r, gr, b, 255); // g.fellipse(sz.div(2), new Coord(15, 15), 90, (int)(90 + (360 // * a))); g.frect(new Coord(sz.x - 5, (int) ((1 - a) * sz.y)), new Coord(5, (int) (a * sz.y))); g.chcolor(); } int tq = (q2 > 0) ? q2 : q; if (Config.showq && (tq > 0)) { tex = getqtex(tq); g.aimage(tex, sz.sub(1, 1), 1, 1); } ttres = res.get(); } if (olcol != null) { Tex bg = ttres.layer(Resource.imgc).tex(); if ((mask == null) && (bg instanceof TexI)) { mask = ((TexI) bg).mkmask(); } if (mask != null) { g.chcolor(olcol); g.image(mask, Coord.z); g.chcolor(); } } if (FEP == null) { calcFEP(); } if (curioStr == null) { calcCurio(); } if (ttres.name.lastIndexOf("waterflask") > 0) { drawBar(g, 2, clrWater, 3); } else if (ttres.name.lastIndexOf("glass-winef") > 0) { drawBar(g, 0.2, clrWine, 3); } else if (ttres.name.lastIndexOf("bottle-winef") > 0) { drawBar(g, 0.6, clrWine, 3); } else if (ttres.name.lastIndexOf("bottle-wine-weißbier") > 0) { drawBar(g, 0.6, clrWine, 3); } else if (ttres.name.lastIndexOf("tankardf") > 0) { drawBar(g, 0.4, clrWine, 3); } else if (ttres.name.lastIndexOf("waterskin") > 0) { drawBar(g, 3, clrWater, 3); } else if (ttres.name.lastIndexOf("bucket-") > 0 || ttres.name.lastIndexOf("waterflask-") > 0) { Color clr; if (ttres.name.lastIndexOf("water") > 0) clr = clrWater; else if (ttres.name.lastIndexOf("wine") > 0 || ttres.name.lastIndexOf("vinegar") > 0) clr = clrWine; else if (ttres.name.lastIndexOf("honey") > 0) clr = clrHoney; else clr = Color.LIGHT_GRAY; drawBar(g, 10, clr, 9); } } private void drawBar(GOut g, double capacity, Color clr, int width) { try { String valStr = tooltip.substring(tooltip.indexOf('(') + 1, tooltip.indexOf('/')); double val = Double.parseDouble(valStr); int h = (int) (val / capacity * sz.y); g.chcolor(clr); int barH = h - shoff.y; g.frect(new Coord(0, sz.y - h), new Coord(width, barH < 0 ? 0 : barH)); g.chcolor(); } catch (Exception e) { } // fail silently. } static Tex getqtex(int q) { synchronized (qmap) { if (qmap.containsKey(q)) { return qmap.get(q); } else { BufferedImage img = Text.render(Integer.toString(q)).img; img = Utils.outline2(img, outcol, true); Tex tex = new TexI(img); qmap.put(q, tex); return tex; } } } static Tex makesh(Resource res) { BufferedImage img = res.layer(Resource.imgc).img; Coord sz = Utils.imgsz(img); BufferedImage sh = new BufferedImage(sz.x, sz.y, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < sz.y; y++) { for (int x = 0; x < sz.x; x++) { long c = img.getRGB(x, y) & 0x00000000ffffffffL; int a = (int) ((c & 0xff000000) >> 24); sh.setRGB(x, y, (a / 2) << 24); } } return (new TexI(sh)); } public String name() { Resource res = this.res.get(); if (res != null) { if (res.layer(Resource.tooltip) != null) { return res.layer(Resource.tooltip).t; } else { return (this.tooltip); } } return null; } public String shorttip() { if (this.tooltip != null) return (this.tooltip); Resource res = this.res.get(); if ((res != null) && (res.layer(Resource.tooltip) != null)) { String tt = res.layer(Resource.tooltip).t; if (tt != null) { if (q > 0) { tt = tt + ", quality " + q; if (hq) tt = tt + "+"; } return (tt); } } return (null); } long hoverstart; Text shorttip = null, longtip = null; public double qmult; private String FEP = null; public Object tooltip(Coord c, boolean again) { long now = System.currentTimeMillis(); if (!again) hoverstart = now; Resource res = this.res.get(); Resource.Pagina pg = (res != null) ? res.layer(Resource.pagina) : null; if (((now - hoverstart) < 500) || (pg == null)) { if (shorttip == null) { String tt = shorttip(); if (tt != null) { tt = RichText.Parser.quote(tt); if (meter > 0) { tt = tt + " (" + meter + "%)"; } if (FEP != null) { tt += FEP; } if (curioStr != null) { tt += curioStr; } shorttip = RichText.render(tt, 200); } } return (shorttip); } else { if ((longtip == null) && (res != null)) { String tip = shorttip(); if (tip == null) return (null); String tt = RichText.Parser.quote(tip); if (meter > 0) { tt = tt + " (" + meter + "%)"; } if (FEP != null) { tt += FEP; } if (curioStr != null) { tt += curioStr; } if (pg != null) tt += "\n\n" + pg.text; longtip = RichText.render(tt, 200); } return (longtip); } } private void resettt() { shorttip = null; longtip = null; } private void decq(int q) { if (q < 0) { this.q = q; hq = false; } else { int fl = (q & 0xff000000) >> 24; this.q = (q & 0xffffff); hq = ((fl & 1) != 0); } } public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag, int num) { super(c, Coord.z, parent); this.res = res; idCounter++; // new id = idCounter; // new decq(q); fixsize(); this.num = num; if (drag == null) { dm = false; } else { dm = true; doff = drag; ui.grabmouse(this); this.c = ui.mc.add(doff.inv()); } qmult = Math.sqrt((float) q / 10); calcFEP(); calcCurio(); } private void calcFEP() { Map<String, Float> fep; String name = name(); if (name == null) { return; } if (name.equals("Ring of Brodgar")) { if (res.get().name.equals("gfx/invobjs/bread-brodgar")) { name = "Ring of Brodgar (Baking)"; } if (res.get().name.equals("gfx/invobjs/feast-rob")) { name = "Ring of Brodgar (Seafood)"; } } name = name.toLowerCase(); boolean isItem = false; if ((fep = Config.FEPMap.get(name)) != null) { if (fep.containsKey("isItem")) { isItem = true; } FEP = "\n"; for (String key : fep.keySet()) { float val = (float) (fep.get(key) * qmult); if (key.equals("isItem")) { continue; } if (isItem) { val = (float) Math.floor(val); FEP += String.format("%s:%.0f ", key, val); } else { FEP += String.format("%s:%.1f ", key, val); } } shorttip = longtip = null; } } public int getLP() { String name = name(); if (name == null) { return 0; } name = name.toLowerCase(); CurioInfo curio; if ((curio = Config.curios.get(name)) != null) { return (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100); } return 0; } private void calcCurio() { String name = name(); if (name == null) { return; } name = name.toLowerCase(); CurioInfo curio; if ((curio = Config.curios.get(name)) != null) { int LP = (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100); int time = curio.time * (100 - meter) / 100; int h = time / 60; int m = time % 60; curioStr = String.format("\nLP: %d, Weight: %d\nStudy time: %dh %2dm", LP, curio.weight, h, m); shorttip = longtip = null; } } public Item(Coord c, int res, int q, Widget parent, Coord drag, int num) { this(c, parent.ui.sess.getres(res), q, parent, drag, num); } public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag) { this(c, res, q, parent, drag, -1); } public Item(Coord c, int res, int q, Widget parent, Coord drag) { this(c, parent.ui.sess.getres(res), q, parent, drag); } public boolean dropon(Widget w, Coord c) { for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) { if (wdg == this) continue; Coord cc = w.xlate(wdg.c, true); if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) { if (dropon(wdg, c.add(cc.inv()))) return (true); } } if (w instanceof DTarget) { if (((DTarget) w).drop(c, c.add(doff.inv()))) return (true); } if (w instanceof DTarget2) { if (((DTarget2) w).drop(c, c.add(doff.inv()), this)) return (true); } return (false); } public boolean interact(Widget w, Coord c) { for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) { if (wdg == this) continue; Coord cc = w.xlate(wdg.c, true); if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) { if (interact(wdg, c.add(cc.inv()))) return (true); } } if (w instanceof DTarget) { if (((DTarget) w).iteminteract(c, c.add(doff.inv()))) return (true); } return (false); } public void chres(Indir<Resource> res, int q) { this.res = res; sh = null; decq(q); } public void uimsg(String name, Object... args) { if (name == "num") { num = (Integer) args[0]; } else if (name == "chres") { chres(ui.sess.getres((Integer) args[0]), (Integer) args[1]); resettt(); } else if (name == "color") { olcol = (Color) args[0]; } else if (name == "tt") { if ((args.length > 0) && (((String) args[0]).length() > 0)) settip((String) args[0]); else settip(null); resettt(); } else if (name == "meter") { meter = (Integer) args[0]; shorttip = null; longtip = null; calcCurio(); } } public String GetResName() { // new if (this.res.get() != null) { return ((Resource) this.res.get()).name; } return ""; } void sortedSkoop() { // new String name = GetResName(); if (parent instanceof Inventory) ((Inventory) parent).skoopItems(name); } public boolean mousedown(Coord c, int button) { if (button == 3 && ui.modflags() == 4) { // new sortedSkoop(); return (true); } if (!dm) { if (button == 1) { if (ui.modshift) if (ui.modmeta) wdgmsg("transfer-same", name(), false); else wdgmsg("transfer", c); else if (ui.modctrl) if (ui.modmeta) wdgmsg("drop-same", name(), false); else wdgmsg("drop", c); else wdgmsg("take", c); return (true); } else if (button == 3) { if (ui.modmeta) { if (ui.modshift) { wdgmsg("transfer-same", name(), true); } else if (ui.modctrl) { wdgmsg("drop-same", name(), true); } } else { wdgmsg("iact", c); } return (true); } } else { if (button == 1) { dropon(parent, c.add(this.c)); } else if (button == 3) { interact(parent, c.add(this.c)); } return (true); } return (false); } public void mousemove(Coord c) { if (dm) this.c = this.c.add(c.add(doff.inv())); } public boolean drop(Coord cc, Coord ul) { return (false); } public boolean iteminteract(Coord cc, Coord ul) { wdgmsg("itemact", ui.modflags()); return (true); } public ItemType getItemType(Item itm) { String resname = itm.res.get().name; int idx = resname.lastIndexOf("/"); resname = resname.substring(idx + 1); if (!Config.itemTypes.containsKey(resname)) return ItemType.NOT_IMPLEMENTED; return Config.itemTypes.get(resname); } }
romovs/anemone
src/haven/Item.java
6,235
// g.fellipse(sz.div(2), new Coord(15, 15), 90, (int)(90 + (360
line_comment
nl
/* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * 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. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import ender.CurioInfo; public class Item extends Widget implements DTarget { static Coord shoff = new Coord(1, 3); static final Pattern patt = Pattern.compile("quality (\\d+) ", Pattern.CASE_INSENSITIVE); static Map<Integer, Tex> qmap; static Resource missing = Resource.load("gfx/invobjs/missing"); static Color outcol = new Color(0, 0, 0, 255); static Color clrWater = new Color(24, 116, 205); static Color clrWine = new Color(139, 71, 137); static Color clrHoney = new Color(238, 173, 14); boolean dm = false; public int q, q2; boolean hq; Coord doff; public String tooltip; int num = -1; Indir<Resource> res; Tex sh; public Color olcol = null; Tex mask = null; int meter = 0; String curioStr = null; public static int idCounter = 0; // new public int id = 0; // new static { Widget.addtype("item", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { int res = (Integer) args[0]; int q = (Integer) args[1]; int num = -1; String tooltip = null; int ca = 3; Coord drag = null; if ((Integer) args[2] != 0) drag = (Coord) args[ca++]; if (args.length > ca) tooltip = (String) args[ca++]; if ((tooltip != null) && tooltip.equals("")) tooltip = null; if (args.length > ca) num = (Integer) args[ca++]; Item item = new Item(c, res, q, parent, drag, num); item.settip(tooltip); return (item); } }); missing.loadwait(); qmap = new HashMap<Integer, Tex>(); } public void settip(String t) { tooltip = t; q2 = -1; if (tooltip != null) { try { Matcher m = patt.matcher(tooltip); while (m.find()) { q2 = Integer.parseInt(m.group(1)); } } catch (IllegalStateException e) { System.out.println(e.getMessage()); } } calcFEP(); calcCurio(); shorttip = longtip = null; } private void fixsize() { if (res.get() != null) { Tex tex = res.get().layer(Resource.imgc).tex(); sz = tex.sz().add(shoff); } else { sz = new Coord(30, 30); } } public void draw(GOut g) { final Resource ttres; if (res.get() == null) { sh = null; sz = new Coord(30, 30); g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz); ttres = missing; } else { Tex tex = res.get().layer(Resource.imgc).tex(); fixsize(); if (dm) { g.chcolor(255, 255, 255, 128); g.image(tex, Coord.z); g.chcolor(); } else { if(res.get().basename().equals("silkmoth") && tooltip != null && tooltip.contains("Female")) g.chcolor(255, 124, 195, 255); g.image(tex, Coord.z); g.chcolor(); } if (num >= 0) { // g.chcolor(Color.WHITE); // g.atext(Integer.toString(num), new Coord(0, 30), 0, 1); g.aimage(getqtex(num), Coord.z, 0, 0); } if (meter > 0) { double a = ((double) meter) / 100.0; int r = (int) ((1 - a) * 255); int gr = (int) (a * 255); int b = 0; g.chcolor(r, gr, b, 255); // g.fellipse(sz.div(2), new<SUF> // * a))); g.frect(new Coord(sz.x - 5, (int) ((1 - a) * sz.y)), new Coord(5, (int) (a * sz.y))); g.chcolor(); } int tq = (q2 > 0) ? q2 : q; if (Config.showq && (tq > 0)) { tex = getqtex(tq); g.aimage(tex, sz.sub(1, 1), 1, 1); } ttres = res.get(); } if (olcol != null) { Tex bg = ttres.layer(Resource.imgc).tex(); if ((mask == null) && (bg instanceof TexI)) { mask = ((TexI) bg).mkmask(); } if (mask != null) { g.chcolor(olcol); g.image(mask, Coord.z); g.chcolor(); } } if (FEP == null) { calcFEP(); } if (curioStr == null) { calcCurio(); } if (ttres.name.lastIndexOf("waterflask") > 0) { drawBar(g, 2, clrWater, 3); } else if (ttres.name.lastIndexOf("glass-winef") > 0) { drawBar(g, 0.2, clrWine, 3); } else if (ttres.name.lastIndexOf("bottle-winef") > 0) { drawBar(g, 0.6, clrWine, 3); } else if (ttres.name.lastIndexOf("bottle-wine-weißbier") > 0) { drawBar(g, 0.6, clrWine, 3); } else if (ttres.name.lastIndexOf("tankardf") > 0) { drawBar(g, 0.4, clrWine, 3); } else if (ttres.name.lastIndexOf("waterskin") > 0) { drawBar(g, 3, clrWater, 3); } else if (ttres.name.lastIndexOf("bucket-") > 0 || ttres.name.lastIndexOf("waterflask-") > 0) { Color clr; if (ttres.name.lastIndexOf("water") > 0) clr = clrWater; else if (ttres.name.lastIndexOf("wine") > 0 || ttres.name.lastIndexOf("vinegar") > 0) clr = clrWine; else if (ttres.name.lastIndexOf("honey") > 0) clr = clrHoney; else clr = Color.LIGHT_GRAY; drawBar(g, 10, clr, 9); } } private void drawBar(GOut g, double capacity, Color clr, int width) { try { String valStr = tooltip.substring(tooltip.indexOf('(') + 1, tooltip.indexOf('/')); double val = Double.parseDouble(valStr); int h = (int) (val / capacity * sz.y); g.chcolor(clr); int barH = h - shoff.y; g.frect(new Coord(0, sz.y - h), new Coord(width, barH < 0 ? 0 : barH)); g.chcolor(); } catch (Exception e) { } // fail silently. } static Tex getqtex(int q) { synchronized (qmap) { if (qmap.containsKey(q)) { return qmap.get(q); } else { BufferedImage img = Text.render(Integer.toString(q)).img; img = Utils.outline2(img, outcol, true); Tex tex = new TexI(img); qmap.put(q, tex); return tex; } } } static Tex makesh(Resource res) { BufferedImage img = res.layer(Resource.imgc).img; Coord sz = Utils.imgsz(img); BufferedImage sh = new BufferedImage(sz.x, sz.y, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < sz.y; y++) { for (int x = 0; x < sz.x; x++) { long c = img.getRGB(x, y) & 0x00000000ffffffffL; int a = (int) ((c & 0xff000000) >> 24); sh.setRGB(x, y, (a / 2) << 24); } } return (new TexI(sh)); } public String name() { Resource res = this.res.get(); if (res != null) { if (res.layer(Resource.tooltip) != null) { return res.layer(Resource.tooltip).t; } else { return (this.tooltip); } } return null; } public String shorttip() { if (this.tooltip != null) return (this.tooltip); Resource res = this.res.get(); if ((res != null) && (res.layer(Resource.tooltip) != null)) { String tt = res.layer(Resource.tooltip).t; if (tt != null) { if (q > 0) { tt = tt + ", quality " + q; if (hq) tt = tt + "+"; } return (tt); } } return (null); } long hoverstart; Text shorttip = null, longtip = null; public double qmult; private String FEP = null; public Object tooltip(Coord c, boolean again) { long now = System.currentTimeMillis(); if (!again) hoverstart = now; Resource res = this.res.get(); Resource.Pagina pg = (res != null) ? res.layer(Resource.pagina) : null; if (((now - hoverstart) < 500) || (pg == null)) { if (shorttip == null) { String tt = shorttip(); if (tt != null) { tt = RichText.Parser.quote(tt); if (meter > 0) { tt = tt + " (" + meter + "%)"; } if (FEP != null) { tt += FEP; } if (curioStr != null) { tt += curioStr; } shorttip = RichText.render(tt, 200); } } return (shorttip); } else { if ((longtip == null) && (res != null)) { String tip = shorttip(); if (tip == null) return (null); String tt = RichText.Parser.quote(tip); if (meter > 0) { tt = tt + " (" + meter + "%)"; } if (FEP != null) { tt += FEP; } if (curioStr != null) { tt += curioStr; } if (pg != null) tt += "\n\n" + pg.text; longtip = RichText.render(tt, 200); } return (longtip); } } private void resettt() { shorttip = null; longtip = null; } private void decq(int q) { if (q < 0) { this.q = q; hq = false; } else { int fl = (q & 0xff000000) >> 24; this.q = (q & 0xffffff); hq = ((fl & 1) != 0); } } public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag, int num) { super(c, Coord.z, parent); this.res = res; idCounter++; // new id = idCounter; // new decq(q); fixsize(); this.num = num; if (drag == null) { dm = false; } else { dm = true; doff = drag; ui.grabmouse(this); this.c = ui.mc.add(doff.inv()); } qmult = Math.sqrt((float) q / 10); calcFEP(); calcCurio(); } private void calcFEP() { Map<String, Float> fep; String name = name(); if (name == null) { return; } if (name.equals("Ring of Brodgar")) { if (res.get().name.equals("gfx/invobjs/bread-brodgar")) { name = "Ring of Brodgar (Baking)"; } if (res.get().name.equals("gfx/invobjs/feast-rob")) { name = "Ring of Brodgar (Seafood)"; } } name = name.toLowerCase(); boolean isItem = false; if ((fep = Config.FEPMap.get(name)) != null) { if (fep.containsKey("isItem")) { isItem = true; } FEP = "\n"; for (String key : fep.keySet()) { float val = (float) (fep.get(key) * qmult); if (key.equals("isItem")) { continue; } if (isItem) { val = (float) Math.floor(val); FEP += String.format("%s:%.0f ", key, val); } else { FEP += String.format("%s:%.1f ", key, val); } } shorttip = longtip = null; } } public int getLP() { String name = name(); if (name == null) { return 0; } name = name.toLowerCase(); CurioInfo curio; if ((curio = Config.curios.get(name)) != null) { return (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100); } return 0; } private void calcCurio() { String name = name(); if (name == null) { return; } name = name.toLowerCase(); CurioInfo curio; if ((curio = Config.curios.get(name)) != null) { int LP = (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100); int time = curio.time * (100 - meter) / 100; int h = time / 60; int m = time % 60; curioStr = String.format("\nLP: %d, Weight: %d\nStudy time: %dh %2dm", LP, curio.weight, h, m); shorttip = longtip = null; } } public Item(Coord c, int res, int q, Widget parent, Coord drag, int num) { this(c, parent.ui.sess.getres(res), q, parent, drag, num); } public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag) { this(c, res, q, parent, drag, -1); } public Item(Coord c, int res, int q, Widget parent, Coord drag) { this(c, parent.ui.sess.getres(res), q, parent, drag); } public boolean dropon(Widget w, Coord c) { for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) { if (wdg == this) continue; Coord cc = w.xlate(wdg.c, true); if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) { if (dropon(wdg, c.add(cc.inv()))) return (true); } } if (w instanceof DTarget) { if (((DTarget) w).drop(c, c.add(doff.inv()))) return (true); } if (w instanceof DTarget2) { if (((DTarget2) w).drop(c, c.add(doff.inv()), this)) return (true); } return (false); } public boolean interact(Widget w, Coord c) { for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) { if (wdg == this) continue; Coord cc = w.xlate(wdg.c, true); if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) { if (interact(wdg, c.add(cc.inv()))) return (true); } } if (w instanceof DTarget) { if (((DTarget) w).iteminteract(c, c.add(doff.inv()))) return (true); } return (false); } public void chres(Indir<Resource> res, int q) { this.res = res; sh = null; decq(q); } public void uimsg(String name, Object... args) { if (name == "num") { num = (Integer) args[0]; } else if (name == "chres") { chres(ui.sess.getres((Integer) args[0]), (Integer) args[1]); resettt(); } else if (name == "color") { olcol = (Color) args[0]; } else if (name == "tt") { if ((args.length > 0) && (((String) args[0]).length() > 0)) settip((String) args[0]); else settip(null); resettt(); } else if (name == "meter") { meter = (Integer) args[0]; shorttip = null; longtip = null; calcCurio(); } } public String GetResName() { // new if (this.res.get() != null) { return ((Resource) this.res.get()).name; } return ""; } void sortedSkoop() { // new String name = GetResName(); if (parent instanceof Inventory) ((Inventory) parent).skoopItems(name); } public boolean mousedown(Coord c, int button) { if (button == 3 && ui.modflags() == 4) { // new sortedSkoop(); return (true); } if (!dm) { if (button == 1) { if (ui.modshift) if (ui.modmeta) wdgmsg("transfer-same", name(), false); else wdgmsg("transfer", c); else if (ui.modctrl) if (ui.modmeta) wdgmsg("drop-same", name(), false); else wdgmsg("drop", c); else wdgmsg("take", c); return (true); } else if (button == 3) { if (ui.modmeta) { if (ui.modshift) { wdgmsg("transfer-same", name(), true); } else if (ui.modctrl) { wdgmsg("drop-same", name(), true); } } else { wdgmsg("iact", c); } return (true); } } else { if (button == 1) { dropon(parent, c.add(this.c)); } else if (button == 3) { interact(parent, c.add(this.c)); } return (true); } return (false); } public void mousemove(Coord c) { if (dm) this.c = this.c.add(c.add(doff.inv())); } public boolean drop(Coord cc, Coord ul) { return (false); } public boolean iteminteract(Coord cc, Coord ul) { wdgmsg("itemact", ui.modflags()); return (true); } public ItemType getItemType(Item itm) { String resname = itm.res.get().name; int idx = resname.lastIndexOf("/"); resname = resname.substring(idx + 1); if (!Config.itemTypes.containsKey(resname)) return ItemType.NOT_IMPLEMENTED; return Config.itemTypes.get(resname); } }
192069_19
/* * Copyright © 2008 Ron de Jong ([email protected]). * * This is free software; you can redistribute it * under the terms of the Creative Commons License * Creative Commons License: (CC BY-NC-ND 4.0) as published by * https://creativecommons.org/licenses/by-nc-nd/4.0/ ; either * version 4.0 of the License, or (at your option) any later version. * * 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 * Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 * International Public License for more details. * * You should have received a copy of the Creative Commons * Public License License along with this software; */ import javax.sdp.*; import javax.sdp.SdpFactory; import java.util.*; /** * * @author ron */ public class SDPConvert { byte[] mySDPBytes; SDPInfo mySDPInfo; Version myVersion; Origin myOrigin; SessionName mySessionName; Connection myConnection; Time myTime; Long ss; Vector myTimeVector; // Vector audioFormats; javax.sdp.SdpFactory mySDPFactory; SessionDescription receiveSessionDescription; String[] myCodecArray; /** * */ public SDPConvert() { mySDPFactory = SdpFactory.getInstance(); myCodecArray = new String[9]; myCodecArray[0] = "ULAW/8000"; myCodecArray[1] = ""; myCodecArray[2] = ""; myCodecArray[3] = "GSM/8000"; myCodecArray[4] = "G723/8000"; myCodecArray[5] = ""; myCodecArray[6] = ""; myCodecArray[7] = ""; myCodecArray[8] = "ALAW/8000"; } /** * * @param mySDPInfo * @param audioFormatParam * @return */ @SuppressWarnings("static-access") public byte[] info2Bytes(SDPInfo mySDPInfo, int audioFormatParam) { // System.out.println("SDPInfo to byte[]: " + mySDPInfo.toString()); myVersion = mySDPFactory.createVersion(0); ss = null; try { ss = mySDPFactory.getNtpTime(new Date()); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: ss = mySDPFactory.getNtpTime(new Date()" + ex.getMessage()); } // myOrigin = null; try { myOrigin = mySDPFactory.createOrigin(mySDPInfo.getUser(), ss, ss, "IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myOrigin = mySDPFactory.createOrigin(\"-\", ss, ss, \"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } myOrigin = null; try { myOrigin = mySDPFactory.createOrigin("-", 0L, 0L, "IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myOrigin = mySDPFactory.createOrigin(\"-\", 0L, 0L, \"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } mySessionName = mySDPFactory.createSessionName("Voice Session"); Connection myConnection = null; try { myConnection = mySDPFactory.createConnection("IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myConnection = mySDPFactory.createConnection(\"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } myTime = null; try { myTime = mySDPFactory.createTime(); } catch (SdpException ex) { System.out.println("Error: SdpException: myTime = mySDPFactory.createTime() " + ex.getMessage()); } myTimeVector = new Vector(); myTimeVector.add(myTime); int[] audioFormatArray = new int[2]; audioFormatArray[0] = mySDPInfo.getAudioFormat(); audioFormatArray[1] = 100; // telephone-event MediaDescription myMediaDescription = null; Vector myMediaDescriptionVector = new Vector(); try { myMediaDescription = mySDPFactory.createMediaDescription("audio", mySDPInfo.getAudioPort(), 1, "RTP/AVP", audioFormatArray); } catch (IllegalArgumentException ex) { System.out.println("Error: IllegalArgumentException: myAudioDescription = mySDPFactory.createMediaDescription(\"audio\", mySDPInfo.getAudioPort(), 1, \"RTP/AVP\", audioFormat) " + ex.getMessage()); } catch (SdpException ex) { System.out.println("Error: SdpException: myAudioDescription = mySDPFactory.createMediaDescription(\"audio\", mySDPInfo.getAudioPort(), 1, \"RTP/AVP\", audioFormat) " + ex.getMessage()); } Attribute myAudioAttribute = null; myAudioAttribute = mySDPFactory.createAttribute("rtpmap", "3 " + myCodecArray[audioFormatParam]); Attribute myTelephoneEvent = null; myTelephoneEvent = mySDPFactory.createAttribute("rtpmap", "100 telephone-event/8000"); // Don't forget to add to Vector myMediaDescriptionVector.add(myMediaDescription); myMediaDescriptionVector.add(myAudioAttribute); myMediaDescriptionVector.add(myTelephoneEvent); // if (mySDPInfo.getVideoPort() > 0) // { // int[] videoFormat = new int[1]; // videoFormat[0] = mySDPInfo.getVideoFormat(); // MediaDescription myVideoDescription = null; try { myVideoDescription = mySDPFactory.createMediaDescription("video", mySDPInfo.getVideoPort(), 1, "RTP/AVP", videoFormat); } // catch (IllegalArgumentException ex) { System.out.println("Error: IllegalArgumentException: myVideoDescription = mySDPFactory.createMediaDescription(\"video\", mySDPInfo.getVideoPort(), 1, \"RTP/AVP\", videoFormat) " + ex.getMessage()); } // catch (SdpException ex) { System.out.println("Error: SdpException: myVideoDescription = mySDPFactory.createMediaDescription(\"video\", mySDPInfo.getVideoPort(), 1, \"RTP/AVP\", videoFormat) " + ex.getMessage()); } // myMediaDescriptionVector.add(myVideoDescription); // } SessionDescription mySessionDescription = null; try { mySessionDescription = mySDPFactory.createSessionDescription(); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription = mySDPFactory.createSessionDescription() " + ex.getMessage()); } try { mySessionDescription.setVersion(myVersion); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setVersion(myVersion) " + ex.getMessage()); } try { mySessionDescription.setOrigin(myOrigin); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setOrigin(myOrigin) " + ex.getMessage()); } try { mySessionDescription.setSessionName(mySessionName); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setSessionName(mySessionName) " + ex.getMessage()); } try { mySessionDescription.setConnection(myConnection); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setConnection(myConnection) " + ex.getMessage()); } try { mySessionDescription.setTimeDescriptions(myTimeVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setTimeDescriptions(myTimeVector) " + ex.getMessage()); } try { mySessionDescription.setMediaDescriptions(myMediaDescriptionVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setMediaDescriptions(myMediaDescriptionVector) " + ex.getMessage()); } // try { mySessionDescription.setAttributes(myAttributeVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setAttributes(myAudioAttributeVector) " + ex.getMessage()); } // byte[] mySDPBytes = new byte[mySessionDescription.toString().getBytes().length+1]; byte[] mySDPBytes = mySessionDescription.toString().getBytes(); return mySDPBytes; } /** * * @param mySDPBytes * @param audioFormatParam * @return */ public SDPInfo bytes2Info(byte[] mySDPBytes, int audioFormatParam) // input byte[] output SDPInfo { //receiveSessionDescription = null; String sdpString = new String(mySDPBytes.clone()); SessionDescription receiveSessionDescription = null; try { receiveSessionDescription = mySDPFactory.createSessionDescription(sdpString); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: receiveSessionDescription = mySDPFactory.createSessionDescription(stringContent) " + ex.getMessage()); } String myPeerIP = null; try { myPeerIP = receiveSessionDescription.getConnection().getAddress(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerIP = receiveSessionDescription.getConnection().getAddress() " + ex.getMessage()); } String myUser = null; try { myUser = receiveSessionDescription.getOrigin().getUsername(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerIP = receiveSessionDescription.getConnection().getAddress() " + ex.getMessage()); } // System.out.println(receiveSessionDescription.getConnection().toString()); // This is only for debugging purposes String myPeerName = null; try { myPeerName = receiveSessionDescription.getOrigin().getUsername(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerName = receiveSessionDescription.getOrigin().getUsername() " + ex.getMessage()); } Vector receiveMediaDescriptionVector = null; receiveMediaDescriptionVector = new Vector(); try { receiveMediaDescriptionVector = receiveSessionDescription.getMediaDescriptions(false); } catch (SdpException ex) { System.out.println("Error: SdpParseException: receiveMediaDescriptionVector = receiveSessionDescription.getMediaDescriptions(false) " + ex.getMessage()); } // First MediaDescription (audio) MediaDescription myAudioDescription = (MediaDescription)receiveMediaDescriptionVector.elementAt(0); Media myAudio = null; myAudio = myAudioDescription.getMedia(); Integer myAudioPort = 0;try { myAudioPort = myAudio.getMediaPort(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myAudioPort = myAudio.getMediaPort() " + ex.getMessage()); } Vector audioFormats = null; audioFormats = new Vector(); try { audioFormats = myAudio.getMediaFormats(false); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: audioFormats = myAudio.getMediaFormats(false) " + ex.getMessage()); } // int myAudioMediaFormat = (Integer) audioFormats.elementAt(0); // zeer problematisch audioFormat momenteel niet automatisch maar statisch // int myVideoPort = -1; // Integer myVideoMediaFormat = new Integer(-1); // //Optional second video medialine // if (receiveMediaDescriptionVector.capacity()>1) // { // MediaDescription myVideoDescription = (MediaDescription)receiveMediaDescriptionVector.elementAt(1); // Media myVideo = null; myVideo = myVideoDescription.getMedia(); // try { myVideoPort = myVideo.getMediaPort(); } catch (SdpParseException error) { SoftPhoneGUI.showStatus("Error: myVideo.getMediaPort(): SdpParseException: " + error.getMessage()); } // Vector videoFormats = null; try { videoFormats = myVideo.getMediaFormats(false); } catch (SdpParseException error) { SoftPhoneGUI.showStatus("Error: myVideo.getMediaFormats(false): SdpParseException: " + error.getMessage()); } // myVideoMediaFormat = (Integer) videoFormats.elementAt(0); // } SDPInfo mySDPInfo = new SDPInfo(); mySDPInfo.setIPAddress(myPeerIP); mySDPInfo.setUser(myUser); mySDPInfo.setAudioPort(myAudioPort); // mySDPInfo.setAudioFormat(myAudioMediaFormat); mySDPInfo.setAudioFormat(audioFormatParam); // mySDPInfo.setAudioFormat(3); // mySDPInfo.setVideoPort(myVideoPort); // mySDPInfo.setVideoFormat(myVideoMediaFormat.intValue()); return mySDPInfo; } }
ron-from-nl/VoipStorm
src/SDPConvert.java
3,506
// int myAudioMediaFormat = (Integer) audioFormats.elementAt(0); // zeer problematisch audioFormat momenteel niet automatisch maar statisch
line_comment
nl
/* * Copyright © 2008 Ron de Jong ([email protected]). * * This is free software; you can redistribute it * under the terms of the Creative Commons License * Creative Commons License: (CC BY-NC-ND 4.0) as published by * https://creativecommons.org/licenses/by-nc-nd/4.0/ ; either * version 4.0 of the License, or (at your option) any later version. * * 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 * Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 * International Public License for more details. * * You should have received a copy of the Creative Commons * Public License License along with this software; */ import javax.sdp.*; import javax.sdp.SdpFactory; import java.util.*; /** * * @author ron */ public class SDPConvert { byte[] mySDPBytes; SDPInfo mySDPInfo; Version myVersion; Origin myOrigin; SessionName mySessionName; Connection myConnection; Time myTime; Long ss; Vector myTimeVector; // Vector audioFormats; javax.sdp.SdpFactory mySDPFactory; SessionDescription receiveSessionDescription; String[] myCodecArray; /** * */ public SDPConvert() { mySDPFactory = SdpFactory.getInstance(); myCodecArray = new String[9]; myCodecArray[0] = "ULAW/8000"; myCodecArray[1] = ""; myCodecArray[2] = ""; myCodecArray[3] = "GSM/8000"; myCodecArray[4] = "G723/8000"; myCodecArray[5] = ""; myCodecArray[6] = ""; myCodecArray[7] = ""; myCodecArray[8] = "ALAW/8000"; } /** * * @param mySDPInfo * @param audioFormatParam * @return */ @SuppressWarnings("static-access") public byte[] info2Bytes(SDPInfo mySDPInfo, int audioFormatParam) { // System.out.println("SDPInfo to byte[]: " + mySDPInfo.toString()); myVersion = mySDPFactory.createVersion(0); ss = null; try { ss = mySDPFactory.getNtpTime(new Date()); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: ss = mySDPFactory.getNtpTime(new Date()" + ex.getMessage()); } // myOrigin = null; try { myOrigin = mySDPFactory.createOrigin(mySDPInfo.getUser(), ss, ss, "IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myOrigin = mySDPFactory.createOrigin(\"-\", ss, ss, \"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } myOrigin = null; try { myOrigin = mySDPFactory.createOrigin("-", 0L, 0L, "IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myOrigin = mySDPFactory.createOrigin(\"-\", 0L, 0L, \"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } mySessionName = mySDPFactory.createSessionName("Voice Session"); Connection myConnection = null; try { myConnection = mySDPFactory.createConnection("IN", "IP4", mySDPInfo.getIPAddress()); } catch (SdpException ex) { System.out.println("Error: SdpException: myConnection = mySDPFactory.createConnection(\"IN\", \"IP4\", " + mySDPInfo.getIPAddress() + ") " + ex.getMessage()); } myTime = null; try { myTime = mySDPFactory.createTime(); } catch (SdpException ex) { System.out.println("Error: SdpException: myTime = mySDPFactory.createTime() " + ex.getMessage()); } myTimeVector = new Vector(); myTimeVector.add(myTime); int[] audioFormatArray = new int[2]; audioFormatArray[0] = mySDPInfo.getAudioFormat(); audioFormatArray[1] = 100; // telephone-event MediaDescription myMediaDescription = null; Vector myMediaDescriptionVector = new Vector(); try { myMediaDescription = mySDPFactory.createMediaDescription("audio", mySDPInfo.getAudioPort(), 1, "RTP/AVP", audioFormatArray); } catch (IllegalArgumentException ex) { System.out.println("Error: IllegalArgumentException: myAudioDescription = mySDPFactory.createMediaDescription(\"audio\", mySDPInfo.getAudioPort(), 1, \"RTP/AVP\", audioFormat) " + ex.getMessage()); } catch (SdpException ex) { System.out.println("Error: SdpException: myAudioDescription = mySDPFactory.createMediaDescription(\"audio\", mySDPInfo.getAudioPort(), 1, \"RTP/AVP\", audioFormat) " + ex.getMessage()); } Attribute myAudioAttribute = null; myAudioAttribute = mySDPFactory.createAttribute("rtpmap", "3 " + myCodecArray[audioFormatParam]); Attribute myTelephoneEvent = null; myTelephoneEvent = mySDPFactory.createAttribute("rtpmap", "100 telephone-event/8000"); // Don't forget to add to Vector myMediaDescriptionVector.add(myMediaDescription); myMediaDescriptionVector.add(myAudioAttribute); myMediaDescriptionVector.add(myTelephoneEvent); // if (mySDPInfo.getVideoPort() > 0) // { // int[] videoFormat = new int[1]; // videoFormat[0] = mySDPInfo.getVideoFormat(); // MediaDescription myVideoDescription = null; try { myVideoDescription = mySDPFactory.createMediaDescription("video", mySDPInfo.getVideoPort(), 1, "RTP/AVP", videoFormat); } // catch (IllegalArgumentException ex) { System.out.println("Error: IllegalArgumentException: myVideoDescription = mySDPFactory.createMediaDescription(\"video\", mySDPInfo.getVideoPort(), 1, \"RTP/AVP\", videoFormat) " + ex.getMessage()); } // catch (SdpException ex) { System.out.println("Error: SdpException: myVideoDescription = mySDPFactory.createMediaDescription(\"video\", mySDPInfo.getVideoPort(), 1, \"RTP/AVP\", videoFormat) " + ex.getMessage()); } // myMediaDescriptionVector.add(myVideoDescription); // } SessionDescription mySessionDescription = null; try { mySessionDescription = mySDPFactory.createSessionDescription(); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription = mySDPFactory.createSessionDescription() " + ex.getMessage()); } try { mySessionDescription.setVersion(myVersion); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setVersion(myVersion) " + ex.getMessage()); } try { mySessionDescription.setOrigin(myOrigin); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setOrigin(myOrigin) " + ex.getMessage()); } try { mySessionDescription.setSessionName(mySessionName); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setSessionName(mySessionName) " + ex.getMessage()); } try { mySessionDescription.setConnection(myConnection); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setConnection(myConnection) " + ex.getMessage()); } try { mySessionDescription.setTimeDescriptions(myTimeVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setTimeDescriptions(myTimeVector) " + ex.getMessage()); } try { mySessionDescription.setMediaDescriptions(myMediaDescriptionVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setMediaDescriptions(myMediaDescriptionVector) " + ex.getMessage()); } // try { mySessionDescription.setAttributes(myAttributeVector); } catch (SdpException ex) { System.out.println("Error: SdpException: mySessionDescription.setAttributes(myAudioAttributeVector) " + ex.getMessage()); } // byte[] mySDPBytes = new byte[mySessionDescription.toString().getBytes().length+1]; byte[] mySDPBytes = mySessionDescription.toString().getBytes(); return mySDPBytes; } /** * * @param mySDPBytes * @param audioFormatParam * @return */ public SDPInfo bytes2Info(byte[] mySDPBytes, int audioFormatParam) // input byte[] output SDPInfo { //receiveSessionDescription = null; String sdpString = new String(mySDPBytes.clone()); SessionDescription receiveSessionDescription = null; try { receiveSessionDescription = mySDPFactory.createSessionDescription(sdpString); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: receiveSessionDescription = mySDPFactory.createSessionDescription(stringContent) " + ex.getMessage()); } String myPeerIP = null; try { myPeerIP = receiveSessionDescription.getConnection().getAddress(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerIP = receiveSessionDescription.getConnection().getAddress() " + ex.getMessage()); } String myUser = null; try { myUser = receiveSessionDescription.getOrigin().getUsername(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerIP = receiveSessionDescription.getConnection().getAddress() " + ex.getMessage()); } // System.out.println(receiveSessionDescription.getConnection().toString()); // This is only for debugging purposes String myPeerName = null; try { myPeerName = receiveSessionDescription.getOrigin().getUsername(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myPeerName = receiveSessionDescription.getOrigin().getUsername() " + ex.getMessage()); } Vector receiveMediaDescriptionVector = null; receiveMediaDescriptionVector = new Vector(); try { receiveMediaDescriptionVector = receiveSessionDescription.getMediaDescriptions(false); } catch (SdpException ex) { System.out.println("Error: SdpParseException: receiveMediaDescriptionVector = receiveSessionDescription.getMediaDescriptions(false) " + ex.getMessage()); } // First MediaDescription (audio) MediaDescription myAudioDescription = (MediaDescription)receiveMediaDescriptionVector.elementAt(0); Media myAudio = null; myAudio = myAudioDescription.getMedia(); Integer myAudioPort = 0;try { myAudioPort = myAudio.getMediaPort(); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: myAudioPort = myAudio.getMediaPort() " + ex.getMessage()); } Vector audioFormats = null; audioFormats = new Vector(); try { audioFormats = myAudio.getMediaFormats(false); } catch (SdpParseException ex) { System.out.println("Error: SdpParseException: audioFormats = myAudio.getMediaFormats(false) " + ex.getMessage()); } // int myAudioMediaFormat<SUF> // int myVideoPort = -1; // Integer myVideoMediaFormat = new Integer(-1); // //Optional second video medialine // if (receiveMediaDescriptionVector.capacity()>1) // { // MediaDescription myVideoDescription = (MediaDescription)receiveMediaDescriptionVector.elementAt(1); // Media myVideo = null; myVideo = myVideoDescription.getMedia(); // try { myVideoPort = myVideo.getMediaPort(); } catch (SdpParseException error) { SoftPhoneGUI.showStatus("Error: myVideo.getMediaPort(): SdpParseException: " + error.getMessage()); } // Vector videoFormats = null; try { videoFormats = myVideo.getMediaFormats(false); } catch (SdpParseException error) { SoftPhoneGUI.showStatus("Error: myVideo.getMediaFormats(false): SdpParseException: " + error.getMessage()); } // myVideoMediaFormat = (Integer) videoFormats.elementAt(0); // } SDPInfo mySDPInfo = new SDPInfo(); mySDPInfo.setIPAddress(myPeerIP); mySDPInfo.setUser(myUser); mySDPInfo.setAudioPort(myAudioPort); // mySDPInfo.setAudioFormat(myAudioMediaFormat); mySDPInfo.setAudioFormat(audioFormatParam); // mySDPInfo.setAudioFormat(3); // mySDPInfo.setVideoPort(myVideoPort); // mySDPInfo.setVideoFormat(myVideoMediaFormat.intValue()); return mySDPInfo; } }
91082_3
/* * Created on 31.05.2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package com.sport.client; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowEvent; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Random; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import org.apache.log4j.Logger; import com.sport.client.export.ExportDialog; import com.sport.client.export.ProgressDialog; import com.sport.client.export.ProgressRunnables; import com.sport.client.panel.NullPanel; import com.sport.client.panel.VolleyPanel; import com.sport.client.panel.gruppen.GruppenPanel; import com.sport.client.panel.mannschaften.MannschaftenPanel; import com.sport.client.panel.platzierungen.PlatzierungenPanel; import com.sport.client.panel.spielplan.ErgebnissePanel; import com.sport.client.panel.spielplan.SpielplanPanel; import com.sport.client.panel.turnier.TurnierPanel; import com.sport.core.bo.LicenceBO; import com.sport.core.bo.Tournament; import com.sport.core.bo.UserBO; import com.sport.core.helper.Messages; import com.sport.server.ejb.HomeGetter; import com.sport.server.remote.TurnierRemote; import com.sport.server.remote.UserRemote; public class VolleyFrame extends JFrame { private static final Logger LOG = Logger.getLogger(VolleyFrame.class .getName()); private static final long serialVersionUID = -7340451118308069158L; private JPanel contentPane; private JLabel statusBar = new JLabel(); private BorderLayout borderLayout1 = new BorderLayout(); private JSplitPane splitPane = null; private NavigationTree navTree = null; private VolleyMenuBar menuBar; public VolleyToolBar toolBar; public LicenceBO licenceBO; private TurnierPanel turnierPanel = new TurnierPanel(this); private MannschaftenPanel mannschaftenPanel = new MannschaftenPanel(this); private GruppenPanel gruppenPanel = new GruppenPanel(this); private SpielplanPanel spielplanPanel = new SpielplanPanel(this); private ErgebnissePanel ergebnissePanel = new ErgebnissePanel(this); private PlatzierungenPanel platzierungenPanel = new PlatzierungenPanel(this); private NullPanel nullPanel = new NullPanel(this); protected VolleyPanel aktPanel = nullPanel; private UserBO userBO = null; // aktuell angemeldeter User public File lastChoosenDir = null; // directory that was last choosen with JFileChooser private static VolleyFrame instance = null; // Singleton pattern static public VolleyFrame getInstance() { if (instance == null) { instance = new VolleyFrame(); } return instance; } static public VolleyFrame getNewInstance() { instance = new VolleyFrame(); return instance; } // Den Frame konstruieren private VolleyFrame() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); setIconImage(Icons.APPLICATION.getImage()); // User laden try { userBO = UserRemote.getUserById(1); licenceBO = TurnierRemote.getLicenceBO(); } catch (Exception e) { LOG .error( "Can't fetch user data from server " + HomeGetter.getHost() + ":" + HomeGetter.getPort() + ". You can modify the host name in the file 'VolleyballManager/admin/jvolley.properties'.", e); // Kann Nutzer nicht anmelden JOptionPane.showMessageDialog(this, Messages .getString("volleyframe_test_server1") //$NON-NLS-1$ + "\n" + Messages.getString("volleyframe_test_server2"), //$NON-NLS-1$ Messages.getString("volleyframe_test_server_titel"), //$NON-NLS-1$ JOptionPane.ERROR_MESSAGE); System.exit(0); } try { init(); // deact. menus in the case that there is no tournament toolBar.setTurnierEnable(false, TreeNodeObject.NOPANEL, null); menuBar.setTurnierEnable(false); // Default: select first tournament in Navigationtree navTree.selectFirstTurnier(); } catch (Exception e) { LOG.error("Can't initial main window", e); } } // Initialisierung der Komponenten private void init() throws Exception { contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(borderLayout1); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = (screenSize.width >= 800) ? 800 : screenSize.width; int height = (screenSize.height >= 600) ? 600 : screenSize.height; int x = (screenSize.width - width) / 2; int y = (screenSize.height - height) / 2; setBounds(x, y, width, height); setSize(width, height); this.setTitle("Volleyball Manager"); //$NON-NLS-1$ statusBar.setText(" "); //$NON-NLS-1$ menuBar = new VolleyMenuBar(this); this.setJMenuBar(menuBar); toolBar = new VolleyToolBar(this); navTree = new NavigationTree(this); navTree.setCellRenderer(new VolleyTreeCellRenderer()); new TreeController(navTree, this); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setContinuousLayout(true); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(250); splitPane.setDividerSize(1); JScrollPane jscroll = new JScrollPane(navTree); jscroll.setMinimumSize(new Dimension(250, 0)); splitPane.add(jscroll); splitPane.add(aktPanel); contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(splitPane, BorderLayout.CENTER); contentPane.add(statusBar, BorderLayout.SOUTH); } // �berschrieben, so dass eine Beendigung beim Schlie�en des Fensters // m�glich ist. protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { setNullPanel(); // if not [chanel] if (aktPanel == nullPanel) { System.exit(0); } } else { super.processWindowEvent(e); } } public VolleyPanel getAktPanel() { return aktPanel; } public void setAktPanelByTreeNodeType(int treeNodeType, Tournament turnierBO) { VolleyPanel newPanel = null; switch (treeNodeType) { case TreeNodeObject.NOPANEL: newPanel = nullPanel; break; case TreeNodeObject.TURNIER: newPanel = turnierPanel; break; case TreeNodeObject.MANNSCHAFTEN: newPanel = mannschaftenPanel; break; case TreeNodeObject.GRUPPEN: newPanel = gruppenPanel; break; case TreeNodeObject.SPIELPLAN: newPanel = spielplanPanel; break; case TreeNodeObject.ERGEBNISSE: newPanel = ergebnissePanel; break; case TreeNodeObject.PLATZIERUNGEN: newPanel = platzierungenPanel; break; default: break; } // unbedingt neu laden, wenn andere Ansicht oder verschiedenes // Turniere! if ((aktPanel != newPanel) || ((aktPanel.turnierBO != null) && turnierBO.getId() != aktPanel.turnierBO .getId())) { boolean keinwechsel = false; // nicht Seite wechseln // �nderungen im alten Panel? -> fragen, ob speichern if (aktPanel.dirty == true) { JOptionPane.setDefaultLocale(Locale.getDefault()); int result = JOptionPane .showConfirmDialog( aktPanel, Messages.getString("volleyframe_save_changes"), Messages.getString("volleyframe_save_changes_title"), JOptionPane.YES_NO_CANCEL_OPTION); //$NON-NLS-1$ // bei [Abbruch] auf alter Seite bleiben if (result == JOptionPane.CANCEL_OPTION) { keinwechsel = true; } if (result == JOptionPane.YES_OPTION) { aktPanel.save(); } } if (!keinwechsel) { // Menu anpassen menuBar.selectView(treeNodeType); navTree.selectTurnierView(turnierBO, treeNodeType); splitPane.remove(aktPanel); aktPanel = newPanel; splitPane.add(aktPanel); aktPanel.updateUI(); getAktPanel().loadData(turnierBO); } } if (aktPanel.turnierBO != null) { String title = "Volleyball Manager - " //$NON-NLS-1$ + aktPanel.turnierBO.getName() + " - " //$NON-NLS-1$ + getStringByAktPanel(); if (licenceBO.licencetype.equals(LicenceBO.LICENCE_DEMO)) { title += " - " + Messages.getString("licence_notregistered"); } this.setTitle(title); String datum = DateFormat.getDateInstance(DateFormat.LONG).format( aktPanel.turnierBO.getDate()); this.statusBar.setText(Messages.getString(licenceBO.licencetype) + " - " + getUserBO().getName() + " - " //$NON-NLS-1$ + aktPanel.turnierBO.getName() + " - " //$NON-NLS-1$ + datum); menuBar.setTurnierEnable(true); toolBar.setTurnierEnable(true, treeNodeType, aktPanel.turnierBO); } else { this.setTitle("Volleyball Manager"); //$NON-NLS-1$ this.statusBar.setText(getUserBO().getName()); menuBar.setTurnierEnable(false); toolBar.setTurnierEnable(false, treeNodeType, null); } } public void setAktPanelByTreeNodeType(int treeNodeType) { setAktPanelByTreeNodeType(treeNodeType, aktPanel.turnierBO); } public String getStringByAktPanel() { switch (getTypeByAktPanel()) { case TreeNodeObject.TURNIER: return Messages.getString("volleyframe_view_challenge"); //$NON-NLS-1$ case TreeNodeObject.MANNSCHAFTEN: return Messages.getString("volleyframe_view_teams"); //$NON-NLS-1$ case TreeNodeObject.GRUPPEN: return Messages.getString("volleyframe_view_groups"); //$NON-NLS-1$ case TreeNodeObject.SPIELPLAN: return Messages.getString("volleyframe_view_schedule"); //$NON-NLS-1$ case TreeNodeObject.ERGEBNISSE: return Messages.getString("volleyframe_view_results"); //$NON-NLS-1$ case TreeNodeObject.PLATZIERUNGEN: return Messages.getString("volleyframe_view_placings"); //$NON-NLS-1$ case TreeNodeObject.NOPANEL: return Messages.getString("volleyframe_view_start"); //$NON-NLS-1$ } return Messages.getString("volleyframe_view_unknown"); //$NON-NLS-1$ } public int getTypeByAktPanel() { if (aktPanel == turnierPanel) { return TreeNodeObject.TURNIER; } if (aktPanel == mannschaftenPanel) { return TreeNodeObject.MANNSCHAFTEN; } if (aktPanel == gruppenPanel) { return TreeNodeObject.GRUPPEN; } if (aktPanel == spielplanPanel) { return TreeNodeObject.SPIELPLAN; } if (aktPanel == ergebnissePanel) { return TreeNodeObject.ERGEBNISSE; } if (aktPanel == platzierungenPanel) { return TreeNodeObject.PLATZIERUNGEN; } if (aktPanel == nullPanel) { return TreeNodeObject.NOPANEL; } return -1; } /** * Setzt auf Anfangsansicht zur�ck * */ public void setNullPanel() { setAktPanelByTreeNodeType(TreeNodeObject.NOPANEL, null); } public void newTurnier() { // Turnier einf�gen Tournament turnierBO = new Tournament(); turnierBO.setDate(new Date()); turnierBO.setName(Messages.getString("title_new_challenge")); //$NON-NLS-1$ // generate some random linkid as default String linkid = ""; Random r = new Random(); String chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (int i = 0; i < 20; i++) { linkid += chars.charAt(r.nextInt(chars.length())); } turnierBO.setLinkid(linkid); try { turnierBO = TurnierRemote.saveByTurnierBO(turnierBO, getUserBO()); } catch (Exception e) { LOG.error("Can't save tournament", e); } navTree.addNewTurnier(turnierBO); navTree.selectTurnier(turnierBO); } public void saveTurnier() { TreePath path = navTree.getSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent(); TreeNodeObject treeNodeObject = (TreeNodeObject) node .getUserObject(); Tournament turnierBO = treeNodeObject.getTurnier(); JFileChooser fc = new JFileChooser(); ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("tur"); //$NON-NLS-1$ filter.setDescription(Messages .getString("volleyframe_jvolley_challenge_file")); //$NON-NLS-1$ fc.setFileFilter(filter); fc.setApproveButtonText(Messages.getString("volleyframe_save")); //$NON-NLS-1$ fc.setDialogTitle(Messages .getString("volleyframe_export_challenge")); //$NON-NLS-1$ fc.setCurrentDirectory(getLastChoosenDir()); // set default save name to the name of the turnament + date String filename = turnierBO.getName() + " "; DateFormat formater = SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); filename += formater.format(new Date()).replaceAll(":", "-") .replaceAll("\\.", "-"); filename += ".tur"; filename = filename.replaceAll(" ", "_"); fc.setSelectedFile(new File(filename)); int result = fc.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); // if the file exist -> ask it should be overwritten boolean write = false; // really save? if (!fc.getSelectedFile().exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int resultDlg = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_file"), Messages.getString("volleyframe_export_challenge"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (resultDlg == JOptionPane.YES_OPTION); } if (write) { ProgressDialog progDlg = new ProgressDialog(this); Runnable runnable = new ProgressRunnables.SaveTournamentRunnable( fc.getSelectedFile(), turnierBO, progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } } } public void openTurnier() { JFileChooser fc = new JFileChooser(); ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("tur"); //$NON-NLS-1$ filter.setDescription(Messages .getString("volleyframe_jvolley_challenge_file")); //$NON-NLS-1$ fc.setFileFilter(filter); fc.setApproveButtonText(Messages.getString("volleyframe_open")); //$NON-NLS-1$ fc.setDialogTitle(Messages.getString("volleyframe_import_challenge")); //$NON-NLS-1$ fc.setCurrentDirectory(getLastChoosenDir()); int result = fc.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); ProgressDialog progDlg = new ProgressDialog(this); Runnable runnable = new ProgressRunnables.OpenTournamentRunnable(fc .getSelectedFile().getPath(), navTree, getUserBO().getId(), progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } /** * @return */ public UserBO getUserBO() { return userBO; } /** * @param userBO */ public void setUserBO(UserBO userBO) { this.userBO = userBO; } /** * Startet Appliaction, um eine PDF/Html-Datei anzuzeigen * * @param pfad */ public static void showExternal(String pfad) { // falls vorhanden -> Acrobat Reader starten try { Runtime.getRuntime().exec( "cmd /q /c start " + pfad.replaceAll(" ", "\" \"")); //$NON-NLS-1$ } catch (Exception ex) { // ok now change show a window JOptionPane .showMessageDialog( getInstance(), Messages.getString("volleyframe_noexternal") + " " + pfad, Messages.getString("volleyframe_noexternal_title"), JOptionPane.WARNING_MESSAGE); //$NON-NLS-1$ } } public static void showExternalExplorer(String pfad) { // falls vorhanden -> Internet Explorer starten try { Runtime.getRuntime().exec("explorer \"" + pfad + "\""); //$NON-NLS-1$ } catch (Exception ex) { // let's try some other common browsers try { String[] cmd = { "mozilla", pfad }; Runtime.getRuntime().exec(cmd); //$NON-NLS-1$ } catch (Exception ex2) { try { String[] cmd = { "netscape", pfad }; Runtime.getRuntime().exec(cmd); //$NON-NLS-1$ } catch (Exception ex3) { // no standard browser available showExternal(pfad); } } } } /** * Shows Terminal view * */ public void showOnline() { try { String param = "linkid=" + URLEncoder .encode(aktPanel.turnierBO.getLinkid(), "utf-8") + "&locale=" + Locale.getDefault().getLanguage(); VolleyFrame.showExternalExplorer(HomeGetter.getWebUrl() + "/turnier.do?" + param); } catch (UnsupportedEncodingException e) { LOG.error("Can't UTF-8 encode", e); } } /** * Shows Beamer view * */ public void showBeamer() { try { String param = "linkid=" + URLEncoder .encode(aktPanel.turnierBO.getLinkid(), "utf-8") + "&locale=" + Locale.getDefault().getLanguage(); VolleyFrame.showExternalExplorer(HomeGetter.getWebUrl() + "/beamerspielplan.do?" + param); } catch (UnsupportedEncodingException e) { LOG.error("Can't UTF-8 encode", e); } } // Spielplan nach Pdf exportieren public void exportPdfSpielplan() { exportPdf(Messages.getString("volleyframe_schedule"), new ProgressRunnables.PdfSpielplanRunnable()); } // Schiedsrichter nach Pdf exportieren public void exportPdfSchiedsrichter() { exportPdf(Messages.getString("volleyframe_referee"), new ProgressRunnables.PdfSchiedsrichterRunnable()); } // Schiedsrichter nach Pdf exportieren public void exportPdfSpielbericht() { exportPdf(Messages.getString("volleyframe_spielbericht"), new ProgressRunnables.PdfSpielberichtRunnable()); } // Gruppenansicht nach Pdf exportieren public void exportPdfGruppen() { exportPdf(Messages.getString("volleyframe_groups"), new ProgressRunnables.PdfGruppenRunnable()); } /** * Generic function to export PDF * */ private void exportPdf(String exportDialogTitle, ProgressRunnables.PdfRunnable runnable) { Tournament turnierBO = navTree.getSelectedTurnierBO(); if (turnierBO != null) { ExportDialog dlg = new ExportDialog(this, turnierBO, exportDialogTitle); //$NON-NLS-1$ dlg.setModal(true); dlg.show(); if (dlg.getResult() == true) { // if the file exist -> ask it should be overwritten File f = new File(dlg.getPfad()); boolean write = false; // really save? if (!f.exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int result = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_file"), exportDialogTitle, JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (result == JOptionPane.YES_OPTION); } if (write) { ProgressDialog progDlg = new ProgressDialog(this); runnable.setValues(dlg.getPfad(), dlg .getSelectedGruppeIds(), turnierBO, progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } } } public void exportHtml() { Tournament turnierBO = navTree.getSelectedTurnierBO(); if (turnierBO != null) { JFileChooser fc = new JFileChooser(); JFileChooser.setDefaultLocale(Locale.getDefault()); fc.setFileFilter(null); fc.setDialogTitle(Messages.getString("volleyframe_export_to_html")); //$NON-NLS-1$ fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setCurrentDirectory(getLastChoosenDir()); int result = fc.showDialog(null, Messages .getString("volleyframe_save")); //$NON-NLS-1$ if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); // if the file exist -> ask it should be overwritten boolean write = false; // really save? if (!fc.getSelectedFile().exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int resultDlg = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_dir"), Messages.getString("volleyframe_export_challenge"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (resultDlg == JOptionPane.YES_OPTION); } if (write) { ProgressDialog dlg = new ProgressDialog(this); Runnable exportRunnable = new ProgressRunnables.ExportHtmlRunnable( fc.getSelectedFile(), turnierBO, dlg); Thread thread = new Thread(exportRunnable); thread.start(); dlg.show(); } } } } /** * @return Returns the lastChoosenDir. */ public File getLastChoosenDir() { return lastChoosenDir; } /** * @param lastChoosenDir * The lastChoosenDir to set. */ public void setLastChoosenDir(File lastChoosenDir) { if (this.lastChoosenDir != lastChoosenDir) { this.lastChoosenDir = lastChoosenDir; VolleyApp.writeLastChoosenDir(lastChoosenDir.getPath()); } } } class TreeController implements TreeSelectionListener { private JTree tree; private VolleyFrame jvolleyFrame; public TreeController(JTree tree, VolleyFrame jvolleyFrame) { super(); this.tree = tree; this.jvolleyFrame = jvolleyFrame; tree.addTreeSelectionListener(this); } public void valueChanged(TreeSelectionEvent e) { if (e.getSource() == tree) { TreePath path = e.getPath(); DefaultMutableTreeNode node = null; if (path != null) node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node == null) { return; } tree.expandPath(path); TreeNodeObject treeNodeObject = (TreeNodeObject) node .getUserObject(); jvolleyFrame.setAktPanelByTreeNodeType(treeNodeObject.getType(), treeNodeObject.getTurnier()); } } }
ronnyroeller/volleyball-manager
admin/src/main/java/com/sport/client/VolleyFrame.java
7,591
// Den Frame konstruieren
line_comment
nl
/* * Created on 31.05.2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package com.sport.client; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowEvent; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Random; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import org.apache.log4j.Logger; import com.sport.client.export.ExportDialog; import com.sport.client.export.ProgressDialog; import com.sport.client.export.ProgressRunnables; import com.sport.client.panel.NullPanel; import com.sport.client.panel.VolleyPanel; import com.sport.client.panel.gruppen.GruppenPanel; import com.sport.client.panel.mannschaften.MannschaftenPanel; import com.sport.client.panel.platzierungen.PlatzierungenPanel; import com.sport.client.panel.spielplan.ErgebnissePanel; import com.sport.client.panel.spielplan.SpielplanPanel; import com.sport.client.panel.turnier.TurnierPanel; import com.sport.core.bo.LicenceBO; import com.sport.core.bo.Tournament; import com.sport.core.bo.UserBO; import com.sport.core.helper.Messages; import com.sport.server.ejb.HomeGetter; import com.sport.server.remote.TurnierRemote; import com.sport.server.remote.UserRemote; public class VolleyFrame extends JFrame { private static final Logger LOG = Logger.getLogger(VolleyFrame.class .getName()); private static final long serialVersionUID = -7340451118308069158L; private JPanel contentPane; private JLabel statusBar = new JLabel(); private BorderLayout borderLayout1 = new BorderLayout(); private JSplitPane splitPane = null; private NavigationTree navTree = null; private VolleyMenuBar menuBar; public VolleyToolBar toolBar; public LicenceBO licenceBO; private TurnierPanel turnierPanel = new TurnierPanel(this); private MannschaftenPanel mannschaftenPanel = new MannschaftenPanel(this); private GruppenPanel gruppenPanel = new GruppenPanel(this); private SpielplanPanel spielplanPanel = new SpielplanPanel(this); private ErgebnissePanel ergebnissePanel = new ErgebnissePanel(this); private PlatzierungenPanel platzierungenPanel = new PlatzierungenPanel(this); private NullPanel nullPanel = new NullPanel(this); protected VolleyPanel aktPanel = nullPanel; private UserBO userBO = null; // aktuell angemeldeter User public File lastChoosenDir = null; // directory that was last choosen with JFileChooser private static VolleyFrame instance = null; // Singleton pattern static public VolleyFrame getInstance() { if (instance == null) { instance = new VolleyFrame(); } return instance; } static public VolleyFrame getNewInstance() { instance = new VolleyFrame(); return instance; } // Den Frame<SUF> private VolleyFrame() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); setIconImage(Icons.APPLICATION.getImage()); // User laden try { userBO = UserRemote.getUserById(1); licenceBO = TurnierRemote.getLicenceBO(); } catch (Exception e) { LOG .error( "Can't fetch user data from server " + HomeGetter.getHost() + ":" + HomeGetter.getPort() + ". You can modify the host name in the file 'VolleyballManager/admin/jvolley.properties'.", e); // Kann Nutzer nicht anmelden JOptionPane.showMessageDialog(this, Messages .getString("volleyframe_test_server1") //$NON-NLS-1$ + "\n" + Messages.getString("volleyframe_test_server2"), //$NON-NLS-1$ Messages.getString("volleyframe_test_server_titel"), //$NON-NLS-1$ JOptionPane.ERROR_MESSAGE); System.exit(0); } try { init(); // deact. menus in the case that there is no tournament toolBar.setTurnierEnable(false, TreeNodeObject.NOPANEL, null); menuBar.setTurnierEnable(false); // Default: select first tournament in Navigationtree navTree.selectFirstTurnier(); } catch (Exception e) { LOG.error("Can't initial main window", e); } } // Initialisierung der Komponenten private void init() throws Exception { contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(borderLayout1); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = (screenSize.width >= 800) ? 800 : screenSize.width; int height = (screenSize.height >= 600) ? 600 : screenSize.height; int x = (screenSize.width - width) / 2; int y = (screenSize.height - height) / 2; setBounds(x, y, width, height); setSize(width, height); this.setTitle("Volleyball Manager"); //$NON-NLS-1$ statusBar.setText(" "); //$NON-NLS-1$ menuBar = new VolleyMenuBar(this); this.setJMenuBar(menuBar); toolBar = new VolleyToolBar(this); navTree = new NavigationTree(this); navTree.setCellRenderer(new VolleyTreeCellRenderer()); new TreeController(navTree, this); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setContinuousLayout(true); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(250); splitPane.setDividerSize(1); JScrollPane jscroll = new JScrollPane(navTree); jscroll.setMinimumSize(new Dimension(250, 0)); splitPane.add(jscroll); splitPane.add(aktPanel); contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(splitPane, BorderLayout.CENTER); contentPane.add(statusBar, BorderLayout.SOUTH); } // �berschrieben, so dass eine Beendigung beim Schlie�en des Fensters // m�glich ist. protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { setNullPanel(); // if not [chanel] if (aktPanel == nullPanel) { System.exit(0); } } else { super.processWindowEvent(e); } } public VolleyPanel getAktPanel() { return aktPanel; } public void setAktPanelByTreeNodeType(int treeNodeType, Tournament turnierBO) { VolleyPanel newPanel = null; switch (treeNodeType) { case TreeNodeObject.NOPANEL: newPanel = nullPanel; break; case TreeNodeObject.TURNIER: newPanel = turnierPanel; break; case TreeNodeObject.MANNSCHAFTEN: newPanel = mannschaftenPanel; break; case TreeNodeObject.GRUPPEN: newPanel = gruppenPanel; break; case TreeNodeObject.SPIELPLAN: newPanel = spielplanPanel; break; case TreeNodeObject.ERGEBNISSE: newPanel = ergebnissePanel; break; case TreeNodeObject.PLATZIERUNGEN: newPanel = platzierungenPanel; break; default: break; } // unbedingt neu laden, wenn andere Ansicht oder verschiedenes // Turniere! if ((aktPanel != newPanel) || ((aktPanel.turnierBO != null) && turnierBO.getId() != aktPanel.turnierBO .getId())) { boolean keinwechsel = false; // nicht Seite wechseln // �nderungen im alten Panel? -> fragen, ob speichern if (aktPanel.dirty == true) { JOptionPane.setDefaultLocale(Locale.getDefault()); int result = JOptionPane .showConfirmDialog( aktPanel, Messages.getString("volleyframe_save_changes"), Messages.getString("volleyframe_save_changes_title"), JOptionPane.YES_NO_CANCEL_OPTION); //$NON-NLS-1$ // bei [Abbruch] auf alter Seite bleiben if (result == JOptionPane.CANCEL_OPTION) { keinwechsel = true; } if (result == JOptionPane.YES_OPTION) { aktPanel.save(); } } if (!keinwechsel) { // Menu anpassen menuBar.selectView(treeNodeType); navTree.selectTurnierView(turnierBO, treeNodeType); splitPane.remove(aktPanel); aktPanel = newPanel; splitPane.add(aktPanel); aktPanel.updateUI(); getAktPanel().loadData(turnierBO); } } if (aktPanel.turnierBO != null) { String title = "Volleyball Manager - " //$NON-NLS-1$ + aktPanel.turnierBO.getName() + " - " //$NON-NLS-1$ + getStringByAktPanel(); if (licenceBO.licencetype.equals(LicenceBO.LICENCE_DEMO)) { title += " - " + Messages.getString("licence_notregistered"); } this.setTitle(title); String datum = DateFormat.getDateInstance(DateFormat.LONG).format( aktPanel.turnierBO.getDate()); this.statusBar.setText(Messages.getString(licenceBO.licencetype) + " - " + getUserBO().getName() + " - " //$NON-NLS-1$ + aktPanel.turnierBO.getName() + " - " //$NON-NLS-1$ + datum); menuBar.setTurnierEnable(true); toolBar.setTurnierEnable(true, treeNodeType, aktPanel.turnierBO); } else { this.setTitle("Volleyball Manager"); //$NON-NLS-1$ this.statusBar.setText(getUserBO().getName()); menuBar.setTurnierEnable(false); toolBar.setTurnierEnable(false, treeNodeType, null); } } public void setAktPanelByTreeNodeType(int treeNodeType) { setAktPanelByTreeNodeType(treeNodeType, aktPanel.turnierBO); } public String getStringByAktPanel() { switch (getTypeByAktPanel()) { case TreeNodeObject.TURNIER: return Messages.getString("volleyframe_view_challenge"); //$NON-NLS-1$ case TreeNodeObject.MANNSCHAFTEN: return Messages.getString("volleyframe_view_teams"); //$NON-NLS-1$ case TreeNodeObject.GRUPPEN: return Messages.getString("volleyframe_view_groups"); //$NON-NLS-1$ case TreeNodeObject.SPIELPLAN: return Messages.getString("volleyframe_view_schedule"); //$NON-NLS-1$ case TreeNodeObject.ERGEBNISSE: return Messages.getString("volleyframe_view_results"); //$NON-NLS-1$ case TreeNodeObject.PLATZIERUNGEN: return Messages.getString("volleyframe_view_placings"); //$NON-NLS-1$ case TreeNodeObject.NOPANEL: return Messages.getString("volleyframe_view_start"); //$NON-NLS-1$ } return Messages.getString("volleyframe_view_unknown"); //$NON-NLS-1$ } public int getTypeByAktPanel() { if (aktPanel == turnierPanel) { return TreeNodeObject.TURNIER; } if (aktPanel == mannschaftenPanel) { return TreeNodeObject.MANNSCHAFTEN; } if (aktPanel == gruppenPanel) { return TreeNodeObject.GRUPPEN; } if (aktPanel == spielplanPanel) { return TreeNodeObject.SPIELPLAN; } if (aktPanel == ergebnissePanel) { return TreeNodeObject.ERGEBNISSE; } if (aktPanel == platzierungenPanel) { return TreeNodeObject.PLATZIERUNGEN; } if (aktPanel == nullPanel) { return TreeNodeObject.NOPANEL; } return -1; } /** * Setzt auf Anfangsansicht zur�ck * */ public void setNullPanel() { setAktPanelByTreeNodeType(TreeNodeObject.NOPANEL, null); } public void newTurnier() { // Turnier einf�gen Tournament turnierBO = new Tournament(); turnierBO.setDate(new Date()); turnierBO.setName(Messages.getString("title_new_challenge")); //$NON-NLS-1$ // generate some random linkid as default String linkid = ""; Random r = new Random(); String chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (int i = 0; i < 20; i++) { linkid += chars.charAt(r.nextInt(chars.length())); } turnierBO.setLinkid(linkid); try { turnierBO = TurnierRemote.saveByTurnierBO(turnierBO, getUserBO()); } catch (Exception e) { LOG.error("Can't save tournament", e); } navTree.addNewTurnier(turnierBO); navTree.selectTurnier(turnierBO); } public void saveTurnier() { TreePath path = navTree.getSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent(); TreeNodeObject treeNodeObject = (TreeNodeObject) node .getUserObject(); Tournament turnierBO = treeNodeObject.getTurnier(); JFileChooser fc = new JFileChooser(); ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("tur"); //$NON-NLS-1$ filter.setDescription(Messages .getString("volleyframe_jvolley_challenge_file")); //$NON-NLS-1$ fc.setFileFilter(filter); fc.setApproveButtonText(Messages.getString("volleyframe_save")); //$NON-NLS-1$ fc.setDialogTitle(Messages .getString("volleyframe_export_challenge")); //$NON-NLS-1$ fc.setCurrentDirectory(getLastChoosenDir()); // set default save name to the name of the turnament + date String filename = turnierBO.getName() + " "; DateFormat formater = SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); filename += formater.format(new Date()).replaceAll(":", "-") .replaceAll("\\.", "-"); filename += ".tur"; filename = filename.replaceAll(" ", "_"); fc.setSelectedFile(new File(filename)); int result = fc.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); // if the file exist -> ask it should be overwritten boolean write = false; // really save? if (!fc.getSelectedFile().exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int resultDlg = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_file"), Messages.getString("volleyframe_export_challenge"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (resultDlg == JOptionPane.YES_OPTION); } if (write) { ProgressDialog progDlg = new ProgressDialog(this); Runnable runnable = new ProgressRunnables.SaveTournamentRunnable( fc.getSelectedFile(), turnierBO, progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } } } public void openTurnier() { JFileChooser fc = new JFileChooser(); ExampleFileFilter filter = new ExampleFileFilter(); filter.addExtension("tur"); //$NON-NLS-1$ filter.setDescription(Messages .getString("volleyframe_jvolley_challenge_file")); //$NON-NLS-1$ fc.setFileFilter(filter); fc.setApproveButtonText(Messages.getString("volleyframe_open")); //$NON-NLS-1$ fc.setDialogTitle(Messages.getString("volleyframe_import_challenge")); //$NON-NLS-1$ fc.setCurrentDirectory(getLastChoosenDir()); int result = fc.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); ProgressDialog progDlg = new ProgressDialog(this); Runnable runnable = new ProgressRunnables.OpenTournamentRunnable(fc .getSelectedFile().getPath(), navTree, getUserBO().getId(), progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } /** * @return */ public UserBO getUserBO() { return userBO; } /** * @param userBO */ public void setUserBO(UserBO userBO) { this.userBO = userBO; } /** * Startet Appliaction, um eine PDF/Html-Datei anzuzeigen * * @param pfad */ public static void showExternal(String pfad) { // falls vorhanden -> Acrobat Reader starten try { Runtime.getRuntime().exec( "cmd /q /c start " + pfad.replaceAll(" ", "\" \"")); //$NON-NLS-1$ } catch (Exception ex) { // ok now change show a window JOptionPane .showMessageDialog( getInstance(), Messages.getString("volleyframe_noexternal") + " " + pfad, Messages.getString("volleyframe_noexternal_title"), JOptionPane.WARNING_MESSAGE); //$NON-NLS-1$ } } public static void showExternalExplorer(String pfad) { // falls vorhanden -> Internet Explorer starten try { Runtime.getRuntime().exec("explorer \"" + pfad + "\""); //$NON-NLS-1$ } catch (Exception ex) { // let's try some other common browsers try { String[] cmd = { "mozilla", pfad }; Runtime.getRuntime().exec(cmd); //$NON-NLS-1$ } catch (Exception ex2) { try { String[] cmd = { "netscape", pfad }; Runtime.getRuntime().exec(cmd); //$NON-NLS-1$ } catch (Exception ex3) { // no standard browser available showExternal(pfad); } } } } /** * Shows Terminal view * */ public void showOnline() { try { String param = "linkid=" + URLEncoder .encode(aktPanel.turnierBO.getLinkid(), "utf-8") + "&locale=" + Locale.getDefault().getLanguage(); VolleyFrame.showExternalExplorer(HomeGetter.getWebUrl() + "/turnier.do?" + param); } catch (UnsupportedEncodingException e) { LOG.error("Can't UTF-8 encode", e); } } /** * Shows Beamer view * */ public void showBeamer() { try { String param = "linkid=" + URLEncoder .encode(aktPanel.turnierBO.getLinkid(), "utf-8") + "&locale=" + Locale.getDefault().getLanguage(); VolleyFrame.showExternalExplorer(HomeGetter.getWebUrl() + "/beamerspielplan.do?" + param); } catch (UnsupportedEncodingException e) { LOG.error("Can't UTF-8 encode", e); } } // Spielplan nach Pdf exportieren public void exportPdfSpielplan() { exportPdf(Messages.getString("volleyframe_schedule"), new ProgressRunnables.PdfSpielplanRunnable()); } // Schiedsrichter nach Pdf exportieren public void exportPdfSchiedsrichter() { exportPdf(Messages.getString("volleyframe_referee"), new ProgressRunnables.PdfSchiedsrichterRunnable()); } // Schiedsrichter nach Pdf exportieren public void exportPdfSpielbericht() { exportPdf(Messages.getString("volleyframe_spielbericht"), new ProgressRunnables.PdfSpielberichtRunnable()); } // Gruppenansicht nach Pdf exportieren public void exportPdfGruppen() { exportPdf(Messages.getString("volleyframe_groups"), new ProgressRunnables.PdfGruppenRunnable()); } /** * Generic function to export PDF * */ private void exportPdf(String exportDialogTitle, ProgressRunnables.PdfRunnable runnable) { Tournament turnierBO = navTree.getSelectedTurnierBO(); if (turnierBO != null) { ExportDialog dlg = new ExportDialog(this, turnierBO, exportDialogTitle); //$NON-NLS-1$ dlg.setModal(true); dlg.show(); if (dlg.getResult() == true) { // if the file exist -> ask it should be overwritten File f = new File(dlg.getPfad()); boolean write = false; // really save? if (!f.exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int result = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_file"), exportDialogTitle, JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (result == JOptionPane.YES_OPTION); } if (write) { ProgressDialog progDlg = new ProgressDialog(this); runnable.setValues(dlg.getPfad(), dlg .getSelectedGruppeIds(), turnierBO, progDlg); Thread thread = new Thread(runnable); thread.start(); progDlg.show(); } } } } public void exportHtml() { Tournament turnierBO = navTree.getSelectedTurnierBO(); if (turnierBO != null) { JFileChooser fc = new JFileChooser(); JFileChooser.setDefaultLocale(Locale.getDefault()); fc.setFileFilter(null); fc.setDialogTitle(Messages.getString("volleyframe_export_to_html")); //$NON-NLS-1$ fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setCurrentDirectory(getLastChoosenDir()); int result = fc.showDialog(null, Messages .getString("volleyframe_save")); //$NON-NLS-1$ if (result == JFileChooser.APPROVE_OPTION) { setLastChoosenDir(fc.getCurrentDirectory()); // if the file exist -> ask it should be overwritten boolean write = false; // really save? if (!fc.getSelectedFile().exists()) { write = true; } else { JOptionPane.setDefaultLocale(Locale.getDefault()); int resultDlg = JOptionPane .showConfirmDialog( this, Messages.getString("overwrite_dir"), Messages.getString("volleyframe_export_challenge"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ write = (resultDlg == JOptionPane.YES_OPTION); } if (write) { ProgressDialog dlg = new ProgressDialog(this); Runnable exportRunnable = new ProgressRunnables.ExportHtmlRunnable( fc.getSelectedFile(), turnierBO, dlg); Thread thread = new Thread(exportRunnable); thread.start(); dlg.show(); } } } } /** * @return Returns the lastChoosenDir. */ public File getLastChoosenDir() { return lastChoosenDir; } /** * @param lastChoosenDir * The lastChoosenDir to set. */ public void setLastChoosenDir(File lastChoosenDir) { if (this.lastChoosenDir != lastChoosenDir) { this.lastChoosenDir = lastChoosenDir; VolleyApp.writeLastChoosenDir(lastChoosenDir.getPath()); } } } class TreeController implements TreeSelectionListener { private JTree tree; private VolleyFrame jvolleyFrame; public TreeController(JTree tree, VolleyFrame jvolleyFrame) { super(); this.tree = tree; this.jvolleyFrame = jvolleyFrame; tree.addTreeSelectionListener(this); } public void valueChanged(TreeSelectionEvent e) { if (e.getSource() == tree) { TreePath path = e.getPath(); DefaultMutableTreeNode node = null; if (path != null) node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node == null) { return; } tree.expandPath(path); TreeNodeObject treeNodeObject = (TreeNodeObject) node .getUserObject(); jvolleyFrame.setAktPanelByTreeNodeType(treeNodeObject.getType(), treeNodeObject.getTurnier()); } } }
6367_110
/* * @(#)FuzzyPendulumModel.java 1.0 2000/06/10 * * Copyright (c) 1998 National Research Council of Canada. * All Rights Reserved. * * This software is the confidential and proprietary information of * the National Research Council of Canada. ("Confidential Information"). * You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into * with the National Research Council of Canada. * * THE NATIONAL RESEARCH COUNCIL OF CANADA MAKES NO REPRESENTATIONS OR * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESSED OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. NRC SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * * Copyright Version 1.0 * */ package examples.fuzzypendulum; import javax.swing.*; import nrc.fuzzy.*; /** * Class to simulate an inverse pendulum balancing (mass balanced on a stick, * with motor at base to apply force to keep mass balanced). * * The mass can be 'bopped' by a rod from the left (it hits the mass pushing it * to the right). The mass can be set to 'bob' up and down (as if it were * on a spring rather than a rigid stick). The size of the mass and the motor * can be varied. * * There are 11 rules that control the balancing. These can be enabled or * disabled (an enhancement that might be considered is to allow the rules to * be dynamically modifed; add new rules, change the membership functions * of existing rules, etc.) The rules each have 2 fuzzy antecedent conditions * and a single fuzzy conclusion. On each cycle of the simulation the rules are * considered for firing, given the current situation (position and motion of * the pendulum). The rules look like: * * if error is Z * and omega is Z * then current is Z * * where: * * error - deviation of the pendulum position from vertical (PI/2) * omega - angular velocity of the pendulum * * and various terms describe the degrees of error, omega and current, * * NM - negative medium * NS - negative small * Z - zero * PS - positive small * PM - positive medium * * Each rule that 'fires' may produce a current fuzzy value. All of these * outputs are combined to form an aggregated result (union of the fuzzy * sets) which is then defuzzified to produce a final 'global' value for the * current. The current is set to this value and the next iteration is done. * The current output determined by the rules is a value between -1.0 and 1.0. * This is scaled by the size of the motor to get the actual current. */ public class FuzzyPendulumModel extends java.lang.Thread { // Some constants final static double G = 9.80666; // gravity constant final static double dT = 0.06; // time delta (.04 was original value, use < 0.1 // or it reacts too slow to control the system) final static double dT2 = dT*dT; // time delta squared final static double ERROR_MIN = -Math.PI/2, ERROR_MAX = Math.PI/2; final static double OMEGA_MIN = -8.5, OMEGA_MAX = 8.5; final static double CURRENT_MIN = -1.0, CURRENT_MAX = 1.0; // state information for the simulation boolean bopping = true; // true is bopping is being done (hit the mass from the left) boolean bobbing = false; // true if mass if to 'bob' up and down boolean stepMode = false;// true if doing one step of the simulation at a time int stepsToDo = 0; // number of steps pending in step mode double motorSize; // size of the motor (max current for Motor, Amps) double minMotorSize; // min size of the motor double maxMotorSize; // max size of the motor double massSize; // size of the mass (kg) double minMassSize; // min size of the mass double maxMassSize; // max size of the mass double stickLength; // current length of the stick/pendulum (meters) double minStickLength; // min length of the stick double maxStickLength; // max length of the stick double stickDirection; // +1 or -1 as the stick 'bobs' up and down double theta; // actual angle of pendulum (0 to PI radians) double thetaMin; // min value for theta double thetaMax; // max value for theta double requiredTheta; // the required value of Theta (PI/2 : vertical) double error; // error from required theta value double omega; // angular velocity of the pendulum double current; // output current (from -1.0 to 1.0; scaled by motor size) FuzzyValue globalCurrentFVal = null; // aggregated result of all rules firing FuzzyPendulumJApplet simGraphics; // the GUI attached to the simulation int freezeSeconds = 0; // number of seconds to freeze the simulation private boolean suspendRequested = false; // set to true if this thread should be suspended // ************************************************* // ***** The Fuzzy Rule definition components ****** // ************************************************* final int NUM_RULES = 11; // The names associated with the rules ... external reference to rules // must use these names ... "Z_NM_PM" means // if error is Z and omega is NM // then current is PM String[] ruleNames = {"Z_NM_PM", "Z_NS_PS", "PS_NS_Z", "NM_Z_PM", "NS_Z_PS", "Z_Z_Z", "PS_Z_NS", "PM_Z_NM", "NS_PS_Z", "Z_PS_NS", "Z_PM_NM" }; // identifies if a rule is being used (true => enabled, false => diabled) boolean[] rulesEnabled = {true, true, true, true, true, true, true, true, true, true, true }; // identifies if a rule was fired in the last iteration boolean[] rulesFired = {false, false, false, false, false, false, false, false, false, false, false }; // the names of the error antecedants, omega antecedents and current // conclusions for each rule String[] errorAntecedents = {"Z", "Z", "PS", "NM", "NS", "Z", "PS", "PM", "NS", "Z", "Z"}; String[] omegaAntecedents = {"NM", "NS", "NS", "Z", "Z", "Z", "Z", "Z", "PS", "PS", "PM"}; String[] currentConclusions = {"PM", "PS", "Z", "PM", "PS", "Z", "NS", "NM", "Z", "NS", "NM"}; // the fuzzy rules FuzzyRule[] fuzzyRules = new FuzzyRule[NUM_RULES]; // define the fuzzy terms for each fuzzy variable FuzzyVariable errorFVar; FuzzyVariable omegaFVar; FuzzyVariable currentFVar; final int numErrorFuzzyTerms = 5; final int numOmegaFuzzyTerms = 5; final int numCurrentFuzzyTerms = 5; String[] termNames = {"NM", "NS", "Z", "PS", "PM"}; FuzzySet[] errorFuzzySets = new FuzzySet[numErrorFuzzyTerms]; FuzzySet[] omegaFuzzySets = new FuzzySet[numOmegaFuzzyTerms]; FuzzySet[] currentFuzzySets = new FuzzySet[numCurrentFuzzyTerms]; /** * Create a model of the fuzzy pendulum, setting the appropriate values * for the mass, motor, stick, theta, and fuzzy rules etc. */ public FuzzyPendulumModel( FuzzyPendulumJApplet a ) { int i; suspendRequested = false; simGraphics = a; massSize = 2.5; // mass is 0.5 kg to 3.5 kg minMassSize = 0.5; maxMassSize = 3.5; motorSize = 100.0; // motor size is from 60 to 180 Amps (or mA?) minMotorSize = 60.0; maxMotorSize = 180.0; stickLength = 1.3; // stick can vary from 0.7 to 1.3 m minStickLength = 0.7; maxStickLength = 1.3; stickDirection = -0.1; theta = Math.PI/2.0; // start vertical requiredTheta = Math.PI/2.0; // want to keep it vertical thetaMin = 0.0; // min value for theta thetaMax = Math.PI; // max value for theta error = 0.0; // initial error is 0.0 (balanced) omega = 0.0; // initial angular velocity is 0.0 (balanced) current = 0.0; // initial current is 0.0 (balanced) setBopping( true ); // initially bopping in ON setBobbing( false ); // initially bobbing (up/down) is OFF setStepMode( false); // initially NOT in step mode // define the fuzzy variables and their terms and the fuzzy rules try { errorFVar = new FuzzyVariable("error", ERROR_MIN, ERROR_MAX); omegaFVar = new FuzzyVariable("omega", OMEGA_MIN, OMEGA_MAX); currentFVar = new FuzzyVariable("current", CURRENT_MIN, CURRENT_MAX); errorFuzzySets[0] = new RFuzzySet(-1.28, -0.64, new RightLinearFunction()); errorFuzzySets[1] = new TriangleFuzzySet(-1.28, -0.64, 0); errorFuzzySets[2] = new TriangleFuzzySet(-0.64, 0, 0.64); errorFuzzySets[3] = new TriangleFuzzySet(0, 0.64, 1.28); errorFuzzySets[4] = new LFuzzySet(0.64, 1.28, new LeftLinearFunction()); omegaFuzzySets[0] = new RFuzzySet(-4.27, -2.13, new RightLinearFunction()); omegaFuzzySets[1] = new TriangleFuzzySet(-4.27, -2.13, 0); omegaFuzzySets[2] = new TriangleFuzzySet(-2.13, 0, 2.13); omegaFuzzySets[3] = new TriangleFuzzySet(0, 2.13, 4.27); omegaFuzzySets[4] = new LFuzzySet(2.13, 4.27, new LeftLinearFunction()); currentFuzzySets[0] = new RFuzzySet(-1.0, -0.25, new RightLinearFunction()); currentFuzzySets[1] = new TriangleFuzzySet(-0.5, -0.25, 0); currentFuzzySets[2] = new TriangleFuzzySet(-0.25, 0, 0.25); currentFuzzySets[3] = new TriangleFuzzySet(0, 0.25, 0.5); currentFuzzySets[4] = new LFuzzySet(0.25, 1.0, new LeftLinearFunction()); for (i=0; i<numErrorFuzzyTerms; i++) errorFVar.addTerm(termNames[i], errorFuzzySets[i]); for (i=0; i<numOmegaFuzzyTerms; i++) omegaFVar.addTerm(termNames[i], omegaFuzzySets[i]); for (i=0; i<numErrorFuzzyTerms; i++) currentFVar.addTerm(termNames[i], currentFuzzySets[i]); for (i=0; i<NUM_RULES; i++) { fuzzyRules[i] = new FuzzyRule(); fuzzyRules[i].addAntecedent(new FuzzyValue(errorFVar, errorAntecedents[i])); fuzzyRules[i].addAntecedent(new FuzzyValue(omegaFVar, omegaAntecedents[i])); fuzzyRules[i].addConclusion(new FuzzyValue(currentFVar, currentConclusions[i])); } } catch (FuzzyException fe) {} } void requestSuspend() { suspendRequested = true; } /** Set the state of 'bopping' for the simulation. * * @param b true when bopping is enabled */ void setBopping( boolean b ) { bopping = b; } /** Get the state of bopping in the simulation * * @return true when bopping is enabled */ boolean isBopping() { return bopping; } /** Set the state of 'bobbing' (up/down motion) for the simulation. * * @param b true when bobbing is enabled */ void setBobbing( boolean b ) { bobbing = b; } /** Get the state of bobbing in the simulation * * @return true when bobbing is enabled */ boolean isBobbing() { return bobbing; } void setMassSize( double size ) /** * Set the size of the mass on the pendulum. * Up to the user to keep values between min and max sizes. * The user can get the min and max sizes and scale appropriately. * * @param size the value to set for the size of the mass on the pendulum */ { if (size > maxMassSize) massSize = maxMassSize; else if (size < minMassSize) massSize = minMassSize; else massSize = size; } /** Get the current size of the mass on the pendulum. * * @return the current size of the mass (KG). */ double getMassSize() { return massSize; } /** Get the current maximum size of the mass on the pendulum. * * @return the current maximum size of the mass (KG). */ double getMaxMassSize() { return maxMassSize; } /** Get the current minimum size of the mass on the pendulum. * * @return the current minimum size of the mass (KG). */ double getMinMassSize() { return minMassSize; } /** * Set the size of the motor on the pendulum. * Up to the user to keep values between min and max sizes. * The user can get the min and max sizes and scale appropriately. * * @param size the value to set for the size of the motor on the pendulum */ void setMotorSize( double size ) { if (size > maxMotorSize) motorSize = maxMotorSize; else if (size < minMotorSize) motorSize = minMotorSize; else motorSize = size; } /** Get the current size of the motor on the pendulum. * * @return the current size of the motor. */ double getMotorSize() { return motorSize; } /** Get the minimum size of the motor on the pendulum. * * @return the minimum size of the motor. */ double getMinMotorSize() { return minMotorSize; } /** Get the maximum size of the motor on the pendulum. * * @return the maximum size of the motor. */ double getMaxMotorSize() { return maxMotorSize; } /** Freeze the simulation for a specified number of seconds. * * @param seconds the number of seconds to freeze the simulation */ void setFreeze( int seconds ) { freezeSeconds = seconds; } /** Bump the mass to the left. In this case just increase the angular * momentum by 3. */ void bumpLeft() { omega += 3.0; } /** Bump the mass to the right. In this case just decrease the angular * momentum by 3. */ void bumpRight() { omega -= 3.0; } /** Pull the mass all the way to the left. In this case set the angular * momentum to 0 and set theta to PI. */ void pullLeft() { omega = 0.0; theta = Math.PI; } /** Pull the mass all the way to the right. In this case set the angular * momentum to 0 and set theta to 0. */ void pullRight() { omega = 0.0; theta = 0.0; } /** Turn on or off step mode, allowing the user to execute one step of the * simulation at a time. * * @param b true if step mode turned on. */ synchronized void setStepMode( boolean b ) { stepMode = b; stepsToDo = 0; } /** Get state of step mode, ON or OFF. * * @return ture if step mode is on. */ boolean isStepMode() { return stepMode; } /** Request that the next step in the simulation be performed. */ synchronized void doNextStep() { if (stepMode) stepsToDo++; } /** Identify that the next step has been done. */ synchronized void nextStepDone() { if (stepsToDo > 0) stepsToDo--; } /** Get the current value of theta, the angle of the pendulum. * * @return the angle of the pendulum. */ double getTheta() { return theta; } /** Get the current value of the length of the pendulum (stick). * * @return the length of the stick. */ double getStickLength() { return stickLength; } /** Get the minimum value of the length of the pendulum (stick). * * @return the minimum length of the stick. */ double getMinStickLength() { return minStickLength; } /** Get the maximum value of the length of the pendulum (stick). * * @return the maximum length of the stick. */ double getMaxStickLength() { return maxStickLength; } /** Enbable or disable a rule from being used in the rule firings. * * @param b true if rule is to be enabled * @param rule string name of the rule to be enabled or disabled. The rule * names have the format Z_NM_PM etc. */ void setRuleEnabled(boolean b, String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) { rulesEnabled[i] = b; return; } } /** Determine if a rule is enabled or disabled. * * @param rule string name of the rule being queried. The rule * names have the format Z_NM_PM etc. */ boolean isRuleEnabled(String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) return rulesEnabled[i]; return false; } /** Get a rule. * * @param rule string name of the rule being queried. The rule * names have the format Z_NM_PM etc. * @return a FuzzyRule object. */ FuzzyRule getFuzzyRule(String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) return fuzzyRules[i]; // error ... rule not found return null; } /** The heart of the simulation, the run method. * * Simulates the balancing of a pendulum. At each cycle (time step) * we calculate the current simulation state (theta, omega, etc.) and * we execute a set of Fuzzy Rules that determine the current to * apply in the motor in order to try to bring the pendulum to a vertical * position. */ public void run() { UpdateSimulationComponentsThread uscThread = new UpdateSimulationComponentsThread(); while (true) { // if being asked to suspend itself call suspend ... // this happens when the Applet leaves a page for example; the applet // will do a resume when it starts again if (suspendRequested) { suspendRequested = false; suspend(); } // if not in step mode or in step mode with a step to do // perform the next step of the simulation if ((isStepMode() && stepsToDo > 0) || !isStepMode() ) { nextStepDone(); // handle freeze frame if required if (freezeSeconds > 0) { try { sleep((long)freezeSeconds*1000); } catch (InterruptedException e) {} freezeSeconds = 0; } // deal with stick 'bobbing' if required if (isBobbing()) { // adjust the length of the stick stickLength += stickDirection; if (stickLength < minStickLength) stickDirection = 0.1; else if (stickLength > maxStickLength) stickDirection = -0.1; } // determine the new value for theta given the current being // applied (size of motor plus normalized current determined), // the size of the mass, the current position of the mass/stick. // // mainTorque ... torque exerted by gravity // coilTorque ... torque exerted by the motor // totalTorque ... combined torque double mainTorque = -(stickLength*massSize*Math.cos(theta)*G); double coilTorque = motorSize*(current); double totalTorque = mainTorque + coilTorque; double inertia = stickLength*stickLength * massSize; double alpha = totalTorque/inertia; // mass angular acceleration omega = omega + alpha*dT; // mass angular velocity theta = theta + omega*dT + alpha*dT2; if (theta > thetaMax) { theta = thetaMax; omega = 0.0; } else if (theta < thetaMin) { theta = thetaMin; omega = 0.0; } // get error and delta error (actually angular velocity!!) error = theta - requiredTheta; // fire rules to calculate the next current setting fireRules( error, omega ); // always draw the modified simulation panel after each time step // and draw the modified rule firings information try { SwingUtilities.invokeAndWait(uscThread); } catch (Throwable t) { t.printStackTrace(); //Ensure the application exits with an error condition. System.exit(1); } } // Seem to need to sleep for >150 ms for things to work // correctly!!! should NOT have to do this?? I guess we // need to give up control at some point so other threads // get in but ... // yield() has the same problem // This problem seems to go away when I get out of Visual Cafe!! // // Always need to sleep (or yield?) so that button clicks etc. // can be processed -- seem to need about 5 millisecs for // tooltips to be recognized! try { sleep(5); } catch (InterruptedException ie) {} } } /** Exceute the rules, calcualting the new value for the current to * be applied in the motor. * * @param error the error from required theta value * @param omega the angular velocity of the pendulum */ public void fireRules(double error, double omega ) { int i; FuzzyValueVector ruleResultFVV = null; globalCurrentFVal = null; // to fuzzify error and omega they need to be in range if (error > ERROR_MAX) error = ERROR_MAX; if (error < ERROR_MIN) error = ERROR_MIN; if (omega > OMEGA_MAX) omega = OMEGA_MAX; if (omega < OMEGA_MIN) omega = OMEGA_MIN; // clear all rulesFired flags; for (i=0; i<NUM_RULES; i++) rulesFired[i] = false; try { // fuzzify error and omega FuzzyValue errorFVal = new FuzzyValue(errorFVar, new TriangleFuzzySet(error, error, error)); FuzzyValue omegaFVal = new FuzzyValue(omegaFVar, new TriangleFuzzySet(omega, omega, omega)); // use these as the inputs to each rule firing FuzzyValueVector ruleInputs = new FuzzyValueVector(2); ruleInputs.addFuzzyValue(errorFVal); ruleInputs.addFuzzyValue(omegaFVal); // fire the rules if they match the inputs for (i=0; i<NUM_RULES; i++) { FuzzyRule rule = fuzzyRules[i]; if (rulesEnabled[i] && rule.testRuleMatching(ruleInputs)) { rulesFired[i] = true; ruleResultFVV = rule.execute(ruleInputs); FuzzyValue fval = ruleResultFVV.fuzzyValueAt(0); if (globalCurrentFVal == null) globalCurrentFVal = fval; else globalCurrentFVal = globalCurrentFVal.fuzzyUnion(fval); } } // determine the new value for the motor current (between -1 and +1) if (globalCurrentFVal != null) current = globalCurrentFVal.momentDefuzzify(); } catch (FuzzyException fe) {} } /* Threads for repainting etc. Note ... MUST do the painting in a separate thread that has been added to the 'event queue' or display can be corrupted ... swing is single threaded! See call to invokeAndWait above! */ class UpdateSimulationComponentsThread implements Runnable { public void run() { // paint the simulation display area FuzzySet gcfs = null; if (globalCurrentFVal != null) gcfs = globalCurrentFVal.getFuzzySet(); simGraphics.updateSimulationComponents(ruleNames, rulesFired, rulesEnabled, theta, error, omega, current, gcfs ); } } }
rorchard/FuzzyJ
examples/fuzzypendulum/FuzzyPendulumModel.java
7,940
// get in but ...
line_comment
nl
/* * @(#)FuzzyPendulumModel.java 1.0 2000/06/10 * * Copyright (c) 1998 National Research Council of Canada. * All Rights Reserved. * * This software is the confidential and proprietary information of * the National Research Council of Canada. ("Confidential Information"). * You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into * with the National Research Council of Canada. * * THE NATIONAL RESEARCH COUNCIL OF CANADA MAKES NO REPRESENTATIONS OR * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESSED OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. NRC SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * * Copyright Version 1.0 * */ package examples.fuzzypendulum; import javax.swing.*; import nrc.fuzzy.*; /** * Class to simulate an inverse pendulum balancing (mass balanced on a stick, * with motor at base to apply force to keep mass balanced). * * The mass can be 'bopped' by a rod from the left (it hits the mass pushing it * to the right). The mass can be set to 'bob' up and down (as if it were * on a spring rather than a rigid stick). The size of the mass and the motor * can be varied. * * There are 11 rules that control the balancing. These can be enabled or * disabled (an enhancement that might be considered is to allow the rules to * be dynamically modifed; add new rules, change the membership functions * of existing rules, etc.) The rules each have 2 fuzzy antecedent conditions * and a single fuzzy conclusion. On each cycle of the simulation the rules are * considered for firing, given the current situation (position and motion of * the pendulum). The rules look like: * * if error is Z * and omega is Z * then current is Z * * where: * * error - deviation of the pendulum position from vertical (PI/2) * omega - angular velocity of the pendulum * * and various terms describe the degrees of error, omega and current, * * NM - negative medium * NS - negative small * Z - zero * PS - positive small * PM - positive medium * * Each rule that 'fires' may produce a current fuzzy value. All of these * outputs are combined to form an aggregated result (union of the fuzzy * sets) which is then defuzzified to produce a final 'global' value for the * current. The current is set to this value and the next iteration is done. * The current output determined by the rules is a value between -1.0 and 1.0. * This is scaled by the size of the motor to get the actual current. */ public class FuzzyPendulumModel extends java.lang.Thread { // Some constants final static double G = 9.80666; // gravity constant final static double dT = 0.06; // time delta (.04 was original value, use < 0.1 // or it reacts too slow to control the system) final static double dT2 = dT*dT; // time delta squared final static double ERROR_MIN = -Math.PI/2, ERROR_MAX = Math.PI/2; final static double OMEGA_MIN = -8.5, OMEGA_MAX = 8.5; final static double CURRENT_MIN = -1.0, CURRENT_MAX = 1.0; // state information for the simulation boolean bopping = true; // true is bopping is being done (hit the mass from the left) boolean bobbing = false; // true if mass if to 'bob' up and down boolean stepMode = false;// true if doing one step of the simulation at a time int stepsToDo = 0; // number of steps pending in step mode double motorSize; // size of the motor (max current for Motor, Amps) double minMotorSize; // min size of the motor double maxMotorSize; // max size of the motor double massSize; // size of the mass (kg) double minMassSize; // min size of the mass double maxMassSize; // max size of the mass double stickLength; // current length of the stick/pendulum (meters) double minStickLength; // min length of the stick double maxStickLength; // max length of the stick double stickDirection; // +1 or -1 as the stick 'bobs' up and down double theta; // actual angle of pendulum (0 to PI radians) double thetaMin; // min value for theta double thetaMax; // max value for theta double requiredTheta; // the required value of Theta (PI/2 : vertical) double error; // error from required theta value double omega; // angular velocity of the pendulum double current; // output current (from -1.0 to 1.0; scaled by motor size) FuzzyValue globalCurrentFVal = null; // aggregated result of all rules firing FuzzyPendulumJApplet simGraphics; // the GUI attached to the simulation int freezeSeconds = 0; // number of seconds to freeze the simulation private boolean suspendRequested = false; // set to true if this thread should be suspended // ************************************************* // ***** The Fuzzy Rule definition components ****** // ************************************************* final int NUM_RULES = 11; // The names associated with the rules ... external reference to rules // must use these names ... "Z_NM_PM" means // if error is Z and omega is NM // then current is PM String[] ruleNames = {"Z_NM_PM", "Z_NS_PS", "PS_NS_Z", "NM_Z_PM", "NS_Z_PS", "Z_Z_Z", "PS_Z_NS", "PM_Z_NM", "NS_PS_Z", "Z_PS_NS", "Z_PM_NM" }; // identifies if a rule is being used (true => enabled, false => diabled) boolean[] rulesEnabled = {true, true, true, true, true, true, true, true, true, true, true }; // identifies if a rule was fired in the last iteration boolean[] rulesFired = {false, false, false, false, false, false, false, false, false, false, false }; // the names of the error antecedants, omega antecedents and current // conclusions for each rule String[] errorAntecedents = {"Z", "Z", "PS", "NM", "NS", "Z", "PS", "PM", "NS", "Z", "Z"}; String[] omegaAntecedents = {"NM", "NS", "NS", "Z", "Z", "Z", "Z", "Z", "PS", "PS", "PM"}; String[] currentConclusions = {"PM", "PS", "Z", "PM", "PS", "Z", "NS", "NM", "Z", "NS", "NM"}; // the fuzzy rules FuzzyRule[] fuzzyRules = new FuzzyRule[NUM_RULES]; // define the fuzzy terms for each fuzzy variable FuzzyVariable errorFVar; FuzzyVariable omegaFVar; FuzzyVariable currentFVar; final int numErrorFuzzyTerms = 5; final int numOmegaFuzzyTerms = 5; final int numCurrentFuzzyTerms = 5; String[] termNames = {"NM", "NS", "Z", "PS", "PM"}; FuzzySet[] errorFuzzySets = new FuzzySet[numErrorFuzzyTerms]; FuzzySet[] omegaFuzzySets = new FuzzySet[numOmegaFuzzyTerms]; FuzzySet[] currentFuzzySets = new FuzzySet[numCurrentFuzzyTerms]; /** * Create a model of the fuzzy pendulum, setting the appropriate values * for the mass, motor, stick, theta, and fuzzy rules etc. */ public FuzzyPendulumModel( FuzzyPendulumJApplet a ) { int i; suspendRequested = false; simGraphics = a; massSize = 2.5; // mass is 0.5 kg to 3.5 kg minMassSize = 0.5; maxMassSize = 3.5; motorSize = 100.0; // motor size is from 60 to 180 Amps (or mA?) minMotorSize = 60.0; maxMotorSize = 180.0; stickLength = 1.3; // stick can vary from 0.7 to 1.3 m minStickLength = 0.7; maxStickLength = 1.3; stickDirection = -0.1; theta = Math.PI/2.0; // start vertical requiredTheta = Math.PI/2.0; // want to keep it vertical thetaMin = 0.0; // min value for theta thetaMax = Math.PI; // max value for theta error = 0.0; // initial error is 0.0 (balanced) omega = 0.0; // initial angular velocity is 0.0 (balanced) current = 0.0; // initial current is 0.0 (balanced) setBopping( true ); // initially bopping in ON setBobbing( false ); // initially bobbing (up/down) is OFF setStepMode( false); // initially NOT in step mode // define the fuzzy variables and their terms and the fuzzy rules try { errorFVar = new FuzzyVariable("error", ERROR_MIN, ERROR_MAX); omegaFVar = new FuzzyVariable("omega", OMEGA_MIN, OMEGA_MAX); currentFVar = new FuzzyVariable("current", CURRENT_MIN, CURRENT_MAX); errorFuzzySets[0] = new RFuzzySet(-1.28, -0.64, new RightLinearFunction()); errorFuzzySets[1] = new TriangleFuzzySet(-1.28, -0.64, 0); errorFuzzySets[2] = new TriangleFuzzySet(-0.64, 0, 0.64); errorFuzzySets[3] = new TriangleFuzzySet(0, 0.64, 1.28); errorFuzzySets[4] = new LFuzzySet(0.64, 1.28, new LeftLinearFunction()); omegaFuzzySets[0] = new RFuzzySet(-4.27, -2.13, new RightLinearFunction()); omegaFuzzySets[1] = new TriangleFuzzySet(-4.27, -2.13, 0); omegaFuzzySets[2] = new TriangleFuzzySet(-2.13, 0, 2.13); omegaFuzzySets[3] = new TriangleFuzzySet(0, 2.13, 4.27); omegaFuzzySets[4] = new LFuzzySet(2.13, 4.27, new LeftLinearFunction()); currentFuzzySets[0] = new RFuzzySet(-1.0, -0.25, new RightLinearFunction()); currentFuzzySets[1] = new TriangleFuzzySet(-0.5, -0.25, 0); currentFuzzySets[2] = new TriangleFuzzySet(-0.25, 0, 0.25); currentFuzzySets[3] = new TriangleFuzzySet(0, 0.25, 0.5); currentFuzzySets[4] = new LFuzzySet(0.25, 1.0, new LeftLinearFunction()); for (i=0; i<numErrorFuzzyTerms; i++) errorFVar.addTerm(termNames[i], errorFuzzySets[i]); for (i=0; i<numOmegaFuzzyTerms; i++) omegaFVar.addTerm(termNames[i], omegaFuzzySets[i]); for (i=0; i<numErrorFuzzyTerms; i++) currentFVar.addTerm(termNames[i], currentFuzzySets[i]); for (i=0; i<NUM_RULES; i++) { fuzzyRules[i] = new FuzzyRule(); fuzzyRules[i].addAntecedent(new FuzzyValue(errorFVar, errorAntecedents[i])); fuzzyRules[i].addAntecedent(new FuzzyValue(omegaFVar, omegaAntecedents[i])); fuzzyRules[i].addConclusion(new FuzzyValue(currentFVar, currentConclusions[i])); } } catch (FuzzyException fe) {} } void requestSuspend() { suspendRequested = true; } /** Set the state of 'bopping' for the simulation. * * @param b true when bopping is enabled */ void setBopping( boolean b ) { bopping = b; } /** Get the state of bopping in the simulation * * @return true when bopping is enabled */ boolean isBopping() { return bopping; } /** Set the state of 'bobbing' (up/down motion) for the simulation. * * @param b true when bobbing is enabled */ void setBobbing( boolean b ) { bobbing = b; } /** Get the state of bobbing in the simulation * * @return true when bobbing is enabled */ boolean isBobbing() { return bobbing; } void setMassSize( double size ) /** * Set the size of the mass on the pendulum. * Up to the user to keep values between min and max sizes. * The user can get the min and max sizes and scale appropriately. * * @param size the value to set for the size of the mass on the pendulum */ { if (size > maxMassSize) massSize = maxMassSize; else if (size < minMassSize) massSize = minMassSize; else massSize = size; } /** Get the current size of the mass on the pendulum. * * @return the current size of the mass (KG). */ double getMassSize() { return massSize; } /** Get the current maximum size of the mass on the pendulum. * * @return the current maximum size of the mass (KG). */ double getMaxMassSize() { return maxMassSize; } /** Get the current minimum size of the mass on the pendulum. * * @return the current minimum size of the mass (KG). */ double getMinMassSize() { return minMassSize; } /** * Set the size of the motor on the pendulum. * Up to the user to keep values between min and max sizes. * The user can get the min and max sizes and scale appropriately. * * @param size the value to set for the size of the motor on the pendulum */ void setMotorSize( double size ) { if (size > maxMotorSize) motorSize = maxMotorSize; else if (size < minMotorSize) motorSize = minMotorSize; else motorSize = size; } /** Get the current size of the motor on the pendulum. * * @return the current size of the motor. */ double getMotorSize() { return motorSize; } /** Get the minimum size of the motor on the pendulum. * * @return the minimum size of the motor. */ double getMinMotorSize() { return minMotorSize; } /** Get the maximum size of the motor on the pendulum. * * @return the maximum size of the motor. */ double getMaxMotorSize() { return maxMotorSize; } /** Freeze the simulation for a specified number of seconds. * * @param seconds the number of seconds to freeze the simulation */ void setFreeze( int seconds ) { freezeSeconds = seconds; } /** Bump the mass to the left. In this case just increase the angular * momentum by 3. */ void bumpLeft() { omega += 3.0; } /** Bump the mass to the right. In this case just decrease the angular * momentum by 3. */ void bumpRight() { omega -= 3.0; } /** Pull the mass all the way to the left. In this case set the angular * momentum to 0 and set theta to PI. */ void pullLeft() { omega = 0.0; theta = Math.PI; } /** Pull the mass all the way to the right. In this case set the angular * momentum to 0 and set theta to 0. */ void pullRight() { omega = 0.0; theta = 0.0; } /** Turn on or off step mode, allowing the user to execute one step of the * simulation at a time. * * @param b true if step mode turned on. */ synchronized void setStepMode( boolean b ) { stepMode = b; stepsToDo = 0; } /** Get state of step mode, ON or OFF. * * @return ture if step mode is on. */ boolean isStepMode() { return stepMode; } /** Request that the next step in the simulation be performed. */ synchronized void doNextStep() { if (stepMode) stepsToDo++; } /** Identify that the next step has been done. */ synchronized void nextStepDone() { if (stepsToDo > 0) stepsToDo--; } /** Get the current value of theta, the angle of the pendulum. * * @return the angle of the pendulum. */ double getTheta() { return theta; } /** Get the current value of the length of the pendulum (stick). * * @return the length of the stick. */ double getStickLength() { return stickLength; } /** Get the minimum value of the length of the pendulum (stick). * * @return the minimum length of the stick. */ double getMinStickLength() { return minStickLength; } /** Get the maximum value of the length of the pendulum (stick). * * @return the maximum length of the stick. */ double getMaxStickLength() { return maxStickLength; } /** Enbable or disable a rule from being used in the rule firings. * * @param b true if rule is to be enabled * @param rule string name of the rule to be enabled or disabled. The rule * names have the format Z_NM_PM etc. */ void setRuleEnabled(boolean b, String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) { rulesEnabled[i] = b; return; } } /** Determine if a rule is enabled or disabled. * * @param rule string name of the rule being queried. The rule * names have the format Z_NM_PM etc. */ boolean isRuleEnabled(String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) return rulesEnabled[i]; return false; } /** Get a rule. * * @param rule string name of the rule being queried. The rule * names have the format Z_NM_PM etc. * @return a FuzzyRule object. */ FuzzyRule getFuzzyRule(String rule) { int i; for (i=0; i<NUM_RULES; i++) if (rule.equalsIgnoreCase(ruleNames[i])) return fuzzyRules[i]; // error ... rule not found return null; } /** The heart of the simulation, the run method. * * Simulates the balancing of a pendulum. At each cycle (time step) * we calculate the current simulation state (theta, omega, etc.) and * we execute a set of Fuzzy Rules that determine the current to * apply in the motor in order to try to bring the pendulum to a vertical * position. */ public void run() { UpdateSimulationComponentsThread uscThread = new UpdateSimulationComponentsThread(); while (true) { // if being asked to suspend itself call suspend ... // this happens when the Applet leaves a page for example; the applet // will do a resume when it starts again if (suspendRequested) { suspendRequested = false; suspend(); } // if not in step mode or in step mode with a step to do // perform the next step of the simulation if ((isStepMode() && stepsToDo > 0) || !isStepMode() ) { nextStepDone(); // handle freeze frame if required if (freezeSeconds > 0) { try { sleep((long)freezeSeconds*1000); } catch (InterruptedException e) {} freezeSeconds = 0; } // deal with stick 'bobbing' if required if (isBobbing()) { // adjust the length of the stick stickLength += stickDirection; if (stickLength < minStickLength) stickDirection = 0.1; else if (stickLength > maxStickLength) stickDirection = -0.1; } // determine the new value for theta given the current being // applied (size of motor plus normalized current determined), // the size of the mass, the current position of the mass/stick. // // mainTorque ... torque exerted by gravity // coilTorque ... torque exerted by the motor // totalTorque ... combined torque double mainTorque = -(stickLength*massSize*Math.cos(theta)*G); double coilTorque = motorSize*(current); double totalTorque = mainTorque + coilTorque; double inertia = stickLength*stickLength * massSize; double alpha = totalTorque/inertia; // mass angular acceleration omega = omega + alpha*dT; // mass angular velocity theta = theta + omega*dT + alpha*dT2; if (theta > thetaMax) { theta = thetaMax; omega = 0.0; } else if (theta < thetaMin) { theta = thetaMin; omega = 0.0; } // get error and delta error (actually angular velocity!!) error = theta - requiredTheta; // fire rules to calculate the next current setting fireRules( error, omega ); // always draw the modified simulation panel after each time step // and draw the modified rule firings information try { SwingUtilities.invokeAndWait(uscThread); } catch (Throwable t) { t.printStackTrace(); //Ensure the application exits with an error condition. System.exit(1); } } // Seem to need to sleep for >150 ms for things to work // correctly!!! should NOT have to do this?? I guess we // need to give up control at some point so other threads // get in<SUF> // yield() has the same problem // This problem seems to go away when I get out of Visual Cafe!! // // Always need to sleep (or yield?) so that button clicks etc. // can be processed -- seem to need about 5 millisecs for // tooltips to be recognized! try { sleep(5); } catch (InterruptedException ie) {} } } /** Exceute the rules, calcualting the new value for the current to * be applied in the motor. * * @param error the error from required theta value * @param omega the angular velocity of the pendulum */ public void fireRules(double error, double omega ) { int i; FuzzyValueVector ruleResultFVV = null; globalCurrentFVal = null; // to fuzzify error and omega they need to be in range if (error > ERROR_MAX) error = ERROR_MAX; if (error < ERROR_MIN) error = ERROR_MIN; if (omega > OMEGA_MAX) omega = OMEGA_MAX; if (omega < OMEGA_MIN) omega = OMEGA_MIN; // clear all rulesFired flags; for (i=0; i<NUM_RULES; i++) rulesFired[i] = false; try { // fuzzify error and omega FuzzyValue errorFVal = new FuzzyValue(errorFVar, new TriangleFuzzySet(error, error, error)); FuzzyValue omegaFVal = new FuzzyValue(omegaFVar, new TriangleFuzzySet(omega, omega, omega)); // use these as the inputs to each rule firing FuzzyValueVector ruleInputs = new FuzzyValueVector(2); ruleInputs.addFuzzyValue(errorFVal); ruleInputs.addFuzzyValue(omegaFVal); // fire the rules if they match the inputs for (i=0; i<NUM_RULES; i++) { FuzzyRule rule = fuzzyRules[i]; if (rulesEnabled[i] && rule.testRuleMatching(ruleInputs)) { rulesFired[i] = true; ruleResultFVV = rule.execute(ruleInputs); FuzzyValue fval = ruleResultFVV.fuzzyValueAt(0); if (globalCurrentFVal == null) globalCurrentFVal = fval; else globalCurrentFVal = globalCurrentFVal.fuzzyUnion(fval); } } // determine the new value for the motor current (between -1 and +1) if (globalCurrentFVal != null) current = globalCurrentFVal.momentDefuzzify(); } catch (FuzzyException fe) {} } /* Threads for repainting etc. Note ... MUST do the painting in a separate thread that has been added to the 'event queue' or display can be corrupted ... swing is single threaded! See call to invokeAndWait above! */ class UpdateSimulationComponentsThread implements Runnable { public void run() { // paint the simulation display area FuzzySet gcfs = null; if (globalCurrentFVal != null) gcfs = globalCurrentFVal.getFuzzySet(); simGraphics.updateSimulationComponents(ruleNames, rulesFired, rulesEnabled, theta, error, omega, current, gcfs ); } } }
53643_34
import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.imageio.ImageIO; /** * web temperature setter * * @author matecsaba */ public class temper implements Runnable { /** * this is needed for cli startup * * @param args command line parameters */ public static void main(String[] args) { temper app = new temper(); String a; try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); a = "" + app.getClass().getName() + "."; a = temper.httpRequest("http://localhost/" + a, "./" + a, "cli", "clibrowser", "user", args, buf); a = "type=" + a + "\r\ndata:\r\n" + buf.toString(); } catch (Exception e) { a = "exception " + e.getMessage(); } System.out.println(a); } /** * where i'm located in ram */ protected static temper staticTemper = null; /** * do one request * * @param url url of app * @param path path of app * @param peer client address * @param agent user agent * @param user auth data * @param par parameters * @param buf result buffer, if empty, pathname must present * @return [pathname"][file name.]extension * @throws Exception if something went wrong */ public static String httpRequest(String url, String path, String peer, String agent, String user, String[] par, ByteArrayOutputStream buf) throws Exception { if (staticTemper == null) { staticTemper = new temper(); staticTemper.path = path.substring(0, path.lastIndexOf(".")); staticTemper.url = new URI(url).toURL().getPath(); staticTemper.doInit(); new Thread(staticTemper).start(); } if (staticTemper.doRequest(par, buf, peer) == 2) { return "png"; } else { return "html"; } } /** * where i'm located on host */ protected String path; /** * where i'm located on net */ protected String url; /** * reading store */ protected temperData measDat[] = new temperData[0]; /** * allowed peers */ protected String allowIp; /** * inside reading used */ protected int measIn = -1; /** * outside reading used */ protected int measOut = -1; /** * current value sent */ protected int currValue = 0x10000; /** * last needed temperature */ protected float lastNeeded = 20; /** * time needed temperature */ protected long timeNeeded = 0; /** * time heating temperature */ protected long timeHeating = 0; /** * time zone to use */ protected String tzdata = "Z"; /** * log file */ protected String logFile = "temper.log"; /** * script file */ protected String scrFile = "temper.sh"; /** * window min time */ protected int windowTim = 15 * 60 * 1000; /** * measure timeout */ protected int measTime = 5 * 60 * 1000; /** * measure timeout */ protected int measIotm = 5 * 1000; /** * measure interval */ protected int collTime = 30 * 1000; /** * measure history */ protected int collHist = 90; /** * measure discard */ protected Float collIlde = 0.2F; /** * temperature minimum */ protected float tempMin = 10; /** * temperature maximum */ protected float tempMax = 30; /** * heat tolerance */ protected float heatTol = 0.3F; /** * cool tolerance */ protected float coolTol = 0.3F; /** * cool tolerance */ protected float ventTol = 0.1F; /** * window tolerance */ protected float windowTol = -0.9F; /** * heat pin */ protected int heatPin = 0x0; /** * cool pin */ protected int coolPin = 0x0; /** * vent pin */ protected int ventPin = 0x0; /** * relay pin */ protected int relayPin = 0x0; /** * door pin */ protected int doorPin = 0x0; /** * door time */ protected int doorTime = 1000; /** * door codes */ protected List<temperCode> doorCode = new ArrayList<temperCode>(); /** * door log */ protected List<temperLog> doorLog = new ArrayList<temperLog>(); /** * door temporary codes allowed */ protected boolean doorTemp = false; /** * door max */ protected int doorMax = 5; /** * door count */ protected int doorCnt = 0; /** * last setter peer */ protected String lastSetter = "nobody"; private synchronized void setValue(int val) { val &= (heatPin | coolPin | ventPin | doorPin | relayPin); if (currValue == val) { return; } try { Runtime rtm = Runtime.getRuntime(); String[] cmd = new String[2]; cmd[0] = scrFile; cmd[1] = val + ""; Process prc = rtm.exec(cmd); prc.waitFor(); } catch (Exception e) { return; } int mask = heatPin | coolPin | ventPin; if ((currValue & mask) != (val & mask)) { timeHeating = temperUtil.getTime(); for (int i = 0; i < measDat.length; i++) { measDat[i].setWindow(); } } currValue = val; } private void rangeCheck() { if (lastNeeded > tempMax) { lastNeeded = tempMax; } if (lastNeeded < tempMin) { lastNeeded = tempMin; } } private int doCalc() { for (int i = 0; i < measDat.length; i++) { measDat[i].getValue(); measDat[i].doCalc(); } measIn = -1; measOut = -1; int prioIn = -1; int prioOut = -1; boolean win = false; for (int i = 0; i < measDat.length; i++) { if (!measDat[i].isWorking) { continue; } if (measDat[i].myPri < 0) { continue; } if (measDat[i].inside) { if (prioIn > measDat[i].myPri) { continue; } measIn = i; prioIn = measDat[i].myPri; } else { if (prioOut > measDat[i].myPri) { continue; } measOut = i; prioOut = measDat[i].myPri; } win |= measDat[i].isWindow; } int i = currValue & ~(heatPin | coolPin | ventPin); if (win) { return i; } if (measIn < 0) { return i; } temperData.results res = measDat[measIn].lastCalc; if ((ventPin != 0) && (measOut >= 0)) { boolean maybe = (currValue & ventPin) != 0; float diff = measDat[measIn].lastMeasure - measDat[measOut].lastMeasure; if (diff < 0) { diff = -diff; } maybe &= diff < ventTol; boolean good; switch (res) { case cool: good = measDat[measIn].lastMeasure > (measDat[measOut].lastMeasure + coolTol); break; case heat: good = measDat[measIn].lastMeasure < (measDat[measOut].lastMeasure - heatTol); break; default: return i; } //good &= (res == measDat[measOut].histRes) || (measDat[measOut].histRes == temperData.results.idle); if (good || maybe) { return i | ventPin; } } switch (res) { case cool: return i | coolPin; case heat: return i | heatPin; default: return i; } } private synchronized void writeLog(String who) { if (who == null) { who = lastSetter; } String a = ""; for (int i = 0; i < measDat.length; i++) { a = a + ";" + measDat[i].getLog(); } temperUtil.append(logFile, temperUtil.getTime() + ";" + who + ";" + currValue + ";" + lastNeeded + ";" + measIn + ";" + measOut + a); } /** * initialize */ public void doInit() { readConfig(); timeNeeded = temperUtil.getTime(); timeHeating = timeNeeded; lastSetter = "boot"; rangeCheck(); writeLog("<boot>"); } public void run() { for (;;) { rangeCheck(); setValue(doCalc()); writeLog(null); temperUtil.sleep(collTime); } } private void readConfig() { logFile = path + ".log"; List<String> c = temperUtil.readup(path + ".cfg"); if (c == null) { return; } List<String> m = new ArrayList<String>(); for (int i = 0; i < c.size(); i++) { String s = c.get(i); int o = s.indexOf("="); if (o < 0) { continue; } String a = s.substring(0, o).trim().toLowerCase(); s = s.substring(o + 1, s.length()).trim(); if (a.equals("script")) { scrFile = s; continue; } if (a.equals("needed")) { lastNeeded = temperUtil.str2num(s); continue; } if (a.equals("tzdata")) { tzdata = s; continue; } if (a.equals("door-count")) { doorMax = (int) temperUtil.str2num(s); continue; } if (a.equals("door-code")) { doorCode.add(new temperCode(doorCode.size() + 1, s, false)); continue; } if (a.equals("door-tcode")) { doorCode.add(new temperCode(doorCode.size() + 1, s, true)); continue; } if (a.equals("door-temp")) { doorTemp = s.equals("on"); continue; } if (a.equals("door-time")) { doorTime = (int) temperUtil.str2num(s); continue; } if (a.equals("door-pin")) { doorPin = (int) temperUtil.str2num(s); continue; } if (a.equals("log-file")) { logFile = s; continue; } if (a.equals("temp-min")) { tempMin = temperUtil.str2num(s); continue; } if (a.equals("temp-max")) { tempMax = temperUtil.str2num(s); continue; } if (a.equals("heat-tol")) { heatTol = temperUtil.str2num(s); continue; } if (a.equals("heat-pin")) { heatPin = (int) temperUtil.str2num(s); continue; } if (a.equals("cool-tol")) { coolTol = temperUtil.str2num(s); continue; } if (a.equals("cool-pin")) { coolPin = (int) temperUtil.str2num(s); continue; } if (a.equals("vent-tol")) { ventTol = temperUtil.str2num(s); continue; } if (a.equals("vent-pin")) { ventPin = (int) temperUtil.str2num(s); continue; } if (a.equals("win-tim")) { windowTim = (int) (temperUtil.str2num(s) * 60 * 1000); continue; } if (a.equals("win-tol")) { windowTol = temperUtil.str2num(s); continue; } if (a.equals("collect")) { collTime = (int) (temperUtil.str2num(s) * 1000); continue; } if (a.equals("history")) { collHist = (int) temperUtil.str2num(s); continue; } if (a.equals("idling")) { collIlde = temperUtil.str2num(s); continue; } if (a.equals("timeout")) { measTime = (int) (temperUtil.str2num(s) * 60 * 1000); continue; } if (a.equals("relay-pin")) { relayPin = (int) temperUtil.str2num(s); continue; } if (a.equals("allowed-ip")) { allowIp = s; continue; } if (a.equals("measure")) { m.add(s); continue; } } measDat = new temperData[m.size()]; for (int i = 0; i < measDat.length; i++) { measDat[i] = new temperData(this, i + 1, m.get(i)); } } private static void drawRightAlighed(Graphics2D g2d, int mx10, int y, String s) { FontMetrics fm = g2d.getFontMetrics(); g2d.drawString(s, mx10 - fm.stringWidth(s), y); } private static void putStart(ByteArrayOutputStream buf, String tit, String res) throws Exception { buf.write("<!DOCTYPE html><html lang=\"en\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\" /><meta http-equiv=refresh content=\"3;url=/index.html\"><title>".getBytes()); buf.write(tit.getBytes()); buf.write("</title><body>".getBytes()); buf.write(res.getBytes()); buf.write("</body></html>".getBytes()); } private temperCode findCode(String s) { for (int i = 0; i < doorCode.size(); i++) { temperCode cur = doorCode.get(i); if (!s.equals(cur.code)) { continue; } return cur; } return null; } private BufferedImage drawHist(List<temperHist> hst, int dot) { float tmpMin = Float.MAX_VALUE; float tmpMax = Float.MIN_VALUE; for (int o = 0; o < hst.size(); o++) { temperHist l = hst.get(o); tmpMin = Float.min(tmpMin, l.need); tmpMax = Float.max(tmpMax, l.need); for (int i = 0; i < l.meas.length; i++) { float v = l.meas[i]; tmpMin = Float.min(tmpMin, v); tmpMax = Float.max(tmpMax, v); } } tmpMax -= tmpMin; final int mx = 1800; final int my = 900; final int mx10 = mx - 10; final int mx20 = mx - 20; final int my1 = my - 1; final int my10 = my - 10; final int my20 = my - 20; final int my30 = my - 30; final int my40 = my - 40; final int my50 = my - 50; BufferedImage img = new BufferedImage(mx, my, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(Color.gray); g2d.setFont(new Font("Serif", Font.BOLD, 20)); g2d.setPaint(Color.gray); g2d.fillRect(0, 0, img.getWidth(), img.getHeight()); g2d.setPaint(Color.black); Color colors[] = { Color.green, Color.red, Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow, Color.white, Color.blue,}; for (int o = 0; o < hst.size(); o++) { temperHist l = hst.get(o); int x = ((o * mx20) / hst.size()) + 10; g2d.setPaint(Color.black); g2d.drawRect(x, my10 - (int) (((l.need - tmpMin) * my20) / tmpMax), dot, dot); if (l.curr != 0) { g2d.drawRect(x, 10, dot, dot); } for (int i = 0; i < l.meas.length; i++) { g2d.setPaint(colors[i]); g2d.drawRect(x, my10 - (int) (((l.meas[i] - tmpMin) * my20) / tmpMax), dot, dot); } } for (int i = 0; i < measDat.length; i++) { g2d.setPaint(colors[i]); drawRightAlighed(g2d, mx10, my50 - (i * 20), measDat[i].myNam); } g2d.setPaint(Color.black); drawRightAlighed(g2d, mx10, my30, "needed"); for (int i = 20; i < my20; i += 50) { float v = (float) i * tmpMax; v = v / (float) my20; v += tmpMin; String a = v + " "; g2d.drawString(a.substring(0, 6), 1, my10 - i); } String a; if ((hst.get(hst.size() - 1).time - hst.get(0).time) < (86400 * 3000)) { a = "HH:mm"; } else { a = "MMMdd"; } for (int i = 0; i < mx20; i += 100) { temperHist l = hst.get((i * hst.size()) / mx20); DateFormat dat = new SimpleDateFormat(a, Locale.US); g2d.drawString(dat.format(new Date((long) l.time)), i + 10, my1); } return img; } private boolean checkPeer(ByteArrayOutputStream buf, String peer) throws Exception { if (allowIp == null) { return false; } if (allowIp.indexOf(";" + peer + ";") >= 0) { return false; } putStart(buf, "restricted", "you are not allowed"); return true; } /** * do one request * * @param par parameters * @param buf buffer to use * @param peer address * @return 1 on html result * @throws Exception on error */ public synchronized int doRequest(String[] par, ByteArrayOutputStream buf, String peer) throws Exception { String tmp = ""; String cmd = ""; for (int i = 0; i < par.length; i++) { String a = par[i]; int o = a.indexOf("="); if (o < 1) { continue; } String b = a.substring(0, o); a = a.substring(o + 1, a.length()); if (b.equals("temp")) { tmp = a; } if (b.equals("cmd")) { cmd = a; } } if (cmd.equals("heat")) { if (checkPeer(buf, peer)) { return 1; } lastNeeded = temperUtil.str2num(tmp); timeNeeded = temperUtil.getTime(); lastSetter = peer; rangeCheck(); } if (cmd.equals("relayor")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue | i); cmd = "relayset"; } if (cmd.equals("relayand")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue & i); cmd = "relayset"; } if (cmd.equals("relayxor")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue ^ i); cmd = "relayset"; } if (cmd.equals("relayset")) { if (checkPeer(buf, peer)) { return 1; } if (relayPin == 0) { putStart(buf, "relay", "relay not set"); return 1; } int i = ((int) temperUtil.str2num(tmp)) & relayPin; setValue((currValue & (~relayPin)) | i); writeLog(peer); putStart(buf, "relay", "relay set to " + i + " from range " + relayPin); return 1; } if (cmd.equals("guests")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp) { putStart(buf, "door", "disabled code"); return 1; } doorTemp = true; putStart(buf, "door", "guests enabled"); return 1; } if (cmd.equals("closed")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp) { putStart(buf, "door", "disabled code"); return 1; } doorTemp = false; putStart(buf, "door", "guests disabled"); return 1; } if (cmd.equals("door")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp && (!doorTemp)) { putStart(buf, "door", "disabled code"); return 1; } setValue(currValue | doorPin); writeLog(peer); temperUtil.sleep(doorTime); setValue(currValue & (~doorPin)); writeLog(peer); doorLog.add(new temperLog(this, peer, res.myNum)); for (;;) { if (doorLog.size() <= doorMax) { break; } doorLog.remove(0); } doorCnt++; putStart(buf, "door", "door opened"); return 1; } if (cmd.equals("history")) { temperData cur = measDat[(int) temperUtil.str2num(tmp) - 1]; ImageIO.write(drawHist(cur.histDat, 10), "png", buf); return 2; } if (!cmd.equals("graph")) { rangeCheck(); String a = "<!DOCTYPE html><html lang=\"en\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\" /><title>temper</title>"; buf.write(a.getBytes()); a = "<meta http-equiv=refresh content=\"30;url=" + url + "\"></head><body>"; buf.write(a.getBytes()); long tim = temperUtil.getTime(); a = "<table><thead><tr><td><b>num</b></td><td><b>name</b></td><td><b>value</b></td><td><b>last</b></td><td><b>err</b></td><td><b>read</b></td><td><b>work</b></td><td><b>win</b></td><td><b>res</b></td><td><b>hst</b></td><td><b>wtmp</b></td><td><b>wtim</b></td></tr></thead><tbody>"; buf.write(a.getBytes()); for (int i = 0; i < measDat.length; i++) { a = measDat[i].getMeas(); buf.write(a.getBytes()); } a = "</tbody></table><br/>"; buf.write(a.getBytes()); a = "tolerance: heat " + heatTol + ", cool " + coolTol + ", vent " + ventTol + ", window " + windowTol + ", time " + temperUtil.timePast(windowTim, 0) + "<br/>"; buf.write(a.getBytes()); a = "needed: " + lastNeeded + " celsius, since " + temperUtil.time2str(tzdata, timeNeeded) + ", " + temperUtil.timePast(tim, timeNeeded) + " ago by " + lastSetter + "<br/>"; buf.write(a.getBytes()); a = "doing: " + currValue + ", since " + temperUtil.time2str(tzdata, timeHeating) + ", " + temperUtil.timePast(tim, timeHeating) + " ago, using #" + (measIn + 1) + "/#" + (measOut + 1) + " for " + temperUtil.timePast(measTime, 0) + "<br/>"; buf.write(a.getBytes()); a = "<form action=\"" + url + "\" method=get>wish: <input type=text name=temp value=\"" + lastNeeded + "\"> celsius (" + tempMin + "-" + tempMax + ")"; buf.write(a.getBytes()); buf.write("<input type=submit name=cmd value=\"heat\">".getBytes()); buf.write("<input type=submit name=cmd value=\"graph\">".getBytes()); buf.write("</form><br/>".getBytes()); for (int i = -3; i <= 3; i++) { int o = i + (int) lastNeeded; a = "((<a href=\"" + url + "?temp=" + o + ".0&cmd=heat\">" + o + ".0</a>))"; buf.write(a.getBytes()); a = "((<a href=\"" + url + "?temp=" + o + ".5&cmd=heat\">" + o + ".5</a>))"; buf.write(a.getBytes()); } a = "<br/><br/>the door was opened " + doorCnt + " times:<br/>"; buf.write(a.getBytes()); a = "<table><thead><tr><td><b>num</b></td><td><b>when</b></td><td><b>ago</b></td><td><b>code</b></td><td><b>peer</b></td></tr></thead><tbody>"; buf.write(a.getBytes()); for (int i = doorLog.size() - 1; i >= 0; i--) { a = doorLog.get(i).getMeas(i, tim); buf.write(a.getBytes()); } a = "</tbody></table><br/>"; buf.write(a.getBytes()); buf.write("</body></html>".getBytes()); return 1; } File fi = new File(logFile); FileReader fr = new FileReader(fi); fr.skip(fi.length() - (long) (temperUtil.str2num(tmp) * 64000)); BufferedReader f = new BufferedReader(fr); f.readLine(); List<temperHist> history = new ArrayList<temperHist>(); while (f.ready()) { String s = f.readLine(); temperHist l = new temperHist(); l.parseLine(s); history.add(l); } f.close(); ImageIO.write(drawHist(history, 1), "png", buf); return 2; } }
rossonet/freeRtr
misc/temper/temper.java
8,091
/** * door pin */
block_comment
nl
import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.imageio.ImageIO; /** * web temperature setter * * @author matecsaba */ public class temper implements Runnable { /** * this is needed for cli startup * * @param args command line parameters */ public static void main(String[] args) { temper app = new temper(); String a; try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); a = "" + app.getClass().getName() + "."; a = temper.httpRequest("http://localhost/" + a, "./" + a, "cli", "clibrowser", "user", args, buf); a = "type=" + a + "\r\ndata:\r\n" + buf.toString(); } catch (Exception e) { a = "exception " + e.getMessage(); } System.out.println(a); } /** * where i'm located in ram */ protected static temper staticTemper = null; /** * do one request * * @param url url of app * @param path path of app * @param peer client address * @param agent user agent * @param user auth data * @param par parameters * @param buf result buffer, if empty, pathname must present * @return [pathname"][file name.]extension * @throws Exception if something went wrong */ public static String httpRequest(String url, String path, String peer, String agent, String user, String[] par, ByteArrayOutputStream buf) throws Exception { if (staticTemper == null) { staticTemper = new temper(); staticTemper.path = path.substring(0, path.lastIndexOf(".")); staticTemper.url = new URI(url).toURL().getPath(); staticTemper.doInit(); new Thread(staticTemper).start(); } if (staticTemper.doRequest(par, buf, peer) == 2) { return "png"; } else { return "html"; } } /** * where i'm located on host */ protected String path; /** * where i'm located on net */ protected String url; /** * reading store */ protected temperData measDat[] = new temperData[0]; /** * allowed peers */ protected String allowIp; /** * inside reading used */ protected int measIn = -1; /** * outside reading used */ protected int measOut = -1; /** * current value sent */ protected int currValue = 0x10000; /** * last needed temperature */ protected float lastNeeded = 20; /** * time needed temperature */ protected long timeNeeded = 0; /** * time heating temperature */ protected long timeHeating = 0; /** * time zone to use */ protected String tzdata = "Z"; /** * log file */ protected String logFile = "temper.log"; /** * script file */ protected String scrFile = "temper.sh"; /** * window min time */ protected int windowTim = 15 * 60 * 1000; /** * measure timeout */ protected int measTime = 5 * 60 * 1000; /** * measure timeout */ protected int measIotm = 5 * 1000; /** * measure interval */ protected int collTime = 30 * 1000; /** * measure history */ protected int collHist = 90; /** * measure discard */ protected Float collIlde = 0.2F; /** * temperature minimum */ protected float tempMin = 10; /** * temperature maximum */ protected float tempMax = 30; /** * heat tolerance */ protected float heatTol = 0.3F; /** * cool tolerance */ protected float coolTol = 0.3F; /** * cool tolerance */ protected float ventTol = 0.1F; /** * window tolerance */ protected float windowTol = -0.9F; /** * heat pin */ protected int heatPin = 0x0; /** * cool pin */ protected int coolPin = 0x0; /** * vent pin */ protected int ventPin = 0x0; /** * relay pin */ protected int relayPin = 0x0; /** * door pin <SUF>*/ protected int doorPin = 0x0; /** * door time */ protected int doorTime = 1000; /** * door codes */ protected List<temperCode> doorCode = new ArrayList<temperCode>(); /** * door log */ protected List<temperLog> doorLog = new ArrayList<temperLog>(); /** * door temporary codes allowed */ protected boolean doorTemp = false; /** * door max */ protected int doorMax = 5; /** * door count */ protected int doorCnt = 0; /** * last setter peer */ protected String lastSetter = "nobody"; private synchronized void setValue(int val) { val &= (heatPin | coolPin | ventPin | doorPin | relayPin); if (currValue == val) { return; } try { Runtime rtm = Runtime.getRuntime(); String[] cmd = new String[2]; cmd[0] = scrFile; cmd[1] = val + ""; Process prc = rtm.exec(cmd); prc.waitFor(); } catch (Exception e) { return; } int mask = heatPin | coolPin | ventPin; if ((currValue & mask) != (val & mask)) { timeHeating = temperUtil.getTime(); for (int i = 0; i < measDat.length; i++) { measDat[i].setWindow(); } } currValue = val; } private void rangeCheck() { if (lastNeeded > tempMax) { lastNeeded = tempMax; } if (lastNeeded < tempMin) { lastNeeded = tempMin; } } private int doCalc() { for (int i = 0; i < measDat.length; i++) { measDat[i].getValue(); measDat[i].doCalc(); } measIn = -1; measOut = -1; int prioIn = -1; int prioOut = -1; boolean win = false; for (int i = 0; i < measDat.length; i++) { if (!measDat[i].isWorking) { continue; } if (measDat[i].myPri < 0) { continue; } if (measDat[i].inside) { if (prioIn > measDat[i].myPri) { continue; } measIn = i; prioIn = measDat[i].myPri; } else { if (prioOut > measDat[i].myPri) { continue; } measOut = i; prioOut = measDat[i].myPri; } win |= measDat[i].isWindow; } int i = currValue & ~(heatPin | coolPin | ventPin); if (win) { return i; } if (measIn < 0) { return i; } temperData.results res = measDat[measIn].lastCalc; if ((ventPin != 0) && (measOut >= 0)) { boolean maybe = (currValue & ventPin) != 0; float diff = measDat[measIn].lastMeasure - measDat[measOut].lastMeasure; if (diff < 0) { diff = -diff; } maybe &= diff < ventTol; boolean good; switch (res) { case cool: good = measDat[measIn].lastMeasure > (measDat[measOut].lastMeasure + coolTol); break; case heat: good = measDat[measIn].lastMeasure < (measDat[measOut].lastMeasure - heatTol); break; default: return i; } //good &= (res == measDat[measOut].histRes) || (measDat[measOut].histRes == temperData.results.idle); if (good || maybe) { return i | ventPin; } } switch (res) { case cool: return i | coolPin; case heat: return i | heatPin; default: return i; } } private synchronized void writeLog(String who) { if (who == null) { who = lastSetter; } String a = ""; for (int i = 0; i < measDat.length; i++) { a = a + ";" + measDat[i].getLog(); } temperUtil.append(logFile, temperUtil.getTime() + ";" + who + ";" + currValue + ";" + lastNeeded + ";" + measIn + ";" + measOut + a); } /** * initialize */ public void doInit() { readConfig(); timeNeeded = temperUtil.getTime(); timeHeating = timeNeeded; lastSetter = "boot"; rangeCheck(); writeLog("<boot>"); } public void run() { for (;;) { rangeCheck(); setValue(doCalc()); writeLog(null); temperUtil.sleep(collTime); } } private void readConfig() { logFile = path + ".log"; List<String> c = temperUtil.readup(path + ".cfg"); if (c == null) { return; } List<String> m = new ArrayList<String>(); for (int i = 0; i < c.size(); i++) { String s = c.get(i); int o = s.indexOf("="); if (o < 0) { continue; } String a = s.substring(0, o).trim().toLowerCase(); s = s.substring(o + 1, s.length()).trim(); if (a.equals("script")) { scrFile = s; continue; } if (a.equals("needed")) { lastNeeded = temperUtil.str2num(s); continue; } if (a.equals("tzdata")) { tzdata = s; continue; } if (a.equals("door-count")) { doorMax = (int) temperUtil.str2num(s); continue; } if (a.equals("door-code")) { doorCode.add(new temperCode(doorCode.size() + 1, s, false)); continue; } if (a.equals("door-tcode")) { doorCode.add(new temperCode(doorCode.size() + 1, s, true)); continue; } if (a.equals("door-temp")) { doorTemp = s.equals("on"); continue; } if (a.equals("door-time")) { doorTime = (int) temperUtil.str2num(s); continue; } if (a.equals("door-pin")) { doorPin = (int) temperUtil.str2num(s); continue; } if (a.equals("log-file")) { logFile = s; continue; } if (a.equals("temp-min")) { tempMin = temperUtil.str2num(s); continue; } if (a.equals("temp-max")) { tempMax = temperUtil.str2num(s); continue; } if (a.equals("heat-tol")) { heatTol = temperUtil.str2num(s); continue; } if (a.equals("heat-pin")) { heatPin = (int) temperUtil.str2num(s); continue; } if (a.equals("cool-tol")) { coolTol = temperUtil.str2num(s); continue; } if (a.equals("cool-pin")) { coolPin = (int) temperUtil.str2num(s); continue; } if (a.equals("vent-tol")) { ventTol = temperUtil.str2num(s); continue; } if (a.equals("vent-pin")) { ventPin = (int) temperUtil.str2num(s); continue; } if (a.equals("win-tim")) { windowTim = (int) (temperUtil.str2num(s) * 60 * 1000); continue; } if (a.equals("win-tol")) { windowTol = temperUtil.str2num(s); continue; } if (a.equals("collect")) { collTime = (int) (temperUtil.str2num(s) * 1000); continue; } if (a.equals("history")) { collHist = (int) temperUtil.str2num(s); continue; } if (a.equals("idling")) { collIlde = temperUtil.str2num(s); continue; } if (a.equals("timeout")) { measTime = (int) (temperUtil.str2num(s) * 60 * 1000); continue; } if (a.equals("relay-pin")) { relayPin = (int) temperUtil.str2num(s); continue; } if (a.equals("allowed-ip")) { allowIp = s; continue; } if (a.equals("measure")) { m.add(s); continue; } } measDat = new temperData[m.size()]; for (int i = 0; i < measDat.length; i++) { measDat[i] = new temperData(this, i + 1, m.get(i)); } } private static void drawRightAlighed(Graphics2D g2d, int mx10, int y, String s) { FontMetrics fm = g2d.getFontMetrics(); g2d.drawString(s, mx10 - fm.stringWidth(s), y); } private static void putStart(ByteArrayOutputStream buf, String tit, String res) throws Exception { buf.write("<!DOCTYPE html><html lang=\"en\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\" /><meta http-equiv=refresh content=\"3;url=/index.html\"><title>".getBytes()); buf.write(tit.getBytes()); buf.write("</title><body>".getBytes()); buf.write(res.getBytes()); buf.write("</body></html>".getBytes()); } private temperCode findCode(String s) { for (int i = 0; i < doorCode.size(); i++) { temperCode cur = doorCode.get(i); if (!s.equals(cur.code)) { continue; } return cur; } return null; } private BufferedImage drawHist(List<temperHist> hst, int dot) { float tmpMin = Float.MAX_VALUE; float tmpMax = Float.MIN_VALUE; for (int o = 0; o < hst.size(); o++) { temperHist l = hst.get(o); tmpMin = Float.min(tmpMin, l.need); tmpMax = Float.max(tmpMax, l.need); for (int i = 0; i < l.meas.length; i++) { float v = l.meas[i]; tmpMin = Float.min(tmpMin, v); tmpMax = Float.max(tmpMax, v); } } tmpMax -= tmpMin; final int mx = 1800; final int my = 900; final int mx10 = mx - 10; final int mx20 = mx - 20; final int my1 = my - 1; final int my10 = my - 10; final int my20 = my - 20; final int my30 = my - 30; final int my40 = my - 40; final int my50 = my - 50; BufferedImage img = new BufferedImage(mx, my, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(Color.gray); g2d.setFont(new Font("Serif", Font.BOLD, 20)); g2d.setPaint(Color.gray); g2d.fillRect(0, 0, img.getWidth(), img.getHeight()); g2d.setPaint(Color.black); Color colors[] = { Color.green, Color.red, Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow, Color.white, Color.blue,}; for (int o = 0; o < hst.size(); o++) { temperHist l = hst.get(o); int x = ((o * mx20) / hst.size()) + 10; g2d.setPaint(Color.black); g2d.drawRect(x, my10 - (int) (((l.need - tmpMin) * my20) / tmpMax), dot, dot); if (l.curr != 0) { g2d.drawRect(x, 10, dot, dot); } for (int i = 0; i < l.meas.length; i++) { g2d.setPaint(colors[i]); g2d.drawRect(x, my10 - (int) (((l.meas[i] - tmpMin) * my20) / tmpMax), dot, dot); } } for (int i = 0; i < measDat.length; i++) { g2d.setPaint(colors[i]); drawRightAlighed(g2d, mx10, my50 - (i * 20), measDat[i].myNam); } g2d.setPaint(Color.black); drawRightAlighed(g2d, mx10, my30, "needed"); for (int i = 20; i < my20; i += 50) { float v = (float) i * tmpMax; v = v / (float) my20; v += tmpMin; String a = v + " "; g2d.drawString(a.substring(0, 6), 1, my10 - i); } String a; if ((hst.get(hst.size() - 1).time - hst.get(0).time) < (86400 * 3000)) { a = "HH:mm"; } else { a = "MMMdd"; } for (int i = 0; i < mx20; i += 100) { temperHist l = hst.get((i * hst.size()) / mx20); DateFormat dat = new SimpleDateFormat(a, Locale.US); g2d.drawString(dat.format(new Date((long) l.time)), i + 10, my1); } return img; } private boolean checkPeer(ByteArrayOutputStream buf, String peer) throws Exception { if (allowIp == null) { return false; } if (allowIp.indexOf(";" + peer + ";") >= 0) { return false; } putStart(buf, "restricted", "you are not allowed"); return true; } /** * do one request * * @param par parameters * @param buf buffer to use * @param peer address * @return 1 on html result * @throws Exception on error */ public synchronized int doRequest(String[] par, ByteArrayOutputStream buf, String peer) throws Exception { String tmp = ""; String cmd = ""; for (int i = 0; i < par.length; i++) { String a = par[i]; int o = a.indexOf("="); if (o < 1) { continue; } String b = a.substring(0, o); a = a.substring(o + 1, a.length()); if (b.equals("temp")) { tmp = a; } if (b.equals("cmd")) { cmd = a; } } if (cmd.equals("heat")) { if (checkPeer(buf, peer)) { return 1; } lastNeeded = temperUtil.str2num(tmp); timeNeeded = temperUtil.getTime(); lastSetter = peer; rangeCheck(); } if (cmd.equals("relayor")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue | i); cmd = "relayset"; } if (cmd.equals("relayand")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue & i); cmd = "relayset"; } if (cmd.equals("relayxor")) { int i = ((int) temperUtil.str2num(tmp)) & relayPin; tmp = "" + (currValue ^ i); cmd = "relayset"; } if (cmd.equals("relayset")) { if (checkPeer(buf, peer)) { return 1; } if (relayPin == 0) { putStart(buf, "relay", "relay not set"); return 1; } int i = ((int) temperUtil.str2num(tmp)) & relayPin; setValue((currValue & (~relayPin)) | i); writeLog(peer); putStart(buf, "relay", "relay set to " + i + " from range " + relayPin); return 1; } if (cmd.equals("guests")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp) { putStart(buf, "door", "disabled code"); return 1; } doorTemp = true; putStart(buf, "door", "guests enabled"); return 1; } if (cmd.equals("closed")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp) { putStart(buf, "door", "disabled code"); return 1; } doorTemp = false; putStart(buf, "door", "guests disabled"); return 1; } if (cmd.equals("door")) { if (checkPeer(buf, peer)) { return 1; } temperCode res = findCode(tmp); if (res == null) { putStart(buf, "door", "invalid code"); return 1; } if (res.temp && (!doorTemp)) { putStart(buf, "door", "disabled code"); return 1; } setValue(currValue | doorPin); writeLog(peer); temperUtil.sleep(doorTime); setValue(currValue & (~doorPin)); writeLog(peer); doorLog.add(new temperLog(this, peer, res.myNum)); for (;;) { if (doorLog.size() <= doorMax) { break; } doorLog.remove(0); } doorCnt++; putStart(buf, "door", "door opened"); return 1; } if (cmd.equals("history")) { temperData cur = measDat[(int) temperUtil.str2num(tmp) - 1]; ImageIO.write(drawHist(cur.histDat, 10), "png", buf); return 2; } if (!cmd.equals("graph")) { rangeCheck(); String a = "<!DOCTYPE html><html lang=\"en\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /><link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\" /><title>temper</title>"; buf.write(a.getBytes()); a = "<meta http-equiv=refresh content=\"30;url=" + url + "\"></head><body>"; buf.write(a.getBytes()); long tim = temperUtil.getTime(); a = "<table><thead><tr><td><b>num</b></td><td><b>name</b></td><td><b>value</b></td><td><b>last</b></td><td><b>err</b></td><td><b>read</b></td><td><b>work</b></td><td><b>win</b></td><td><b>res</b></td><td><b>hst</b></td><td><b>wtmp</b></td><td><b>wtim</b></td></tr></thead><tbody>"; buf.write(a.getBytes()); for (int i = 0; i < measDat.length; i++) { a = measDat[i].getMeas(); buf.write(a.getBytes()); } a = "</tbody></table><br/>"; buf.write(a.getBytes()); a = "tolerance: heat " + heatTol + ", cool " + coolTol + ", vent " + ventTol + ", window " + windowTol + ", time " + temperUtil.timePast(windowTim, 0) + "<br/>"; buf.write(a.getBytes()); a = "needed: " + lastNeeded + " celsius, since " + temperUtil.time2str(tzdata, timeNeeded) + ", " + temperUtil.timePast(tim, timeNeeded) + " ago by " + lastSetter + "<br/>"; buf.write(a.getBytes()); a = "doing: " + currValue + ", since " + temperUtil.time2str(tzdata, timeHeating) + ", " + temperUtil.timePast(tim, timeHeating) + " ago, using #" + (measIn + 1) + "/#" + (measOut + 1) + " for " + temperUtil.timePast(measTime, 0) + "<br/>"; buf.write(a.getBytes()); a = "<form action=\"" + url + "\" method=get>wish: <input type=text name=temp value=\"" + lastNeeded + "\"> celsius (" + tempMin + "-" + tempMax + ")"; buf.write(a.getBytes()); buf.write("<input type=submit name=cmd value=\"heat\">".getBytes()); buf.write("<input type=submit name=cmd value=\"graph\">".getBytes()); buf.write("</form><br/>".getBytes()); for (int i = -3; i <= 3; i++) { int o = i + (int) lastNeeded; a = "((<a href=\"" + url + "?temp=" + o + ".0&cmd=heat\">" + o + ".0</a>))"; buf.write(a.getBytes()); a = "((<a href=\"" + url + "?temp=" + o + ".5&cmd=heat\">" + o + ".5</a>))"; buf.write(a.getBytes()); } a = "<br/><br/>the door was opened " + doorCnt + " times:<br/>"; buf.write(a.getBytes()); a = "<table><thead><tr><td><b>num</b></td><td><b>when</b></td><td><b>ago</b></td><td><b>code</b></td><td><b>peer</b></td></tr></thead><tbody>"; buf.write(a.getBytes()); for (int i = doorLog.size() - 1; i >= 0; i--) { a = doorLog.get(i).getMeas(i, tim); buf.write(a.getBytes()); } a = "</tbody></table><br/>"; buf.write(a.getBytes()); buf.write("</body></html>".getBytes()); return 1; } File fi = new File(logFile); FileReader fr = new FileReader(fi); fr.skip(fi.length() - (long) (temperUtil.str2num(tmp) * 64000)); BufferedReader f = new BufferedReader(fr); f.readLine(); List<temperHist> history = new ArrayList<temperHist>(); while (f.ready()) { String s = f.readLine(); temperHist l = new temperHist(); l.parseLine(s); history.add(l); } f.close(); ImageIO.write(drawHist(history, 1), "png", buf); return 2; } }
186682_0
package les6.Practicum6A; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class GameTest { private Game game1JrOud; private int ditJaar; @BeforeEach public void init(){ ditJaar = LocalDate.now().getYear(); game1JrOud = new Game("Mario Kart", ditJaar-1, 50.0); } //region Tests met huidigeWaarde() @Test public void testHuidigeWaardeNwPrijsNa0Jr(){ Game game0JrOud = new Game("Mario Kart", ditJaar, 50.0); assertEquals(50.0, Math.round(game0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 0 jr niet correct."); } @Test public void testHuidigeWaardeNwPrijsNa1Jr(){ assertEquals(35.0, Math.round(game1JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 1 jr niet correct."); } @Test public void testHuidigeWaardeNwPrijsNa5Jr(){ Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0); assertEquals(8.4, Math.round(game5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 5 jr niet correct."); } @Test public void testHuidigeWaardeGratisGameNa0Jr(){ Game gratisGame0JrOud = new Game("Mario Kart Free", ditJaar, 0.0); assertEquals(0.0, Math.round(gratisGame0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 0 jr niet correct."); } @Test public void testHuidigeWaardeGratisGameNa5Jr(){ Game gratisGame5JrOud = new Game("Mario Kart Free", ditJaar-5, 0.0); assertEquals(0.0, Math.round(gratisGame5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 5 jr niet correct."); } //endregion //region Tests met equals() @Test public void testGameEqualsZelfdeGame() { Game zelfdeGame1JrOud = new Game("Mario Kart", ditJaar-1, 50.0); assertTrue(game1JrOud.equals(zelfdeGame1JrOud), "equals() geeft false bij vgl. met zelfde game"); } @Test public void testGameEqualsSelf() { assertTrue(game1JrOud.equals(game1JrOud), "equals() geeft false bij vgl. met zichzelf"); } @Test public void testGameNotEqualsString() { assertFalse(game1JrOud.equals("testString"), "equals() geeft true bij vgl. tussen game en String"); } @Test public void testGameNotEqualsGameAndereNaam() { Game otherGame1JrOud = new Game("Zelda", ditJaar-1, 35.0); assertFalse(game1JrOud.equals(otherGame1JrOud), "equals() geeft true bij vgl. met game met andere naam"); } @Test public void testGameNotEqualsGameAnderJaar() { Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0); assertFalse(game1JrOud.equals(game5JrOud), "equals() geeft true bij vgl. met game met ander releaseJaar"); } @Test public void testGameEqualsGameAndereNwPrijs() { Game duurdereGame1JrOud = new Game("Mario Kart", ditJaar-1, 59.95); assertTrue(game1JrOud.equals(duurdereGame1JrOud), "equals() geeft false bij vgl. met zelfde game met andere nieuwprijs"); } @Test public void testGameNotEqualsGameHeelAndereGame() { Game heelAndereGame = new Game("Zelda", ditJaar-2, 41.95); assertFalse(game1JrOud.equals(heelAndereGame), "equals() geeft true bij vgl. met heel andere game"); } //endregion @Test public void testToString(){ assertEquals("Mario Kart, uitgegeven in " + (ditJaar-1) + "; nieuwprijs: €50,00 nu voor: €35,00", game1JrOud.toString(), "toString() geeft niet de juiste tekst terug."); } }
rosstuck/practica-tests
test/les6/Practicum6A/GameTest.java
1,323
//region Tests met huidigeWaarde()
line_comment
nl
package les6.Practicum6A; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class GameTest { private Game game1JrOud; private int ditJaar; @BeforeEach public void init(){ ditJaar = LocalDate.now().getYear(); game1JrOud = new Game("Mario Kart", ditJaar-1, 50.0); } //region Tests<SUF> @Test public void testHuidigeWaardeNwPrijsNa0Jr(){ Game game0JrOud = new Game("Mario Kart", ditJaar, 50.0); assertEquals(50.0, Math.round(game0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 0 jr niet correct."); } @Test public void testHuidigeWaardeNwPrijsNa1Jr(){ assertEquals(35.0, Math.round(game1JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 1 jr niet correct."); } @Test public void testHuidigeWaardeNwPrijsNa5Jr(){ Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0); assertEquals(8.4, Math.round(game5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde na 5 jr niet correct."); } @Test public void testHuidigeWaardeGratisGameNa0Jr(){ Game gratisGame0JrOud = new Game("Mario Kart Free", ditJaar, 0.0); assertEquals(0.0, Math.round(gratisGame0JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 0 jr niet correct."); } @Test public void testHuidigeWaardeGratisGameNa5Jr(){ Game gratisGame5JrOud = new Game("Mario Kart Free", ditJaar-5, 0.0); assertEquals(0.0, Math.round(gratisGame5JrOud.huidigeWaarde() * 100)/100d, "Huidige waarde gratis game na 5 jr niet correct."); } //endregion //region Tests met equals() @Test public void testGameEqualsZelfdeGame() { Game zelfdeGame1JrOud = new Game("Mario Kart", ditJaar-1, 50.0); assertTrue(game1JrOud.equals(zelfdeGame1JrOud), "equals() geeft false bij vgl. met zelfde game"); } @Test public void testGameEqualsSelf() { assertTrue(game1JrOud.equals(game1JrOud), "equals() geeft false bij vgl. met zichzelf"); } @Test public void testGameNotEqualsString() { assertFalse(game1JrOud.equals("testString"), "equals() geeft true bij vgl. tussen game en String"); } @Test public void testGameNotEqualsGameAndereNaam() { Game otherGame1JrOud = new Game("Zelda", ditJaar-1, 35.0); assertFalse(game1JrOud.equals(otherGame1JrOud), "equals() geeft true bij vgl. met game met andere naam"); } @Test public void testGameNotEqualsGameAnderJaar() { Game game5JrOud = new Game("Mario Kart", ditJaar-5, 50.0); assertFalse(game1JrOud.equals(game5JrOud), "equals() geeft true bij vgl. met game met ander releaseJaar"); } @Test public void testGameEqualsGameAndereNwPrijs() { Game duurdereGame1JrOud = new Game("Mario Kart", ditJaar-1, 59.95); assertTrue(game1JrOud.equals(duurdereGame1JrOud), "equals() geeft false bij vgl. met zelfde game met andere nieuwprijs"); } @Test public void testGameNotEqualsGameHeelAndereGame() { Game heelAndereGame = new Game("Zelda", ditJaar-2, 41.95); assertFalse(game1JrOud.equals(heelAndereGame), "equals() geeft true bij vgl. met heel andere game"); } //endregion @Test public void testToString(){ assertEquals("Mario Kart, uitgegeven in " + (ditJaar-1) + "; nieuwprijs: €50,00 nu voor: €35,00", game1JrOud.toString(), "toString() geeft niet de juiste tekst terug."); } }
196166_4
/** * Roundware Android code is released under the terms of the GNU General Public License. * See COPYRIGHT.txt, AUTHORS.txt, and LICENSE.txt in the project root directory for details. */ package org.roundware.service; import android.content.Context; import android.util.Log; import org.roundware.service.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.UUID; /** * Project configuration parameters. * * Note: the use of getters and setters in this class is deliberate, the * Behavior and access to the parameters of the configuration might be * changed in the future. * * @author Rob Knapen */ public class RWConfiguration { // debugging private final static String TAG = "RWConfiguration"; private final static boolean D = false; // data source public final static int DEFAULTS = 0; public final static int FROM_CACHE = 1; public final static int FROM_SERVER = 2; // json names private final static String JSON_KEY_CONFIG_SECTION_DEVICE = "device"; private final static String JSON_KEY_CONFIG_DEVICE_ID = "device_id"; private final static String JSON_KEY_CONFIG_SECTION_SESSION = "session"; private final static String JSON_KEY_CONFIG_SESSION_ID = "session_id"; private final static String JSON_KEY_CONFIG_SECTION_PROJECT = "project"; private final static String JSON_KEY_CONFIG_PROJECT_ID = "project_id"; private final static String JSON_KEY_CONFIG_PROJECT_NAME = "project_name"; private final static String JSON_KEY_CONFIG_HEARTBEAT_TIMER_SEC = "heartbeat_timer"; private final static String JSON_KEY_CONFIG_MAX_RECORDING_LENGTH_SEC = "max_recording_length"; private final static String JSON_KEY_CONFIG_SHARING_MESSAGE = "sharing_message"; private final static String JSON_KEY_CONFIG_SHARING_URL = "sharing_url"; private final static String JSON_KEY_CONFIG_LEGAL_AGREEMENT = "legal_agreement"; private final static String JSON_KEY_CONFIG_DYNAMIC_LISTEN_TAGS = "listen_questions_dynamic"; private final static String JSON_KEY_CONFIG_DYNAMIC_SPEAK_TAGS = "speak_questions_dynamic"; private final static String JSON_KEY_CONFIG_GEO_LISTEN_ENABLED = "geo_listen_enabled"; private final static String JSON_KEY_CONFIG_GEO_SPEAK_ENABLED = "geo_speak_enabled"; private final static String JSON_KEY_CONFIG_LISTEN_ENABLED = "listen_enabled"; private final static String JSON_KEY_CONFIG_SPEAK_ENABLED = "speak_enabled"; private final static String JSON_KEY_CONFIG_FILES_URL = "files_url"; private final static String JSON_KEY_CONFIG_FILES_VERSION = "files_version"; private final static String JSON_KEY_CONFIG_SECTION_SERVER = "server"; private final static String JSON_KEY_CONFIG_CURRENT_VERSION = "version"; // not yet returned by server: private final static String JSON_KEY_CONFIG_STREAM_METADATA_ENABLED = "stream_metadata_enabled"; private final static String JSON_KEY_CONFIG_RESET_TAG_DEFAULTS_ON_STARTUP = "reset_tag_defaults_on_startup"; private final static String JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_TIME_MSEC = "min_location_update_time_msec"; private final static String JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_DISTANCE_METER = "min_location_update_distance_meter"; private final static String JSON_KEY_CONFIG_USE_GPS_IF_POSSIBLE = "use_gps_if_possible"; private final static String JSON_KEY_CONFIG_HTTP_TIMEOUT_SEC = "http_timeout_sec"; // json parsing error message public final static String JSON_SYNTAX_ERROR_MESSAGE = "Invalid server response received!"; private int mDataSource = DEFAULTS; private String mDeviceId = UUID.randomUUID().toString(); private String mProjectId = null; private String mSessionId = null; private String mProjectName = null; // (web) content file management private String mContentFilesUrl = null; private int mContentFilesVersion = -1; private boolean mContentFilesAlwaysDownload = false; // timing variables private int mHeartbeatTimerSec = 15; private int mQueueCheckIntervalSec = 60; private int mStreamMetadataTimerIntervalMSec = 2000; private int mMaxRecordingTimeSec = 30; // social sharing private String mSharingUrl = null; private String mSharingMessage = null; private String mLegalAgreement = null; // listen questions can change (e.g. based on location) private boolean mDynamicListenQuestions = false; // speak questions can change (e.g. based on location) private boolean mDynamicSpeakQuestions = false; // allow audio playing functionality for the project private boolean mListenEnabled = true; // allow recording functionality for the project private boolean mSpeakEnabled = true; // enable sending location updates while stream is playing private boolean mGeoListenEnabled = false; // enable adding location (one-shot update) to recording private boolean mGeoSpeakEnabled = false; // use defaults for tag selection on app startup, do not restore them private boolean mResetTagDefaultsOnStartup = true; // enabled tracking of stream metadata private boolean mStreamMetadataEnabled = false; /* The frequency of notification or new locations may be controlled using * the minTime and minDistance parameters. If minTime is greater than 0, the * LocationManager could potentially rest for minTime milliseconds between * location updates to conserve power. If minDistance is greater than 0, a * location will only be broadcast if the device moves by minDistance meters. * To obtain notifications as frequently as possible, set both parameters to 0. */ private long mMinLocationUpdateTimeMSec = 60000; private double mMinLocationUpdateDistanceMeter = 5.0; /** * Use GPS for location tracking if possible on the device. It needs to be * present and activated for this to work. Using GPS indoors is not a good * idea, since it will have a hard time getting a position fix from the * satellites. If possible stick with lesser accurate WiFi or network * location and do not try to use the GPS. */ private boolean mUseGpsIfPossible = false; // http call timeout private int mHttpTimeOutSec = 45; // current Roundware software version on the server private String mServerVersion = null; /** * Creates an instance and fills it with default values read from the * resources. */ public RWConfiguration(Context context) { mDataSource = DEFAULTS; // overwrite defaults from resources if (context != null) { String val; val = context.getString(R.string.rw_spec_heartbeat_interval_in_sec); mHeartbeatTimerSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_queue_check_interval_in_sec); mQueueCheckIntervalSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_stream_metadata_timer_interval_in_msec); mStreamMetadataTimerIntervalMSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_min_location_update_time_msec); mMinLocationUpdateTimeMSec = Long.valueOf(val); val = context.getString(R.string.rw_spec_min_location_update_distance_meters); mMinLocationUpdateDistanceMeter = Double.valueOf(val); val = context.getString(R.string.rw_spec_files_url); mContentFilesUrl = val; val = context.getString(R.string.rw_spec_files_version); if (val != null) { mContentFilesVersion = Integer.valueOf(val); } mContentFilesAlwaysDownload = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_files_always_download)); mListenEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_listen_enabled_yn)); mGeoListenEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_geo_listen_enabled_yn)); mSpeakEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_speak_enabled_yn)); mGeoSpeakEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_geo_speak_enabled_yn)); mStreamMetadataEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_stream_metadata_enabled_yn)); mResetTagDefaultsOnStartup = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_reset_tag_defaults_on_startup_yn)); mUseGpsIfPossible = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_use_gps_if_possible)); } } /** * Overwrites configuration values from the specified key-value map. * If there is no matching key in the map, the value will remain * unchanged. * * @param jsonResponse to process * @param fromCache true if using cached data */ public void assignFromJsonServerResponse(String jsonResponse, boolean fromCache) { JSONObject specs = null; try { JSONArray entries = new JSONArray(jsonResponse); for (int i = 0; i < entries.length(); i++) { JSONObject jsonObj = entries.getJSONObject(i); if (D) { Log.d(TAG, jsonObj.toString()); } if (jsonObj.has(JSON_KEY_CONFIG_SECTION_DEVICE)) { // decode section with device specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_DEVICE); setDeviceId(specs.optString(JSON_KEY_CONFIG_DEVICE_ID, getDeviceId())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_SESSION)) { // decode section with session specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_SESSION); setSessionId(specs.optString(JSON_KEY_CONFIG_SESSION_ID, getSessionId())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_PROJECT)) { // decode section with project specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_PROJECT); setProjectId(specs.optString(JSON_KEY_CONFIG_PROJECT_ID, getProjectId())); setProjectName(specs.optString(JSON_KEY_CONFIG_PROJECT_NAME, getProjectName())); setContentFilesUrl(specs.optString(JSON_KEY_CONFIG_FILES_URL, getContentFilesUrl())); setContentFilesVersion(specs.optInt(JSON_KEY_CONFIG_FILES_VERSION, getContentFilesVersion())); setHeartbeatTimerSec(specs.optInt(JSON_KEY_CONFIG_HEARTBEAT_TIMER_SEC, getHeartbeatTimerSec())); setMaxRecordingTimeSec(specs.optInt(JSON_KEY_CONFIG_MAX_RECORDING_LENGTH_SEC, getMaxRecordingTimeSec())); setSharingMessage(specs.optString(JSON_KEY_CONFIG_SHARING_MESSAGE, getSharingMessage())); setSharingUrl(specs.optString(JSON_KEY_CONFIG_SHARING_URL, getSharingUrl())); setLegalAgreement(specs.optString(JSON_KEY_CONFIG_LEGAL_AGREEMENT, getLegalAgreement())); setDynamicListenQuestions(specs.optBoolean(JSON_KEY_CONFIG_DYNAMIC_LISTEN_TAGS, isDynamicListenQuestions())); setDynamicSpeakQuestions(specs.optBoolean(JSON_KEY_CONFIG_DYNAMIC_SPEAK_TAGS, isDynamicSpeakQuestions())); setListenEnabled(specs.optBoolean(JSON_KEY_CONFIG_LISTEN_ENABLED, isListenEnabled())); setGeoListenEnabled(specs.optBoolean(JSON_KEY_CONFIG_GEO_LISTEN_ENABLED, isGeoListenEnabled())); setSpeakEnabled(specs.optBoolean(JSON_KEY_CONFIG_SPEAK_ENABLED, isSpeakEnabled())); setGeoSpeakEnabled(specs.optBoolean(JSON_KEY_CONFIG_GEO_SPEAK_ENABLED, isGeoSpeakEnabled())); setResetTagsDefaultsOnStartup(specs.optBoolean(JSON_KEY_CONFIG_RESET_TAG_DEFAULTS_ON_STARTUP, isResetTagsDefaultOnStartup())); setStreamMetadataEnabled(specs.optBoolean(JSON_KEY_CONFIG_STREAM_METADATA_ENABLED, isStreamMetadataEnabled())); setMinLocationUpdateTimeMSec(specs.optLong(JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_TIME_MSEC, getMinLocationUpdateTimeMSec())); setMinLocationUpdateDistanceMeter(specs.optDouble(JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_DISTANCE_METER, getMinLocationUpdateDistanceMeter())); setHttpTimeOutSec(specs.optInt(JSON_KEY_CONFIG_HTTP_TIMEOUT_SEC, getHttpTimeOutSec())); setUseGpsIfPossible(specs.optBoolean(JSON_KEY_CONFIG_USE_GPS_IF_POSSIBLE, getUseGpsIfPossible())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_SERVER)) { specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_SERVER); setServerVersion(specs.optString(JSON_KEY_CONFIG_CURRENT_VERSION, getServerVersion())); } } mDataSource = fromCache ? FROM_CACHE : FROM_SERVER; if (fromCache) { setSessionId(null); } } catch (JSONException e) { Log.e(TAG, JSON_SYNTAX_ERROR_MESSAGE, e); } } /** * Returns true if any of the configuration parameters related to the use * of device location is true. * * @return true if configuration requires use of device location services */ public boolean isUsingLocation() { return isUsingLocationBasedListen() || isUsingLocationBasedSpeak(); } /*** * Returns true if any of the configuration parameters related to Listen * functionality require use of device positioning. * * @return true if positioning is needed for Listen functionality */ public boolean isUsingLocationBasedListen() { return isGeoListenEnabled() || isDynamicListenQuestions(); } /*** * Returns true if any of the configuration parameters related to Speak * functionality require use of device positioning. * * @return true if positioning is needed for Speak functionality */ public boolean isUsingLocationBasedSpeak() { return isGeoSpeakEnabled() || isDynamicSpeakQuestions(); } public String getDeviceId() { return mDeviceId; } public void setDeviceId(String deviceId) { mDeviceId = deviceId; } public String getProjectId() { return mProjectId; } public void setProjectId(String projectId) { mProjectId = projectId; } public String getSessionId() { return mSessionId; } public void setSessionId(String sessionId) { mSessionId = sessionId; } public String getProjectName() { return mProjectName; } public void setProjectName(String projectName) { mProjectName = projectName; } public int getHeartbeatTimerSec() { return mHeartbeatTimerSec; } public void setHeartbeatTimerSec(int heartbeatTimerSec) { mHeartbeatTimerSec = heartbeatTimerSec; } public int getQueueCheckIntervalSec() { return mQueueCheckIntervalSec; } public void setQueueCheckIntervalSec(int queueCheckIntervalSec) { mQueueCheckIntervalSec = queueCheckIntervalSec; } public int getStreamMetadataTimerIntervalMSec() { return mStreamMetadataTimerIntervalMSec; } public void setStreamMetadataTimerIntervalMSec(int metadataTimerIntervalMSec) { mStreamMetadataTimerIntervalMSec = metadataTimerIntervalMSec; } public int getMaxRecordingTimeSec() { return mMaxRecordingTimeSec; } public void setMaxRecordingTimeSec(int maxRecordingTimeSec) { mMaxRecordingTimeSec = maxRecordingTimeSec; } public String getSharingUrl() { return mSharingUrl; } public void setSharingUrl(String sharingUrl) { mSharingUrl = sharingUrl; } public String getSharingMessage() { return mSharingMessage; } public void setSharingMessage(String sharingMessage) { mSharingMessage = sharingMessage; } public String getLegalAgreement() { return mLegalAgreement; } public void setLegalAgreement(String legalAgreement) { mLegalAgreement = legalAgreement; } public boolean isDynamicListenQuestions() { return mDynamicListenQuestions; } public void setDynamicListenQuestions(boolean dynamicListenQuestions) { mDynamicListenQuestions = dynamicListenQuestions; } public boolean isDynamicSpeakQuestions() { return mDynamicSpeakQuestions; } public void setDynamicSpeakQuestions(boolean dynamicSpeakQuestions) { mDynamicSpeakQuestions = dynamicSpeakQuestions; } public boolean isGeoListenEnabled() { return mGeoListenEnabled; } public void setGeoListenEnabled(boolean geoListenEnabled) { mGeoListenEnabled = geoListenEnabled; } public boolean isSpeakEnabled() { return mSpeakEnabled; } public void setSpeakEnabled(boolean speakEnabled) { mSpeakEnabled = speakEnabled; } public boolean isGeoSpeakEnabled() { return mGeoSpeakEnabled; } public void setGeoSpeakEnabled(boolean geoSpeakEnabled) { mGeoSpeakEnabled = geoSpeakEnabled; } public boolean isResetTagsDefaultOnStartup() { return mResetTagDefaultsOnStartup; } public void setResetTagsDefaultsOnStartup(boolean resetTagsDefaultsOnStartup) { mResetTagDefaultsOnStartup = resetTagsDefaultsOnStartup; } public long getMinLocationUpdateTimeMSec() { return mMinLocationUpdateTimeMSec; } public void setMinLocationUpdateTimeMSec(long minLocationUpdateTimeMSec) { mMinLocationUpdateTimeMSec = minLocationUpdateTimeMSec; } public double getMinLocationUpdateDistanceMeter() { return mMinLocationUpdateDistanceMeter; } public void setMinLocationUpdateDistanceMeter(double minLocationUpdateDistanceMeter) { mMinLocationUpdateDistanceMeter = minLocationUpdateDistanceMeter; } public int getHttpTimeOutSec() { return mHttpTimeOutSec; } public void setHttpTimeOutSec(int httpTimeOutSec) { mHttpTimeOutSec = httpTimeOutSec; } public int getDataSource() { return mDataSource; } public String getServerVersion() { return mServerVersion; } public void setServerVersion(String serverVersion) { mServerVersion = serverVersion; } public boolean isListenEnabled() { return mListenEnabled; } public void setListenEnabled(boolean listenEnabled) { mListenEnabled = listenEnabled; } public boolean isStreamMetadataEnabled() { return mStreamMetadataEnabled; } public void setStreamMetadataEnabled(boolean streamMetadataEnabled) { mStreamMetadataEnabled = streamMetadataEnabled; } public String getContentFilesUrl() { return mContentFilesUrl; } public void setContentFilesUrl(String filesUrl) { mContentFilesUrl = filesUrl; } public int getContentFilesVersion() { return mContentFilesVersion; } public void setContentFilesVersion(int filesVersion) { mContentFilesVersion = filesVersion; } public boolean isContentFilesAlwaysDownload() { return mContentFilesAlwaysDownload; } public void setUseGpsIfPossible(boolean useGps) { mUseGpsIfPossible = useGps; } public boolean getUseGpsIfPossible() { return mUseGpsIfPossible; } public void setContentFilesAlwaysDownload(boolean contentFilesAlwaysDownload) { mContentFilesAlwaysDownload = contentFilesAlwaysDownload; } }
roundware/roundware-android
rwservice/src/main/java/org/roundware/service/RWConfiguration.java
5,663
// (web) content file management
line_comment
nl
/** * Roundware Android code is released under the terms of the GNU General Public License. * See COPYRIGHT.txt, AUTHORS.txt, and LICENSE.txt in the project root directory for details. */ package org.roundware.service; import android.content.Context; import android.util.Log; import org.roundware.service.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.UUID; /** * Project configuration parameters. * * Note: the use of getters and setters in this class is deliberate, the * Behavior and access to the parameters of the configuration might be * changed in the future. * * @author Rob Knapen */ public class RWConfiguration { // debugging private final static String TAG = "RWConfiguration"; private final static boolean D = false; // data source public final static int DEFAULTS = 0; public final static int FROM_CACHE = 1; public final static int FROM_SERVER = 2; // json names private final static String JSON_KEY_CONFIG_SECTION_DEVICE = "device"; private final static String JSON_KEY_CONFIG_DEVICE_ID = "device_id"; private final static String JSON_KEY_CONFIG_SECTION_SESSION = "session"; private final static String JSON_KEY_CONFIG_SESSION_ID = "session_id"; private final static String JSON_KEY_CONFIG_SECTION_PROJECT = "project"; private final static String JSON_KEY_CONFIG_PROJECT_ID = "project_id"; private final static String JSON_KEY_CONFIG_PROJECT_NAME = "project_name"; private final static String JSON_KEY_CONFIG_HEARTBEAT_TIMER_SEC = "heartbeat_timer"; private final static String JSON_KEY_CONFIG_MAX_RECORDING_LENGTH_SEC = "max_recording_length"; private final static String JSON_KEY_CONFIG_SHARING_MESSAGE = "sharing_message"; private final static String JSON_KEY_CONFIG_SHARING_URL = "sharing_url"; private final static String JSON_KEY_CONFIG_LEGAL_AGREEMENT = "legal_agreement"; private final static String JSON_KEY_CONFIG_DYNAMIC_LISTEN_TAGS = "listen_questions_dynamic"; private final static String JSON_KEY_CONFIG_DYNAMIC_SPEAK_TAGS = "speak_questions_dynamic"; private final static String JSON_KEY_CONFIG_GEO_LISTEN_ENABLED = "geo_listen_enabled"; private final static String JSON_KEY_CONFIG_GEO_SPEAK_ENABLED = "geo_speak_enabled"; private final static String JSON_KEY_CONFIG_LISTEN_ENABLED = "listen_enabled"; private final static String JSON_KEY_CONFIG_SPEAK_ENABLED = "speak_enabled"; private final static String JSON_KEY_CONFIG_FILES_URL = "files_url"; private final static String JSON_KEY_CONFIG_FILES_VERSION = "files_version"; private final static String JSON_KEY_CONFIG_SECTION_SERVER = "server"; private final static String JSON_KEY_CONFIG_CURRENT_VERSION = "version"; // not yet returned by server: private final static String JSON_KEY_CONFIG_STREAM_METADATA_ENABLED = "stream_metadata_enabled"; private final static String JSON_KEY_CONFIG_RESET_TAG_DEFAULTS_ON_STARTUP = "reset_tag_defaults_on_startup"; private final static String JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_TIME_MSEC = "min_location_update_time_msec"; private final static String JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_DISTANCE_METER = "min_location_update_distance_meter"; private final static String JSON_KEY_CONFIG_USE_GPS_IF_POSSIBLE = "use_gps_if_possible"; private final static String JSON_KEY_CONFIG_HTTP_TIMEOUT_SEC = "http_timeout_sec"; // json parsing error message public final static String JSON_SYNTAX_ERROR_MESSAGE = "Invalid server response received!"; private int mDataSource = DEFAULTS; private String mDeviceId = UUID.randomUUID().toString(); private String mProjectId = null; private String mSessionId = null; private String mProjectName = null; // (web) content<SUF> private String mContentFilesUrl = null; private int mContentFilesVersion = -1; private boolean mContentFilesAlwaysDownload = false; // timing variables private int mHeartbeatTimerSec = 15; private int mQueueCheckIntervalSec = 60; private int mStreamMetadataTimerIntervalMSec = 2000; private int mMaxRecordingTimeSec = 30; // social sharing private String mSharingUrl = null; private String mSharingMessage = null; private String mLegalAgreement = null; // listen questions can change (e.g. based on location) private boolean mDynamicListenQuestions = false; // speak questions can change (e.g. based on location) private boolean mDynamicSpeakQuestions = false; // allow audio playing functionality for the project private boolean mListenEnabled = true; // allow recording functionality for the project private boolean mSpeakEnabled = true; // enable sending location updates while stream is playing private boolean mGeoListenEnabled = false; // enable adding location (one-shot update) to recording private boolean mGeoSpeakEnabled = false; // use defaults for tag selection on app startup, do not restore them private boolean mResetTagDefaultsOnStartup = true; // enabled tracking of stream metadata private boolean mStreamMetadataEnabled = false; /* The frequency of notification or new locations may be controlled using * the minTime and minDistance parameters. If minTime is greater than 0, the * LocationManager could potentially rest for minTime milliseconds between * location updates to conserve power. If minDistance is greater than 0, a * location will only be broadcast if the device moves by minDistance meters. * To obtain notifications as frequently as possible, set both parameters to 0. */ private long mMinLocationUpdateTimeMSec = 60000; private double mMinLocationUpdateDistanceMeter = 5.0; /** * Use GPS for location tracking if possible on the device. It needs to be * present and activated for this to work. Using GPS indoors is not a good * idea, since it will have a hard time getting a position fix from the * satellites. If possible stick with lesser accurate WiFi or network * location and do not try to use the GPS. */ private boolean mUseGpsIfPossible = false; // http call timeout private int mHttpTimeOutSec = 45; // current Roundware software version on the server private String mServerVersion = null; /** * Creates an instance and fills it with default values read from the * resources. */ public RWConfiguration(Context context) { mDataSource = DEFAULTS; // overwrite defaults from resources if (context != null) { String val; val = context.getString(R.string.rw_spec_heartbeat_interval_in_sec); mHeartbeatTimerSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_queue_check_interval_in_sec); mQueueCheckIntervalSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_stream_metadata_timer_interval_in_msec); mStreamMetadataTimerIntervalMSec = Integer.valueOf(val); val = context.getString(R.string.rw_spec_min_location_update_time_msec); mMinLocationUpdateTimeMSec = Long.valueOf(val); val = context.getString(R.string.rw_spec_min_location_update_distance_meters); mMinLocationUpdateDistanceMeter = Double.valueOf(val); val = context.getString(R.string.rw_spec_files_url); mContentFilesUrl = val; val = context.getString(R.string.rw_spec_files_version); if (val != null) { mContentFilesVersion = Integer.valueOf(val); } mContentFilesAlwaysDownload = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_files_always_download)); mListenEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_listen_enabled_yn)); mGeoListenEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_geo_listen_enabled_yn)); mSpeakEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_speak_enabled_yn)); mGeoSpeakEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_geo_speak_enabled_yn)); mStreamMetadataEnabled = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_stream_metadata_enabled_yn)); mResetTagDefaultsOnStartup = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_reset_tag_defaults_on_startup_yn)); mUseGpsIfPossible = "Y".equalsIgnoreCase(context.getString(R.string.rw_spec_use_gps_if_possible)); } } /** * Overwrites configuration values from the specified key-value map. * If there is no matching key in the map, the value will remain * unchanged. * * @param jsonResponse to process * @param fromCache true if using cached data */ public void assignFromJsonServerResponse(String jsonResponse, boolean fromCache) { JSONObject specs = null; try { JSONArray entries = new JSONArray(jsonResponse); for (int i = 0; i < entries.length(); i++) { JSONObject jsonObj = entries.getJSONObject(i); if (D) { Log.d(TAG, jsonObj.toString()); } if (jsonObj.has(JSON_KEY_CONFIG_SECTION_DEVICE)) { // decode section with device specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_DEVICE); setDeviceId(specs.optString(JSON_KEY_CONFIG_DEVICE_ID, getDeviceId())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_SESSION)) { // decode section with session specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_SESSION); setSessionId(specs.optString(JSON_KEY_CONFIG_SESSION_ID, getSessionId())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_PROJECT)) { // decode section with project specific settings specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_PROJECT); setProjectId(specs.optString(JSON_KEY_CONFIG_PROJECT_ID, getProjectId())); setProjectName(specs.optString(JSON_KEY_CONFIG_PROJECT_NAME, getProjectName())); setContentFilesUrl(specs.optString(JSON_KEY_CONFIG_FILES_URL, getContentFilesUrl())); setContentFilesVersion(specs.optInt(JSON_KEY_CONFIG_FILES_VERSION, getContentFilesVersion())); setHeartbeatTimerSec(specs.optInt(JSON_KEY_CONFIG_HEARTBEAT_TIMER_SEC, getHeartbeatTimerSec())); setMaxRecordingTimeSec(specs.optInt(JSON_KEY_CONFIG_MAX_RECORDING_LENGTH_SEC, getMaxRecordingTimeSec())); setSharingMessage(specs.optString(JSON_KEY_CONFIG_SHARING_MESSAGE, getSharingMessage())); setSharingUrl(specs.optString(JSON_KEY_CONFIG_SHARING_URL, getSharingUrl())); setLegalAgreement(specs.optString(JSON_KEY_CONFIG_LEGAL_AGREEMENT, getLegalAgreement())); setDynamicListenQuestions(specs.optBoolean(JSON_KEY_CONFIG_DYNAMIC_LISTEN_TAGS, isDynamicListenQuestions())); setDynamicSpeakQuestions(specs.optBoolean(JSON_KEY_CONFIG_DYNAMIC_SPEAK_TAGS, isDynamicSpeakQuestions())); setListenEnabled(specs.optBoolean(JSON_KEY_CONFIG_LISTEN_ENABLED, isListenEnabled())); setGeoListenEnabled(specs.optBoolean(JSON_KEY_CONFIG_GEO_LISTEN_ENABLED, isGeoListenEnabled())); setSpeakEnabled(specs.optBoolean(JSON_KEY_CONFIG_SPEAK_ENABLED, isSpeakEnabled())); setGeoSpeakEnabled(specs.optBoolean(JSON_KEY_CONFIG_GEO_SPEAK_ENABLED, isGeoSpeakEnabled())); setResetTagsDefaultsOnStartup(specs.optBoolean(JSON_KEY_CONFIG_RESET_TAG_DEFAULTS_ON_STARTUP, isResetTagsDefaultOnStartup())); setStreamMetadataEnabled(specs.optBoolean(JSON_KEY_CONFIG_STREAM_METADATA_ENABLED, isStreamMetadataEnabled())); setMinLocationUpdateTimeMSec(specs.optLong(JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_TIME_MSEC, getMinLocationUpdateTimeMSec())); setMinLocationUpdateDistanceMeter(specs.optDouble(JSON_KEY_CONFIG_MIN_LOCATION_UPDATE_DISTANCE_METER, getMinLocationUpdateDistanceMeter())); setHttpTimeOutSec(specs.optInt(JSON_KEY_CONFIG_HTTP_TIMEOUT_SEC, getHttpTimeOutSec())); setUseGpsIfPossible(specs.optBoolean(JSON_KEY_CONFIG_USE_GPS_IF_POSSIBLE, getUseGpsIfPossible())); } else if (jsonObj.has(JSON_KEY_CONFIG_SECTION_SERVER)) { specs = jsonObj.getJSONObject(JSON_KEY_CONFIG_SECTION_SERVER); setServerVersion(specs.optString(JSON_KEY_CONFIG_CURRENT_VERSION, getServerVersion())); } } mDataSource = fromCache ? FROM_CACHE : FROM_SERVER; if (fromCache) { setSessionId(null); } } catch (JSONException e) { Log.e(TAG, JSON_SYNTAX_ERROR_MESSAGE, e); } } /** * Returns true if any of the configuration parameters related to the use * of device location is true. * * @return true if configuration requires use of device location services */ public boolean isUsingLocation() { return isUsingLocationBasedListen() || isUsingLocationBasedSpeak(); } /*** * Returns true if any of the configuration parameters related to Listen * functionality require use of device positioning. * * @return true if positioning is needed for Listen functionality */ public boolean isUsingLocationBasedListen() { return isGeoListenEnabled() || isDynamicListenQuestions(); } /*** * Returns true if any of the configuration parameters related to Speak * functionality require use of device positioning. * * @return true if positioning is needed for Speak functionality */ public boolean isUsingLocationBasedSpeak() { return isGeoSpeakEnabled() || isDynamicSpeakQuestions(); } public String getDeviceId() { return mDeviceId; } public void setDeviceId(String deviceId) { mDeviceId = deviceId; } public String getProjectId() { return mProjectId; } public void setProjectId(String projectId) { mProjectId = projectId; } public String getSessionId() { return mSessionId; } public void setSessionId(String sessionId) { mSessionId = sessionId; } public String getProjectName() { return mProjectName; } public void setProjectName(String projectName) { mProjectName = projectName; } public int getHeartbeatTimerSec() { return mHeartbeatTimerSec; } public void setHeartbeatTimerSec(int heartbeatTimerSec) { mHeartbeatTimerSec = heartbeatTimerSec; } public int getQueueCheckIntervalSec() { return mQueueCheckIntervalSec; } public void setQueueCheckIntervalSec(int queueCheckIntervalSec) { mQueueCheckIntervalSec = queueCheckIntervalSec; } public int getStreamMetadataTimerIntervalMSec() { return mStreamMetadataTimerIntervalMSec; } public void setStreamMetadataTimerIntervalMSec(int metadataTimerIntervalMSec) { mStreamMetadataTimerIntervalMSec = metadataTimerIntervalMSec; } public int getMaxRecordingTimeSec() { return mMaxRecordingTimeSec; } public void setMaxRecordingTimeSec(int maxRecordingTimeSec) { mMaxRecordingTimeSec = maxRecordingTimeSec; } public String getSharingUrl() { return mSharingUrl; } public void setSharingUrl(String sharingUrl) { mSharingUrl = sharingUrl; } public String getSharingMessage() { return mSharingMessage; } public void setSharingMessage(String sharingMessage) { mSharingMessage = sharingMessage; } public String getLegalAgreement() { return mLegalAgreement; } public void setLegalAgreement(String legalAgreement) { mLegalAgreement = legalAgreement; } public boolean isDynamicListenQuestions() { return mDynamicListenQuestions; } public void setDynamicListenQuestions(boolean dynamicListenQuestions) { mDynamicListenQuestions = dynamicListenQuestions; } public boolean isDynamicSpeakQuestions() { return mDynamicSpeakQuestions; } public void setDynamicSpeakQuestions(boolean dynamicSpeakQuestions) { mDynamicSpeakQuestions = dynamicSpeakQuestions; } public boolean isGeoListenEnabled() { return mGeoListenEnabled; } public void setGeoListenEnabled(boolean geoListenEnabled) { mGeoListenEnabled = geoListenEnabled; } public boolean isSpeakEnabled() { return mSpeakEnabled; } public void setSpeakEnabled(boolean speakEnabled) { mSpeakEnabled = speakEnabled; } public boolean isGeoSpeakEnabled() { return mGeoSpeakEnabled; } public void setGeoSpeakEnabled(boolean geoSpeakEnabled) { mGeoSpeakEnabled = geoSpeakEnabled; } public boolean isResetTagsDefaultOnStartup() { return mResetTagDefaultsOnStartup; } public void setResetTagsDefaultsOnStartup(boolean resetTagsDefaultsOnStartup) { mResetTagDefaultsOnStartup = resetTagsDefaultsOnStartup; } public long getMinLocationUpdateTimeMSec() { return mMinLocationUpdateTimeMSec; } public void setMinLocationUpdateTimeMSec(long minLocationUpdateTimeMSec) { mMinLocationUpdateTimeMSec = minLocationUpdateTimeMSec; } public double getMinLocationUpdateDistanceMeter() { return mMinLocationUpdateDistanceMeter; } public void setMinLocationUpdateDistanceMeter(double minLocationUpdateDistanceMeter) { mMinLocationUpdateDistanceMeter = minLocationUpdateDistanceMeter; } public int getHttpTimeOutSec() { return mHttpTimeOutSec; } public void setHttpTimeOutSec(int httpTimeOutSec) { mHttpTimeOutSec = httpTimeOutSec; } public int getDataSource() { return mDataSource; } public String getServerVersion() { return mServerVersion; } public void setServerVersion(String serverVersion) { mServerVersion = serverVersion; } public boolean isListenEnabled() { return mListenEnabled; } public void setListenEnabled(boolean listenEnabled) { mListenEnabled = listenEnabled; } public boolean isStreamMetadataEnabled() { return mStreamMetadataEnabled; } public void setStreamMetadataEnabled(boolean streamMetadataEnabled) { mStreamMetadataEnabled = streamMetadataEnabled; } public String getContentFilesUrl() { return mContentFilesUrl; } public void setContentFilesUrl(String filesUrl) { mContentFilesUrl = filesUrl; } public int getContentFilesVersion() { return mContentFilesVersion; } public void setContentFilesVersion(int filesVersion) { mContentFilesVersion = filesVersion; } public boolean isContentFilesAlwaysDownload() { return mContentFilesAlwaysDownload; } public void setUseGpsIfPossible(boolean useGps) { mUseGpsIfPossible = useGps; } public boolean getUseGpsIfPossible() { return mUseGpsIfPossible; } public void setContentFilesAlwaysDownload(boolean contentFilesAlwaysDownload) { mContentFilesAlwaysDownload = contentFilesAlwaysDownload; } }
52438_0
package com.assistant.aiassistant; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class FileIOManager { private static final String PATH_GEBRUIKERS = "gebruikers.txt"; private static final String SEPERATOR = "/~/"; public ArrayList<String> readFile(String path) { ArrayList<String> data = new ArrayList<>(); File fileOBJ = new File(path); try { Scanner fileReader = new Scanner(fileOBJ); while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); data.add(line); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Bestand niet gevonden."); // e.printStackTrace(); } return data; } // leest alle gebruikers uit het gebruikers.txt bestand en zet ze in een ArrayList public ArrayList<User> getUsersFromFile() { ArrayList<String> lines = readFile(PATH_GEBRUIKERS); ArrayList<User> usersReadFromFile = new ArrayList<>(); for (String line : lines) { String[] parts = line.split(SEPERATOR); // elke part is een attribuut van de gebruiker User userReadFromFile = new User(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]); // voeg de gebruiker toe aan de ArrayList met alle gebruikers usersReadFromFile.add(userReadFromFile); } // return de ArrayList met alle gebruikers return usersReadFromFile; } // slaat een gebruiker op in het gebruikers.txt bestand public void saveUserToFile(User userToSave){ try { // maak een nieuwe regel in gebruikers.txt en slaat de gebruiker daar op FileWriter myWriter = new FileWriter(PATH_GEBRUIKERS, true); // schrijf de gebruiker naar het bestand myWriter.write(userToSave.getUsername() + SEPERATOR + userToSave.getPassword() + SEPERATOR + userToSave.getEmail() + SEPERATOR + userToSave.getVoornaam() + SEPERATOR + userToSave.getAchternaam() + SEPERATOR + userToSave.getPreferredLanguage() + "\n"); myWriter.close(); } catch (IOException e) { System.out.println("Er ging iets mis"); } } // Herschrijft alle gebruikers in het gebruikers.txt bestand // Pas op: dit kan alle gebruikers in de lijst verwijderen! public void rewriteUsersToFile(ArrayList<User> users) { try { new FileWriter(PATH_GEBRUIKERS, false).close(); for(User user : users) { saveUserToFile(user); } } catch (IOException e) { System.out.println("Er ging iets mis"); } } // verwijdert een gebruiker uit het gebruikers.txt bestand public void removeUserFromFile(User selectedUser) { ArrayList<User> users = getUsersFromFile(); // zoekt de geselecteerde gebruiker in de ArrayList en verwijder deze for (int i = 0; i < users.size(); i++) { if (selectedUser.getUsername().equals(users.get(i).getUsername())) { users.remove(i); break; } } rewriteUsersToFile(users); } // gebruiker bewerken // nieuw is de waarde waarin het attribuut van de gebruiker moet worden veranderd // aspect is het attribuut dat moet worden veranderd (wachtwoord, gebruikersnaam, email enz.) // vergeet niet het aspect mee te geven aan deze methode als er iets veranderd moet worden. public void editUser(User user, String nieuw, String aspect){ ArrayList<User> users = getUsersFromFile(); for (User u : users) { if (user.getUsername().equals(u.getUsername())) { switch (aspect) { case "gebruikersnaam": u.setUsername(nieuw); break; case "wachtwoord": u.setPassword(nieuw); break; case "email": u.setEmail(nieuw); break; case "voornaam": u.setVoornaam(nieuw); break; case "achternaam": u.setAchternaam(nieuw); break; case "preferredLanguage": u.setPreferredLanguage(nieuw); break; default: System.out.println("Er ging iets mis."); } } } rewriteUsersToFile(users); } }
rowanDEJ/43-project-2
src/java/com/assistant/aiassistant/FileIOManager.java
1,321
// leest alle gebruikers uit het gebruikers.txt bestand en zet ze in een ArrayList
line_comment
nl
package com.assistant.aiassistant; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class FileIOManager { private static final String PATH_GEBRUIKERS = "gebruikers.txt"; private static final String SEPERATOR = "/~/"; public ArrayList<String> readFile(String path) { ArrayList<String> data = new ArrayList<>(); File fileOBJ = new File(path); try { Scanner fileReader = new Scanner(fileOBJ); while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); data.add(line); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Bestand niet gevonden."); // e.printStackTrace(); } return data; } // leest alle<SUF> public ArrayList<User> getUsersFromFile() { ArrayList<String> lines = readFile(PATH_GEBRUIKERS); ArrayList<User> usersReadFromFile = new ArrayList<>(); for (String line : lines) { String[] parts = line.split(SEPERATOR); // elke part is een attribuut van de gebruiker User userReadFromFile = new User(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]); // voeg de gebruiker toe aan de ArrayList met alle gebruikers usersReadFromFile.add(userReadFromFile); } // return de ArrayList met alle gebruikers return usersReadFromFile; } // slaat een gebruiker op in het gebruikers.txt bestand public void saveUserToFile(User userToSave){ try { // maak een nieuwe regel in gebruikers.txt en slaat de gebruiker daar op FileWriter myWriter = new FileWriter(PATH_GEBRUIKERS, true); // schrijf de gebruiker naar het bestand myWriter.write(userToSave.getUsername() + SEPERATOR + userToSave.getPassword() + SEPERATOR + userToSave.getEmail() + SEPERATOR + userToSave.getVoornaam() + SEPERATOR + userToSave.getAchternaam() + SEPERATOR + userToSave.getPreferredLanguage() + "\n"); myWriter.close(); } catch (IOException e) { System.out.println("Er ging iets mis"); } } // Herschrijft alle gebruikers in het gebruikers.txt bestand // Pas op: dit kan alle gebruikers in de lijst verwijderen! public void rewriteUsersToFile(ArrayList<User> users) { try { new FileWriter(PATH_GEBRUIKERS, false).close(); for(User user : users) { saveUserToFile(user); } } catch (IOException e) { System.out.println("Er ging iets mis"); } } // verwijdert een gebruiker uit het gebruikers.txt bestand public void removeUserFromFile(User selectedUser) { ArrayList<User> users = getUsersFromFile(); // zoekt de geselecteerde gebruiker in de ArrayList en verwijder deze for (int i = 0; i < users.size(); i++) { if (selectedUser.getUsername().equals(users.get(i).getUsername())) { users.remove(i); break; } } rewriteUsersToFile(users); } // gebruiker bewerken // nieuw is de waarde waarin het attribuut van de gebruiker moet worden veranderd // aspect is het attribuut dat moet worden veranderd (wachtwoord, gebruikersnaam, email enz.) // vergeet niet het aspect mee te geven aan deze methode als er iets veranderd moet worden. public void editUser(User user, String nieuw, String aspect){ ArrayList<User> users = getUsersFromFile(); for (User u : users) { if (user.getUsername().equals(u.getUsername())) { switch (aspect) { case "gebruikersnaam": u.setUsername(nieuw); break; case "wachtwoord": u.setPassword(nieuw); break; case "email": u.setEmail(nieuw); break; case "voornaam": u.setVoornaam(nieuw); break; case "achternaam": u.setAchternaam(nieuw); break; case "preferredLanguage": u.setPreferredLanguage(nieuw); break; default: System.out.println("Er ging iets mis."); } } } rewriteUsersToFile(users); } }
126168_24
package nl.vpro.poms.selenium.poms.pages; import nl.vpro.domain.image.ImageType; import nl.vpro.domain.support.License; import nl.vpro.poms.selenium.pages.AbstractPage; import nl.vpro.poms.selenium.util.WebDriverUtil; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import java.io.File; import java.net.URL; import static org.assertj.core.api.Fail.fail; public class MediaItemPage extends AbstractPage { private static final String xpathViewerTitle = "//*[@class='viewer-title' and contains(text(), '%s')]"; private static final String xpathViewerSubTitle = "//*[@class='viewer-subtitle' and contains(text(), '%s')]"; private static final String xpathUitzendingen = "//*[@class='media-section-title' and contains(text(), '%s')]"; private static final String xpathAfbeeldingen = "//*[@class='media-section-title' and contains(text(), '%s')]"; private static final String buttonAfbeeldingToevoegen = "//button[contains(text(), 'Afbeelding toevoegen')]"; private static final String cssInputUploadAfbeelding = "input#inputFile"; private static final String cssImageTitle = "input#inputTitle"; private static final String cssImageDescription = "textarea#inputDescription"; private static final String xpathInputSelectImageType = "//*[contains(text(), 'Afbeeldingstype')]/../descendant::input"; private static final String xpathInputSelectLicense = "//*[contains(text(), 'Licentie')]/../descendant::input"; private static final String xpathImageTypeOption = "//*[contains(@class, 'option')]/descendant::*[contains(text(), '%s')]"; private static final String xpathLicenseTypeOption = "//*[contains(@class, 'option')]/descendant::*[contains(text(), '%s')]"; private static final String xpathButtonMaakAan = "//button[contains(text(), '%s')]"; public MediaItemPage(WebDriverUtil driver) { super(driver); } public String getMID() { webDriverUtil.clickIfAvailable(By.xpath("//span[text() = 'Mid' and not(contains(@class, 'active'))]")); return webDriverUtil.getAtrributeFrom(By.cssSelector("[field='media.mid'] > input"), "value"); } public String getURN() { webDriverUtil.clickIfAvailable(By.xpath("//span[text() = 'Urn' and not(contains(@class, 'active'))]")); return webDriverUtil.getAtrributeFrom(By.cssSelector("[field='media.urn'] > input"), "value"); } public String getStatus() { return driver.findElement(By.xpath("//h2[text() = 'Status']/../*/p")).getText(); } public String getMediaType() { return driver.findElement(By.xpath("//h2[text() = 'Type']/../p[contains(@class, 'editable')]")).getText(); } public MediaItemPage changeMediaType(String mediaType) { webDriverUtil.waitAndClick(By.xpath("//h2[text() = 'Type']")); webDriverUtil.waitAndClick(By.cssSelector("input[value='" + mediaType.toUpperCase() + "']")); webDriverUtil.waitAndClick(By.cssSelector("button[type='submit']")); return this; } public String getSorteerDatumTijd() { webDriverUtil.waitForVisible(By.xpath("//h2[text() = 'Sorteerdatum']/../p")); return driver.findElement(By.xpath("//h2[text() = 'Sorteerdatum']/../p")).getText(); } public String getUitzendigData(){ webDriverUtil.waitForVisible(By.cssSelector("[title='bekijk alle uitzenddata']")); return driver.findElement(By.cssSelector("[title='bekijk alle uitzenddata']")).getText(); } public void clickMenuItem(String menuItem) { // Nog verder uitzoeken webDriverUtil.waitForVisible(By.xpath("(//span[contains(text(), '" + menuItem +"')])[last()]")); webDriverUtil.waitAndClick(By.xpath("(//span[contains(text(), '" + menuItem +"')])[last()]")); webDriverUtil.waitForVisible(By.xpath("//li[@class='media-item-navigation-link active']/descendant::*[contains(text(), '" + menuItem + "')]")); } public void checkOfPopupUitzendingDissappear(){ webDriverUtil.waitForInvisible(By.name("editScheduleEventForm")); webDriverUtil.waitForInvisible(By.xpath("//label[@label-for='channel' and contains(text(), 'Kanaal:')]")); } public void clickAlgemeen() { webDriverUtil.waitAndClick(By.xpath("(//span[contains(text(), 'Uitzendingen')])[last()]")); // // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // e.printStackTrace(); // } } public void doubleClickUitzending(String date) { //waitUtil.waitForVisible(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr")); //waitUtil.isElementPresent(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr")); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr"))).doubleClick().perform(); } public void moveToUitzendingen(){ moveToElement(By.xpath(xpathUitzendingen)); } public void moveToAfbeeldingen(){ moveToElement(By.xpath(String.format(xpathAfbeeldingen, "Afbeeldingen"))); } public void clickOnAfbeeldingToevoegen(){ ngWait.waitForAngularRequestsToFinish(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(buttonAfbeeldingToevoegen))); driver.findElement(By.xpath(buttonAfbeeldingToevoegen)).click(); } public void upLoadAfbeeldingMetNaam(String naam) { wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssInputUploadAfbeelding))); WebElement inputUploadAfbeelding = driver.findElement(By.cssSelector(cssInputUploadAfbeelding)); URL url = getClass().getClassLoader().getResource(naam); File file = new File(url.getFile()); String path = file.getAbsolutePath(); inputUploadAfbeelding.sendKeys(path); } public void imageAddTitle(String title){ wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssImageTitle))); WebElement imageTitle = driver.findElement(By.cssSelector(cssImageTitle)); imageTitle.sendKeys(title); } public void imageAddDescription(String description){ wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssImageDescription))); WebElement imageDescription = driver.findElement(By.cssSelector(cssImageDescription)); imageDescription.sendKeys(description); } public void imageAddType(ImageType type){ wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpathInputSelectImageType))); WebElement imageType = driver.findElement(By.xpath(xpathInputSelectImageType)); imageType.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(String.format(xpathImageTypeOption, type.getDisplayName())))); WebElement option = driver.findElement(By.xpath(String.format(xpathImageTypeOption, type.getDisplayName()))); option.click(); } public void imageLicentie(License license) { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpathInputSelectLicense))); WebElement licentieElement = driver.findElement(By.xpath(xpathInputSelectLicense)); licentieElement.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(String.format(xpathLicenseTypeOption, license.getDisplayName())))); WebElement option = driver.findElement(By.xpath(String.format(xpathLicenseTypeOption, license.getDisplayName()))); option.click(); } public void clickButtonMaakAan(){ wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(xpathButtonMaakAan, "Maak aan")))); WebElement buttonMaakAan = driver.findElement(By.xpath(String.format(xpathButtonMaakAan, "Maak aan"))); buttonMaakAan.click(); } public void changeStartDate(String date) { webDriverUtil.waitAndSendkeys(By.name("start"), date); } public void clickOpslaan() { webDriverUtil.waitAndClick(By.xpath("//button[contains(text(), 'Bewaar')]")); } public void changeKanaal(String kanaal){ Select itemKanaal = new Select(driver.findElement(By.name("channel"))); itemKanaal.selectByVisibleText(kanaal); } public void changeEndDate(String date) { webDriverUtil.waitAndSendkeys(By.name("stop"), date); } public void inputValueInInput(String name, String value) { webDriverUtil.waitAndSendkeys(By.name(name), value); } public String getValueForInInputWithName(String name) { Object value = ((JavascriptExecutor) driver).executeScript("return document.getElementsByName('" + name +"')[0].value"); String returnValue = ""; if (value instanceof String) { returnValue = value.toString(); } else { fail("Error in the javascript on the page"); System.out.println("Error in the javascript on the page"); } return returnValue; } public String getUitzendingGegevensEersteKanaal(){ return driver.findElement(By.xpath("(//td/descendant::*[@ng-switch-when='channel'])[1]")).getText(); } public String getUitzendingGegevensEersteDatum(){ return driver.findElement(By.xpath("(//td/descendant::*[@ng-switch-when='start'])[1]")).getText(); } public String getUitzendingTitel(){ return driver.findElement(By.xpath("//td/descendant::*[@ng-switch-when='title']")).getText(); } public String getUitzendingOmschrijving(){ return driver.findElement(By.xpath("//td/descendant::*[@ng-switch-when='description']")).getText(); } public void klikOpKnopMetNaam(String naambutton){ webDriverUtil.waitAndClick(By.xpath("//button[contains(text(), '" + naambutton + "')]")); } public String getMediaItemTitle() { return webDriverUtil.waitAndGetText(By.cssSelector("h1[class='viewer-title']")); } public void waitAndCheckMediaItemTitle(String title) { webDriverUtil.waitForVisible(By.xpath(String.format(xpathViewerTitle, title))); } public void waitAndCheckMediaItemSubTitle(String title) { webDriverUtil.waitForVisible(By.xpath(String.format(xpathViewerSubTitle, title))); } public void refreshUntilUitzendingGegevensWithStartDate(String startDate) { webDriverUtil.refreshUntilVisible("//*[@title='bekijk alle uitzenddata' and contains(text(), '" +startDate+" (Nederland 1)')]"); } public void moveToElement(By by) { ngWait.waitForAngularRequestsToFinish(); WebElement element = driver.findElement(by); ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element); } }
roydekleijn/functional-tests
poms-functional-tests-selenium/src/test/java/nl/vpro/poms/selenium/poms/pages/MediaItemPage.java
3,354
//*[@title='bekijk alle uitzenddata' and contains(text(), '" +startDate+" (Nederland 1)')]");
line_comment
nl
package nl.vpro.poms.selenium.poms.pages; import nl.vpro.domain.image.ImageType; import nl.vpro.domain.support.License; import nl.vpro.poms.selenium.pages.AbstractPage; import nl.vpro.poms.selenium.util.WebDriverUtil; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import java.io.File; import java.net.URL; import static org.assertj.core.api.Fail.fail; public class MediaItemPage extends AbstractPage { private static final String xpathViewerTitle = "//*[@class='viewer-title' and contains(text(), '%s')]"; private static final String xpathViewerSubTitle = "//*[@class='viewer-subtitle' and contains(text(), '%s')]"; private static final String xpathUitzendingen = "//*[@class='media-section-title' and contains(text(), '%s')]"; private static final String xpathAfbeeldingen = "//*[@class='media-section-title' and contains(text(), '%s')]"; private static final String buttonAfbeeldingToevoegen = "//button[contains(text(), 'Afbeelding toevoegen')]"; private static final String cssInputUploadAfbeelding = "input#inputFile"; private static final String cssImageTitle = "input#inputTitle"; private static final String cssImageDescription = "textarea#inputDescription"; private static final String xpathInputSelectImageType = "//*[contains(text(), 'Afbeeldingstype')]/../descendant::input"; private static final String xpathInputSelectLicense = "//*[contains(text(), 'Licentie')]/../descendant::input"; private static final String xpathImageTypeOption = "//*[contains(@class, 'option')]/descendant::*[contains(text(), '%s')]"; private static final String xpathLicenseTypeOption = "//*[contains(@class, 'option')]/descendant::*[contains(text(), '%s')]"; private static final String xpathButtonMaakAan = "//button[contains(text(), '%s')]"; public MediaItemPage(WebDriverUtil driver) { super(driver); } public String getMID() { webDriverUtil.clickIfAvailable(By.xpath("//span[text() = 'Mid' and not(contains(@class, 'active'))]")); return webDriverUtil.getAtrributeFrom(By.cssSelector("[field='media.mid'] > input"), "value"); } public String getURN() { webDriverUtil.clickIfAvailable(By.xpath("//span[text() = 'Urn' and not(contains(@class, 'active'))]")); return webDriverUtil.getAtrributeFrom(By.cssSelector("[field='media.urn'] > input"), "value"); } public String getStatus() { return driver.findElement(By.xpath("//h2[text() = 'Status']/../*/p")).getText(); } public String getMediaType() { return driver.findElement(By.xpath("//h2[text() = 'Type']/../p[contains(@class, 'editable')]")).getText(); } public MediaItemPage changeMediaType(String mediaType) { webDriverUtil.waitAndClick(By.xpath("//h2[text() = 'Type']")); webDriverUtil.waitAndClick(By.cssSelector("input[value='" + mediaType.toUpperCase() + "']")); webDriverUtil.waitAndClick(By.cssSelector("button[type='submit']")); return this; } public String getSorteerDatumTijd() { webDriverUtil.waitForVisible(By.xpath("//h2[text() = 'Sorteerdatum']/../p")); return driver.findElement(By.xpath("//h2[text() = 'Sorteerdatum']/../p")).getText(); } public String getUitzendigData(){ webDriverUtil.waitForVisible(By.cssSelector("[title='bekijk alle uitzenddata']")); return driver.findElement(By.cssSelector("[title='bekijk alle uitzenddata']")).getText(); } public void clickMenuItem(String menuItem) { // Nog verder uitzoeken webDriverUtil.waitForVisible(By.xpath("(//span[contains(text(), '" + menuItem +"')])[last()]")); webDriverUtil.waitAndClick(By.xpath("(//span[contains(text(), '" + menuItem +"')])[last()]")); webDriverUtil.waitForVisible(By.xpath("//li[@class='media-item-navigation-link active']/descendant::*[contains(text(), '" + menuItem + "')]")); } public void checkOfPopupUitzendingDissappear(){ webDriverUtil.waitForInvisible(By.name("editScheduleEventForm")); webDriverUtil.waitForInvisible(By.xpath("//label[@label-for='channel' and contains(text(), 'Kanaal:')]")); } public void clickAlgemeen() { webDriverUtil.waitAndClick(By.xpath("(//span[contains(text(), 'Uitzendingen')])[last()]")); // // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // e.printStackTrace(); // } } public void doubleClickUitzending(String date) { //waitUtil.waitForVisible(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr")); //waitUtil.isElementPresent(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr")); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.xpath("//span[contains(text(), '" + date + "')]/../../../tr"))).doubleClick().perform(); } public void moveToUitzendingen(){ moveToElement(By.xpath(xpathUitzendingen)); } public void moveToAfbeeldingen(){ moveToElement(By.xpath(String.format(xpathAfbeeldingen, "Afbeeldingen"))); } public void clickOnAfbeeldingToevoegen(){ ngWait.waitForAngularRequestsToFinish(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(buttonAfbeeldingToevoegen))); driver.findElement(By.xpath(buttonAfbeeldingToevoegen)).click(); } public void upLoadAfbeeldingMetNaam(String naam) { wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssInputUploadAfbeelding))); WebElement inputUploadAfbeelding = driver.findElement(By.cssSelector(cssInputUploadAfbeelding)); URL url = getClass().getClassLoader().getResource(naam); File file = new File(url.getFile()); String path = file.getAbsolutePath(); inputUploadAfbeelding.sendKeys(path); } public void imageAddTitle(String title){ wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssImageTitle))); WebElement imageTitle = driver.findElement(By.cssSelector(cssImageTitle)); imageTitle.sendKeys(title); } public void imageAddDescription(String description){ wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssImageDescription))); WebElement imageDescription = driver.findElement(By.cssSelector(cssImageDescription)); imageDescription.sendKeys(description); } public void imageAddType(ImageType type){ wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpathInputSelectImageType))); WebElement imageType = driver.findElement(By.xpath(xpathInputSelectImageType)); imageType.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(String.format(xpathImageTypeOption, type.getDisplayName())))); WebElement option = driver.findElement(By.xpath(String.format(xpathImageTypeOption, type.getDisplayName()))); option.click(); } public void imageLicentie(License license) { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpathInputSelectLicense))); WebElement licentieElement = driver.findElement(By.xpath(xpathInputSelectLicense)); licentieElement.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(String.format(xpathLicenseTypeOption, license.getDisplayName())))); WebElement option = driver.findElement(By.xpath(String.format(xpathLicenseTypeOption, license.getDisplayName()))); option.click(); } public void clickButtonMaakAan(){ wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(xpathButtonMaakAan, "Maak aan")))); WebElement buttonMaakAan = driver.findElement(By.xpath(String.format(xpathButtonMaakAan, "Maak aan"))); buttonMaakAan.click(); } public void changeStartDate(String date) { webDriverUtil.waitAndSendkeys(By.name("start"), date); } public void clickOpslaan() { webDriverUtil.waitAndClick(By.xpath("//button[contains(text(), 'Bewaar')]")); } public void changeKanaal(String kanaal){ Select itemKanaal = new Select(driver.findElement(By.name("channel"))); itemKanaal.selectByVisibleText(kanaal); } public void changeEndDate(String date) { webDriverUtil.waitAndSendkeys(By.name("stop"), date); } public void inputValueInInput(String name, String value) { webDriverUtil.waitAndSendkeys(By.name(name), value); } public String getValueForInInputWithName(String name) { Object value = ((JavascriptExecutor) driver).executeScript("return document.getElementsByName('" + name +"')[0].value"); String returnValue = ""; if (value instanceof String) { returnValue = value.toString(); } else { fail("Error in the javascript on the page"); System.out.println("Error in the javascript on the page"); } return returnValue; } public String getUitzendingGegevensEersteKanaal(){ return driver.findElement(By.xpath("(//td/descendant::*[@ng-switch-when='channel'])[1]")).getText(); } public String getUitzendingGegevensEersteDatum(){ return driver.findElement(By.xpath("(//td/descendant::*[@ng-switch-when='start'])[1]")).getText(); } public String getUitzendingTitel(){ return driver.findElement(By.xpath("//td/descendant::*[@ng-switch-when='title']")).getText(); } public String getUitzendingOmschrijving(){ return driver.findElement(By.xpath("//td/descendant::*[@ng-switch-when='description']")).getText(); } public void klikOpKnopMetNaam(String naambutton){ webDriverUtil.waitAndClick(By.xpath("//button[contains(text(), '" + naambutton + "')]")); } public String getMediaItemTitle() { return webDriverUtil.waitAndGetText(By.cssSelector("h1[class='viewer-title']")); } public void waitAndCheckMediaItemTitle(String title) { webDriverUtil.waitForVisible(By.xpath(String.format(xpathViewerTitle, title))); } public void waitAndCheckMediaItemSubTitle(String title) { webDriverUtil.waitForVisible(By.xpath(String.format(xpathViewerSubTitle, title))); } public void refreshUntilUitzendingGegevensWithStartDate(String startDate) { webDriverUtil.refreshUntilVisible("//*[@title='bekijk alle<SUF> } public void moveToElement(By by) { ngWait.waitForAngularRequestsToFinish(); WebElement element = driver.findElement(by); ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element); } }
75231_0
package pojo; import javax.xml.bind.annotation.XmlElement; public class VertrekkendeTrein { private int ritNummer; private String vertrekTijd; private String eindBestemming; private String treinSoort; private String routeTekst; private String vervoerder; private String vertrekSpoor; @XmlElement(name = "RitNummer") public int getRitNummer() { return ritNummer; } @XmlElement(name = "VertrekTijd") public String getVertrekTijd() { return vertrekTijd; } @XmlElement(name = "EindBestemming") public String getEindBestemming() { return eindBestemming; } @XmlElement(name = "TreinSoort") public String getTreinSoort() { return treinSoort; } @XmlElement(name = "RouteTekst") public String getRouteTekst() { return routeTekst; } @XmlElement(name = "Vervoerder") public String getVervoerder() { return vervoerder; } @XmlElement(name = "VertrekSpoor") public String getVertrekSpoor() { return vertrekSpoor; } public void setRitNummer(int ritNummer) { this.ritNummer = ritNummer; } public void setVertrekTijd(String vertrekTijd) { this.vertrekTijd = vertrekTijd; } public void setEindBestemming(String eindBestemming) { this.eindBestemming = eindBestemming; } public void setTreinSoort(String treinSoort) { this.treinSoort = treinSoort; } public void setRouteTekst(String routeTekst) { this.routeTekst = routeTekst; } public void setVervoerder(String vervoerder) { this.vervoerder = vervoerder; } public void setVertrekSpoor(String vertrekSpoor) { this.vertrekSpoor = vertrekSpoor; } /* * <RitNummer>9844</RitNummer> * <VertrekTijd>2013-06-05T14:05:00+0200</VertrekTijd> <EindBestemming>Den * Haag Centraal</EindBestemming> <TreinSoort>Sprinter</TreinSoort> * <RouteTekst>Woerden, Gouda, Zoetermeer</RouteTekst> * <Vervoerder>NS</Vervoerder> <VertrekSpoor * wijziging="false">18a</VertrekSpoor> */ }
roydekleijn/webservicetests
src/test/java/pojo/VertrekkendeTrein.java
812
/* * <RitNummer>9844</RitNummer> * <VertrekTijd>2013-06-05T14:05:00+0200</VertrekTijd> <EindBestemming>Den * Haag Centraal</EindBestemming> <TreinSoort>Sprinter</TreinSoort> * <RouteTekst>Woerden, Gouda, Zoetermeer</RouteTekst> * <Vervoerder>NS</Vervoerder> <VertrekSpoor * wijziging="false">18a</VertrekSpoor> */
block_comment
nl
package pojo; import javax.xml.bind.annotation.XmlElement; public class VertrekkendeTrein { private int ritNummer; private String vertrekTijd; private String eindBestemming; private String treinSoort; private String routeTekst; private String vervoerder; private String vertrekSpoor; @XmlElement(name = "RitNummer") public int getRitNummer() { return ritNummer; } @XmlElement(name = "VertrekTijd") public String getVertrekTijd() { return vertrekTijd; } @XmlElement(name = "EindBestemming") public String getEindBestemming() { return eindBestemming; } @XmlElement(name = "TreinSoort") public String getTreinSoort() { return treinSoort; } @XmlElement(name = "RouteTekst") public String getRouteTekst() { return routeTekst; } @XmlElement(name = "Vervoerder") public String getVervoerder() { return vervoerder; } @XmlElement(name = "VertrekSpoor") public String getVertrekSpoor() { return vertrekSpoor; } public void setRitNummer(int ritNummer) { this.ritNummer = ritNummer; } public void setVertrekTijd(String vertrekTijd) { this.vertrekTijd = vertrekTijd; } public void setEindBestemming(String eindBestemming) { this.eindBestemming = eindBestemming; } public void setTreinSoort(String treinSoort) { this.treinSoort = treinSoort; } public void setRouteTekst(String routeTekst) { this.routeTekst = routeTekst; } public void setVervoerder(String vervoerder) { this.vervoerder = vervoerder; } public void setVertrekSpoor(String vertrekSpoor) { this.vertrekSpoor = vertrekSpoor; } /* * <RitNummer>9844</RitNummer> <SUF>*/ }
29083_26
/* * Copyright (c) 2009-2021 jMonkeyEngine * 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 'jMonkeyEngine' 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. */ package com.jme3.util; import com.jme3.bounding.BoundingBox; import com.jme3.collision.CollisionResults; import com.jme3.collision.bih.BIHNode.BIHStackData; import com.jme3.math.*; import com.jme3.scene.Spatial; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; /** * Temporary variables assigned to each thread. Engine classes may access * these temp variables with TempVars.get(), all retrieved TempVars * instances must be returned via TempVars.release(). * This returns an available instance of the TempVar class ensuring this * particular instance is never used elsewhere in the meantime. */ public class TempVars { /** * Allow X instances of TempVars in a single thread. */ private static final int STACK_SIZE = 5; /** * <code>TempVarsStack</code> contains a stack of TempVars. * Every time TempVars.get() is called, a new entry is added to the stack, * and the index incremented. * When TempVars.release() is called, the entry is checked against * the current instance and then the index is decremented. */ private static class TempVarsStack { int index = 0; TempVars[] tempVars = new TempVars[STACK_SIZE]; } /** * ThreadLocal to store a TempVarsStack for each thread. * This ensures each thread has a single TempVarsStack that is * used only in method calls in that thread. */ private static final ThreadLocal<TempVarsStack> varsLocal = new ThreadLocal<TempVarsStack>() { @Override public TempVarsStack initialValue() { return new TempVarsStack(); } }; /** * This instance of TempVars has been retrieved but not released yet. */ private boolean isUsed = false; private TempVars() { } /** * Acquire an instance of the TempVar class. * You have to release the instance after use by calling the * release() method. * If more than STACK_SIZE (currently 5) instances are requested * in a single thread then an ArrayIndexOutOfBoundsException will be thrown. * * @return A TempVar instance */ public static TempVars get() { TempVarsStack stack = varsLocal.get(); TempVars instance = stack.tempVars[stack.index]; if (instance == null) { // Create new instance = new TempVars(); // Put it in there stack.tempVars[stack.index] = instance; } stack.index++; instance.isUsed = true; return instance; } /** * Releases this instance of TempVars. * Once released, the contents of the TempVars are undefined. * The TempVars must be released in the opposite order that they are retrieved, * e.g. Acquiring vars1, then acquiring vars2, vars2 MUST be released * first otherwise an exception will be thrown. */ public void release() { if (!isUsed) { throw new IllegalStateException("This instance of TempVars was already released!"); } isUsed = false; TempVarsStack stack = varsLocal.get(); // Return it to the stack stack.index--; // Check if it is actually there if (stack.tempVars[stack.index] != this) { throw new IllegalStateException("An instance of TempVars has not been released in a called method!"); } } /** * For interfacing with OpenGL in Renderer. */ public final IntBuffer intBuffer1 = BufferUtils.createIntBuffer(1); public final IntBuffer intBuffer16 = BufferUtils.createIntBuffer(16); public final FloatBuffer floatBuffer16 = BufferUtils.createFloatBuffer(16); /** * BoundingVolumes (for shadows etc.) */ public final BoundingBox bbox = new BoundingBox(); /** * Skinning buffers */ public final float[] skinPositions = new float[512 * 3]; public final float[] skinNormals = new float[512 * 3]; //tangent buffer as 4 components by elements public final float[] skinTangents = new float[512 * 4]; /** * Fetching triangle from mesh */ public final Triangle triangle = new Triangle(); /** * Color */ public final ColorRGBA color = new ColorRGBA(); /** * General vectors. */ public final Vector3f vect1 = new Vector3f(); public final Vector3f vect2 = new Vector3f(); public final Vector3f vect3 = new Vector3f(); public final Vector3f vect4 = new Vector3f(); public final Vector3f vect5 = new Vector3f(); public final Vector3f vect6 = new Vector3f(); public final Vector3f vect7 = new Vector3f(); //seems the maximum number of vector used is 7 in com.jme3.bounding.java public final Vector3f vect8 = new Vector3f(); public final Vector3f vect9 = new Vector3f(); public final Vector3f vect10 = new Vector3f(); public final Vector4f vect4f1 = new Vector4f(); public final Vector4f vect4f2 = new Vector4f(); public final Vector3f[] tri = {new Vector3f(), new Vector3f(), new Vector3f()}; /** * 2D vector */ public final Vector2f vect2d = new Vector2f(); public final Vector2f vect2d2 = new Vector2f(); /** * General matrices. */ public final Matrix3f tempMat3 = new Matrix3f(); public final Matrix4f tempMat4 = new Matrix4f(); public final Matrix4f tempMat42 = new Matrix4f(); /** * General quaternions. */ public final Quaternion quat1 = new Quaternion(); public final Quaternion quat2 = new Quaternion(); /** * Eigen */ public final Eigen3f eigen = new Eigen3f(); /** * Plane */ public final Plane plane = new Plane(); /** * BoundingBox ray collision */ public final float[] fWdU = new float[3]; public final float[] fAWdU = new float[3]; public final float[] fDdU = new float[3]; public final float[] fADdU = new float[3]; public final float[] fAWxDdU = new float[3]; /** * Maximum tree depth .. 32 levels?? */ public final Spatial[] spatialStack = new Spatial[32]; public final float[] matrixWrite = new float[16]; /** * BIHTree */ public final CollisionResults collisionResults = new CollisionResults(); public final float[] bihSwapTmp = new float[9]; public final ArrayList<BIHStackData> bihStack = new ArrayList<>(); }
rpax/jmonkeyengine
jme3-core/src/main/java/com/jme3/util/TempVars.java
2,505
/** * BIHTree */
block_comment
nl
/* * Copyright (c) 2009-2021 jMonkeyEngine * 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 'jMonkeyEngine' 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. */ package com.jme3.util; import com.jme3.bounding.BoundingBox; import com.jme3.collision.CollisionResults; import com.jme3.collision.bih.BIHNode.BIHStackData; import com.jme3.math.*; import com.jme3.scene.Spatial; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; /** * Temporary variables assigned to each thread. Engine classes may access * these temp variables with TempVars.get(), all retrieved TempVars * instances must be returned via TempVars.release(). * This returns an available instance of the TempVar class ensuring this * particular instance is never used elsewhere in the meantime. */ public class TempVars { /** * Allow X instances of TempVars in a single thread. */ private static final int STACK_SIZE = 5; /** * <code>TempVarsStack</code> contains a stack of TempVars. * Every time TempVars.get() is called, a new entry is added to the stack, * and the index incremented. * When TempVars.release() is called, the entry is checked against * the current instance and then the index is decremented. */ private static class TempVarsStack { int index = 0; TempVars[] tempVars = new TempVars[STACK_SIZE]; } /** * ThreadLocal to store a TempVarsStack for each thread. * This ensures each thread has a single TempVarsStack that is * used only in method calls in that thread. */ private static final ThreadLocal<TempVarsStack> varsLocal = new ThreadLocal<TempVarsStack>() { @Override public TempVarsStack initialValue() { return new TempVarsStack(); } }; /** * This instance of TempVars has been retrieved but not released yet. */ private boolean isUsed = false; private TempVars() { } /** * Acquire an instance of the TempVar class. * You have to release the instance after use by calling the * release() method. * If more than STACK_SIZE (currently 5) instances are requested * in a single thread then an ArrayIndexOutOfBoundsException will be thrown. * * @return A TempVar instance */ public static TempVars get() { TempVarsStack stack = varsLocal.get(); TempVars instance = stack.tempVars[stack.index]; if (instance == null) { // Create new instance = new TempVars(); // Put it in there stack.tempVars[stack.index] = instance; } stack.index++; instance.isUsed = true; return instance; } /** * Releases this instance of TempVars. * Once released, the contents of the TempVars are undefined. * The TempVars must be released in the opposite order that they are retrieved, * e.g. Acquiring vars1, then acquiring vars2, vars2 MUST be released * first otherwise an exception will be thrown. */ public void release() { if (!isUsed) { throw new IllegalStateException("This instance of TempVars was already released!"); } isUsed = false; TempVarsStack stack = varsLocal.get(); // Return it to the stack stack.index--; // Check if it is actually there if (stack.tempVars[stack.index] != this) { throw new IllegalStateException("An instance of TempVars has not been released in a called method!"); } } /** * For interfacing with OpenGL in Renderer. */ public final IntBuffer intBuffer1 = BufferUtils.createIntBuffer(1); public final IntBuffer intBuffer16 = BufferUtils.createIntBuffer(16); public final FloatBuffer floatBuffer16 = BufferUtils.createFloatBuffer(16); /** * BoundingVolumes (for shadows etc.) */ public final BoundingBox bbox = new BoundingBox(); /** * Skinning buffers */ public final float[] skinPositions = new float[512 * 3]; public final float[] skinNormals = new float[512 * 3]; //tangent buffer as 4 components by elements public final float[] skinTangents = new float[512 * 4]; /** * Fetching triangle from mesh */ public final Triangle triangle = new Triangle(); /** * Color */ public final ColorRGBA color = new ColorRGBA(); /** * General vectors. */ public final Vector3f vect1 = new Vector3f(); public final Vector3f vect2 = new Vector3f(); public final Vector3f vect3 = new Vector3f(); public final Vector3f vect4 = new Vector3f(); public final Vector3f vect5 = new Vector3f(); public final Vector3f vect6 = new Vector3f(); public final Vector3f vect7 = new Vector3f(); //seems the maximum number of vector used is 7 in com.jme3.bounding.java public final Vector3f vect8 = new Vector3f(); public final Vector3f vect9 = new Vector3f(); public final Vector3f vect10 = new Vector3f(); public final Vector4f vect4f1 = new Vector4f(); public final Vector4f vect4f2 = new Vector4f(); public final Vector3f[] tri = {new Vector3f(), new Vector3f(), new Vector3f()}; /** * 2D vector */ public final Vector2f vect2d = new Vector2f(); public final Vector2f vect2d2 = new Vector2f(); /** * General matrices. */ public final Matrix3f tempMat3 = new Matrix3f(); public final Matrix4f tempMat4 = new Matrix4f(); public final Matrix4f tempMat42 = new Matrix4f(); /** * General quaternions. */ public final Quaternion quat1 = new Quaternion(); public final Quaternion quat2 = new Quaternion(); /** * Eigen */ public final Eigen3f eigen = new Eigen3f(); /** * Plane */ public final Plane plane = new Plane(); /** * BoundingBox ray collision */ public final float[] fWdU = new float[3]; public final float[] fAWdU = new float[3]; public final float[] fDdU = new float[3]; public final float[] fADdU = new float[3]; public final float[] fAWxDdU = new float[3]; /** * Maximum tree depth .. 32 levels?? */ public final Spatial[] spatialStack = new Spatial[32]; public final float[] matrixWrite = new float[16]; /** * BIHTree <SUF>*/ public final CollisionResults collisionResults = new CollisionResults(); public final float[] bihSwapTmp = new float[9]; public final ArrayList<BIHStackData> bihStack = new ArrayList<>(); }
209708_18
/* * Static methods dealing with the Atmosphere * ===================================================================== * This file is part of JSatTrak. * * Copyright 2007-2013 Shawn E. Gano * * 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 name.gano.astro; import name.gano.astro.bodies.Sun; /** * * @author sgano */ public class Atmosphere { /** * Computes the acceleration due to the atmospheric drag. * (uses modified Harris-Priester model) * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r Satellite position vector in the inertial system [m] * @param v Satellite velocity vector in the inertial system [m/s] * @param T Transformation matrix to true-of-date inertial system * @param Area Cross-section [m^2] * @param mass Spacecraft mass [kg] * @param CD Drag coefficient * @return Acceleration (a=d^2r/dt^2) [m/s^2] */ public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v, final double[][] T, double Area, double mass, double CD) { // Constants // Earth angular velocity vector [rad/s] final double[] omega = {0.0, 0.0, 7.29212e-5}; // Variables double v_abs, dens; double[] r_tod = new double[3]; double[] v_tod = new double[3]; double[] v_rel = new double[3]; double[] a_tod = new double[3]; double[][] T_trp = new double[3][3]; // Transformation matrix to ICRF/EME2000 system T_trp = MathUtils.transpose(T); // Position and velocity in true-of-date system r_tod = MathUtils.mult(T, r); v_tod = MathUtils.mult(T, v); // Velocity relative to the Earth's atmosphere v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod)); v_abs = MathUtils.norm(v_rel); // Atmospheric density due to modified Harris-Priester model dens = Density_HP(Mjd_TT, r_tod); // Acceleration a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs); return MathUtils.mult(T_trp, a_tod); } // accellDrag /** * Computes the atmospheric density for the modified Harris-Priester model. * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r_tod Satellite position vector in the inertial system [m] * @return Density [kg/m^3] */ public static double Density_HP(double Mjd_TT, final double[] r_tod) { // Constants final double upper_limit = 1000.0; // Upper height limit [km] final double lower_limit = 100.0; // Lower height limit [km] final double ra_lag = 0.523599; // Right ascension lag [rad] final int n_prm = 3; // Harris-Priester parameter // 2(6) low(high) inclination // Harris-Priester atmospheric density model parameters // Height [km], minimum density, maximum density [gm/km^3] final int N_Coef = 50; final double[] h = { 100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0, 210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0, 320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0, 520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0, 720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0 }; final double[] c_min = { 4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03, 8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02, 9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01, 2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00, 2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01, 2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02, 4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02, 1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03, 1.560e-03, 1.150e-03 }; final double[] c_max = { 4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03, 8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02, 1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01, 4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00, 7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00, 1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01, 4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01, 1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02, 2.360e-02, 1.810e-02 }; // Variables int i, ih; // Height section variables double height; // Earth flattening double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc. double c_psi2; // Harris-Priester modification double density, h_min, h_max, d_min, d_max;// Height, density parameters double[] r_Sun = new double[3]; // Sun position double[] u = new double[3]; // Apex of diurnal bulge // Satellite height (in km) height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km] // Exit with zero density outside height model limits if (height >= upper_limit || height <= lower_limit) { return 0.0; } // Sun right ascension, declination r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT); ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]); dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2))); // Unit vector u towards the apex of the diurnal bulge // in inertial geocentric coordinates c_dec = Math.cos(dec_Sun); u[0] = c_dec * Math.cos(ra_Sun + ra_lag); u[1] = c_dec * Math.sin(ra_Sun + ra_lag); u[2] = Math.sin(dec_Sun); // Cosine of half angle between satellite position vector and // apex of diurnal bulge c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod); // Height index search and exponential density interpolation ih = 0; // section index reset for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes { if (height >= h[i] && height < h[i + 1]) { ih = i; // ih identifies height section break; } } h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]); h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]); d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min); d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max); // Density computation density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm); return density * 1.0e-12; // [kg/m^3] } // Density_HP }
rrr6399/JSatTrakLib
src/name/gano/astro/Atmosphere.java
3,310
// Height, density parameters
line_comment
nl
/* * Static methods dealing with the Atmosphere * ===================================================================== * This file is part of JSatTrak. * * Copyright 2007-2013 Shawn E. Gano * * 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 name.gano.astro; import name.gano.astro.bodies.Sun; /** * * @author sgano */ public class Atmosphere { /** * Computes the acceleration due to the atmospheric drag. * (uses modified Harris-Priester model) * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r Satellite position vector in the inertial system [m] * @param v Satellite velocity vector in the inertial system [m/s] * @param T Transformation matrix to true-of-date inertial system * @param Area Cross-section [m^2] * @param mass Spacecraft mass [kg] * @param CD Drag coefficient * @return Acceleration (a=d^2r/dt^2) [m/s^2] */ public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v, final double[][] T, double Area, double mass, double CD) { // Constants // Earth angular velocity vector [rad/s] final double[] omega = {0.0, 0.0, 7.29212e-5}; // Variables double v_abs, dens; double[] r_tod = new double[3]; double[] v_tod = new double[3]; double[] v_rel = new double[3]; double[] a_tod = new double[3]; double[][] T_trp = new double[3][3]; // Transformation matrix to ICRF/EME2000 system T_trp = MathUtils.transpose(T); // Position and velocity in true-of-date system r_tod = MathUtils.mult(T, r); v_tod = MathUtils.mult(T, v); // Velocity relative to the Earth's atmosphere v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod)); v_abs = MathUtils.norm(v_rel); // Atmospheric density due to modified Harris-Priester model dens = Density_HP(Mjd_TT, r_tod); // Acceleration a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs); return MathUtils.mult(T_trp, a_tod); } // accellDrag /** * Computes the atmospheric density for the modified Harris-Priester model. * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r_tod Satellite position vector in the inertial system [m] * @return Density [kg/m^3] */ public static double Density_HP(double Mjd_TT, final double[] r_tod) { // Constants final double upper_limit = 1000.0; // Upper height limit [km] final double lower_limit = 100.0; // Lower height limit [km] final double ra_lag = 0.523599; // Right ascension lag [rad] final int n_prm = 3; // Harris-Priester parameter // 2(6) low(high) inclination // Harris-Priester atmospheric density model parameters // Height [km], minimum density, maximum density [gm/km^3] final int N_Coef = 50; final double[] h = { 100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0, 210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0, 320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0, 520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0, 720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0 }; final double[] c_min = { 4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03, 8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02, 9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01, 2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00, 2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01, 2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02, 4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02, 1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03, 1.560e-03, 1.150e-03 }; final double[] c_max = { 4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03, 8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02, 1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01, 4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00, 7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00, 1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01, 4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01, 1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02, 2.360e-02, 1.810e-02 }; // Variables int i, ih; // Height section variables double height; // Earth flattening double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc. double c_psi2; // Harris-Priester modification double density, h_min, h_max, d_min, d_max;// Height, density<SUF> double[] r_Sun = new double[3]; // Sun position double[] u = new double[3]; // Apex of diurnal bulge // Satellite height (in km) height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km] // Exit with zero density outside height model limits if (height >= upper_limit || height <= lower_limit) { return 0.0; } // Sun right ascension, declination r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT); ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]); dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2))); // Unit vector u towards the apex of the diurnal bulge // in inertial geocentric coordinates c_dec = Math.cos(dec_Sun); u[0] = c_dec * Math.cos(ra_Sun + ra_lag); u[1] = c_dec * Math.sin(ra_Sun + ra_lag); u[2] = Math.sin(dec_Sun); // Cosine of half angle between satellite position vector and // apex of diurnal bulge c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod); // Height index search and exponential density interpolation ih = 0; // section index reset for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes { if (height >= h[i] && height < h[i + 1]) { ih = i; // ih identifies height section break; } } h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]); h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]); d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min); d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max); // Density computation density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm); return density * 1.0e-12; // [kg/m^3] } // Density_HP }
35160_0
package nl.avans.ivh5.springmvc.library.controller; import com.bol.api.openapi_4_0.Product; import nl.avans.ivh5.springmvc.library.model.Copy; import nl.avans.ivh5.springmvc.library.service.CopyService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.util.List; /** * */ @Controller public class CopyController { private final Logger logger = LoggerFactory.getLogger(CopyController.class);; private CopyService copyService; @Autowired public CopyController(CopyService copyService) { this.copyService = copyService; } @ModelAttribute("page") public String module() { return "copies"; } /** * Maak een record voor een Book aan als die nog niet bestaat, en voeg een Copy daarvan toe. * De input (RequestBody) is JSON met het product uit de view. * Resultaat (ResponseBody) is een Json object met data. * * With @RequestBody, Spring will maps the POST data to Book POJO (by name) automatically. * */ @RequestMapping(value="/createcopy", method = RequestMethod.POST) @ResponseBody public Copy createBookAndCopy(@RequestBody Product product, final BindingResult bindingResult) { // De service doet het werkt, en heeft koppelingen met de andere controllers, en // met de CopyRepository. return copyService.createBookAndCopy(product); } /** * Deze methode heeft geen RequestMapping omdat hij niet via een URL wordt aangeroepen, * maar vanuit de BookController. * * @param ean Het Ean van het boek waarvan we de copies zoeken * @return Een lijst met de gevonden copies. */ public List<Copy> findLendingInfoByBookEAN(Long ean) { logger.debug("findLendingInfoByBookEAN " + ean); return copyService.findLendingInfoByBookEAN(ean); } }
rschellius/spring-mvc-library
src/main/java/nl/avans/ivh5/springmvc/library/controller/CopyController.java
595
/** * Maak een record voor een Book aan als die nog niet bestaat, en voeg een Copy daarvan toe. * De input (RequestBody) is JSON met het product uit de view. * Resultaat (ResponseBody) is een Json object met data. * * With @RequestBody, Spring will maps the POST data to Book POJO (by name) automatically. * */
block_comment
nl
package nl.avans.ivh5.springmvc.library.controller; import com.bol.api.openapi_4_0.Product; import nl.avans.ivh5.springmvc.library.model.Copy; import nl.avans.ivh5.springmvc.library.service.CopyService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.util.List; /** * */ @Controller public class CopyController { private final Logger logger = LoggerFactory.getLogger(CopyController.class);; private CopyService copyService; @Autowired public CopyController(CopyService copyService) { this.copyService = copyService; } @ModelAttribute("page") public String module() { return "copies"; } /** * Maak een record<SUF>*/ @RequestMapping(value="/createcopy", method = RequestMethod.POST) @ResponseBody public Copy createBookAndCopy(@RequestBody Product product, final BindingResult bindingResult) { // De service doet het werkt, en heeft koppelingen met de andere controllers, en // met de CopyRepository. return copyService.createBookAndCopy(product); } /** * Deze methode heeft geen RequestMapping omdat hij niet via een URL wordt aangeroepen, * maar vanuit de BookController. * * @param ean Het Ean van het boek waarvan we de copies zoeken * @return Een lijst met de gevonden copies. */ public List<Copy> findLendingInfoByBookEAN(Long ean) { logger.debug("findLendingInfoByBookEAN " + ean); return copyService.findLendingInfoByBookEAN(ean); } }
13997_7
/* * FastSelectTable.java * * Copyright (C) 2021 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.*; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import org.rstudio.core.client.ClassIds; import org.rstudio.core.client.Rectangle; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.NativeWindow; import org.rstudio.core.client.widget.events.SelectionChangedEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class FastSelectTable<TItemInput, TItemOutput, TItemOutput2> extends Widget implements HasAllMouseHandlers, HasClickHandlers, HasAllKeyHandlers { public interface ItemCodec<T, TItemOutput, TItemOutput2> { TableRowElement getRowForItem(T entry); void onRowsChanged(TableSectionElement tbody); TItemOutput getOutputForRow(TableRowElement row); TItemOutput2 getOutputForRow2(TableRowElement row); boolean isValueRow(TableRowElement row); boolean hasNonValueRows(); Integer logicalOffsetToPhysicalOffset(TableElement table, int offset); Integer physicalOffsetToLogicalOffset(TableElement table, int offset); int getLogicalRowCount(TableElement table); } public FastSelectTable(ItemCodec<TItemInput, TItemOutput, TItemOutput2> codec, String selectedClassName, boolean focusable, boolean allowMultiSelect, String title) { codec_ = codec; selectedClassName_ = selectedClassName; focusable_ = focusable; allowMultiSelect_ = allowMultiSelect; table_ = Document.get().createTableElement(); if (focusable_) table_.setTabIndex(0); table_.setCellPadding(0); table_.setCellSpacing(0); table_.setBorder(0); table_.getStyle().setCursor(Cursor.DEFAULT); setClassId(title); setElement(table_); addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { if (event.getNativeButton() != NativeEvent.BUTTON_LEFT) return; event.preventDefault(); NativeWindow.get().focus(); DomUtils.setActive(getElement()); Element cell = getEventTargetCell((Event) event.getNativeEvent()); if (cell == null) return; TableRowElement row = (TableRowElement) cell.getParentElement(); if (codec_.isValueRow(row)) handleRowClick(event, row); } }); addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { event.preventDefault(); } }); addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { handleKeyDown(event); } }); } public void setClassId(String name) { table_.setClassName(ClassIds.FAST_SELECT_TABLE + "_" + ClassIds.idSafeString(name)); } public void setCellPadding(int padding) { table_.setCellPadding(padding); } public void setCellSpacing(int spacing) { table_.setCellSpacing(spacing); } public void setOwningScrollPanel(ScrollPanel scrollPanel) { scrollPanel_ = scrollPanel; } private void handleRowClick(MouseDownEvent event, TableRowElement row) { int modifiers = KeyboardShortcut.getModifierValue(event.getNativeEvent()); modifiers &= ~KeyboardShortcut.ALT; // ALT has no effect if (!allowMultiSelect_) modifiers = KeyboardShortcut.NONE; // We'll treat Ctrl and Meta as equivalent--and normalize to Ctrl. if (KeyboardShortcut.META == (modifiers & KeyboardShortcut.META)) modifiers |= KeyboardShortcut.CTRL; modifiers &= ~KeyboardShortcut.META; if (modifiers == KeyboardShortcut.NONE) { // Select only the target row clearSelection(); setSelected(row, true); } else if (modifiers == KeyboardShortcut.CTRL) { // Toggle the target row setSelected(row, !isSelected(row)); } else { // SHIFT or CTRL+SHIFT int target = row.getRowIndex(); Integer min = null; Integer max = null; for (TableRowElement selectedRow : selectedRows_) { if (min == null) min = selectedRow.getRowIndex(); max = selectedRow.getRowIndex(); } int offset; // selection offset int length; // selection length if (min == null) { // Nothing is selected offset = target; length = 1; } else if (target < min) { // Select target..max offset = target; length = max - target + 1; } else if (target > max) { offset = min; length = target - min + 1; } else { // target is in between min and max if (modifiers == (KeyboardShortcut.CTRL | KeyboardShortcut.SHIFT)) { offset = min; length = target - min + 1; } else { offset = target; length = 1; } } clearSelection(); if (length > 0) { setSelectedPhysical(offset, length, true); } } } private void handleKeyDown(KeyDownEvent event) { int modifiers = KeyboardShortcut.getModifierValue(event.getNativeEvent()); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_UP: case KeyCodes.KEY_DOWN: break; default: return; } if (!allowMultiSelect_) modifiers = KeyboardShortcut.NONE; event.preventDefault(); event.stopPropagation(); switch (modifiers) { case 0: case KeyboardShortcut.SHIFT: break; default: return; } sortSelectedRows(); boolean clearSelection = modifiers != KeyboardShortcut.SHIFT; switch (event.getNativeKeyCode()) { case KeyCodes.KEY_UP: { selectPreviousRow(clearSelection); break; } case KeyCodes.KEY_DOWN: { selectNextRow(clearSelection); break; } } } private void selectPreviousRow(boolean clearSelection) { int min = selectedRows_.size() > 0 ? selectedRows_.get(0).getRowIndex() : table_.getRows().getLength(); Integer row = findNextValueRow(min, true); if (row != null) { if (clearSelection) clearSelection(); setSelectedPhysical(row, 1, true); ensureRowVisible(row); } } public void selectPreviousRow() { selectPreviousRow(true); } private void selectNextRow(boolean clearSelection) { int max = selectedRows_.size() > 0 ? selectedRows_.get(selectedRows_.size() - 1).getRowIndex() : -1; Integer row = findNextValueRow(max, false); if (row != null) { if (clearSelection) clearSelection(); setSelectedPhysical(row, 1, true); ensureRowVisible(row); } } public void selectNextRow() { selectNextRow(true); } private void ensureRowVisible(final int row) { if (scrollPanel_ != null) DomUtils.ensureVisibleVert(scrollPanel_.getElement(), getRow(row), 0); } private Integer findNextValueRow(int physicalRowIndex, boolean up) { int limit = up ? -1 : table_.getRows().getLength(); int increment = up ? -1 : 1; for (int i = physicalRowIndex + increment; i != limit; i += increment) { if (codec_.isValueRow(getRow(i))) return i; } return null; } public void clearSelection() { while (selectedRows_.size() > 0) setSelected(selectedRows_.get(0), false); } public void addItems(Iterable<TItemInput> items, boolean top) { TableSectionElement tbody = Document.get().createTBodyElement(); for (TItemInput item : items) tbody.appendChild(codec_.getRowForItem(item)); if (top) addToTop(tbody); else getElement().appendChild(tbody); codec_.onRowsChanged(tbody); } protected void addToTop(TableSectionElement tbody) { getElement().insertFirst(tbody); } public void clear() { table_.setInnerText(""); selectedRows_.clear(); } public void focus() { if (focusable_) table_.focus(); } public int getRowCount() { return codec_.getLogicalRowCount(table_); } public void removeTopRows(int rowCount) { if (rowCount <= 0) return; NodeList<TableSectionElement> tBodies = table_.getTBodies(); for (int i = 0; i < tBodies.getLength(); i++) { rowCount = removeTopRows(tBodies.getItem(i), rowCount); if (rowCount == 0) return; } } private int removeTopRows(TableSectionElement tbody, int rowCount) { while (rowCount > 0 && tbody.getRows().getLength() >= 0) { TableRowElement topRow = tbody.getRows().getItem(0); if (codec_.isValueRow(topRow)) rowCount--; selectedRows_.remove(topRow); topRow.removeFromParent(); } if (tbody.getRows().getLength() > 0) codec_.onRowsChanged(tbody); else tbody.removeFromParent(); return rowCount; } public ArrayList<Integer> getSelectedRowIndexes() { sortSelectedRows(); ArrayList<Integer> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.physicalOffsetToLogicalOffset(table_, row.getRowIndex())); return results; } private boolean isSelected(TableRowElement tr) { return tr.getClassName().contains(selectedClassName_); } @Deprecated public void setSelected(int row, boolean selected) { setSelected(getRow(row), selected); } public void setSelected(int offset, int length, boolean selected) { if (codec_.hasNonValueRows()) { // If the codec might have stuck in some non-value rows, we need // to translate the given offset/length to the actual row // offset/length, which may be different (greater). Integer start = codec_.logicalOffsetToPhysicalOffset(table_, offset); Integer end = codec_.logicalOffsetToPhysicalOffset(table_, offset + length); if (start == null || end == null) { return; } offset = start; length = end - start; } setSelectedPhysical(offset, length, selected); } private void setSelectedPhysical(int offset, int length, boolean selected) { for (int i = 0; i < length; i++) setSelected(getRow(offset + i), selected); } public void setSelected(TableRowElement row, boolean selected) { try { if (row.getParentElement().getParentElement() != table_) return; } catch (NullPointerException npe) { return; } catch (JavaScriptException ex) { return; } boolean isCurrentlySelected = isSelected(row); if (isCurrentlySelected == selected) return; if (selected && !codec_.isValueRow(row)) return; setStyleName(row, selectedClassName_, selected); if (selected) selectedRows_.add(row); else selectedRows_.remove(row); if (selected && !allowMultiSelect_) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { fireEvent(new SelectionChangedEvent()); } }); } } public ArrayList<TItemOutput> getSelectedValues() { sortSelectedRows(); ArrayList<TItemOutput> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.getOutputForRow(row)); return results; } private void sortSelectedRows() { Collections.sort(selectedRows_, new Comparator<TableRowElement>() { public int compare(TableRowElement r1, TableRowElement r2) { return r1.getRowIndex() - r2.getRowIndex(); } }); } public ArrayList<TItemOutput2> getSelectedValues2() { sortSelectedRows(); ArrayList<TItemOutput2> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.getOutputForRow2(row)); return results; } public boolean moveSelectionUp() { if (selectedRows_.isEmpty()) return false; sortSelectedRows(); int top = selectedRows_.get(0).getRowIndex(); NodeList<TableRowElement> rows = table_.getRows(); TableRowElement rowToSelect = null; while (--top >= 0) { TableRowElement row = rows.getItem(top); if (codec_.isValueRow(row)) { rowToSelect = row; break; } } if (rowToSelect == null) return false; clearSelection(); setSelected(rowToSelect, true); return true; } public boolean moveSelectionDown() { if (selectedRows_.isEmpty()) return false; sortSelectedRows(); int bottom = selectedRows_.get(selectedRows_.size() - 1).getRowIndex(); NodeList<TableRowElement> rows = table_.getRows(); TableRowElement rowToSelect = null; while (++bottom < rows.getLength()) { TableRowElement row = rows.getItem(bottom); if (codec_.isValueRow(row)) { rowToSelect = row; break; } } if (rowToSelect == null) return false; clearSelection(); setSelected(rowToSelect, true); return true; } private TableRowElement getRow(int row) { return (TableRowElement) table_.getRows().getItem(row).cast(); } public TableRowElement getTopRow() { if (table_.getRows().getLength() > 0) return getRow(0); else return null; } public ArrayList<TableRowElement> getSelectedRows() { return new ArrayList<>(selectedRows_); } public Rectangle getSelectionRect() { if (selectedRows_.isEmpty()) return null; sortSelectedRows(); TableRowElement first = selectedRows_.get(0); TableRowElement last = selectedRows_.get(selectedRows_.size() - 1); int top = first.getOffsetTop(); int bottom = last.getOffsetTop() + last.getOffsetHeight(); int left = first.getOffsetLeft(); int width = first.getOffsetWidth(); return new Rectangle(left, top, width, bottom - top); } protected Element getEventTargetCell(Event event) { Element td = DOM.eventGetTarget(event); for (; td != null; td = DOM.getParent(td)) { // If it's a TD, it might be the one we're looking for. if (td.getPropertyString("tagName").equalsIgnoreCase("td")) { // Make sure it's directly a part of this table before returning // it. Element tr = td.getParentElement(); Element body = tr.getParentElement(); Element table = body.getParentElement(); if (table == getElement()) { return td; } } // If we run into this table's body, we're out of options. if (td == getElement()) { return null; } } return null; } public HandlerRegistration addMouseUpHandler(MouseUpHandler handler) { return addDomHandler(handler, MouseUpEvent.getType()); } public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) { return addDomHandler(handler, MouseWheelEvent.getType()); } public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) { return addDomHandler(handler, MouseDownEvent.getType()); } public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler) { return addDomHandler(handler, MouseMoveEvent.getType()); } public HandlerRegistration addClickHandler(ClickHandler handler) { return addDomHandler(handler, ClickEvent.getType()); } public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) { return addDomHandler(handler, KeyUpEvent.getType()); } public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) { return addDomHandler(handler, KeyDownEvent.getType()); } public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) { return addDomHandler(handler, KeyPressEvent.getType()); } public HandlerRegistration addSelectionChangedHandler( SelectionChangedEvent.Handler handler) { assert !allowMultiSelect_ : "Selection changed event will only fire " + "if multiselect is disabled"; return addHandler(handler, SelectionChangedEvent.TYPE); } private final ArrayList<TableRowElement> selectedRows_ = new ArrayList<>(); private final ItemCodec<TItemInput, TItemOutput, TItemOutput2> codec_; private final TableElement table_; private final String selectedClassName_; private final boolean allowMultiSelect_; private ScrollPanel scrollPanel_; private final boolean focusable_; }
rstudio/rstudio
src/gwt/src/org/rstudio/core/client/widget/FastSelectTable.java
5,588
// target is in between min and max
line_comment
nl
/* * FastSelectTable.java * * Copyright (C) 2021 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.*; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import org.rstudio.core.client.ClassIds; import org.rstudio.core.client.Rectangle; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.NativeWindow; import org.rstudio.core.client.widget.events.SelectionChangedEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class FastSelectTable<TItemInput, TItemOutput, TItemOutput2> extends Widget implements HasAllMouseHandlers, HasClickHandlers, HasAllKeyHandlers { public interface ItemCodec<T, TItemOutput, TItemOutput2> { TableRowElement getRowForItem(T entry); void onRowsChanged(TableSectionElement tbody); TItemOutput getOutputForRow(TableRowElement row); TItemOutput2 getOutputForRow2(TableRowElement row); boolean isValueRow(TableRowElement row); boolean hasNonValueRows(); Integer logicalOffsetToPhysicalOffset(TableElement table, int offset); Integer physicalOffsetToLogicalOffset(TableElement table, int offset); int getLogicalRowCount(TableElement table); } public FastSelectTable(ItemCodec<TItemInput, TItemOutput, TItemOutput2> codec, String selectedClassName, boolean focusable, boolean allowMultiSelect, String title) { codec_ = codec; selectedClassName_ = selectedClassName; focusable_ = focusable; allowMultiSelect_ = allowMultiSelect; table_ = Document.get().createTableElement(); if (focusable_) table_.setTabIndex(0); table_.setCellPadding(0); table_.setCellSpacing(0); table_.setBorder(0); table_.getStyle().setCursor(Cursor.DEFAULT); setClassId(title); setElement(table_); addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { if (event.getNativeButton() != NativeEvent.BUTTON_LEFT) return; event.preventDefault(); NativeWindow.get().focus(); DomUtils.setActive(getElement()); Element cell = getEventTargetCell((Event) event.getNativeEvent()); if (cell == null) return; TableRowElement row = (TableRowElement) cell.getParentElement(); if (codec_.isValueRow(row)) handleRowClick(event, row); } }); addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { event.preventDefault(); } }); addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { handleKeyDown(event); } }); } public void setClassId(String name) { table_.setClassName(ClassIds.FAST_SELECT_TABLE + "_" + ClassIds.idSafeString(name)); } public void setCellPadding(int padding) { table_.setCellPadding(padding); } public void setCellSpacing(int spacing) { table_.setCellSpacing(spacing); } public void setOwningScrollPanel(ScrollPanel scrollPanel) { scrollPanel_ = scrollPanel; } private void handleRowClick(MouseDownEvent event, TableRowElement row) { int modifiers = KeyboardShortcut.getModifierValue(event.getNativeEvent()); modifiers &= ~KeyboardShortcut.ALT; // ALT has no effect if (!allowMultiSelect_) modifiers = KeyboardShortcut.NONE; // We'll treat Ctrl and Meta as equivalent--and normalize to Ctrl. if (KeyboardShortcut.META == (modifiers & KeyboardShortcut.META)) modifiers |= KeyboardShortcut.CTRL; modifiers &= ~KeyboardShortcut.META; if (modifiers == KeyboardShortcut.NONE) { // Select only the target row clearSelection(); setSelected(row, true); } else if (modifiers == KeyboardShortcut.CTRL) { // Toggle the target row setSelected(row, !isSelected(row)); } else { // SHIFT or CTRL+SHIFT int target = row.getRowIndex(); Integer min = null; Integer max = null; for (TableRowElement selectedRow : selectedRows_) { if (min == null) min = selectedRow.getRowIndex(); max = selectedRow.getRowIndex(); } int offset; // selection offset int length; // selection length if (min == null) { // Nothing is selected offset = target; length = 1; } else if (target < min) { // Select target..max offset = target; length = max - target + 1; } else if (target > max) { offset = min; length = target - min + 1; } else { // target is<SUF> if (modifiers == (KeyboardShortcut.CTRL | KeyboardShortcut.SHIFT)) { offset = min; length = target - min + 1; } else { offset = target; length = 1; } } clearSelection(); if (length > 0) { setSelectedPhysical(offset, length, true); } } } private void handleKeyDown(KeyDownEvent event) { int modifiers = KeyboardShortcut.getModifierValue(event.getNativeEvent()); switch (event.getNativeKeyCode()) { case KeyCodes.KEY_UP: case KeyCodes.KEY_DOWN: break; default: return; } if (!allowMultiSelect_) modifiers = KeyboardShortcut.NONE; event.preventDefault(); event.stopPropagation(); switch (modifiers) { case 0: case KeyboardShortcut.SHIFT: break; default: return; } sortSelectedRows(); boolean clearSelection = modifiers != KeyboardShortcut.SHIFT; switch (event.getNativeKeyCode()) { case KeyCodes.KEY_UP: { selectPreviousRow(clearSelection); break; } case KeyCodes.KEY_DOWN: { selectNextRow(clearSelection); break; } } } private void selectPreviousRow(boolean clearSelection) { int min = selectedRows_.size() > 0 ? selectedRows_.get(0).getRowIndex() : table_.getRows().getLength(); Integer row = findNextValueRow(min, true); if (row != null) { if (clearSelection) clearSelection(); setSelectedPhysical(row, 1, true); ensureRowVisible(row); } } public void selectPreviousRow() { selectPreviousRow(true); } private void selectNextRow(boolean clearSelection) { int max = selectedRows_.size() > 0 ? selectedRows_.get(selectedRows_.size() - 1).getRowIndex() : -1; Integer row = findNextValueRow(max, false); if (row != null) { if (clearSelection) clearSelection(); setSelectedPhysical(row, 1, true); ensureRowVisible(row); } } public void selectNextRow() { selectNextRow(true); } private void ensureRowVisible(final int row) { if (scrollPanel_ != null) DomUtils.ensureVisibleVert(scrollPanel_.getElement(), getRow(row), 0); } private Integer findNextValueRow(int physicalRowIndex, boolean up) { int limit = up ? -1 : table_.getRows().getLength(); int increment = up ? -1 : 1; for (int i = physicalRowIndex + increment; i != limit; i += increment) { if (codec_.isValueRow(getRow(i))) return i; } return null; } public void clearSelection() { while (selectedRows_.size() > 0) setSelected(selectedRows_.get(0), false); } public void addItems(Iterable<TItemInput> items, boolean top) { TableSectionElement tbody = Document.get().createTBodyElement(); for (TItemInput item : items) tbody.appendChild(codec_.getRowForItem(item)); if (top) addToTop(tbody); else getElement().appendChild(tbody); codec_.onRowsChanged(tbody); } protected void addToTop(TableSectionElement tbody) { getElement().insertFirst(tbody); } public void clear() { table_.setInnerText(""); selectedRows_.clear(); } public void focus() { if (focusable_) table_.focus(); } public int getRowCount() { return codec_.getLogicalRowCount(table_); } public void removeTopRows(int rowCount) { if (rowCount <= 0) return; NodeList<TableSectionElement> tBodies = table_.getTBodies(); for (int i = 0; i < tBodies.getLength(); i++) { rowCount = removeTopRows(tBodies.getItem(i), rowCount); if (rowCount == 0) return; } } private int removeTopRows(TableSectionElement tbody, int rowCount) { while (rowCount > 0 && tbody.getRows().getLength() >= 0) { TableRowElement topRow = tbody.getRows().getItem(0); if (codec_.isValueRow(topRow)) rowCount--; selectedRows_.remove(topRow); topRow.removeFromParent(); } if (tbody.getRows().getLength() > 0) codec_.onRowsChanged(tbody); else tbody.removeFromParent(); return rowCount; } public ArrayList<Integer> getSelectedRowIndexes() { sortSelectedRows(); ArrayList<Integer> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.physicalOffsetToLogicalOffset(table_, row.getRowIndex())); return results; } private boolean isSelected(TableRowElement tr) { return tr.getClassName().contains(selectedClassName_); } @Deprecated public void setSelected(int row, boolean selected) { setSelected(getRow(row), selected); } public void setSelected(int offset, int length, boolean selected) { if (codec_.hasNonValueRows()) { // If the codec might have stuck in some non-value rows, we need // to translate the given offset/length to the actual row // offset/length, which may be different (greater). Integer start = codec_.logicalOffsetToPhysicalOffset(table_, offset); Integer end = codec_.logicalOffsetToPhysicalOffset(table_, offset + length); if (start == null || end == null) { return; } offset = start; length = end - start; } setSelectedPhysical(offset, length, selected); } private void setSelectedPhysical(int offset, int length, boolean selected) { for (int i = 0; i < length; i++) setSelected(getRow(offset + i), selected); } public void setSelected(TableRowElement row, boolean selected) { try { if (row.getParentElement().getParentElement() != table_) return; } catch (NullPointerException npe) { return; } catch (JavaScriptException ex) { return; } boolean isCurrentlySelected = isSelected(row); if (isCurrentlySelected == selected) return; if (selected && !codec_.isValueRow(row)) return; setStyleName(row, selectedClassName_, selected); if (selected) selectedRows_.add(row); else selectedRows_.remove(row); if (selected && !allowMultiSelect_) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { fireEvent(new SelectionChangedEvent()); } }); } } public ArrayList<TItemOutput> getSelectedValues() { sortSelectedRows(); ArrayList<TItemOutput> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.getOutputForRow(row)); return results; } private void sortSelectedRows() { Collections.sort(selectedRows_, new Comparator<TableRowElement>() { public int compare(TableRowElement r1, TableRowElement r2) { return r1.getRowIndex() - r2.getRowIndex(); } }); } public ArrayList<TItemOutput2> getSelectedValues2() { sortSelectedRows(); ArrayList<TItemOutput2> results = new ArrayList<>(); for (TableRowElement row : selectedRows_) results.add(codec_.getOutputForRow2(row)); return results; } public boolean moveSelectionUp() { if (selectedRows_.isEmpty()) return false; sortSelectedRows(); int top = selectedRows_.get(0).getRowIndex(); NodeList<TableRowElement> rows = table_.getRows(); TableRowElement rowToSelect = null; while (--top >= 0) { TableRowElement row = rows.getItem(top); if (codec_.isValueRow(row)) { rowToSelect = row; break; } } if (rowToSelect == null) return false; clearSelection(); setSelected(rowToSelect, true); return true; } public boolean moveSelectionDown() { if (selectedRows_.isEmpty()) return false; sortSelectedRows(); int bottom = selectedRows_.get(selectedRows_.size() - 1).getRowIndex(); NodeList<TableRowElement> rows = table_.getRows(); TableRowElement rowToSelect = null; while (++bottom < rows.getLength()) { TableRowElement row = rows.getItem(bottom); if (codec_.isValueRow(row)) { rowToSelect = row; break; } } if (rowToSelect == null) return false; clearSelection(); setSelected(rowToSelect, true); return true; } private TableRowElement getRow(int row) { return (TableRowElement) table_.getRows().getItem(row).cast(); } public TableRowElement getTopRow() { if (table_.getRows().getLength() > 0) return getRow(0); else return null; } public ArrayList<TableRowElement> getSelectedRows() { return new ArrayList<>(selectedRows_); } public Rectangle getSelectionRect() { if (selectedRows_.isEmpty()) return null; sortSelectedRows(); TableRowElement first = selectedRows_.get(0); TableRowElement last = selectedRows_.get(selectedRows_.size() - 1); int top = first.getOffsetTop(); int bottom = last.getOffsetTop() + last.getOffsetHeight(); int left = first.getOffsetLeft(); int width = first.getOffsetWidth(); return new Rectangle(left, top, width, bottom - top); } protected Element getEventTargetCell(Event event) { Element td = DOM.eventGetTarget(event); for (; td != null; td = DOM.getParent(td)) { // If it's a TD, it might be the one we're looking for. if (td.getPropertyString("tagName").equalsIgnoreCase("td")) { // Make sure it's directly a part of this table before returning // it. Element tr = td.getParentElement(); Element body = tr.getParentElement(); Element table = body.getParentElement(); if (table == getElement()) { return td; } } // If we run into this table's body, we're out of options. if (td == getElement()) { return null; } } return null; } public HandlerRegistration addMouseUpHandler(MouseUpHandler handler) { return addDomHandler(handler, MouseUpEvent.getType()); } public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) { return addDomHandler(handler, MouseWheelEvent.getType()); } public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) { return addDomHandler(handler, MouseDownEvent.getType()); } public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler) { return addDomHandler(handler, MouseMoveEvent.getType()); } public HandlerRegistration addClickHandler(ClickHandler handler) { return addDomHandler(handler, ClickEvent.getType()); } public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) { return addDomHandler(handler, KeyUpEvent.getType()); } public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) { return addDomHandler(handler, KeyDownEvent.getType()); } public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) { return addDomHandler(handler, KeyPressEvent.getType()); } public HandlerRegistration addSelectionChangedHandler( SelectionChangedEvent.Handler handler) { assert !allowMultiSelect_ : "Selection changed event will only fire " + "if multiselect is disabled"; return addHandler(handler, SelectionChangedEvent.TYPE); } private final ArrayList<TableRowElement> selectedRows_ = new ArrayList<>(); private final ItemCodec<TItemInput, TItemOutput, TItemOutput2> codec_; private final TableElement table_; private final String selectedClassName_; private final boolean allowMultiSelect_; private ScrollPanel scrollPanel_; private final boolean focusable_; }
52522_1
package project2_webgame; import java.awt.Image; import java.awt.Point; public class Map08 extends Map { public Map08(Image[][] sprites) { super.sprites = sprites; } @Override public void doStuff() { data[26][2] = true; data[27][2] = true; data[28][2] = true; data[3][3] = true; data[26][3] = true; data[27][3] = true; data[28][3] = true; data[15][4] = true; data[16][4] = true; data[26][4] = true; data[27][4] = true; data[28][4] = true; data[15][5] = true; data[16][5] = true; data[18][5] = true; data[19][5] = true; data[15][6] = true; data[16][6] = true; data[18][6] = true; data[19][6] = true; data[15][7] = true; data[16][7] = true; data[19][7] = true; data[20][7] = true; data[8][8] = true; data[9][8] = true; data[14][8] = true; data[15][8] = true; data[16][8] = true; data[17][8] = true; data[19][8] = true; data[20][8] = true; data[8][9] = true; data[9][9] = true; data[14][9] = true; data[15][9] = true; data[16][9] = true; data[17][9] = true; data[14][10] = true; data[15][10] = true; data[16][10] = true; data[17][10] = true; data[20][10] = true; data[21][10] = true; data[22][10] = true; data[8][11] = true; data[9][11] = true; data[10][11] = true; data[14][11] = true; data[15][11] = true; data[16][11] = true; data[17][11] = true; data[20][11] = true; data[21][11] = true; data[22][11] = true; data[8][12] = true; data[9][12] = true; data[10][12] = true; data[20][12] = true; data[21][12] = true; data[22][12] = true; data[10][13] = true; data[20][13] = true; data[21][13] = true; data[22][13] = true; data[10][14] = true; data[16][14] = true; data[17][14] = true; data[18][14] = true; data[19][14] = true; data[20][14] = true; data[21][14] = true; data[22][14] = true; data[10][15] = true; data[11][15] = true; data[12][15] = true; data[13][15] = true; data[14][15] = true; data[17][15] = true; data[18][15] = true; data[19][15] = true; data[20][15] = true; data[21][15] = true; data[22][15] = true; data[17][16] = true; data[18][16] = true; data[19][16] = true; data[28][16] = true; data[29][16] = true; data[5][17] = true; data[6][17] = true; data[28][17] = true; data[29][17] = true; data[5][18] = true; data[6][18] = true; startPositions = new Point[] { new Point(2, 3), new Point(6, 5), new Point(3, 8), new Point(6, 13), new Point(2, 16), new Point(12, 17), new Point(20, 7), new Point(25, 14), new Point(30, 7), new Point(21, 2), }; // pad1 naar boven vanaf zeikant // pad2 naar beneden vanaf zeikant // pad3 naar boven // pad4 naar beneden // pad5+6 van zeikant naar beneden waypoints.add(new Point[] { new Point(14, 0), new Point(14, 1), new Point(14, 2), new Point(14, 3), new Point(14, 4), new Point(14, 5), new Point(14, 6), new Point(14, 7), new Point(13, 7), new Point(13, 8), new Point(13, 9), new Point(13, 10), new Point(13, 11), new Point(13, 12), new Point(14, 12), new Point(15, 12), new Point(16, 12), new Point(17, 12), new Point(18, 12), new Point(18, 11), new Point(18, 10), new Point(18, 9), new Point(18, 8), new Point(18, 7), new Point(17, 7), new Point(17, 6), new Point(17, 5), new Point(17, 4), new Point(17, 3), new Point(17, 2), new Point(17, 1), new Point(17, 0), }); waypoints.add(new Point[] { new Point(13, 0), new Point(13, 1), new Point(13, 2), new Point(13, 3), new Point(13, 4), new Point(13, 5), new Point(13, 6), new Point(12, 6), new Point(12, 7), new Point(12, 8), new Point(12, 9), new Point(12, 10), new Point(12, 11), new Point(12, 12), new Point(12, 13), new Point(13, 13), new Point(14, 13), new Point(15, 13), new Point(16, 13), new Point(17, 13), new Point(18, 13), new Point(19, 13), new Point(19, 12), new Point(19, 11), new Point(19, 10), new Point(19, 9), new Point(20, 9), new Point(21, 9), new Point(22, 9), new Point(23, 9), new Point(24, 9), new Point(24, 8), new Point(24, 7), new Point(25, 7), new Point(26, 7), new Point(27, 7), new Point(27, 8), new Point(27, 9), new Point(27, 10), new Point(28, 10), new Point(29, 10), new Point(30, 10), new Point(31, 10), new Point(32, 10), new Point(33, 10), }); waypoints.add(new Point[] { new Point(12, 0), new Point(12, 1), new Point(12, 2), new Point(12, 3), new Point(12, 4), new Point(12, 5), new Point(11, 5), new Point(11, 6), new Point(11, 7), new Point(11, 8), new Point(11, 9), new Point(11, 10), new Point(11, 11), new Point(11, 12), new Point(11, 13), new Point(11, 14), new Point(12, 14), new Point(13, 14), new Point(14, 14), new Point(15, 14), new Point(15, 15), new Point(15, 16), new Point(15, 17), new Point(15, 18), new Point(15, 19), }); waypoints.add(new Point[] { new Point(11, 0), new Point(11, 1), new Point(11, 2), new Point(11, 3), new Point(11, 4), new Point(10, 4), new Point(10, 5), new Point(10, 6), new Point(10, 7), new Point(10, 8), new Point(10, 9), new Point(10, 10), new Point(9, 10), new Point(8, 10), new Point(7, 10), new Point(6, 10), new Point(5, 10), new Point(4, 10), new Point(4, 11), new Point(4, 12), new Point(4, 13), new Point(3, 13), new Point(2, 13), new Point(2, 12), new Point(2, 11), new Point(2, 10), new Point(1, 10), new Point(0, 10), }); // 26 - 29 // 4 waves /** Amount of enemies */ // 10, // /** Time between the last wave and this wave */ // 10, // /** Spawn time between each enemy */ // 5, // /** Health */ // 10, // /** Speed multiplier */ // 1f, // /** Texture for this enemy */ // sprites[1], // /** Way-points to walk on */ // waypoints.get(0), // /** Reference to player */ // player, // /** Reference to waveManager */ // waveManager) // money = 15 waves = new Wave[] { new Wave(10, 10, 5, 160, 2f, sprites[26], waypoints.get(0), player, waveManager, 13, 1), new Wave(10, 0, 5, 160, 2f, sprites[27], waypoints.get(2), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(1), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[27], waypoints.get(3), player, waveManager, 13, 1), new Wave(15, 40, 5, 170, 2f, sprites[27], waypoints.get(3), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(2), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[26], waypoints.get(1), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(0), player, waveManager, 13, 1), new Wave(40, 60, 3, 130, 4f, sprites[27], waypoints.get(0), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[28], waypoints.get(3), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[26], waypoints.get(1), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[28], waypoints.get(2), player, waveManager, 13, 1), new Wave(1, 100, 6, 3000, 0.5f, sprites[29], waypoints.get(0), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(1), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(2), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(3), player, waveManager, 250, 5), }; } }
rtroost/The_Final_War
src/project2_webgame/Map08.java
3,462
// pad2 naar beneden vanaf zeikant
line_comment
nl
package project2_webgame; import java.awt.Image; import java.awt.Point; public class Map08 extends Map { public Map08(Image[][] sprites) { super.sprites = sprites; } @Override public void doStuff() { data[26][2] = true; data[27][2] = true; data[28][2] = true; data[3][3] = true; data[26][3] = true; data[27][3] = true; data[28][3] = true; data[15][4] = true; data[16][4] = true; data[26][4] = true; data[27][4] = true; data[28][4] = true; data[15][5] = true; data[16][5] = true; data[18][5] = true; data[19][5] = true; data[15][6] = true; data[16][6] = true; data[18][6] = true; data[19][6] = true; data[15][7] = true; data[16][7] = true; data[19][7] = true; data[20][7] = true; data[8][8] = true; data[9][8] = true; data[14][8] = true; data[15][8] = true; data[16][8] = true; data[17][8] = true; data[19][8] = true; data[20][8] = true; data[8][9] = true; data[9][9] = true; data[14][9] = true; data[15][9] = true; data[16][9] = true; data[17][9] = true; data[14][10] = true; data[15][10] = true; data[16][10] = true; data[17][10] = true; data[20][10] = true; data[21][10] = true; data[22][10] = true; data[8][11] = true; data[9][11] = true; data[10][11] = true; data[14][11] = true; data[15][11] = true; data[16][11] = true; data[17][11] = true; data[20][11] = true; data[21][11] = true; data[22][11] = true; data[8][12] = true; data[9][12] = true; data[10][12] = true; data[20][12] = true; data[21][12] = true; data[22][12] = true; data[10][13] = true; data[20][13] = true; data[21][13] = true; data[22][13] = true; data[10][14] = true; data[16][14] = true; data[17][14] = true; data[18][14] = true; data[19][14] = true; data[20][14] = true; data[21][14] = true; data[22][14] = true; data[10][15] = true; data[11][15] = true; data[12][15] = true; data[13][15] = true; data[14][15] = true; data[17][15] = true; data[18][15] = true; data[19][15] = true; data[20][15] = true; data[21][15] = true; data[22][15] = true; data[17][16] = true; data[18][16] = true; data[19][16] = true; data[28][16] = true; data[29][16] = true; data[5][17] = true; data[6][17] = true; data[28][17] = true; data[29][17] = true; data[5][18] = true; data[6][18] = true; startPositions = new Point[] { new Point(2, 3), new Point(6, 5), new Point(3, 8), new Point(6, 13), new Point(2, 16), new Point(12, 17), new Point(20, 7), new Point(25, 14), new Point(30, 7), new Point(21, 2), }; // pad1 naar boven vanaf zeikant // pad2 naar<SUF> // pad3 naar boven // pad4 naar beneden // pad5+6 van zeikant naar beneden waypoints.add(new Point[] { new Point(14, 0), new Point(14, 1), new Point(14, 2), new Point(14, 3), new Point(14, 4), new Point(14, 5), new Point(14, 6), new Point(14, 7), new Point(13, 7), new Point(13, 8), new Point(13, 9), new Point(13, 10), new Point(13, 11), new Point(13, 12), new Point(14, 12), new Point(15, 12), new Point(16, 12), new Point(17, 12), new Point(18, 12), new Point(18, 11), new Point(18, 10), new Point(18, 9), new Point(18, 8), new Point(18, 7), new Point(17, 7), new Point(17, 6), new Point(17, 5), new Point(17, 4), new Point(17, 3), new Point(17, 2), new Point(17, 1), new Point(17, 0), }); waypoints.add(new Point[] { new Point(13, 0), new Point(13, 1), new Point(13, 2), new Point(13, 3), new Point(13, 4), new Point(13, 5), new Point(13, 6), new Point(12, 6), new Point(12, 7), new Point(12, 8), new Point(12, 9), new Point(12, 10), new Point(12, 11), new Point(12, 12), new Point(12, 13), new Point(13, 13), new Point(14, 13), new Point(15, 13), new Point(16, 13), new Point(17, 13), new Point(18, 13), new Point(19, 13), new Point(19, 12), new Point(19, 11), new Point(19, 10), new Point(19, 9), new Point(20, 9), new Point(21, 9), new Point(22, 9), new Point(23, 9), new Point(24, 9), new Point(24, 8), new Point(24, 7), new Point(25, 7), new Point(26, 7), new Point(27, 7), new Point(27, 8), new Point(27, 9), new Point(27, 10), new Point(28, 10), new Point(29, 10), new Point(30, 10), new Point(31, 10), new Point(32, 10), new Point(33, 10), }); waypoints.add(new Point[] { new Point(12, 0), new Point(12, 1), new Point(12, 2), new Point(12, 3), new Point(12, 4), new Point(12, 5), new Point(11, 5), new Point(11, 6), new Point(11, 7), new Point(11, 8), new Point(11, 9), new Point(11, 10), new Point(11, 11), new Point(11, 12), new Point(11, 13), new Point(11, 14), new Point(12, 14), new Point(13, 14), new Point(14, 14), new Point(15, 14), new Point(15, 15), new Point(15, 16), new Point(15, 17), new Point(15, 18), new Point(15, 19), }); waypoints.add(new Point[] { new Point(11, 0), new Point(11, 1), new Point(11, 2), new Point(11, 3), new Point(11, 4), new Point(10, 4), new Point(10, 5), new Point(10, 6), new Point(10, 7), new Point(10, 8), new Point(10, 9), new Point(10, 10), new Point(9, 10), new Point(8, 10), new Point(7, 10), new Point(6, 10), new Point(5, 10), new Point(4, 10), new Point(4, 11), new Point(4, 12), new Point(4, 13), new Point(3, 13), new Point(2, 13), new Point(2, 12), new Point(2, 11), new Point(2, 10), new Point(1, 10), new Point(0, 10), }); // 26 - 29 // 4 waves /** Amount of enemies */ // 10, // /** Time between the last wave and this wave */ // 10, // /** Spawn time between each enemy */ // 5, // /** Health */ // 10, // /** Speed multiplier */ // 1f, // /** Texture for this enemy */ // sprites[1], // /** Way-points to walk on */ // waypoints.get(0), // /** Reference to player */ // player, // /** Reference to waveManager */ // waveManager) // money = 15 waves = new Wave[] { new Wave(10, 10, 5, 160, 2f, sprites[26], waypoints.get(0), player, waveManager, 13, 1), new Wave(10, 0, 5, 160, 2f, sprites[27], waypoints.get(2), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(1), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[27], waypoints.get(3), player, waveManager, 13, 1), new Wave(15, 40, 5, 170, 2f, sprites[27], waypoints.get(3), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(2), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[26], waypoints.get(1), player, waveManager, 13, 1), new Wave(15, 0, 5, 170, 2f, sprites[28], waypoints.get(0), player, waveManager, 13, 1), new Wave(40, 60, 3, 130, 4f, sprites[27], waypoints.get(0), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[28], waypoints.get(3), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[26], waypoints.get(1), player, waveManager, 13, 1), new Wave(40, 0, 3, 130, 4f, sprites[28], waypoints.get(2), player, waveManager, 13, 1), new Wave(1, 100, 6, 3000, 0.5f, sprites[29], waypoints.get(0), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(1), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(2), player, waveManager, 250, 5), new Wave(1, 0, 6, 3000, 0.5f, sprites[29], waypoints.get(3), player, waveManager, 250, 5), }; } }
132034_22
/* * @(#)DropTarget.java 1.53 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.awt.dnd; import java.util.TooManyListenersException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.SystemFlavorMap; import javax.swing.Timer; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.awt.dnd.peer.DropTargetPeer; /** * The <code>DropTarget</code> is associated * with a <code>Component</code> when that <code>Component</code> * wishes * to accept drops during Drag and Drop operations. * <P> * Each * <code>DropTarget</code> is associated with a <code>FlavorMap</code>. * The default <code>FlavorMap</code> hereafter designates the * <code>FlavorMap</code> returned by <code>SystemFlavorMap.getDefaultFlavorMap()</code>. * * @version 1.53, 03/23/10 * @since 1.2 */ public class DropTarget implements DropTargetListener, Serializable { private static final long serialVersionUID = -6283860791671019047L; /** * Creates a new DropTarget given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) to * support, a <code>DropTargetListener</code> * to handle event processing, a <code>boolean</code> indicating * if the <code>DropTarget</code> is currently accepting drops, and * a <code>FlavorMap</code> to use (or null for the default <CODE>FlavorMap</CODE>). * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @param act Is the <code>DropTarget</code> accepting drops. * @param fm The <code>FlavorMap</code> to use, or null for the default <CODE>FlavorMap</CODE> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl, boolean act, FlavorMap fm) throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } component = c; setDefaultActions(ops); if (dtl != null) try { addDropTargetListener(dtl); } catch (TooManyListenersException tmle) { // do nothing! } if (c != null) { c.setDropTarget(this); setActive(act); } if (fm != null) { flavorMap = fm; } else { flavorMap = SystemFlavorMap.getDefaultFlavorMap(); } } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) * to support, a <code>DropTargetListener</code> * to handle event processing, and a <code>boolean</code> indicating * if the <code>DropTarget</code> is currently accepting drops. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @param act Is the <code>DropTarget</code> accepting drops. * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl, boolean act) throws HeadlessException { this(c, ops, dtl, act, null); } /** * Creates a <code>DropTarget</code>. * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget() throws HeadlessException { this(null, DnDConstants.ACTION_COPY_OR_MOVE, null, true, null); } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, and the <code>DropTargetListener</code> * to handle event processing. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, DropTargetListener dtl) throws HeadlessException { this(c, DnDConstants.ACTION_COPY_OR_MOVE, dtl, true, null); } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) to support, and a * <code>DropTargetListener</code> to handle event processing. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl) throws HeadlessException { this(c, ops, dtl, true); } /** * Note: this interface is required to permit the safe association * of a DropTarget with a Component in one of two ways, either: * <code> component.setDropTarget(droptarget); </code> * or <code> droptarget.setComponent(component); </code> * <P> * The Component will receive drops only if it is enabled. * @param c The new <code>Component</code> this <code>DropTarget</code> * is to be associated with.<P> */ public synchronized void setComponent(Component c) { if (component == c || component != null && component.equals(c)) return; Component old; ComponentPeer oldPeer = null; if ((old = component) != null) { clearAutoscroll(); component = null; if (componentPeer != null) { oldPeer = componentPeer; removeNotify(componentPeer); } old.setDropTarget(null); } if ((component = c) != null) try { c.setDropTarget(this); } catch (Exception e) { // undo the change if (old != null) { old.setDropTarget(this); addNotify(oldPeer); } } } /** * Gets the <code>Component</code> associated * with this <code>DropTarget</code>. * <P> * @return the current <code>Component</code> */ public synchronized Component getComponent() { return component; } /** * Sets the default acceptable actions for this <code>DropTarget</code> * <P> * @param ops the default actions * <P> * @see java.awt.dnd.DnDConstants */ public void setDefaultActions(int ops) { getDropTargetContext().setTargetActions(ops & (DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_REFERENCE)); } /* * Called by DropTargetContext.setTargetActions() * with appropriate synchronization. */ void doSetDefaultActions(int ops) { actions = ops; } /** * Gets an <code>int</code> representing the * current action(s) supported by this <code>DropTarget</code>. * <P> * @return the current default actions */ public int getDefaultActions() { return actions; } /** * Sets the DropTarget active if <code>true</code>, * inactive if <code>false</code>. * <P> * @param isActive sets the <code>DropTarget</code> (in)active. */ public synchronized void setActive(boolean isActive) { if (isActive != active) { active = isActive; } if (!active) clearAutoscroll(); } /** * Reports whether or not * this <code>DropTarget</code> * is currently active (ready to accept drops). * <P> * @return <CODE>true</CODE> if active, <CODE>false</CODE> if not */ public boolean isActive() { return active; } /** * Adds a new <code>DropTargetListener</code> (UNICAST SOURCE). * <P> * @param dtl The new <code>DropTargetListener</code> * <P> * @throws <code>TooManyListenersException</code> if a * <code>DropTargetListener</code> is already added to this * <code>DropTarget</code>. */ public synchronized void addDropTargetListener(DropTargetListener dtl) throws TooManyListenersException { if (dtl == null) return; if (equals(dtl)) throw new IllegalArgumentException("DropTarget may not be its own Listener"); if (dtListener == null) dtListener = dtl; else throw new TooManyListenersException(); } /** * Removes the current <code>DropTargetListener</code> (UNICAST SOURCE). * <P> * @param dtl the DropTargetListener to deregister. */ public synchronized void removeDropTargetListener(DropTargetListener dtl) { if (dtl != null && dtListener != null) { if(dtListener.equals(dtl)) dtListener = null; else throw new IllegalArgumentException("listener mismatch"); } } /** * Calls <code>dragEnter</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dragEnter(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null) { dtListener.dragEnter(dtde); } else dtde.getDropTargetContext().setTargetActions(DnDConstants.ACTION_NONE); initializeAutoscrolling(dtde.getLocation()); } /** * Calls <code>dragOver</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dragOver(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null && active) dtListener.dragOver(dtde); updateAutoscroll(dtde.getLocation()); } /** * Calls <code>dropActionChanged</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dropActionChanged(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null) dtListener.dropActionChanged(dtde); updateAutoscroll(dtde.getLocation()); } /** * Calls <code>dragExit</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * <p> * This method itself does not throw any exception * for null parameter but for exceptions thrown by * the respective method of the listener. * * @param dte the <code>DropTargetEvent</code> * * @see #isActive */ public synchronized void dragExit(DropTargetEvent dte) { if (!active) return; if (dtListener != null && active) dtListener.dragExit(dte); clearAutoscroll(); } /** * Calls <code>drop</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDropEvent</code> * if this <code>DropTarget</code> is active. * * @param dtde the <code>DropTargetDropEvent</code> * * @throws NullPointerException if <code>dtde</code> is null * and at least one of the following is true: this * <code>DropTarget</code> is not active, or there is * no a <code>DropTargetListener</code> registered. * * @see #isActive */ public synchronized void drop(DropTargetDropEvent dtde) { clearAutoscroll(); if (dtListener != null && active) dtListener.drop(dtde); else { // we should'nt get here ... dtde.rejectDrop(); } } /** * Gets the <code>FlavorMap</code> * associated with this <code>DropTarget</code>. * If no <code>FlavorMap</code> has been set for this * <code>DropTarget</code>, it is associated with the default * <code>FlavorMap</code>. * <P> * @return the FlavorMap for this DropTarget */ public FlavorMap getFlavorMap() { return flavorMap; } /** * Sets the <code>FlavorMap</code> associated * with this <code>DropTarget</code>. * <P> * @param fm the new <code>FlavorMap</code>, or null to * associate the default FlavorMap with this DropTarget. */ public void setFlavorMap(FlavorMap fm) { flavorMap = fm == null ? SystemFlavorMap.getDefaultFlavorMap() : fm; } /** * Notify the DropTarget that it has been associated with a Component * ********************************************************************** * This method is usually called from java.awt.Component.addNotify() of * the Component associated with this DropTarget to notify the DropTarget * that a ComponentPeer has been associated with that Component. * * Calling this method, other than to notify this DropTarget of the * association of the ComponentPeer with the Component may result in * a malfunction of the DnD system. ********************************************************************** * <P> * @param peer The Peer of the Component we are associated with! * */ public void addNotify(ComponentPeer peer) { if (peer == componentPeer) return; componentPeer = peer; for (Component c = component; c != null && peer instanceof LightweightPeer; c = c.getParent()) { peer = c.getPeer(); } if (peer instanceof DropTargetPeer) { nativePeer = peer; ((DropTargetPeer)peer).addDropTarget(this); } else { nativePeer = null; } } /** * Notify the DropTarget that it has been disassociated from a Component * ********************************************************************** * This method is usually called from java.awt.Component.removeNotify() of * the Component associated with this DropTarget to notify the DropTarget * that a ComponentPeer has been disassociated with that Component. * * Calling this method, other than to notify this DropTarget of the * disassociation of the ComponentPeer from the Component may result in * a malfunction of the DnD system. ********************************************************************** * <P> * @param peer The Peer of the Component we are being disassociated from! */ public void removeNotify(ComponentPeer peer) { if (nativePeer != null) ((DropTargetPeer)nativePeer).removeDropTarget(this); componentPeer = nativePeer = null; } /** * Gets the <code>DropTargetContext</code> associated * with this <code>DropTarget</code>. * <P> * @return the <code>DropTargetContext</code> associated with this <code>DropTarget</code>. */ public DropTargetContext getDropTargetContext() { return dropTargetContext; } /** * Creates the DropTargetContext associated with this DropTarget. * Subclasses may override this method to instantiate their own * DropTargetContext subclass. * * This call is typically *only* called by the platform's * DropTargetContextPeer as a drag operation encounters this * DropTarget. Accessing the Context while no Drag is current * has undefined results. */ protected DropTargetContext createDropTargetContext() { return new DropTargetContext(this); } /** * Serializes this <code>DropTarget</code>. Performs default serialization, * and then writes out this object's <code>DropTargetListener</code> if and * only if it can be serialized. If not, <code>null</code> is written * instead. * * @serialData The default serializable fields, in alphabetical order, * followed by either a <code>DropTargetListener</code> * instance, or <code>null</code>. * @since 1.4 */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeObject(SerializationTester.test(dtListener) ? dtListener : null); } /** * Deserializes this <code>DropTarget</code>. This method first performs * default deserialization for all non-<code>transient</code> fields. An * attempt is then made to deserialize this object's * <code>DropTargetListener</code> as well. This is first attempted by * deserializing the field <code>dtListener</code>, because, in releases * prior to 1.4, a non-<code>transient</code> field of this name stored the * <code>DropTargetListener</code>. If this fails, the next object in the * stream is used instead. * * @since 1.4 */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { ObjectInputStream.GetField f = s.readFields(); try { dropTargetContext = (DropTargetContext)f.get("dropTargetContext", null); } catch (IllegalArgumentException e) { // Pre-1.4 support. 'dropTargetContext' was previoulsy transient } if (dropTargetContext == null) { dropTargetContext = createDropTargetContext(); } component = (Component)f.get("component", null); actions = f.get("actions", DnDConstants.ACTION_COPY_OR_MOVE); active = f.get("active", true); // Pre-1.4 support. 'dtListener' was previously non-transient try { dtListener = (DropTargetListener)f.get("dtListener", null); } catch (IllegalArgumentException e) { // 1.4-compatible byte stream. 'dtListener' was written explicitly dtListener = (DropTargetListener)s.readObject(); } } /*********************************************************************/ /** * this protected nested class implements autoscrolling */ protected static class DropTargetAutoScroller implements ActionListener { /** * construct a DropTargetAutoScroller * <P> * @param c the <code>Component</code> * @param p the <code>Point</code> */ protected DropTargetAutoScroller(Component c, Point p) { super(); component = c; autoScroll = (Autoscroll)component; Toolkit t = Toolkit.getDefaultToolkit(); Integer initial = Integer.valueOf(100); Integer interval = Integer.valueOf(100); try { initial = (Integer)t.getDesktopProperty("DnD.Autoscroll.initialDelay"); } catch (Exception e) { // ignore } try { interval = (Integer)t.getDesktopProperty("DnD.Autoscroll.interval"); } catch (Exception e) { // ignore } timer = new Timer(interval.intValue(), this); timer.setCoalesce(true); timer.setInitialDelay(initial.intValue()); locn = p; prev = p; try { hysteresis = ((Integer)t.getDesktopProperty("DnD.Autoscroll.cursorHysteresis")).intValue(); } catch (Exception e) { // ignore } timer.start(); } /** * update the geometry of the autoscroll region */ private void updateRegion() { Insets i = autoScroll.getAutoscrollInsets(); Dimension size = component.getSize(); if (size.width != outer.width || size.height != outer.height) outer.reshape(0, 0, size.width, size.height); if (inner.x != i.left || inner.y != i.top) inner.setLocation(i.left, i.top); int newWidth = size.width - (i.left + i.right); int newHeight = size.height - (i.top + i.bottom); if (newWidth != inner.width || newHeight != inner.height) inner.setSize(newWidth, newHeight); } /** * cause autoscroll to occur * <P> * @param newLocn the <code>Point</code> */ protected synchronized void updateLocation(Point newLocn) { prev = locn; locn = newLocn; if (Math.abs(locn.x - prev.x) > hysteresis || Math.abs(locn.y - prev.y) > hysteresis) { if (timer.isRunning()) timer.stop(); } else { if (!timer.isRunning()) timer.start(); } } /** * cause autoscrolling to stop */ protected void stop() { timer.stop(); } /** * cause autoscroll to occur * <P> * @param e the <code>ActionEvent</code> */ public synchronized void actionPerformed(ActionEvent e) { updateRegion(); if (outer.contains(locn) && !inner.contains(locn)) autoScroll.autoscroll(locn); } /* * fields */ private Component component; private Autoscroll autoScroll; private Timer timer; private Point locn; private Point prev; private Rectangle outer = new Rectangle(); private Rectangle inner = new Rectangle(); private int hysteresis = 10; } /*********************************************************************/ /** * create an embedded autoscroller * <P> * @param c the <code>Component</code> * @param p the <code>Point</code> */ protected DropTargetAutoScroller createDropTargetAutoScroller(Component c, Point p) { return new DropTargetAutoScroller(c, p); } /** * initialize autoscrolling * <P> * @param p the <code>Point</code> */ protected void initializeAutoscrolling(Point p) { if (component == null || !(component instanceof Autoscroll)) return; autoScroller = createDropTargetAutoScroller(component, p); } /** * update autoscrolling with current cursor locn * <P> * @param dragCursorLocn the <code>Point</code> */ protected void updateAutoscroll(Point dragCursorLocn) { if (autoScroller != null) autoScroller.updateLocation(dragCursorLocn); } /** * clear autoscrolling */ protected void clearAutoscroll() { if (autoScroller != null) { autoScroller.stop(); autoScroller = null; } } /** * The DropTargetContext associated with this DropTarget. * * @serial */ private DropTargetContext dropTargetContext = createDropTargetContext(); /** * The Component associated with this DropTarget. * * @serial */ private Component component; /* * That Component's Peer */ private transient ComponentPeer componentPeer; /* * That Component's "native" Peer */ private transient ComponentPeer nativePeer; /** * Default permissible actions supported by this DropTarget. * * @see #setDefaultActions * @see #getDefaultActions * @serial */ int actions = DnDConstants.ACTION_COPY_OR_MOVE; /** * <code>true</code> if the DropTarget is accepting Drag & Drop operations. * * @serial */ boolean active = true; /* * the auto scrolling object */ private transient DropTargetAutoScroller autoScroller; /* * The delegate */ private transient DropTargetListener dtListener; /* * The FlavorMap */ private transient FlavorMap flavorMap; }
ru-doc/java-sdk
java/awt/dnd/DropTarget.java
7,524
// we should'nt get here ...
line_comment
nl
/* * @(#)DropTarget.java 1.53 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.awt.dnd; import java.util.TooManyListenersException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.SystemFlavorMap; import javax.swing.Timer; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.awt.dnd.peer.DropTargetPeer; /** * The <code>DropTarget</code> is associated * with a <code>Component</code> when that <code>Component</code> * wishes * to accept drops during Drag and Drop operations. * <P> * Each * <code>DropTarget</code> is associated with a <code>FlavorMap</code>. * The default <code>FlavorMap</code> hereafter designates the * <code>FlavorMap</code> returned by <code>SystemFlavorMap.getDefaultFlavorMap()</code>. * * @version 1.53, 03/23/10 * @since 1.2 */ public class DropTarget implements DropTargetListener, Serializable { private static final long serialVersionUID = -6283860791671019047L; /** * Creates a new DropTarget given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) to * support, a <code>DropTargetListener</code> * to handle event processing, a <code>boolean</code> indicating * if the <code>DropTarget</code> is currently accepting drops, and * a <code>FlavorMap</code> to use (or null for the default <CODE>FlavorMap</CODE>). * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @param act Is the <code>DropTarget</code> accepting drops. * @param fm The <code>FlavorMap</code> to use, or null for the default <CODE>FlavorMap</CODE> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl, boolean act, FlavorMap fm) throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } component = c; setDefaultActions(ops); if (dtl != null) try { addDropTargetListener(dtl); } catch (TooManyListenersException tmle) { // do nothing! } if (c != null) { c.setDropTarget(this); setActive(act); } if (fm != null) { flavorMap = fm; } else { flavorMap = SystemFlavorMap.getDefaultFlavorMap(); } } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) * to support, a <code>DropTargetListener</code> * to handle event processing, and a <code>boolean</code> indicating * if the <code>DropTarget</code> is currently accepting drops. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @param act Is the <code>DropTarget</code> accepting drops. * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl, boolean act) throws HeadlessException { this(c, ops, dtl, act, null); } /** * Creates a <code>DropTarget</code>. * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget() throws HeadlessException { this(null, DnDConstants.ACTION_COPY_OR_MOVE, null, true, null); } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, and the <code>DropTargetListener</code> * to handle event processing. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, DropTargetListener dtl) throws HeadlessException { this(c, DnDConstants.ACTION_COPY_OR_MOVE, dtl, true, null); } /** * Creates a <code>DropTarget</code> given the <code>Component</code> * to associate itself with, an <code>int</code> representing * the default acceptable action(s) to support, and a * <code>DropTargetListener</code> to handle event processing. * <P> * The Component will receive drops only if it is enabled. * @param c The <code>Component</code> with which this <code>DropTarget</code> is associated * @param ops The default acceptable actions for this <code>DropTarget</code> * @param dtl The <code>DropTargetListener</code> for this <code>DropTarget</code> * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless */ public DropTarget(Component c, int ops, DropTargetListener dtl) throws HeadlessException { this(c, ops, dtl, true); } /** * Note: this interface is required to permit the safe association * of a DropTarget with a Component in one of two ways, either: * <code> component.setDropTarget(droptarget); </code> * or <code> droptarget.setComponent(component); </code> * <P> * The Component will receive drops only if it is enabled. * @param c The new <code>Component</code> this <code>DropTarget</code> * is to be associated with.<P> */ public synchronized void setComponent(Component c) { if (component == c || component != null && component.equals(c)) return; Component old; ComponentPeer oldPeer = null; if ((old = component) != null) { clearAutoscroll(); component = null; if (componentPeer != null) { oldPeer = componentPeer; removeNotify(componentPeer); } old.setDropTarget(null); } if ((component = c) != null) try { c.setDropTarget(this); } catch (Exception e) { // undo the change if (old != null) { old.setDropTarget(this); addNotify(oldPeer); } } } /** * Gets the <code>Component</code> associated * with this <code>DropTarget</code>. * <P> * @return the current <code>Component</code> */ public synchronized Component getComponent() { return component; } /** * Sets the default acceptable actions for this <code>DropTarget</code> * <P> * @param ops the default actions * <P> * @see java.awt.dnd.DnDConstants */ public void setDefaultActions(int ops) { getDropTargetContext().setTargetActions(ops & (DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_REFERENCE)); } /* * Called by DropTargetContext.setTargetActions() * with appropriate synchronization. */ void doSetDefaultActions(int ops) { actions = ops; } /** * Gets an <code>int</code> representing the * current action(s) supported by this <code>DropTarget</code>. * <P> * @return the current default actions */ public int getDefaultActions() { return actions; } /** * Sets the DropTarget active if <code>true</code>, * inactive if <code>false</code>. * <P> * @param isActive sets the <code>DropTarget</code> (in)active. */ public synchronized void setActive(boolean isActive) { if (isActive != active) { active = isActive; } if (!active) clearAutoscroll(); } /** * Reports whether or not * this <code>DropTarget</code> * is currently active (ready to accept drops). * <P> * @return <CODE>true</CODE> if active, <CODE>false</CODE> if not */ public boolean isActive() { return active; } /** * Adds a new <code>DropTargetListener</code> (UNICAST SOURCE). * <P> * @param dtl The new <code>DropTargetListener</code> * <P> * @throws <code>TooManyListenersException</code> if a * <code>DropTargetListener</code> is already added to this * <code>DropTarget</code>. */ public synchronized void addDropTargetListener(DropTargetListener dtl) throws TooManyListenersException { if (dtl == null) return; if (equals(dtl)) throw new IllegalArgumentException("DropTarget may not be its own Listener"); if (dtListener == null) dtListener = dtl; else throw new TooManyListenersException(); } /** * Removes the current <code>DropTargetListener</code> (UNICAST SOURCE). * <P> * @param dtl the DropTargetListener to deregister. */ public synchronized void removeDropTargetListener(DropTargetListener dtl) { if (dtl != null && dtListener != null) { if(dtListener.equals(dtl)) dtListener = null; else throw new IllegalArgumentException("listener mismatch"); } } /** * Calls <code>dragEnter</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dragEnter(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null) { dtListener.dragEnter(dtde); } else dtde.getDropTargetContext().setTargetActions(DnDConstants.ACTION_NONE); initializeAutoscrolling(dtde.getLocation()); } /** * Calls <code>dragOver</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dragOver(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null && active) dtListener.dragOver(dtde); updateAutoscroll(dtde.getLocation()); } /** * Calls <code>dropActionChanged</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDragEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * * @param dtde the <code>DropTargetDragEvent</code> * * @throws NullPointerException if this <code>DropTarget</code> * is active and <code>dtde</code> is <code>null</code> * * @see #isActive */ public synchronized void dropActionChanged(DropTargetDragEvent dtde) { if (!active) return; if (dtListener != null) dtListener.dropActionChanged(dtde); updateAutoscroll(dtde.getLocation()); } /** * Calls <code>dragExit</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetEvent</code>. * Has no effect if this <code>DropTarget</code> * is not active. * <p> * This method itself does not throw any exception * for null parameter but for exceptions thrown by * the respective method of the listener. * * @param dte the <code>DropTargetEvent</code> * * @see #isActive */ public synchronized void dragExit(DropTargetEvent dte) { if (!active) return; if (dtListener != null && active) dtListener.dragExit(dte); clearAutoscroll(); } /** * Calls <code>drop</code> on the registered * <code>DropTargetListener</code> and passes it * the specified <code>DropTargetDropEvent</code> * if this <code>DropTarget</code> is active. * * @param dtde the <code>DropTargetDropEvent</code> * * @throws NullPointerException if <code>dtde</code> is null * and at least one of the following is true: this * <code>DropTarget</code> is not active, or there is * no a <code>DropTargetListener</code> registered. * * @see #isActive */ public synchronized void drop(DropTargetDropEvent dtde) { clearAutoscroll(); if (dtListener != null && active) dtListener.drop(dtde); else { // we should'nt<SUF> dtde.rejectDrop(); } } /** * Gets the <code>FlavorMap</code> * associated with this <code>DropTarget</code>. * If no <code>FlavorMap</code> has been set for this * <code>DropTarget</code>, it is associated with the default * <code>FlavorMap</code>. * <P> * @return the FlavorMap for this DropTarget */ public FlavorMap getFlavorMap() { return flavorMap; } /** * Sets the <code>FlavorMap</code> associated * with this <code>DropTarget</code>. * <P> * @param fm the new <code>FlavorMap</code>, or null to * associate the default FlavorMap with this DropTarget. */ public void setFlavorMap(FlavorMap fm) { flavorMap = fm == null ? SystemFlavorMap.getDefaultFlavorMap() : fm; } /** * Notify the DropTarget that it has been associated with a Component * ********************************************************************** * This method is usually called from java.awt.Component.addNotify() of * the Component associated with this DropTarget to notify the DropTarget * that a ComponentPeer has been associated with that Component. * * Calling this method, other than to notify this DropTarget of the * association of the ComponentPeer with the Component may result in * a malfunction of the DnD system. ********************************************************************** * <P> * @param peer The Peer of the Component we are associated with! * */ public void addNotify(ComponentPeer peer) { if (peer == componentPeer) return; componentPeer = peer; for (Component c = component; c != null && peer instanceof LightweightPeer; c = c.getParent()) { peer = c.getPeer(); } if (peer instanceof DropTargetPeer) { nativePeer = peer; ((DropTargetPeer)peer).addDropTarget(this); } else { nativePeer = null; } } /** * Notify the DropTarget that it has been disassociated from a Component * ********************************************************************** * This method is usually called from java.awt.Component.removeNotify() of * the Component associated with this DropTarget to notify the DropTarget * that a ComponentPeer has been disassociated with that Component. * * Calling this method, other than to notify this DropTarget of the * disassociation of the ComponentPeer from the Component may result in * a malfunction of the DnD system. ********************************************************************** * <P> * @param peer The Peer of the Component we are being disassociated from! */ public void removeNotify(ComponentPeer peer) { if (nativePeer != null) ((DropTargetPeer)nativePeer).removeDropTarget(this); componentPeer = nativePeer = null; } /** * Gets the <code>DropTargetContext</code> associated * with this <code>DropTarget</code>. * <P> * @return the <code>DropTargetContext</code> associated with this <code>DropTarget</code>. */ public DropTargetContext getDropTargetContext() { return dropTargetContext; } /** * Creates the DropTargetContext associated with this DropTarget. * Subclasses may override this method to instantiate their own * DropTargetContext subclass. * * This call is typically *only* called by the platform's * DropTargetContextPeer as a drag operation encounters this * DropTarget. Accessing the Context while no Drag is current * has undefined results. */ protected DropTargetContext createDropTargetContext() { return new DropTargetContext(this); } /** * Serializes this <code>DropTarget</code>. Performs default serialization, * and then writes out this object's <code>DropTargetListener</code> if and * only if it can be serialized. If not, <code>null</code> is written * instead. * * @serialData The default serializable fields, in alphabetical order, * followed by either a <code>DropTargetListener</code> * instance, or <code>null</code>. * @since 1.4 */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeObject(SerializationTester.test(dtListener) ? dtListener : null); } /** * Deserializes this <code>DropTarget</code>. This method first performs * default deserialization for all non-<code>transient</code> fields. An * attempt is then made to deserialize this object's * <code>DropTargetListener</code> as well. This is first attempted by * deserializing the field <code>dtListener</code>, because, in releases * prior to 1.4, a non-<code>transient</code> field of this name stored the * <code>DropTargetListener</code>. If this fails, the next object in the * stream is used instead. * * @since 1.4 */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { ObjectInputStream.GetField f = s.readFields(); try { dropTargetContext = (DropTargetContext)f.get("dropTargetContext", null); } catch (IllegalArgumentException e) { // Pre-1.4 support. 'dropTargetContext' was previoulsy transient } if (dropTargetContext == null) { dropTargetContext = createDropTargetContext(); } component = (Component)f.get("component", null); actions = f.get("actions", DnDConstants.ACTION_COPY_OR_MOVE); active = f.get("active", true); // Pre-1.4 support. 'dtListener' was previously non-transient try { dtListener = (DropTargetListener)f.get("dtListener", null); } catch (IllegalArgumentException e) { // 1.4-compatible byte stream. 'dtListener' was written explicitly dtListener = (DropTargetListener)s.readObject(); } } /*********************************************************************/ /** * this protected nested class implements autoscrolling */ protected static class DropTargetAutoScroller implements ActionListener { /** * construct a DropTargetAutoScroller * <P> * @param c the <code>Component</code> * @param p the <code>Point</code> */ protected DropTargetAutoScroller(Component c, Point p) { super(); component = c; autoScroll = (Autoscroll)component; Toolkit t = Toolkit.getDefaultToolkit(); Integer initial = Integer.valueOf(100); Integer interval = Integer.valueOf(100); try { initial = (Integer)t.getDesktopProperty("DnD.Autoscroll.initialDelay"); } catch (Exception e) { // ignore } try { interval = (Integer)t.getDesktopProperty("DnD.Autoscroll.interval"); } catch (Exception e) { // ignore } timer = new Timer(interval.intValue(), this); timer.setCoalesce(true); timer.setInitialDelay(initial.intValue()); locn = p; prev = p; try { hysteresis = ((Integer)t.getDesktopProperty("DnD.Autoscroll.cursorHysteresis")).intValue(); } catch (Exception e) { // ignore } timer.start(); } /** * update the geometry of the autoscroll region */ private void updateRegion() { Insets i = autoScroll.getAutoscrollInsets(); Dimension size = component.getSize(); if (size.width != outer.width || size.height != outer.height) outer.reshape(0, 0, size.width, size.height); if (inner.x != i.left || inner.y != i.top) inner.setLocation(i.left, i.top); int newWidth = size.width - (i.left + i.right); int newHeight = size.height - (i.top + i.bottom); if (newWidth != inner.width || newHeight != inner.height) inner.setSize(newWidth, newHeight); } /** * cause autoscroll to occur * <P> * @param newLocn the <code>Point</code> */ protected synchronized void updateLocation(Point newLocn) { prev = locn; locn = newLocn; if (Math.abs(locn.x - prev.x) > hysteresis || Math.abs(locn.y - prev.y) > hysteresis) { if (timer.isRunning()) timer.stop(); } else { if (!timer.isRunning()) timer.start(); } } /** * cause autoscrolling to stop */ protected void stop() { timer.stop(); } /** * cause autoscroll to occur * <P> * @param e the <code>ActionEvent</code> */ public synchronized void actionPerformed(ActionEvent e) { updateRegion(); if (outer.contains(locn) && !inner.contains(locn)) autoScroll.autoscroll(locn); } /* * fields */ private Component component; private Autoscroll autoScroll; private Timer timer; private Point locn; private Point prev; private Rectangle outer = new Rectangle(); private Rectangle inner = new Rectangle(); private int hysteresis = 10; } /*********************************************************************/ /** * create an embedded autoscroller * <P> * @param c the <code>Component</code> * @param p the <code>Point</code> */ protected DropTargetAutoScroller createDropTargetAutoScroller(Component c, Point p) { return new DropTargetAutoScroller(c, p); } /** * initialize autoscrolling * <P> * @param p the <code>Point</code> */ protected void initializeAutoscrolling(Point p) { if (component == null || !(component instanceof Autoscroll)) return; autoScroller = createDropTargetAutoScroller(component, p); } /** * update autoscrolling with current cursor locn * <P> * @param dragCursorLocn the <code>Point</code> */ protected void updateAutoscroll(Point dragCursorLocn) { if (autoScroller != null) autoScroller.updateLocation(dragCursorLocn); } /** * clear autoscrolling */ protected void clearAutoscroll() { if (autoScroller != null) { autoScroller.stop(); autoScroller = null; } } /** * The DropTargetContext associated with this DropTarget. * * @serial */ private DropTargetContext dropTargetContext = createDropTargetContext(); /** * The Component associated with this DropTarget. * * @serial */ private Component component; /* * That Component's Peer */ private transient ComponentPeer componentPeer; /* * That Component's "native" Peer */ private transient ComponentPeer nativePeer; /** * Default permissible actions supported by this DropTarget. * * @see #setDefaultActions * @see #getDefaultActions * @serial */ int actions = DnDConstants.ACTION_COPY_OR_MOVE; /** * <code>true</code> if the DropTarget is accepting Drag & Drop operations. * * @serial */ boolean active = true; /* * the auto scrolling object */ private transient DropTargetAutoScroller autoScroller; /* * The delegate */ private transient DropTargetListener dtListener; /* * The FlavorMap */ private transient FlavorMap flavorMap; }
36181_1
package com.example.ruben.sqlliteinsertruben; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Ruben on 9-11-2017. */ public class DbAdapter { DbHelper helper; public DbAdapter(Context context) { helper = new DbHelper(context); } public long insertData(String name, String password) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(DbHelper.NAME, name); contentValues.put(DbHelper.PASSWORD, password); long id = db.insert(DbHelper.TABLE_NAME, null , contentValues); return id; } static class DbHelper extends SQLiteOpenHelper { //velden private static final String DATABASE_NAME = "myDatabase"; private static final String TABLE_NAME = "myTable"; //als deze hoger wordt gaat die naar onUpgrade private static final int DATABASE_Version = 1; private static final String UID="_id"; private static final String NAME = "Name"; private static final String PASSWORD= "Password"; private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME + "( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225), " + PASSWORD+ " VARCHAR(225));"; //private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME; private Context context; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_Version); this.context=context; Message.message(context,"Started..."); } @Override //Als die een nieuwe versie van de database vindt gooit de ouwe weg. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Message.message(context,"OnUpgrade"); db.execSQL("DROP_TABLE"); onCreate(db); }catch (Exception e) { Message.message(context,""+e); } } public void onCreate(SQLiteDatabase db) { //tabel maken in De database. String SQL_CREATE_WERKNEMER_TABLE = "CREATE TABLE " + Contract.ContractEntry.TABLE_NAME + " (" + Contract.ContractEntry.COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " //Wordt automaties een value aan gegeven. + Contract.ContractEntry.COLUMN_NAME + " TEXT NOT NULL, " + Contract.ContractEntry.COLUMN_PASSWORD + " TEXT NOT NULL, "; db.execSQL(CREATE_TABLE); } } }
rubendijkstra02/SqlLiteInsertRuben
app/src/main/java/com/example/ruben/sqlliteinsertruben/DbAdapter.java
749
//als deze hoger wordt gaat die naar onUpgrade
line_comment
nl
package com.example.ruben.sqlliteinsertruben; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Ruben on 9-11-2017. */ public class DbAdapter { DbHelper helper; public DbAdapter(Context context) { helper = new DbHelper(context); } public long insertData(String name, String password) { SQLiteDatabase db = helper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(DbHelper.NAME, name); contentValues.put(DbHelper.PASSWORD, password); long id = db.insert(DbHelper.TABLE_NAME, null , contentValues); return id; } static class DbHelper extends SQLiteOpenHelper { //velden private static final String DATABASE_NAME = "myDatabase"; private static final String TABLE_NAME = "myTable"; //als deze<SUF> private static final int DATABASE_Version = 1; private static final String UID="_id"; private static final String NAME = "Name"; private static final String PASSWORD= "Password"; private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME + "( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225), " + PASSWORD+ " VARCHAR(225));"; //private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME; private Context context; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_Version); this.context=context; Message.message(context,"Started..."); } @Override //Als die een nieuwe versie van de database vindt gooit de ouwe weg. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Message.message(context,"OnUpgrade"); db.execSQL("DROP_TABLE"); onCreate(db); }catch (Exception e) { Message.message(context,""+e); } } public void onCreate(SQLiteDatabase db) { //tabel maken in De database. String SQL_CREATE_WERKNEMER_TABLE = "CREATE TABLE " + Contract.ContractEntry.TABLE_NAME + " (" + Contract.ContractEntry.COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " //Wordt automaties een value aan gegeven. + Contract.ContractEntry.COLUMN_NAME + " TEXT NOT NULL, " + Contract.ContractEntry.COLUMN_PASSWORD + " TEXT NOT NULL, "; db.execSQL(CREATE_TABLE); } } }
4352_4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package keygamep3; import javax.swing.ImageIcon; /** * Een level bestaat uit verschillende velden waar zich Spelelementen en/of een speler kan bevinden * @author rubenvde */ public class Veld { private SpelElement spelElement; /** * De constructor van Veld zonder Spelelement */ public Veld() { this.spelElement = null; } /** * De constructor van Veld met Spelelement * @param spelElement */ public Veld(SpelElement spelElement) { this.spelElement = spelElement; } /** * Hier verwijder je het Spelelement van het Veld */ public void verwijderSpelElement() { this.spelElement = null; } /** * Vraag Spelelement op * @return */ public SpelElement getSpelElement() { return spelElement; } /** * Check of een Veld bezetbaar is * @param speler * @return */ public boolean isBezetBaar(Speler speler) { if (this.spelElement != null) { if (speler.getSleutel() != null) { //Als speler een sleutel heeft dan kan stuur die mee return spelElement.isToegankelijk(speler.getSleutel().getPincode()); } else { //Als speler geen sleutel heeft dan stuur dan 0 mee return spelElement.isToegankelijk(0); } } else { //Als spelElement een gang is waar door gelopen kan worden return true; } } /** * Schrijf Spelement * @return */ public ImageIcon getSpelElementIcon() { if (this.spelElement != null) { return this.spelElement.getAfbeelding(); } else { return null; } } }
rubenvde/KeyGameP3
src/keygamep3/Veld.java
577
/** * Hier verwijder je het Spelelement van het Veld */
block_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package keygamep3; import javax.swing.ImageIcon; /** * Een level bestaat uit verschillende velden waar zich Spelelementen en/of een speler kan bevinden * @author rubenvde */ public class Veld { private SpelElement spelElement; /** * De constructor van Veld zonder Spelelement */ public Veld() { this.spelElement = null; } /** * De constructor van Veld met Spelelement * @param spelElement */ public Veld(SpelElement spelElement) { this.spelElement = spelElement; } /** * Hier verwijder je<SUF>*/ public void verwijderSpelElement() { this.spelElement = null; } /** * Vraag Spelelement op * @return */ public SpelElement getSpelElement() { return spelElement; } /** * Check of een Veld bezetbaar is * @param speler * @return */ public boolean isBezetBaar(Speler speler) { if (this.spelElement != null) { if (speler.getSleutel() != null) { //Als speler een sleutel heeft dan kan stuur die mee return spelElement.isToegankelijk(speler.getSleutel().getPincode()); } else { //Als speler geen sleutel heeft dan stuur dan 0 mee return spelElement.isToegankelijk(0); } } else { //Als spelElement een gang is waar door gelopen kan worden return true; } } /** * Schrijf Spelement * @return */ public ImageIcon getSpelElementIcon() { if (this.spelElement != null) { return this.spelElement.getAfbeelding(); } else { return null; } } }
37799_2
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package View; import Controller.DatabaseManager; import Model.Onderwijseenheid; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.JTable; /** * * @author rubenvde */ public class OnderwijseenheidView extends javax.swing.JFrame { private int ond_id; private int periode_id; private int bedrijf_id; private int opleiding_id; private String studie_soort; private String type_ond; private DatabaseManager dm = new DatabaseManager(); private boolean wijzigen; private HoofdView hv; /** * Creates new form OnderwijseenheidView2 */ public OnderwijseenheidView(HoofdView hv) { super("Onderwijseenheid"); this.ond_id = 0; this.periode_id = 0; this.bedrijf_id = 0; this.opleiding_id = 0; this.studie_soort = ""; this.type_ond = ""; this.wijzigen = false; this.hv = hv; initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1_persoonsgegevens = new javax.swing.JLabel(); jLabel_studiepunten = new javax.swing.JLabel(); studiepunten = new javax.swing.JTextField(); jLabel5_opleiding = new javax.swing.JLabel(); jComboBox1_opleiding = new javax.swing.JComboBox(); jLabel5_type = new javax.swing.JLabel(); jComboBox1_type = new javax.swing.JComboBox(); jLabel4_soortstudie = new javax.swing.JLabel(); jLabel5_bedrijf = new javax.swing.JLabel(); jComboBox1_bedrijf = new javax.swing.JComboBox(); jButton_toevoegen = new javax.swing.JButton(); jButton_annuleren = new javax.swing.JButton(); jComboBox1_soort_studie = new javax.swing.JComboBox(); jLabel4_soortstudie2 = new javax.swing.JLabel(); jComboBox1_periode = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); stad = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); land = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1_persoonsgegevens.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jLabel1_persoonsgegevens.setText("Onderwijseenheid"); jLabel_studiepunten.setText("Studiepunten"); jLabel5_opleiding.setText("Opleiding"); try{ String [] opleidingen = new String[dm.getOpleidingNamen().size()]; for(int i = 0; i < opleidingen.length; i++){ opleidingen[i] = dm.getOpleidingNamen().get(i); jComboBox1_opleiding.addItem(opleidingen[i]); } /* for(int i = 0; i < opleidingen.length; i++){ jComboBox1_type.addItem(opleidingen[i]); } */ }catch(SQLException e){ System.out.println("Fout bij combobox opleiding van Binnenlandse StudentView."); e.printStackTrace(); } /* jComboBox1_opleiding.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_opleiding.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_opleidingActionPerformed(evt); } }); jLabel5_type.setText("Type"); jComboBox1_type.addItem("Leeg"); jComboBox1_type.addItem("Studie"); jComboBox1_type.addItem("Stage"); jComboBox1_type.addItem("Afstudeerstage"); jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(false); /* jComboBox1_type.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_type.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_typeActionPerformed(evt); } }); jLabel4_soortstudie.setText("Soort studie"); jLabel5_bedrijf.setText("Bedrijf"); try{ ArrayList<String> bedrijven = new ArrayList<>(dm.getBedrijfsNamen()); String [] bedrijf = new String[bedrijven.size()]; bedrijf = bedrijven.toArray(bedrijf); for(int i = 0; i < bedrijf.length; i++){ jComboBox1_bedrijf.addItem(bedrijf[i]); } }catch(SQLException e){ System.out.println("Fout bij combobox opleiding van Binnenlandse StudentView."); e.printStackTrace(); } /* jComboBox1_bedrijf.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_bedrijf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_bedrijfActionPerformed(evt); } }); jButton_toevoegen.setText("Toevoegen"); jButton_toevoegen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_toevoegenActionPerformed(evt); } }); jButton_annuleren.setText("Annuleren"); jButton_annuleren.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_annulerenActionPerformed(evt); } }); jComboBox1_soort_studie.addItem("Minors"); jComboBox1_soort_studie.addItem("European Project Semesters"); jComboBox1_soort_studie.addItem("Summer schools"); /* for(int i = 0; i < opleidingen.length; i++){ jComboBox1_type.addItem(opleidingen[i]); } */ /* jComboBox1_soort_studie.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_soort_studie.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_soort_studieActionPerformed(evt); } }); jLabel4_soortstudie2.setText("Periode"); try{ String [] periodes = new String[dm.getPeriodes().size()]; for(int i = 0; i < periodes.length; i++){ periodes[i] = dm.getPeriodes().get(i); jComboBox1_periode.addItem(periodes[i]); } }catch(SQLException e){ System.out.println("Fout bij combobox periode van Onderwijseenheid."); e.printStackTrace(); } /* jComboBox1_periode.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_periode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_periodeActionPerformed(evt); } }); jLabel1.setText("Stad"); jLabel2.setText("Land"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton_toevoegen) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton_annuleren)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1_persoonsgegevens) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_type, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_type, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4_soortstudie2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_periode, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel_studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(land, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4_soortstudie, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_soort_studie, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(stad, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1_persoonsgegevens, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel_studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4_soortstudie2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1_periode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_type, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4_soortstudie, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1_soort_studie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(stad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(land, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_annuleren) .addComponent(jButton_toevoegen)) .addGap(15, 15, 15)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jComboBox1_opleidingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_opleidingActionPerformed try { opleiding_id = dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()); } catch (SQLException ex) { System.out.println("Opleiding id niet gevonden"); } }//GEN-LAST:event_jComboBox1_opleidingActionPerformed private void jComboBox1_typeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_typeActionPerformed type_ond = jComboBox1_type.getSelectedItem().toString(); switch(type_ond) { case "Studie": jComboBox1_soort_studie.setEnabled(true); jComboBox1_bedrijf.setEnabled(false); break; case "Stage": jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(true); break; case "Afstudeerstage": jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(true); break; case "Leeg": type_ond = ""; break; default: jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(false); break; } }//GEN-LAST:event_jComboBox1_typeActionPerformed private void jComboBox1_bedrijfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_bedrijfActionPerformed try { bedrijf_id = dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()); } catch (SQLException ex) { System.out.println("Bedrijfs id niet gevonden"); } }//GEN-LAST:event_jComboBox1_bedrijfActionPerformed private void jButton_toevoegenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_toevoegenActionPerformed Onderwijseenheid onderwijseenheid; dm = new DatabaseManager(); try { if(!wijzigen){ onderwijseenheid = new Onderwijseenheid(dm.getOnderwijseenheidID(), Integer.parseInt(studiepunten.getText()), "" +jComboBox1_soort_studie.getSelectedItem(), dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()), jComboBox1_type.getSelectedItem().toString(), land.getText(), stad.getText(), dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()), dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem())); dm.insertEntity(onderwijseenheid); JOptionPane.showMessageDialog(null, "Met succes toegevoegd."); }else{ JTable viewTable = hv.getTable(); onderwijseenheid = new Onderwijseenheid((int) viewTable.getValueAt(viewTable.getSelectedRow(), 0), Integer.parseInt(studiepunten.getText()), "" +jComboBox1_soort_studie.getSelectedItem(), dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()), jComboBox1_type.getSelectedItem().toString(), land.getText(), stad.getText(), dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()), dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem())); dm.updateEntity(onderwijseenheid); JOptionPane.showMessageDialog(null, "Met succes gewijzigd."); } } catch (SQLException ex) { System.out.println("Onderwijseenheid is niet gewijzigd of toegevoegd in database!"); ex.printStackTrace(); } this.dispose(); //hv.getRefreshJTable(); }//GEN-LAST:event_jButton_toevoegenActionPerformed public void onderwijseenheidWijzigen(boolean wijzigen, JTable table){ this.wijzigen = wijzigen; this.jButton_toevoegen.setText("Wijzigen"); this.setTitle("Wijzigen onderwijseenheid"); String [] col = new String[table.getColumnCount()]; for (int i = 0; i < col.length; i++) { col[i] = "" + table.getValueAt(table.getSelectedRow(), i); } } private void jButton_annulerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_annulerenActionPerformed this.dispose(); }//GEN-LAST:event_jButton_annulerenActionPerformed private void jComboBox1_soort_studieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_soort_studieActionPerformed this.studie_soort = "" + jComboBox1_soort_studie.getSelectedItem(); }//GEN-LAST:event_jComboBox1_soort_studieActionPerformed private void jComboBox1_periodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_periodeActionPerformed try { periode_id = dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem()); } catch (Exception e) { System.out.println("Periode id niet gevoden"); } }//GEN-LAST:event_jComboBox1_periodeActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_annuleren; private javax.swing.JButton jButton_toevoegen; private javax.swing.JComboBox jComboBox1_bedrijf; private javax.swing.JComboBox jComboBox1_opleiding; private javax.swing.JComboBox jComboBox1_periode; private javax.swing.JComboBox jComboBox1_soort_studie; private javax.swing.JComboBox jComboBox1_type; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel1_persoonsgegevens; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4_soortstudie; private javax.swing.JLabel jLabel4_soortstudie2; private javax.swing.JLabel jLabel5_bedrijf; private javax.swing.JLabel jLabel5_opleiding; private javax.swing.JLabel jLabel5_type; private javax.swing.JLabel jLabel_studiepunten; private javax.swing.JTextField land; private javax.swing.JTextField stad; private javax.swing.JTextField studiepunten; // End of variables declaration//GEN-END:variables }
rubenvde/MESS
src/View/OnderwijseenheidView.java
7,458
/** * Creates new form OnderwijseenheidView2 */
block_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package View; import Controller.DatabaseManager; import Model.Onderwijseenheid; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.JTable; /** * * @author rubenvde */ public class OnderwijseenheidView extends javax.swing.JFrame { private int ond_id; private int periode_id; private int bedrijf_id; private int opleiding_id; private String studie_soort; private String type_ond; private DatabaseManager dm = new DatabaseManager(); private boolean wijzigen; private HoofdView hv; /** * Creates new form<SUF>*/ public OnderwijseenheidView(HoofdView hv) { super("Onderwijseenheid"); this.ond_id = 0; this.periode_id = 0; this.bedrijf_id = 0; this.opleiding_id = 0; this.studie_soort = ""; this.type_ond = ""; this.wijzigen = false; this.hv = hv; initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1_persoonsgegevens = new javax.swing.JLabel(); jLabel_studiepunten = new javax.swing.JLabel(); studiepunten = new javax.swing.JTextField(); jLabel5_opleiding = new javax.swing.JLabel(); jComboBox1_opleiding = new javax.swing.JComboBox(); jLabel5_type = new javax.swing.JLabel(); jComboBox1_type = new javax.swing.JComboBox(); jLabel4_soortstudie = new javax.swing.JLabel(); jLabel5_bedrijf = new javax.swing.JLabel(); jComboBox1_bedrijf = new javax.swing.JComboBox(); jButton_toevoegen = new javax.swing.JButton(); jButton_annuleren = new javax.swing.JButton(); jComboBox1_soort_studie = new javax.swing.JComboBox(); jLabel4_soortstudie2 = new javax.swing.JLabel(); jComboBox1_periode = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); stad = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); land = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1_persoonsgegevens.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jLabel1_persoonsgegevens.setText("Onderwijseenheid"); jLabel_studiepunten.setText("Studiepunten"); jLabel5_opleiding.setText("Opleiding"); try{ String [] opleidingen = new String[dm.getOpleidingNamen().size()]; for(int i = 0; i < opleidingen.length; i++){ opleidingen[i] = dm.getOpleidingNamen().get(i); jComboBox1_opleiding.addItem(opleidingen[i]); } /* for(int i = 0; i < opleidingen.length; i++){ jComboBox1_type.addItem(opleidingen[i]); } */ }catch(SQLException e){ System.out.println("Fout bij combobox opleiding van Binnenlandse StudentView."); e.printStackTrace(); } /* jComboBox1_opleiding.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_opleiding.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_opleidingActionPerformed(evt); } }); jLabel5_type.setText("Type"); jComboBox1_type.addItem("Leeg"); jComboBox1_type.addItem("Studie"); jComboBox1_type.addItem("Stage"); jComboBox1_type.addItem("Afstudeerstage"); jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(false); /* jComboBox1_type.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_type.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_typeActionPerformed(evt); } }); jLabel4_soortstudie.setText("Soort studie"); jLabel5_bedrijf.setText("Bedrijf"); try{ ArrayList<String> bedrijven = new ArrayList<>(dm.getBedrijfsNamen()); String [] bedrijf = new String[bedrijven.size()]; bedrijf = bedrijven.toArray(bedrijf); for(int i = 0; i < bedrijf.length; i++){ jComboBox1_bedrijf.addItem(bedrijf[i]); } }catch(SQLException e){ System.out.println("Fout bij combobox opleiding van Binnenlandse StudentView."); e.printStackTrace(); } /* jComboBox1_bedrijf.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_bedrijf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_bedrijfActionPerformed(evt); } }); jButton_toevoegen.setText("Toevoegen"); jButton_toevoegen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_toevoegenActionPerformed(evt); } }); jButton_annuleren.setText("Annuleren"); jButton_annuleren.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_annulerenActionPerformed(evt); } }); jComboBox1_soort_studie.addItem("Minors"); jComboBox1_soort_studie.addItem("European Project Semesters"); jComboBox1_soort_studie.addItem("Summer schools"); /* for(int i = 0; i < opleidingen.length; i++){ jComboBox1_type.addItem(opleidingen[i]); } */ /* jComboBox1_soort_studie.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_soort_studie.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_soort_studieActionPerformed(evt); } }); jLabel4_soortstudie2.setText("Periode"); try{ String [] periodes = new String[dm.getPeriodes().size()]; for(int i = 0; i < periodes.length; i++){ periodes[i] = dm.getPeriodes().get(i); jComboBox1_periode.addItem(periodes[i]); } }catch(SQLException e){ System.out.println("Fout bij combobox periode van Onderwijseenheid."); e.printStackTrace(); } /* jComboBox1_periode.setModel(new javax.swing.DefaultComboBoxModel(opleidingen)); */ jComboBox1_periode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1_periodeActionPerformed(evt); } }); jLabel1.setText("Stad"); jLabel2.setText("Land"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton_toevoegen) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton_annuleren)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1_persoonsgegevens) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_type, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_type, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4_soortstudie2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_periode, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel_studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(land, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4_soortstudie, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_soort_studie, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(stad, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1_persoonsgegevens, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel_studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(studiepunten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_opleiding, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4_soortstudie2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1_periode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_type, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4_soortstudie, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1_soort_studie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5_bedrijf, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(stad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(land, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_annuleren) .addComponent(jButton_toevoegen)) .addGap(15, 15, 15)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jComboBox1_opleidingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_opleidingActionPerformed try { opleiding_id = dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()); } catch (SQLException ex) { System.out.println("Opleiding id niet gevonden"); } }//GEN-LAST:event_jComboBox1_opleidingActionPerformed private void jComboBox1_typeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_typeActionPerformed type_ond = jComboBox1_type.getSelectedItem().toString(); switch(type_ond) { case "Studie": jComboBox1_soort_studie.setEnabled(true); jComboBox1_bedrijf.setEnabled(false); break; case "Stage": jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(true); break; case "Afstudeerstage": jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(true); break; case "Leeg": type_ond = ""; break; default: jComboBox1_soort_studie.setEnabled(false); jComboBox1_bedrijf.setEnabled(false); break; } }//GEN-LAST:event_jComboBox1_typeActionPerformed private void jComboBox1_bedrijfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_bedrijfActionPerformed try { bedrijf_id = dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()); } catch (SQLException ex) { System.out.println("Bedrijfs id niet gevonden"); } }//GEN-LAST:event_jComboBox1_bedrijfActionPerformed private void jButton_toevoegenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_toevoegenActionPerformed Onderwijseenheid onderwijseenheid; dm = new DatabaseManager(); try { if(!wijzigen){ onderwijseenheid = new Onderwijseenheid(dm.getOnderwijseenheidID(), Integer.parseInt(studiepunten.getText()), "" +jComboBox1_soort_studie.getSelectedItem(), dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()), jComboBox1_type.getSelectedItem().toString(), land.getText(), stad.getText(), dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()), dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem())); dm.insertEntity(onderwijseenheid); JOptionPane.showMessageDialog(null, "Met succes toegevoegd."); }else{ JTable viewTable = hv.getTable(); onderwijseenheid = new Onderwijseenheid((int) viewTable.getValueAt(viewTable.getSelectedRow(), 0), Integer.parseInt(studiepunten.getText()), "" +jComboBox1_soort_studie.getSelectedItem(), dm.getBedrijfID(jComboBox1_bedrijf.getSelectedItem().toString()), jComboBox1_type.getSelectedItem().toString(), land.getText(), stad.getText(), dm.getOpleidingID(jComboBox1_opleiding.getSelectedItem().toString()), dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem())); dm.updateEntity(onderwijseenheid); JOptionPane.showMessageDialog(null, "Met succes gewijzigd."); } } catch (SQLException ex) { System.out.println("Onderwijseenheid is niet gewijzigd of toegevoegd in database!"); ex.printStackTrace(); } this.dispose(); //hv.getRefreshJTable(); }//GEN-LAST:event_jButton_toevoegenActionPerformed public void onderwijseenheidWijzigen(boolean wijzigen, JTable table){ this.wijzigen = wijzigen; this.jButton_toevoegen.setText("Wijzigen"); this.setTitle("Wijzigen onderwijseenheid"); String [] col = new String[table.getColumnCount()]; for (int i = 0; i < col.length; i++) { col[i] = "" + table.getValueAt(table.getSelectedRow(), i); } } private void jButton_annulerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_annulerenActionPerformed this.dispose(); }//GEN-LAST:event_jButton_annulerenActionPerformed private void jComboBox1_soort_studieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_soort_studieActionPerformed this.studie_soort = "" + jComboBox1_soort_studie.getSelectedItem(); }//GEN-LAST:event_jComboBox1_soort_studieActionPerformed private void jComboBox1_periodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1_periodeActionPerformed try { periode_id = dm.getPeriodeID("" + jComboBox1_periode.getSelectedItem()); } catch (Exception e) { System.out.println("Periode id niet gevoden"); } }//GEN-LAST:event_jComboBox1_periodeActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_annuleren; private javax.swing.JButton jButton_toevoegen; private javax.swing.JComboBox jComboBox1_bedrijf; private javax.swing.JComboBox jComboBox1_opleiding; private javax.swing.JComboBox jComboBox1_periode; private javax.swing.JComboBox jComboBox1_soort_studie; private javax.swing.JComboBox jComboBox1_type; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel1_persoonsgegevens; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4_soortstudie; private javax.swing.JLabel jLabel4_soortstudie2; private javax.swing.JLabel jLabel5_bedrijf; private javax.swing.JLabel jLabel5_opleiding; private javax.swing.JLabel jLabel5_type; private javax.swing.JLabel jLabel_studiepunten; private javax.swing.JTextField land; private javax.swing.JTextField stad; private javax.swing.JTextField studiepunten; // End of variables declaration//GEN-END:variables }
174768_5
// ============================================================================ // // Copyright (C) 2006-2015 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package com.amalto.workbench.editors; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormToolkit; import com.amalto.workbench.dialogs.DOMViewDialog; import com.amalto.workbench.i18n.Messages; import com.amalto.workbench.image.ImageCache; import com.amalto.workbench.models.IXObjectModelListener; import com.amalto.workbench.models.TreeObject; import com.amalto.workbench.providers.XObjectBrowserInput; import com.amalto.workbench.utils.Util; import com.amalto.workbench.utils.XtentisException; import com.amalto.workbench.webservices.TMDMService; import com.amalto.workbench.webservices.WSDataClusterPK; import com.amalto.workbench.webservices.WSGetView; import com.amalto.workbench.webservices.WSQuickSearch; import com.amalto.workbench.webservices.WSStringPredicate; import com.amalto.workbench.webservices.WSView; import com.amalto.workbench.webservices.WSViewPK; import com.amalto.workbench.webservices.WSViewSearch; import com.amalto.workbench.webservices.WSWhereAnd; import com.amalto.workbench.webservices.WSWhereCondition; import com.amalto.workbench.webservices.WSWhereItem; import com.amalto.workbench.webservices.WSWhereOperator; public class ViewBrowserMainPage extends AMainPage implements IXObjectModelListener { private static Log log = LogFactory.getLog(ViewBrowserMainPage.class); protected Combo dataClusterCombo; protected Text searchText; protected TableViewer resultsViewer; protected List viewableBEsList; protected List searchableBEsList; protected ListViewer wcListViewer; protected Label resultsLabel; protected Button matchAllWordsBtn; private Combo searchItemCombo; private final String FULL_TEXT = Messages.ViewBrowserMainPage_fullText; protected Combo clusterTypeCombo; public ViewBrowserMainPage(FormEditor editor) { super(editor, ViewBrowserMainPage.class.getName(), Messages.ViewBrowserMainPage_ViewBrowser + ((XObjectBrowserInput) editor.getEditorInput()).getName()); // listen to events ((XObjectBrowserInput) editor.getEditorInput()).addListener(this); } @Override protected void createCharacteristicsContent(FormToolkit toolkit, Composite charComposite) { try { Label vbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_ViewableElements, SWT.NULL); vbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); Label sbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_SearchableElements, SWT.NULL); sbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); viewableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); viewableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); ((GridData) viewableBEsList.getLayoutData()).heightHint = 100; searchableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); searchableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); ((GridData) searchableBEsList.getLayoutData()).heightHint = 100; Label wcLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_Conditions, SWT.NULL); wcLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); wcListViewer = new ListViewer(charComposite, SWT.BORDER); wcListViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); ((GridData) wcListViewer.getControl().getLayoutData()).minimumHeight = 100; wcListViewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { return ((WSView) inputElement).getWhereConditions().toArray(); } }); wcListViewer.setLabelProvider(new ILabelProvider() { public Image getImage(Object element) { return null; } public String getText(Object element) { WSWhereCondition wc = (WSWhereCondition) element; String text = wc.getLeftPath() + " ";//$NON-NLS-1$ if (wc.getOperator().equals(WSWhereOperator.CONTAINS)) { text += "Contains";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.CONTAINS_TEXT_OF)) { text += "Contains Text Of";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.EQUALS)) { text += "=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN)) { text += ">";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN_OR_EQUAL)) { text += ">=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "Joins With";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN)) { text += "<";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN_OR_EQUAL)) { text += "<=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.NOT_EQUALS)) { text += "!=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.STARTSWITH)) { text += "Starts With";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.STRICTCONTAINS)) { text += "Strict Contains";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.EMPTY_NULL)) { text += "Is Empty Or Null";//$NON-NLS-1$ } text += " ";//$NON-NLS-1$ if (!wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "\"";//$NON-NLS-1$ } text += wc.getRightValueOrPath(); if (!wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "\"";//$NON-NLS-1$ } text += " ";//$NON-NLS-1$ if (wc.getStringPredicate().equals(WSStringPredicate.AND)) { text += "[and]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.EXACTLY)) { text += "[exactly]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.NONE)) { text += "";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) { text += "[not]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) { text += "[or]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.STRICTAND)) { text += "[strict and]";//$NON-NLS-1$ } return text; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } }); int columns = 6; Composite resultsGroup = this.getNewSectionComposite(Messages.ViewBrowserMainPage_SearchAndResults); resultsGroup.setLayout(new GridLayout(columns, false)); Composite createComposite = toolkit.createComposite(resultsGroup); GridLayout layout = new GridLayout(3, false); layout.marginWidth = 0; createComposite.setLayout(layout); createComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); Label containerLabel = toolkit.createLabel(createComposite, Messages.ViewBrowserMainPage_Container, SWT.NULL); containerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); dataClusterCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE); dataClusterCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); ((GridData) dataClusterCombo.getLayoutData()).minimumWidth = 100; clusterTypeCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.SINGLE); GridData typeLayout = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1); typeLayout.horizontalIndent = 10; clusterTypeCombo.setLayoutData(typeLayout); Label searchOnLabel = toolkit.createLabel(resultsGroup, Messages.ViewBrowserMainPage_SearchOn, SWT.NULL); GridData layoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); layoutData.horizontalIndent = 20; searchOnLabel.setLayoutData(layoutData); searchItemCombo = new Combo(resultsGroup, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE); searchItemCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); ((GridData) searchItemCombo.getLayoutData()).minimumWidth = 100; searchItemCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (FULL_TEXT.equals(searchItemCombo.getText())) { matchAllWordsBtn.setEnabled(true); } else { matchAllWordsBtn.setSelection(false); matchAllWordsBtn.setEnabled(false); } } }); searchText = toolkit.createText(resultsGroup, "", SWT.BORDER);//$NON-NLS-1$ searchText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); searchText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if ((e.stateMask == 0) && (e.character == SWT.CR)) { ViewBrowserMainPage.this.resultsViewer.setInput(getResults()); } }// keyReleased }// keyListener ); Button bSearch = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_Search, SWT.CENTER); bSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1)); bSearch.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { ViewBrowserMainPage.this.resultsViewer.setInput(getResults()); }; }); matchAllWordsBtn = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_MatchWholeSentence, SWT.CHECK); matchAllWordsBtn.setSelection(true); resultsLabel = toolkit.createLabel(resultsGroup, "", SWT.NULL); //$NON-NLS-1$ GridData resultLayoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, columns - 1, 1); resultLayoutData.widthHint = 100; resultsLabel.setLayoutData(resultLayoutData); resultsViewer = new TableViewer(resultsGroup); resultsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1)); ((GridData) resultsViewer.getControl().getLayoutData()).heightHint = 500; resultsViewer.setContentProvider(new ArrayContentProvider()); resultsViewer.setLabelProvider(new XMLTableLabelProvider()); resultsViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { resultsViewer.setSelection(event.getSelection()); try { new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), resultsViewer).run(); } catch (Exception e) { MessageDialog.openError( ViewBrowserMainPage.this.getSite().getShell(), Messages._Error, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg, e.getClass().getName(), e.getLocalizedMessage())); } } }); hookContextMenu(); addListener(); } catch (Exception e) { log.error(e.getMessage(), e); } }// createCharacteristicsContent @Override protected void refreshData() { try { if (viewableBEsList.isDisposed() || searchableBEsList.isDisposed() || wcListViewer.getList().isDisposed() || searchItemCombo.isDisposed() || dataClusterCombo.isDisposed()) { return; } WSView view = null; if (getXObject().getWsObject() == null) { // then fetch from server TMDMService port = getMDMService(); view = port.getView(new WSGetView((WSViewPK) getXObject().getWsKey())); getXObject().setWsObject(view); } else { // it has been opened by an editor - use the object there view = (WSView) getXObject().getWsObject(); } java.util.List<String> paths = view.getViewableBusinessElements(); // Fill the vbe List viewableBEsList.removeAll(); for (String path : paths) { viewableBEsList.add(path); } paths = view.getSearchableBusinessElements(); searchableBEsList.removeAll(); searchItemCombo.removeAll(); if (paths != null) { for (String path : paths) { searchableBEsList.add(path); searchItemCombo.add(path); } } searchItemCombo.add(FULL_TEXT); searchItemCombo.setText(FULL_TEXT); wcListViewer.setInput(view); wcListViewer.refresh(); dataClusterCombo.removeAll(); java.util.List<WSDataClusterPK> dataClusterPKs = getDataClusterPKs(); if ((dataClusterPKs == null) || (dataClusterPKs.size() == 0)) { MessageDialog.openError(this.getSite().getShell(), Messages._Error, Messages.ViewBrowserMainPage_ErrorMsg1); return; } for (WSDataClusterPK pk : dataClusterPKs) { dataClusterCombo.add(pk.getPk()); } dataClusterCombo.select(0); clusterTypeCombo.setItems(getClusterTypes()); clusterTypeCombo.select(0); this.getManagedForm().reflow(true); searchText.setFocus(); } catch (Exception e) { log.error(e.getMessage(), e); if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle2)) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle2, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg2, e.getLocalizedMessage())); } } } protected String[] getClusterTypes() { return new String[0]; } protected java.util.List<WSDataClusterPK> getDataClusterPKs() throws MalformedURLException, XtentisException { return Util.getAllDataClusterPKs(new URL(getXObject().getEndpointAddress()), getXObject().getUsername(), getXObject() .getPassword()); } @Override protected void commit() { try { } catch (Exception e) { log.error(e.getMessage(), e); MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle3, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg3, e.getLocalizedMessage())); } } @Override protected void createActions() { } private void hookContextMenu() { MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { manager.add(new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), ViewBrowserMainPage.this.resultsViewer)); } }); Menu menu = menuMgr.createContextMenu(resultsViewer.getControl()); resultsViewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, resultsViewer); } private void addListener() { dataClusterCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clusterTypeCombo.setItems(getClusterTypes()); clusterTypeCombo.select(0); } }); } protected void fillContextMenu(IMenuManager manager) { return; } protected WSViewPK getViewPK() { return (WSViewPK) getXObject().getWsKey(); } public String[] getResults() { Cursor waitCursor = null; try { Display display = getEditor().getSite().getPage().getWorkbenchWindow().getWorkbench().getDisplay(); waitCursor = new Cursor(display, SWT.CURSOR_WAIT); this.getSite().getShell().setCursor(waitCursor); TMDMService service = getMDMService(); java.util.List<String> results = null; int maxItem = 10; String search = "".equals(searchText.getText()) ? "*" : searchText.getText(); //$NON-NLS-1$ //$NON-NLS-2$ WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataClusterCombo.getText() + getPkAddition()); if (FULL_TEXT.equals(searchItemCombo.getText())) { boolean matchAllWords = matchAllWordsBtn.getSelection(); results = service.quickSearch( new WSQuickSearch(null, matchAllWords, maxItem, null, search, 0, Integer.MAX_VALUE, wsDataClusterPK, getViewPK())).getStrings(); } else { WSView wsview = (WSView) wcListViewer.getInput(); java.util.List<WSWhereCondition> array = wsview.getWhereConditions(); java.util.List<WSWhereItem> conditions = new ArrayList<WSWhereItem>(); for (WSWhereCondition condition : array) { WSWhereItem item = new WSWhereItem(null, condition, null); conditions.add(item); } WSWhereCondition condition = new WSWhereCondition(searchItemCombo.getText(), WSWhereOperator.CONTAINS, search, true, WSStringPredicate.AND); WSWhereItem item = new WSWhereItem(null, condition, null); conditions.add(item); WSWhereAnd and = new WSWhereAnd(conditions); WSWhereItem wi = new WSWhereItem(and, null, null); results = service.viewSearch( new WSViewSearch("ascending", maxItem, null, 0, -1, wi, wsDataClusterPK, getViewPK())).getStrings(); //$NON-NLS-1$ } resultsLabel.setText(Messages.bind(Messages.ViewBrowserMainPage_Results, results.size() - 1)); if (results.size() > 1) { return results.subList(1, results.size()).toArray(new String[0]); } return new String[0]; } catch (Exception e) { log.error(e.getMessage(), e); if ((e.getLocalizedMessage() != null) && e.getLocalizedMessage().contains("10000")) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle4, Messages.ViewBrowserMainPage_ErrorMsg4); } else if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle5)) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle5, e.getLocalizedMessage()); } return null; } finally { try { this.getSite().getShell().setCursor(null); waitCursor.dispose(); } catch (Exception e) { } } } protected String getPkAddition() { return ""; //$NON-NLS-1$ } class DOMViewAction extends Action { private Shell shell = null; private Viewer viewer; public DOMViewAction(Shell shell, Viewer viewer) { super(); this.shell = shell; this.viewer = viewer; setImageDescriptor(ImageCache.getImage("icons/add_obj.gif"));//$NON-NLS-1$ setText(Messages.ViewBrowserMainPage_ViewTree); setToolTipText(Messages.ViewBrowserMainPage_ViewAsDOMTree); } @Override public void run() { try { super.run(); IStructuredSelection selection = ((IStructuredSelection) viewer.getSelection()); String xml = (String) selection.getFirstElement(); // clean up highlights xml = xml.replaceAll("\\s*__h", "").replaceAll("h__\\s*", "");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ final DOMViewDialog d = new DOMViewDialog(ViewBrowserMainPage.this.getSite().getShell(), Util.parse(xml)); d.addListener(new Listener() { public void handleEvent(Event event) { if (event.button == DOMViewDialog.BUTTON_CLOSE) { d.close(); } } }); d.setBlockOnOpen(true); d.open(); d.close(); } catch (Exception e) { log.error(e.getMessage(), e); MessageDialog.openError(shell, Messages._Error, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg5, e.getLocalizedMessage())); } } @Override public void runWithEvent(Event event) { super.runWithEvent(event); } } protected static Pattern highlightLeft = Pattern.compile("\\s*__h");//$NON-NLS-1$ protected static Pattern highlightRight = Pattern.compile("h__\\s*");//$NON-NLS-1$ protected static Pattern emptyTags = Pattern.compile("\\s*<(.*?)\\/>\\s*");//$NON-NLS-1$ protected static Pattern openingTags = Pattern.compile("\\s*<([^\\/].*?[^\\/])>\\s*");//$NON-NLS-1$ protected static Pattern closingTags = Pattern.compile("\\s*</(.*?)>\\s*");//$NON-NLS-1$ class XMLTableLabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { String xml = (String) element; xml = highlightLeft.matcher(xml).replaceAll("");//$NON-NLS-1$ xml = highlightRight.matcher(xml).replaceAll("");//$NON-NLS-1$ xml = emptyTags.matcher(xml).replaceAll("[$1]");//$NON-NLS-1$ xml = openingTags.matcher(xml).replaceAll("[$1: ");//$NON-NLS-1$ xml = closingTags.matcher(xml).replaceAll("]");//$NON-NLS-1$ if (xml.length() >= 150) { return xml.substring(0, 150) + "...";//$NON-NLS-1$ } return xml; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } } /********************************* * IXObjectModelListener interface */ public void handleEvent(int type, TreeObject parent, TreeObject child) { refreshData(); } }
rubikloud/tmdm-studio-se
main/plugins/org.talend.mdm.workbench/src/com/amalto/workbench/editors/ViewBrowserMainPage.java
7,952
// listen to events
line_comment
nl
// ============================================================================ // // Copyright (C) 2006-2015 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package com.amalto.workbench.editors; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormToolkit; import com.amalto.workbench.dialogs.DOMViewDialog; import com.amalto.workbench.i18n.Messages; import com.amalto.workbench.image.ImageCache; import com.amalto.workbench.models.IXObjectModelListener; import com.amalto.workbench.models.TreeObject; import com.amalto.workbench.providers.XObjectBrowserInput; import com.amalto.workbench.utils.Util; import com.amalto.workbench.utils.XtentisException; import com.amalto.workbench.webservices.TMDMService; import com.amalto.workbench.webservices.WSDataClusterPK; import com.amalto.workbench.webservices.WSGetView; import com.amalto.workbench.webservices.WSQuickSearch; import com.amalto.workbench.webservices.WSStringPredicate; import com.amalto.workbench.webservices.WSView; import com.amalto.workbench.webservices.WSViewPK; import com.amalto.workbench.webservices.WSViewSearch; import com.amalto.workbench.webservices.WSWhereAnd; import com.amalto.workbench.webservices.WSWhereCondition; import com.amalto.workbench.webservices.WSWhereItem; import com.amalto.workbench.webservices.WSWhereOperator; public class ViewBrowserMainPage extends AMainPage implements IXObjectModelListener { private static Log log = LogFactory.getLog(ViewBrowserMainPage.class); protected Combo dataClusterCombo; protected Text searchText; protected TableViewer resultsViewer; protected List viewableBEsList; protected List searchableBEsList; protected ListViewer wcListViewer; protected Label resultsLabel; protected Button matchAllWordsBtn; private Combo searchItemCombo; private final String FULL_TEXT = Messages.ViewBrowserMainPage_fullText; protected Combo clusterTypeCombo; public ViewBrowserMainPage(FormEditor editor) { super(editor, ViewBrowserMainPage.class.getName(), Messages.ViewBrowserMainPage_ViewBrowser + ((XObjectBrowserInput) editor.getEditorInput()).getName()); // listen to<SUF> ((XObjectBrowserInput) editor.getEditorInput()).addListener(this); } @Override protected void createCharacteristicsContent(FormToolkit toolkit, Composite charComposite) { try { Label vbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_ViewableElements, SWT.NULL); vbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); Label sbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_SearchableElements, SWT.NULL); sbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); viewableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); viewableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); ((GridData) viewableBEsList.getLayoutData()).heightHint = 100; searchableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); searchableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); ((GridData) searchableBEsList.getLayoutData()).heightHint = 100; Label wcLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_Conditions, SWT.NULL); wcLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); wcListViewer = new ListViewer(charComposite, SWT.BORDER); wcListViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); ((GridData) wcListViewer.getControl().getLayoutData()).minimumHeight = 100; wcListViewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { return ((WSView) inputElement).getWhereConditions().toArray(); } }); wcListViewer.setLabelProvider(new ILabelProvider() { public Image getImage(Object element) { return null; } public String getText(Object element) { WSWhereCondition wc = (WSWhereCondition) element; String text = wc.getLeftPath() + " ";//$NON-NLS-1$ if (wc.getOperator().equals(WSWhereOperator.CONTAINS)) { text += "Contains";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.CONTAINS_TEXT_OF)) { text += "Contains Text Of";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.EQUALS)) { text += "=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN)) { text += ">";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN_OR_EQUAL)) { text += ">=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "Joins With";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN)) { text += "<";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN_OR_EQUAL)) { text += "<=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.NOT_EQUALS)) { text += "!=";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.STARTSWITH)) { text += "Starts With";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.STRICTCONTAINS)) { text += "Strict Contains";//$NON-NLS-1$ } else if (wc.getOperator().equals(WSWhereOperator.EMPTY_NULL)) { text += "Is Empty Or Null";//$NON-NLS-1$ } text += " ";//$NON-NLS-1$ if (!wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "\"";//$NON-NLS-1$ } text += wc.getRightValueOrPath(); if (!wc.getOperator().equals(WSWhereOperator.JOIN)) { text += "\"";//$NON-NLS-1$ } text += " ";//$NON-NLS-1$ if (wc.getStringPredicate().equals(WSStringPredicate.AND)) { text += "[and]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.EXACTLY)) { text += "[exactly]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.NONE)) { text += "";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) { text += "[not]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) { text += "[or]";//$NON-NLS-1$ } else if (wc.getStringPredicate().equals(WSStringPredicate.STRICTAND)) { text += "[strict and]";//$NON-NLS-1$ } return text; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } }); int columns = 6; Composite resultsGroup = this.getNewSectionComposite(Messages.ViewBrowserMainPage_SearchAndResults); resultsGroup.setLayout(new GridLayout(columns, false)); Composite createComposite = toolkit.createComposite(resultsGroup); GridLayout layout = new GridLayout(3, false); layout.marginWidth = 0; createComposite.setLayout(layout); createComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); Label containerLabel = toolkit.createLabel(createComposite, Messages.ViewBrowserMainPage_Container, SWT.NULL); containerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); dataClusterCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE); dataClusterCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); ((GridData) dataClusterCombo.getLayoutData()).minimumWidth = 100; clusterTypeCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.SINGLE); GridData typeLayout = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1); typeLayout.horizontalIndent = 10; clusterTypeCombo.setLayoutData(typeLayout); Label searchOnLabel = toolkit.createLabel(resultsGroup, Messages.ViewBrowserMainPage_SearchOn, SWT.NULL); GridData layoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); layoutData.horizontalIndent = 20; searchOnLabel.setLayoutData(layoutData); searchItemCombo = new Combo(resultsGroup, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE); searchItemCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); ((GridData) searchItemCombo.getLayoutData()).minimumWidth = 100; searchItemCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (FULL_TEXT.equals(searchItemCombo.getText())) { matchAllWordsBtn.setEnabled(true); } else { matchAllWordsBtn.setSelection(false); matchAllWordsBtn.setEnabled(false); } } }); searchText = toolkit.createText(resultsGroup, "", SWT.BORDER);//$NON-NLS-1$ searchText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); searchText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if ((e.stateMask == 0) && (e.character == SWT.CR)) { ViewBrowserMainPage.this.resultsViewer.setInput(getResults()); } }// keyReleased }// keyListener ); Button bSearch = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_Search, SWT.CENTER); bSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1)); bSearch.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { ViewBrowserMainPage.this.resultsViewer.setInput(getResults()); }; }); matchAllWordsBtn = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_MatchWholeSentence, SWT.CHECK); matchAllWordsBtn.setSelection(true); resultsLabel = toolkit.createLabel(resultsGroup, "", SWT.NULL); //$NON-NLS-1$ GridData resultLayoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, columns - 1, 1); resultLayoutData.widthHint = 100; resultsLabel.setLayoutData(resultLayoutData); resultsViewer = new TableViewer(resultsGroup); resultsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1)); ((GridData) resultsViewer.getControl().getLayoutData()).heightHint = 500; resultsViewer.setContentProvider(new ArrayContentProvider()); resultsViewer.setLabelProvider(new XMLTableLabelProvider()); resultsViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { resultsViewer.setSelection(event.getSelection()); try { new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), resultsViewer).run(); } catch (Exception e) { MessageDialog.openError( ViewBrowserMainPage.this.getSite().getShell(), Messages._Error, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg, e.getClass().getName(), e.getLocalizedMessage())); } } }); hookContextMenu(); addListener(); } catch (Exception e) { log.error(e.getMessage(), e); } }// createCharacteristicsContent @Override protected void refreshData() { try { if (viewableBEsList.isDisposed() || searchableBEsList.isDisposed() || wcListViewer.getList().isDisposed() || searchItemCombo.isDisposed() || dataClusterCombo.isDisposed()) { return; } WSView view = null; if (getXObject().getWsObject() == null) { // then fetch from server TMDMService port = getMDMService(); view = port.getView(new WSGetView((WSViewPK) getXObject().getWsKey())); getXObject().setWsObject(view); } else { // it has been opened by an editor - use the object there view = (WSView) getXObject().getWsObject(); } java.util.List<String> paths = view.getViewableBusinessElements(); // Fill the vbe List viewableBEsList.removeAll(); for (String path : paths) { viewableBEsList.add(path); } paths = view.getSearchableBusinessElements(); searchableBEsList.removeAll(); searchItemCombo.removeAll(); if (paths != null) { for (String path : paths) { searchableBEsList.add(path); searchItemCombo.add(path); } } searchItemCombo.add(FULL_TEXT); searchItemCombo.setText(FULL_TEXT); wcListViewer.setInput(view); wcListViewer.refresh(); dataClusterCombo.removeAll(); java.util.List<WSDataClusterPK> dataClusterPKs = getDataClusterPKs(); if ((dataClusterPKs == null) || (dataClusterPKs.size() == 0)) { MessageDialog.openError(this.getSite().getShell(), Messages._Error, Messages.ViewBrowserMainPage_ErrorMsg1); return; } for (WSDataClusterPK pk : dataClusterPKs) { dataClusterCombo.add(pk.getPk()); } dataClusterCombo.select(0); clusterTypeCombo.setItems(getClusterTypes()); clusterTypeCombo.select(0); this.getManagedForm().reflow(true); searchText.setFocus(); } catch (Exception e) { log.error(e.getMessage(), e); if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle2)) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle2, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg2, e.getLocalizedMessage())); } } } protected String[] getClusterTypes() { return new String[0]; } protected java.util.List<WSDataClusterPK> getDataClusterPKs() throws MalformedURLException, XtentisException { return Util.getAllDataClusterPKs(new URL(getXObject().getEndpointAddress()), getXObject().getUsername(), getXObject() .getPassword()); } @Override protected void commit() { try { } catch (Exception e) { log.error(e.getMessage(), e); MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle3, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg3, e.getLocalizedMessage())); } } @Override protected void createActions() { } private void hookContextMenu() { MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { manager.add(new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), ViewBrowserMainPage.this.resultsViewer)); } }); Menu menu = menuMgr.createContextMenu(resultsViewer.getControl()); resultsViewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, resultsViewer); } private void addListener() { dataClusterCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clusterTypeCombo.setItems(getClusterTypes()); clusterTypeCombo.select(0); } }); } protected void fillContextMenu(IMenuManager manager) { return; } protected WSViewPK getViewPK() { return (WSViewPK) getXObject().getWsKey(); } public String[] getResults() { Cursor waitCursor = null; try { Display display = getEditor().getSite().getPage().getWorkbenchWindow().getWorkbench().getDisplay(); waitCursor = new Cursor(display, SWT.CURSOR_WAIT); this.getSite().getShell().setCursor(waitCursor); TMDMService service = getMDMService(); java.util.List<String> results = null; int maxItem = 10; String search = "".equals(searchText.getText()) ? "*" : searchText.getText(); //$NON-NLS-1$ //$NON-NLS-2$ WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataClusterCombo.getText() + getPkAddition()); if (FULL_TEXT.equals(searchItemCombo.getText())) { boolean matchAllWords = matchAllWordsBtn.getSelection(); results = service.quickSearch( new WSQuickSearch(null, matchAllWords, maxItem, null, search, 0, Integer.MAX_VALUE, wsDataClusterPK, getViewPK())).getStrings(); } else { WSView wsview = (WSView) wcListViewer.getInput(); java.util.List<WSWhereCondition> array = wsview.getWhereConditions(); java.util.List<WSWhereItem> conditions = new ArrayList<WSWhereItem>(); for (WSWhereCondition condition : array) { WSWhereItem item = new WSWhereItem(null, condition, null); conditions.add(item); } WSWhereCondition condition = new WSWhereCondition(searchItemCombo.getText(), WSWhereOperator.CONTAINS, search, true, WSStringPredicate.AND); WSWhereItem item = new WSWhereItem(null, condition, null); conditions.add(item); WSWhereAnd and = new WSWhereAnd(conditions); WSWhereItem wi = new WSWhereItem(and, null, null); results = service.viewSearch( new WSViewSearch("ascending", maxItem, null, 0, -1, wi, wsDataClusterPK, getViewPK())).getStrings(); //$NON-NLS-1$ } resultsLabel.setText(Messages.bind(Messages.ViewBrowserMainPage_Results, results.size() - 1)); if (results.size() > 1) { return results.subList(1, results.size()).toArray(new String[0]); } return new String[0]; } catch (Exception e) { log.error(e.getMessage(), e); if ((e.getLocalizedMessage() != null) && e.getLocalizedMessage().contains("10000")) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle4, Messages.ViewBrowserMainPage_ErrorMsg4); } else if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle5)) { MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle5, e.getLocalizedMessage()); } return null; } finally { try { this.getSite().getShell().setCursor(null); waitCursor.dispose(); } catch (Exception e) { } } } protected String getPkAddition() { return ""; //$NON-NLS-1$ } class DOMViewAction extends Action { private Shell shell = null; private Viewer viewer; public DOMViewAction(Shell shell, Viewer viewer) { super(); this.shell = shell; this.viewer = viewer; setImageDescriptor(ImageCache.getImage("icons/add_obj.gif"));//$NON-NLS-1$ setText(Messages.ViewBrowserMainPage_ViewTree); setToolTipText(Messages.ViewBrowserMainPage_ViewAsDOMTree); } @Override public void run() { try { super.run(); IStructuredSelection selection = ((IStructuredSelection) viewer.getSelection()); String xml = (String) selection.getFirstElement(); // clean up highlights xml = xml.replaceAll("\\s*__h", "").replaceAll("h__\\s*", "");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ final DOMViewDialog d = new DOMViewDialog(ViewBrowserMainPage.this.getSite().getShell(), Util.parse(xml)); d.addListener(new Listener() { public void handleEvent(Event event) { if (event.button == DOMViewDialog.BUTTON_CLOSE) { d.close(); } } }); d.setBlockOnOpen(true); d.open(); d.close(); } catch (Exception e) { log.error(e.getMessage(), e); MessageDialog.openError(shell, Messages._Error, Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg5, e.getLocalizedMessage())); } } @Override public void runWithEvent(Event event) { super.runWithEvent(event); } } protected static Pattern highlightLeft = Pattern.compile("\\s*__h");//$NON-NLS-1$ protected static Pattern highlightRight = Pattern.compile("h__\\s*");//$NON-NLS-1$ protected static Pattern emptyTags = Pattern.compile("\\s*<(.*?)\\/>\\s*");//$NON-NLS-1$ protected static Pattern openingTags = Pattern.compile("\\s*<([^\\/].*?[^\\/])>\\s*");//$NON-NLS-1$ protected static Pattern closingTags = Pattern.compile("\\s*</(.*?)>\\s*");//$NON-NLS-1$ class XMLTableLabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { String xml = (String) element; xml = highlightLeft.matcher(xml).replaceAll("");//$NON-NLS-1$ xml = highlightRight.matcher(xml).replaceAll("");//$NON-NLS-1$ xml = emptyTags.matcher(xml).replaceAll("[$1]");//$NON-NLS-1$ xml = openingTags.matcher(xml).replaceAll("[$1: ");//$NON-NLS-1$ xml = closingTags.matcher(xml).replaceAll("]");//$NON-NLS-1$ if (xml.length() >= 150) { return xml.substring(0, 150) + "...";//$NON-NLS-1$ } return xml; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } } /********************************* * IXObjectModelListener interface */ public void handleEvent(int type, TreeObject parent, TreeObject child) { refreshData(); } }
50716_3
package gui.components; import static gui.LayoutService.getDefaultPadding; import static gui.LayoutService.getTitleFont; import java.util.ArrayList; import java.util.List; import basic.action.Action; import basic.attack.Attack; import basic.attack.types.SpecialAttack; import basic.monsters.AbstractEnemy; import basic.monsters.interfaces.DamageTypeCausesDisadvantage; import basic.monsters.specialabilities.SpecialAbility; import basic.ruleobjects.DamageType; import basic.services.DamageService; import gui.LayoutService; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; public class NewEnemyPane<T extends AbstractEnemy> extends GridPane { protected T enemy; private ComboBox<DamageType> damageTypesBox; private TextField inputField; private Statblock<T> statblock; protected VBox attackPane; private VBox specialAttackPane; private CheckBox disadvantageBox; private CheckBox advantageBox; private VBox checkboxes; private VBox additionalTextPane; public NewEnemyPane(T enemy) { this.enemy = enemy; add(new TitleBlock<T>(enemy), 0, 0); addDamagePane(); // 0, 1 addStatBlock(); // 0, 2 refreshAttackPanes(true); // attackPane 0, 4 & specialAttackpane 0, 5 addOtherActionsPane(); // 0, 5 addAdvantageCheckBoxes(); // 0, 6 addSpecialAbilitiesPane(); // 0, 7 } public NewEnemyPane(T enemy, String additionalText) { this(enemy); addAdditonalTextPane(additionalText); // 0, 8 } private void addDamagePane() { HBox damagePane = new HBox(10); damagePane.setPadding(getDefaultPadding()); Button addDamage = new Button("Add damage"); addDamage.setOnAction(e -> onDamageAdded()); damageTypesBox = new ComboBox<>(); damageTypesBox.getItems().addAll(DamageType.values()); inputField = new TextField(); damagePane.getChildren().addAll(inputField, damageTypesBox, addDamage); add(damagePane, 0, 1); } private void onDamageAdded() { String inputText = inputField.getText(); int damage = inputText.isEmpty() ? 0 : Integer.parseInt(inputText); enemy.doDamage(damage, damageTypesBox.getValue()); statblock.updateHitpointsText(); if (enemy instanceof DamageTypeCausesDisadvantage && ((DamageTypeCausesDisadvantage) enemy).getRoundsAffected() > 0) { disadvantageBox.setSelected(enemy.isDisadvantageOnAttacks()); } inputField.clear(); damageTypesBox.setValue(null); } private void addStatBlock() { statblock = new Statblock<T>(enemy); add(statblock, 0, 2); } public void refreshAttackPanes(boolean start) { if (this.getChildren().contains(attackPane)) { this.getChildren().remove(attackPane); } if (this.getChildren().contains(specialAttackPane) && !enemy.getSpecialAttacks().isEmpty()) { this.getChildren().remove(specialAttackPane); } updateAttackPane(start); updateSpecialAttackPane(start); } private void updateAttackPane(boolean start) { attackPane = new VBox(10); attackPane.setPadding(getDefaultPadding()); attackPane.setMinHeight(enemy.getAvailableAttacks().size() * enemy.getAttacksOnAttackAction() * 30); attackPane.setMinWidth(600); List<Text> texts = new ArrayList<>(); Text title = new Text("Attacks: (" + enemy.getAttacksOnAttackAction() + ")"); title.setFont(getTitleFont()); texts.add(title); if (!start && enemy.isAlive()) { getAttackText(texts); } attackPane.getChildren().addAll(texts); add(attackPane, 0, 3); } protected void getAttackText(List<Text> texts) { if (heeftScheveVerdelingAttacksByMultiAttack()) { for (Attack a : enemy.getAvailableAttacks()) { for (int i = 0; i < a.getNumberOfUsesOnMultiAttack(); i++) { addAttackText(texts, a); } } } else { for (int i = 0; i < enemy.getAttacksOnAttackAction(); i++) { for (Attack a : enemy.getAvailableAttacks()) { addAttackText(texts, a); } } } texts.forEach(t -> t.setWrappingWidth(580)); } protected boolean heeftScheveVerdelingAttacksByMultiAttack() { // of het getal is 0 --> niet ingesteld, toon available attacks zo vaak als er // attacks on attack action zijn // of het getal is gelijk aan attacks on attack action --> toon alle attacks zo // vaak als ze uses hebben // of het getal is kleiner dan attacks on attack action --> er is iets fout, // IllegalArgumentException // of het getal is groter dan attacks on attack action --> zoals bij 0 int totalAttacksFromUses = enemy.getAvailableAttacks()// .stream()// .mapToInt(a -> a.getNumberOfUsesOnMultiAttack())// .sum(); int attacksOnAttackAction = enemy.getAttacksOnAttackAction(); // TODO dit klopt niet helemaal zoals bij de medusa het geval is. Die heeft 3 // soorten aanvallen. Ze kan 3 melee of 2 ranged in een beurt if (totalAttacksFromUses == 0 || (totalAttacksFromUses > attacksOnAttackAction)) return false; if (totalAttacksFromUses == attacksOnAttackAction) return true; if (totalAttacksFromUses < attacksOnAttackAction) throw new IllegalArgumentException("De som van de uses van attacks on attack" + " action is kleiner dan attacks on attack action, er is ergens iets niet goed ingevuld"); return false; } protected void addAttackText(List<Text> texts, Attack a) { AttackText text = DamageService.getAttackText(a, enemy.isAdvantageOnAttacks(), enemy.isDisadvantageOnAttacks()); Text attackText = new Text(text.getText()); if (text.isCritical()) { attackText.setFill(LayoutService.getCritical()); } texts.add(attackText); } private void updateSpecialAttackPane(boolean start) { specialAttackPane = new VBox(10); specialAttackPane.setPadding(getDefaultPadding()); specialAttackPane.setMinHeight(150); specialAttackPane.setMinWidth(500); if (!enemy.getSpecialAttacks().isEmpty()) { Text title = new Text("Special Attacks: "); title.setFont(getTitleFont()); specialAttackPane.getChildren().add(title); if (!start && enemy.isAlive()) { List<Pane> sAIP = new ArrayList<>(); for (SpecialAttack attack : enemy.getSpecialAttacks()) { VBox sAP = new VBox(10); sAP.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); if (attack.isAvailable()) { texts.add(new Text(DamageService.getSpecialAttackText(attack))); texts.add(new Text("Description: ")); texts.add(new Text(attack.getDescription())); texts.forEach(t -> t.setWrappingWidth(550)); } else { texts.add(new Text(attack.getWeaponName() + " is not available")); } sAP.getChildren().addAll(texts); if (attack.isAvailable() && attack.hasRecharge()) { Button useButton = new Button("Use " + attack.getWeaponName()); useButton.setOnAction(e -> attack.useAttack()); sAP.getChildren().add(useButton); } sAIP.add(sAP); } specialAttackPane.getChildren().addAll(sAIP); } add(specialAttackPane, 0, 4); } } private void addOtherActionsPane() { if (!enemy.getActions().isEmpty()) { VBox actionsPane = new VBox(10); actionsPane.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); for (Action a : enemy.getActions()) { Text title = new Text("Other Actions: "); title.setFont(getTitleFont()); texts.add(title); texts.add(new Text(a.toString())); } texts.forEach(t -> t.setWrappingWidth(580)); actionsPane.getChildren().addAll(texts); add(actionsPane, 0, 5); } } private void addAdvantageCheckBoxes() { checkboxes = new VBox(10); checkboxes.setPadding(getDefaultPadding()); advantageBox = new CheckBox("Has advantage on attacks"); advantageBox.setOnAction(e -> enemy.setAdvantageOnAttacks(!enemy.isAdvantageOnAttacks())); disadvantageBox = new CheckBox("Has disadvantage on attacks"); disadvantageBox.setOnAction(e -> enemy.setDisadvantageOnAttacks(!enemy.isDisadvantageOnAttacks())); Button rerollAttacks = new Button("Reroll attacks"); rerollAttacks.setOnAction(e -> refreshAttackPanes(false)); checkboxes.getChildren().addAll(advantageBox, disadvantageBox, rerollAttacks); add(checkboxes, 0, 6); } private void addSpecialAbilitiesPane() { if (!enemy.getSpecialAbilities().isEmpty()) { VBox specAbPane = new VBox(10); specAbPane.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); for (SpecialAbility s : enemy.getSpecialAbilities()) { Text title = new Text(s.getName()); title.setFont(getTitleFont()); texts.add(title); texts.add(new Text(s.getDescription())); } texts.forEach(t -> t.setWrappingWidth(580)); specAbPane.getChildren().addAll(texts); add(specAbPane, 0, 7); } } public void refreshCheckBoxes() { disadvantageBox.setSelected(enemy.isDisadvantageOnAttacks()); advantageBox.setSelected(enemy.isAdvantageOnAttacks()); } private void addAdditonalTextPane(String additionalText) { if (additionalText != null) { additionalTextPane = new VBox(10); additionalTextPane.setPadding(getDefaultPadding()); if (!additionalText.isEmpty()) { additionalTextPane.getChildren().add(new Text(additionalText)); } add(additionalTextPane, 0, 8); } } public VBox getAdditionalTextPane() { return additionalTextPane; } public AbstractEnemy getEnemy() { return enemy; } }
rudinebijlsma/DungeonsAndDragons
src/gui/components/NewEnemyPane.java
3,374
// of het getal is gelijk aan attacks on attack action --> toon alle attacks zo
line_comment
nl
package gui.components; import static gui.LayoutService.getDefaultPadding; import static gui.LayoutService.getTitleFont; import java.util.ArrayList; import java.util.List; import basic.action.Action; import basic.attack.Attack; import basic.attack.types.SpecialAttack; import basic.monsters.AbstractEnemy; import basic.monsters.interfaces.DamageTypeCausesDisadvantage; import basic.monsters.specialabilities.SpecialAbility; import basic.ruleobjects.DamageType; import basic.services.DamageService; import gui.LayoutService; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; public class NewEnemyPane<T extends AbstractEnemy> extends GridPane { protected T enemy; private ComboBox<DamageType> damageTypesBox; private TextField inputField; private Statblock<T> statblock; protected VBox attackPane; private VBox specialAttackPane; private CheckBox disadvantageBox; private CheckBox advantageBox; private VBox checkboxes; private VBox additionalTextPane; public NewEnemyPane(T enemy) { this.enemy = enemy; add(new TitleBlock<T>(enemy), 0, 0); addDamagePane(); // 0, 1 addStatBlock(); // 0, 2 refreshAttackPanes(true); // attackPane 0, 4 & specialAttackpane 0, 5 addOtherActionsPane(); // 0, 5 addAdvantageCheckBoxes(); // 0, 6 addSpecialAbilitiesPane(); // 0, 7 } public NewEnemyPane(T enemy, String additionalText) { this(enemy); addAdditonalTextPane(additionalText); // 0, 8 } private void addDamagePane() { HBox damagePane = new HBox(10); damagePane.setPadding(getDefaultPadding()); Button addDamage = new Button("Add damage"); addDamage.setOnAction(e -> onDamageAdded()); damageTypesBox = new ComboBox<>(); damageTypesBox.getItems().addAll(DamageType.values()); inputField = new TextField(); damagePane.getChildren().addAll(inputField, damageTypesBox, addDamage); add(damagePane, 0, 1); } private void onDamageAdded() { String inputText = inputField.getText(); int damage = inputText.isEmpty() ? 0 : Integer.parseInt(inputText); enemy.doDamage(damage, damageTypesBox.getValue()); statblock.updateHitpointsText(); if (enemy instanceof DamageTypeCausesDisadvantage && ((DamageTypeCausesDisadvantage) enemy).getRoundsAffected() > 0) { disadvantageBox.setSelected(enemy.isDisadvantageOnAttacks()); } inputField.clear(); damageTypesBox.setValue(null); } private void addStatBlock() { statblock = new Statblock<T>(enemy); add(statblock, 0, 2); } public void refreshAttackPanes(boolean start) { if (this.getChildren().contains(attackPane)) { this.getChildren().remove(attackPane); } if (this.getChildren().contains(specialAttackPane) && !enemy.getSpecialAttacks().isEmpty()) { this.getChildren().remove(specialAttackPane); } updateAttackPane(start); updateSpecialAttackPane(start); } private void updateAttackPane(boolean start) { attackPane = new VBox(10); attackPane.setPadding(getDefaultPadding()); attackPane.setMinHeight(enemy.getAvailableAttacks().size() * enemy.getAttacksOnAttackAction() * 30); attackPane.setMinWidth(600); List<Text> texts = new ArrayList<>(); Text title = new Text("Attacks: (" + enemy.getAttacksOnAttackAction() + ")"); title.setFont(getTitleFont()); texts.add(title); if (!start && enemy.isAlive()) { getAttackText(texts); } attackPane.getChildren().addAll(texts); add(attackPane, 0, 3); } protected void getAttackText(List<Text> texts) { if (heeftScheveVerdelingAttacksByMultiAttack()) { for (Attack a : enemy.getAvailableAttacks()) { for (int i = 0; i < a.getNumberOfUsesOnMultiAttack(); i++) { addAttackText(texts, a); } } } else { for (int i = 0; i < enemy.getAttacksOnAttackAction(); i++) { for (Attack a : enemy.getAvailableAttacks()) { addAttackText(texts, a); } } } texts.forEach(t -> t.setWrappingWidth(580)); } protected boolean heeftScheveVerdelingAttacksByMultiAttack() { // of het getal is 0 --> niet ingesteld, toon available attacks zo vaak als er // attacks on attack action zijn // of het<SUF> // vaak als ze uses hebben // of het getal is kleiner dan attacks on attack action --> er is iets fout, // IllegalArgumentException // of het getal is groter dan attacks on attack action --> zoals bij 0 int totalAttacksFromUses = enemy.getAvailableAttacks()// .stream()// .mapToInt(a -> a.getNumberOfUsesOnMultiAttack())// .sum(); int attacksOnAttackAction = enemy.getAttacksOnAttackAction(); // TODO dit klopt niet helemaal zoals bij de medusa het geval is. Die heeft 3 // soorten aanvallen. Ze kan 3 melee of 2 ranged in een beurt if (totalAttacksFromUses == 0 || (totalAttacksFromUses > attacksOnAttackAction)) return false; if (totalAttacksFromUses == attacksOnAttackAction) return true; if (totalAttacksFromUses < attacksOnAttackAction) throw new IllegalArgumentException("De som van de uses van attacks on attack" + " action is kleiner dan attacks on attack action, er is ergens iets niet goed ingevuld"); return false; } protected void addAttackText(List<Text> texts, Attack a) { AttackText text = DamageService.getAttackText(a, enemy.isAdvantageOnAttacks(), enemy.isDisadvantageOnAttacks()); Text attackText = new Text(text.getText()); if (text.isCritical()) { attackText.setFill(LayoutService.getCritical()); } texts.add(attackText); } private void updateSpecialAttackPane(boolean start) { specialAttackPane = new VBox(10); specialAttackPane.setPadding(getDefaultPadding()); specialAttackPane.setMinHeight(150); specialAttackPane.setMinWidth(500); if (!enemy.getSpecialAttacks().isEmpty()) { Text title = new Text("Special Attacks: "); title.setFont(getTitleFont()); specialAttackPane.getChildren().add(title); if (!start && enemy.isAlive()) { List<Pane> sAIP = new ArrayList<>(); for (SpecialAttack attack : enemy.getSpecialAttacks()) { VBox sAP = new VBox(10); sAP.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); if (attack.isAvailable()) { texts.add(new Text(DamageService.getSpecialAttackText(attack))); texts.add(new Text("Description: ")); texts.add(new Text(attack.getDescription())); texts.forEach(t -> t.setWrappingWidth(550)); } else { texts.add(new Text(attack.getWeaponName() + " is not available")); } sAP.getChildren().addAll(texts); if (attack.isAvailable() && attack.hasRecharge()) { Button useButton = new Button("Use " + attack.getWeaponName()); useButton.setOnAction(e -> attack.useAttack()); sAP.getChildren().add(useButton); } sAIP.add(sAP); } specialAttackPane.getChildren().addAll(sAIP); } add(specialAttackPane, 0, 4); } } private void addOtherActionsPane() { if (!enemy.getActions().isEmpty()) { VBox actionsPane = new VBox(10); actionsPane.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); for (Action a : enemy.getActions()) { Text title = new Text("Other Actions: "); title.setFont(getTitleFont()); texts.add(title); texts.add(new Text(a.toString())); } texts.forEach(t -> t.setWrappingWidth(580)); actionsPane.getChildren().addAll(texts); add(actionsPane, 0, 5); } } private void addAdvantageCheckBoxes() { checkboxes = new VBox(10); checkboxes.setPadding(getDefaultPadding()); advantageBox = new CheckBox("Has advantage on attacks"); advantageBox.setOnAction(e -> enemy.setAdvantageOnAttacks(!enemy.isAdvantageOnAttacks())); disadvantageBox = new CheckBox("Has disadvantage on attacks"); disadvantageBox.setOnAction(e -> enemy.setDisadvantageOnAttacks(!enemy.isDisadvantageOnAttacks())); Button rerollAttacks = new Button("Reroll attacks"); rerollAttacks.setOnAction(e -> refreshAttackPanes(false)); checkboxes.getChildren().addAll(advantageBox, disadvantageBox, rerollAttacks); add(checkboxes, 0, 6); } private void addSpecialAbilitiesPane() { if (!enemy.getSpecialAbilities().isEmpty()) { VBox specAbPane = new VBox(10); specAbPane.setPadding(getDefaultPadding()); List<Text> texts = new ArrayList<>(); for (SpecialAbility s : enemy.getSpecialAbilities()) { Text title = new Text(s.getName()); title.setFont(getTitleFont()); texts.add(title); texts.add(new Text(s.getDescription())); } texts.forEach(t -> t.setWrappingWidth(580)); specAbPane.getChildren().addAll(texts); add(specAbPane, 0, 7); } } public void refreshCheckBoxes() { disadvantageBox.setSelected(enemy.isDisadvantageOnAttacks()); advantageBox.setSelected(enemy.isAdvantageOnAttacks()); } private void addAdditonalTextPane(String additionalText) { if (additionalText != null) { additionalTextPane = new VBox(10); additionalTextPane.setPadding(getDefaultPadding()); if (!additionalText.isEmpty()) { additionalTextPane.getChildren().add(new Text(additionalText)); } add(additionalTextPane, 0, 8); } } public VBox getAdditionalTextPane() { return additionalTextPane; } public AbstractEnemy getEnemy() { return enemy; } }
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,588
/* 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); } } }
44765_6
package com.istc.action; import com.istc.Entities.Entity.*; import com.istc.Service.EntityService.*; import com.istc.Validation.*; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.AllowedMethods; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import org.apache.struts2.json.annotations.JSON; import com.istc.Utilities.Encoder; import com.istc.Utilities.TokenUtils; import com.istc.Utilities.CookieUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 用于管理成员信息的增删改查,其中手动增加成员仅可以由部长级以上成员完成 */ @Controller("personnelAction") @Scope("prototype") @ParentPackage("ajax") @AllowedMethods({"addMember","addMinister","changePassword","personUpgrade","chooseDept","fetchAllPerson","getRestInterviewees","deleteMemberSubmit","resetPasswordSubmit","fetchMemberInfo","modifyInfo"}) public class PersonalAction extends ActionSupport implements SessionAware,ServletResponseAware,ServletRequestAware { private HttpServletRequest request; private HttpServletResponse response; //生日字符串模板格式 private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); //会话 private Map<String, Object> session; @Resource(name = "intervieweeService") private IntervieweeService intervieweeService; @Resource(name = "personService") private PersonService personService; @Resource(name = "departmentService") private DepartmentService departmentService; @Resource(name = "memberService") private MemberService memberService; //表单传入值 private String id; private String name; private String oldpassword; private String password; private String repassword; private int dept; private boolean gender; private String birthday; private String QQ; private String phoneNumber; private String token; private String newToken; //部长下属所有部员or部长下属部门id为dept的所有成员 private List<Member> deptMember; //要升级为部员成员id组,字符串 private String readyIntervieweeIdLine; //要升级为部员成员id组,action中分割得到 private String[] readyIntervieweeId; //要升级为部长的部员id private String readyMemberId; private Map<String,Object> jsonresult=new HashMap<String,Object>(); //默认重置密码为111111,用以部长重置部员 public static final String defaultPassword="111111"; private String deletedLine; private String[] deleted; private String needreset; //工具 private TokenUtils tokenUtil; private CookieUtils cookieUtil; private RegisterCheck registerUtil; private Encoder encoder; //定义全局常量 private final String loginKey = "member"; private final String tokenKey = "token"; private final String prePageKey = "prePage"; public PersonalAction(){ tokenUtil = TokenUtils.getInstance(); cookieUtil = CookieUtils.getInstance(); registerUtil = RegisterCheck.getInstance(); encoder = Encoder.getInstance(); } @Action( value="addMember", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * addMember为直接添加部门成员,不是从person转变为member,通过添加含有所属部门的部员来建立关系 */ public String addMember(){ newToken = tokenUtil.tokenCheck(this, session, token); System.out.println(id+" "+password+" "+name+" "+dept); Member p=new Member(); p.setID(id); password= encoder.encodeSHA512(password.getBytes()); p.setPassword(password); p.setName(name); p.setGender(gender); p.setQQ(QQ); p.setPhoneNumber(phoneNumber); Calendar calendar=Calendar.getInstance(); try { calendar.setTime(simpleDateFormat.parse(birthday)); } catch (ParseException e) { e.printStackTrace(); } System.out.println(p.toString()); p.setBirthday(calendar); Department depart0=departmentService.get(dept); p.addDepartment(depart0); memberService.save(p); return INPUT; } public void validateAddMember(){ if (dept==0||!departmentService.exist(dept)){ addFieldError("dept", "不存在该部门!"); } if (id==null || id.equals("")) { addFieldError("id", "请输入学号!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.ID,id)) { addFieldError("id", "学号输入有误,请检查并重新输入。"); } if (personService.exist(id)){ addFieldError("id","该学号仍为preson或member,请删除后添加"); } } if (password==null || password.equals("")) { addFieldError("password", "请设置密码!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PASSWORD,password)) { addFieldError("password", "密码中只允许使用数字、字母和下划线。长度不小于6位,不大于30位。"); } else if (!password.equals(repassword)) { addFieldError("repassword", "两次输入的密码不一致!"); } } if (name==null || name.equals("")) { addFieldError("name", "请输入姓名!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.NAME,name)) { addFieldError("name", "请输入正确的姓名信息!"); } } } @Action( value="getRestInterviewees", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** *取出所有面试者,以 形式置于json(可以改为使用isPassed参数有选择的取人, * 但因为目前通过面试方法为删去interviewee故暂为取所有interviewee) */ public String getRestInterviewees(){ Interviewee[] interviewees=intervieweeService.getRestInterviewees(); if(interviewees==null|| interviewees[0] ==null){ addFieldError("getRestInterviewees","已无未面试人员,面试终了!"); return INPUT; } jsonresult.put("interviewees",interviewees); return INPUT; } @Action( value="changePassword", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String changePassword(){ newToken = tokenUtil.tokenCheck(this, session, token); try { /** * 假定struts已经把要修改的新密码放入private String password * 旧密码置入private string oldpassword */ id= ((Person)session.get(loginKey)).getID(); Person person= personService.get(id); oldpassword=person.getPassword(); person.setPassword(password); personService.update(person); System.out.println("修改前的密码:"+oldpassword); System.out.println("修改后的密码:"+password); this.session.clear(); cookieUtil.clearCookie(request,response);//返回值为void,不会给response/ System.out.println("session和cookie均被清除"); } catch (Exception e){ addFieldError("changePassword","密码修改失败!"); } return INPUT; } public void validateChangePassword(){ //此处有从数据库获取旧密码的步骤,用户ID的来源是session //struts能够通过session GET到操作者ID this.id = ((Person)session.get(loginKey)).getID(); Person person = personService.get(id); if(!personService.exist(id))addFieldError("id", "当前用户不存在"); String passwordFD = person.getPassword(); //密码合法性检查 if (oldpassword==null || oldpassword.equals("")){ addFieldError("oldpassword","请输入旧密码!"); } if (password==null || password.equals("")){ addFieldError("password","请键入新密码!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PASSWORD,password)){ addFieldError("password","密码中只允许使用数字、字母和下划线。长度不小于6位,不大于30位。"); } if (!password.equals(repassword)){ addFieldError("repassword","两次输入的密码不一致!"); } } //后台加密并检验密码正确性 password= encoder.encodeSHA512(password.getBytes()); oldpassword= encoder.encodeSHA512(oldpassword.getBytes()); System.out.println("user input:"+oldpassword); System.out.println("DB input :"+passwordFD); if (passwordFD.equals(password)){ addFieldError("password","请键入与旧密码不同的新密码!"); } if (!oldpassword.equals(passwordFD)){ addFieldError("oldpassword","您输入的旧密码不正确!"); } } @Action( value="chooseDept", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String chooseDept(){ newToken = tokenUtil.tokenCheck(this, session, token); Member tommy; tommy=memberService.get(id); tommy.getEnterDepts().add(departmentService.get(dept)); memberService.update(tommy); return INPUT; } public void validateChooseDept(){ id = ((Person)session.get(loginKey)).getID(); if (!departmentService.exist(dept))addFieldError("dept","您要加入的部门不存在"); System.out.println("memberService.exist(id): "+memberService.exist(id)); if (id==null||!memberService.exist(id))addFieldError("id","您不是member类成员!"); else for (Department department:memberService.get(id).getEnterDepts()){ if (department.getDeptID()==dept) addFieldError("dept","您已加入该部门"); } } @Action( value="fetchAllPerson", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String fetchAllPerson(){ /** * 需要注意的问题:部门对部长为多对多关系,可能一个部长下属多个部门 * 这里将下属部门id为int dept的部门所有成员返回 */ if (!departmentService.exist(dept)){ addFieldError("fetchPerson","并没有这个部门!"); return INPUT; } deptMember = departmentService.getInsideMembers(dept); System.out.println("deptMember.toString()"+deptMember.toString()); System.out.println("deptMember.size() "+deptMember.size()); try { jsonresult.put("deptmember",deptMember); if (deptMember.size()==0){ addFieldError("fetchPerson","该部门暂无成员!"); jsonresult.put("hasmember","false"); } return INPUT; } catch (Exception e){ addFieldError("fetchPerson","成员获取失败!"); return INPUT; } } @Action( value="memberUpgrade", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 部员升级为无部门部长 */ public String memberUpgrade(){ memberService.setMemberToMinister(readyMemberId); return INPUT; } public void validateMemberUpgrade(){ if (readyMemberId==null||readyMemberId==""){ addFieldError("readyMemberId","请输入要升级的部员"); } else if (!memberService.exist(readyMemberId)){ addFieldError("readyMemberId","ta并不是member类成员"); } } /** * 将传入interviwee等人升级为部门为dept的member */ public String personUpgrade(){ newToken = tokenUtil.tokenCheck(this, session, token); intervieweeService.setIntervieweesToMembers(readyIntervieweeId); return INPUT; } public void validatePersonUpgrade(){ //要通过人员的id的分割 if (readyIntervieweeIdLine==null) addFieldError("personUpgrade","请输入面试者ID!"); readyIntervieweeId=readyIntervieweeIdLine.split(","); if (readyIntervieweeId==null||readyIntervieweeId[0]==null){ addFieldError("personUpgrade","输入面试者ID格式有误"); } else for (int i=0;i<readyIntervieweeId.length;i++){ if (!intervieweeService.exist(readyIntervieweeId[i])){ addFieldError("personUpgrade","所选成员中有的不是interviewee!"); break; } } } @Action( value="deleteMemberSubmit", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String deleteMemberSubmit(){ newToken = tokenUtil.tokenCheck(this, session, token); try { //在数据库中删除对应人员。因为人员与部门为多对多双向管理,所以这里是用的方法是使用字符串拼接直接删除member memberService.remove(deleted); } catch (Exception e){ addFieldError("deleteMember","删除人员失败!"); } return INPUT; } public void validateDeleteMemberSubmit(){ if (deletedLine==null) addFieldError("deleted","请输入要删除者ID!"); else { deleted = deletedLine.split(","); if (deleted == null | deleted[0] == null) { addFieldError("deleted", "输入删除者ID格式有误"); } else for (String id:deleted){ if (!memberService.exist(id)){ addFieldError("deleted","被删除者有的不为member"); break; } } } } @Action( value="resetPasswordSubmit", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 修改id为needreset的member密码为defaultPassword= "111111" */ public String resetPasswordSubmit(){ newToken = tokenUtil.tokenCheck(this, session, token); try { Member curmember=memberService.get(needreset.trim()); System.out.println("修改前的密码加密:"+curmember.getPassword()); curmember.setPassword(defaultPassword); memberService.update(curmember); System.out.println("重置后的密码加密:"+memberService.get(needreset.trim()).getPassword()); jsonresult.put("resetresult",true); } catch (Exception e){ addFieldError("resetPassword","密码重置失败!"); } return INPUT; } @Action( value="fetchMemberInfo", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 取当前操作者的信息,即((Person)session.get(loginKey)).getID()的id */ public String fetchMemberInfo(){ try { this.id=((Person)session.get(loginKey)).getID(); Member curMember= memberService.get(id); jsonresult.put("curPerson",curMember); return INPUT; } catch (Exception e){ addFieldError("fetchMemberInfo","成员获取失败!"); return INPUT; } } @Action( value="modifyInfo", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 修改Member类型对象并保存 */ public String modifyInfo(){ newToken = tokenUtil.tokenCheck(this, session, token); try { id= ((Person)session.get(loginKey)).getID(); Member member_on; member_on=memberService.get(id); if (member_on==null){ addFieldError("fetchPersonInfo","您的id不存在!"); return INPUT;} member_on.setQQ(QQ); member_on.setGender(gender); member_on.setPhoneNumber(phoneNumber); Calendar calendar=Calendar.getInstance(); calendar.setTime(simpleDateFormat.parse(birthday)); member_on.setBirthday(calendar); personService.update(member_on); System.out.println(member_on); } catch (Exception e){ e.printStackTrace(); addFieldError("fetchPersonInfo","修改用户信息失败!"); } return INPUT; } public void validateModifyInfo(){ if (name==null || name.equals("")) { addFieldError("name", "请输入您的姓名!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.NAME,name)) { addFieldError("name", "请输入正确的姓名信息!"); } } if (phoneNumber==null || phoneNumber.equals("")) { addFieldError("phoneNumber", "请告诉我们您的手机号以方便联系您。"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PHONE_NUMBER,phoneNumber)) { addFieldError("phoneNumber", "请输入有效的大陆手机号码!"); } } if (QQ==null || QQ.equals("")) { addFieldError("QQ", "请告诉我们您的QQ号以方便日后您与社团其他成员的互动。"); } else { if (!registerUtil.isValid(RegisterCheck.Type.QQ,QQ)) { addFieldError("QQ", "您的QQ号输入有误,请检查并重新输入!"); } } //西安交通大学招生简章规定,少年班的入学年龄不得低于14岁 Calendar curtime = Calendar.getInstance(); if (birthday.equals("")) { addFieldError("birthday", "请输入您的生日以便社团成员为您庆祝生日!"); } else { if(!registerUtil.isValid(RegisterCheck.Type.BIRTHDAY,birthday)){ addFieldError("birthday", "您输入的生日已经超越极限啦!您是来逗逼的吧!"); } } return; } @Override public void setSession(Map<String, Object> map) { this.session=map; } public String getReadyMemberId() { return readyMemberId; } public void setReadyMemberId(String readyMemberId) { this.readyMemberId = readyMemberId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public String getDeletedLine() { return deletedLine; } public void setDeletedLine(String deletedLine) { this.deletedLine = deletedLine; } public void setName(String name) { this.name = name; } @JSON(serialize = false) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public int getDept() { return dept; } public void setDept(int dept) { this.dept = dept; } public String getOldpassword() { return oldpassword; } public void setOldpassword(String oldpassword) { this.oldpassword = oldpassword; } @JSON(serialize = false) public String[] getDeleted() { return deleted; } public void setDeleted(String[] deleted) { this.deleted = deleted; } public Map<String, Object> getJsonresult() { return jsonresult; } public void setJsonresult(Map<String, Object> jsonresult) { this.jsonresult = jsonresult; } public String getNeedreset() { return needreset; } public void setNeedreset(String needreset) { this.needreset = needreset; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getQQ() { return QQ; } public void setQQ(String QQ) { this.QQ = QQ; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getReadyIntervieweeIdLine() { return readyIntervieweeIdLine; } public void setReadyIntervieweeIdLine(String readyIntervieweeIdLine) { this.readyIntervieweeIdLine = readyIntervieweeIdLine; } public String[] getReadyIntervieweeId() { return readyIntervieweeId; } public void setReadyIntervieweeId(String[] readyIntervieweeId) { this.readyIntervieweeId = readyIntervieweeId; } @Override public void setServletRequest(HttpServletRequest httpServletRequest) { this.request=httpServletRequest; } @Override public void setServletResponse(HttpServletResponse httpServletResponse) { this.response=httpServletResponse; } }
ruiyuanlu/IBM_CLUB_WEB
src/com/istc/action/PersonalAction.java
6,094
/** * 将传入interviwee等人升级为部门为dept的member */
block_comment
nl
package com.istc.action; import com.istc.Entities.Entity.*; import com.istc.Service.EntityService.*; import com.istc.Validation.*; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.AllowedMethods; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import org.apache.struts2.json.annotations.JSON; import com.istc.Utilities.Encoder; import com.istc.Utilities.TokenUtils; import com.istc.Utilities.CookieUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 用于管理成员信息的增删改查,其中手动增加成员仅可以由部长级以上成员完成 */ @Controller("personnelAction") @Scope("prototype") @ParentPackage("ajax") @AllowedMethods({"addMember","addMinister","changePassword","personUpgrade","chooseDept","fetchAllPerson","getRestInterviewees","deleteMemberSubmit","resetPasswordSubmit","fetchMemberInfo","modifyInfo"}) public class PersonalAction extends ActionSupport implements SessionAware,ServletResponseAware,ServletRequestAware { private HttpServletRequest request; private HttpServletResponse response; //生日字符串模板格式 private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); //会话 private Map<String, Object> session; @Resource(name = "intervieweeService") private IntervieweeService intervieweeService; @Resource(name = "personService") private PersonService personService; @Resource(name = "departmentService") private DepartmentService departmentService; @Resource(name = "memberService") private MemberService memberService; //表单传入值 private String id; private String name; private String oldpassword; private String password; private String repassword; private int dept; private boolean gender; private String birthday; private String QQ; private String phoneNumber; private String token; private String newToken; //部长下属所有部员or部长下属部门id为dept的所有成员 private List<Member> deptMember; //要升级为部员成员id组,字符串 private String readyIntervieweeIdLine; //要升级为部员成员id组,action中分割得到 private String[] readyIntervieweeId; //要升级为部长的部员id private String readyMemberId; private Map<String,Object> jsonresult=new HashMap<String,Object>(); //默认重置密码为111111,用以部长重置部员 public static final String defaultPassword="111111"; private String deletedLine; private String[] deleted; private String needreset; //工具 private TokenUtils tokenUtil; private CookieUtils cookieUtil; private RegisterCheck registerUtil; private Encoder encoder; //定义全局常量 private final String loginKey = "member"; private final String tokenKey = "token"; private final String prePageKey = "prePage"; public PersonalAction(){ tokenUtil = TokenUtils.getInstance(); cookieUtil = CookieUtils.getInstance(); registerUtil = RegisterCheck.getInstance(); encoder = Encoder.getInstance(); } @Action( value="addMember", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * addMember为直接添加部门成员,不是从person转变为member,通过添加含有所属部门的部员来建立关系 */ public String addMember(){ newToken = tokenUtil.tokenCheck(this, session, token); System.out.println(id+" "+password+" "+name+" "+dept); Member p=new Member(); p.setID(id); password= encoder.encodeSHA512(password.getBytes()); p.setPassword(password); p.setName(name); p.setGender(gender); p.setQQ(QQ); p.setPhoneNumber(phoneNumber); Calendar calendar=Calendar.getInstance(); try { calendar.setTime(simpleDateFormat.parse(birthday)); } catch (ParseException e) { e.printStackTrace(); } System.out.println(p.toString()); p.setBirthday(calendar); Department depart0=departmentService.get(dept); p.addDepartment(depart0); memberService.save(p); return INPUT; } public void validateAddMember(){ if (dept==0||!departmentService.exist(dept)){ addFieldError("dept", "不存在该部门!"); } if (id==null || id.equals("")) { addFieldError("id", "请输入学号!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.ID,id)) { addFieldError("id", "学号输入有误,请检查并重新输入。"); } if (personService.exist(id)){ addFieldError("id","该学号仍为preson或member,请删除后添加"); } } if (password==null || password.equals("")) { addFieldError("password", "请设置密码!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PASSWORD,password)) { addFieldError("password", "密码中只允许使用数字、字母和下划线。长度不小于6位,不大于30位。"); } else if (!password.equals(repassword)) { addFieldError("repassword", "两次输入的密码不一致!"); } } if (name==null || name.equals("")) { addFieldError("name", "请输入姓名!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.NAME,name)) { addFieldError("name", "请输入正确的姓名信息!"); } } } @Action( value="getRestInterviewees", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** *取出所有面试者,以 形式置于json(可以改为使用isPassed参数有选择的取人, * 但因为目前通过面试方法为删去interviewee故暂为取所有interviewee) */ public String getRestInterviewees(){ Interviewee[] interviewees=intervieweeService.getRestInterviewees(); if(interviewees==null|| interviewees[0] ==null){ addFieldError("getRestInterviewees","已无未面试人员,面试终了!"); return INPUT; } jsonresult.put("interviewees",interviewees); return INPUT; } @Action( value="changePassword", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String changePassword(){ newToken = tokenUtil.tokenCheck(this, session, token); try { /** * 假定struts已经把要修改的新密码放入private String password * 旧密码置入private string oldpassword */ id= ((Person)session.get(loginKey)).getID(); Person person= personService.get(id); oldpassword=person.getPassword(); person.setPassword(password); personService.update(person); System.out.println("修改前的密码:"+oldpassword); System.out.println("修改后的密码:"+password); this.session.clear(); cookieUtil.clearCookie(request,response);//返回值为void,不会给response/ System.out.println("session和cookie均被清除"); } catch (Exception e){ addFieldError("changePassword","密码修改失败!"); } return INPUT; } public void validateChangePassword(){ //此处有从数据库获取旧密码的步骤,用户ID的来源是session //struts能够通过session GET到操作者ID this.id = ((Person)session.get(loginKey)).getID(); Person person = personService.get(id); if(!personService.exist(id))addFieldError("id", "当前用户不存在"); String passwordFD = person.getPassword(); //密码合法性检查 if (oldpassword==null || oldpassword.equals("")){ addFieldError("oldpassword","请输入旧密码!"); } if (password==null || password.equals("")){ addFieldError("password","请键入新密码!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PASSWORD,password)){ addFieldError("password","密码中只允许使用数字、字母和下划线。长度不小于6位,不大于30位。"); } if (!password.equals(repassword)){ addFieldError("repassword","两次输入的密码不一致!"); } } //后台加密并检验密码正确性 password= encoder.encodeSHA512(password.getBytes()); oldpassword= encoder.encodeSHA512(oldpassword.getBytes()); System.out.println("user input:"+oldpassword); System.out.println("DB input :"+passwordFD); if (passwordFD.equals(password)){ addFieldError("password","请键入与旧密码不同的新密码!"); } if (!oldpassword.equals(passwordFD)){ addFieldError("oldpassword","您输入的旧密码不正确!"); } } @Action( value="chooseDept", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String chooseDept(){ newToken = tokenUtil.tokenCheck(this, session, token); Member tommy; tommy=memberService.get(id); tommy.getEnterDepts().add(departmentService.get(dept)); memberService.update(tommy); return INPUT; } public void validateChooseDept(){ id = ((Person)session.get(loginKey)).getID(); if (!departmentService.exist(dept))addFieldError("dept","您要加入的部门不存在"); System.out.println("memberService.exist(id): "+memberService.exist(id)); if (id==null||!memberService.exist(id))addFieldError("id","您不是member类成员!"); else for (Department department:memberService.get(id).getEnterDepts()){ if (department.getDeptID()==dept) addFieldError("dept","您已加入该部门"); } } @Action( value="fetchAllPerson", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String fetchAllPerson(){ /** * 需要注意的问题:部门对部长为多对多关系,可能一个部长下属多个部门 * 这里将下属部门id为int dept的部门所有成员返回 */ if (!departmentService.exist(dept)){ addFieldError("fetchPerson","并没有这个部门!"); return INPUT; } deptMember = departmentService.getInsideMembers(dept); System.out.println("deptMember.toString()"+deptMember.toString()); System.out.println("deptMember.size() "+deptMember.size()); try { jsonresult.put("deptmember",deptMember); if (deptMember.size()==0){ addFieldError("fetchPerson","该部门暂无成员!"); jsonresult.put("hasmember","false"); } return INPUT; } catch (Exception e){ addFieldError("fetchPerson","成员获取失败!"); return INPUT; } } @Action( value="memberUpgrade", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 部员升级为无部门部长 */ public String memberUpgrade(){ memberService.setMemberToMinister(readyMemberId); return INPUT; } public void validateMemberUpgrade(){ if (readyMemberId==null||readyMemberId==""){ addFieldError("readyMemberId","请输入要升级的部员"); } else if (!memberService.exist(readyMemberId)){ addFieldError("readyMemberId","ta并不是member类成员"); } } /** * 将传入interviwee等人升级为部门为dept的member <SUF>*/ public String personUpgrade(){ newToken = tokenUtil.tokenCheck(this, session, token); intervieweeService.setIntervieweesToMembers(readyIntervieweeId); return INPUT; } public void validatePersonUpgrade(){ //要通过人员的id的分割 if (readyIntervieweeIdLine==null) addFieldError("personUpgrade","请输入面试者ID!"); readyIntervieweeId=readyIntervieweeIdLine.split(","); if (readyIntervieweeId==null||readyIntervieweeId[0]==null){ addFieldError("personUpgrade","输入面试者ID格式有误"); } else for (int i=0;i<readyIntervieweeId.length;i++){ if (!intervieweeService.exist(readyIntervieweeId[i])){ addFieldError("personUpgrade","所选成员中有的不是interviewee!"); break; } } } @Action( value="deleteMemberSubmit", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) public String deleteMemberSubmit(){ newToken = tokenUtil.tokenCheck(this, session, token); try { //在数据库中删除对应人员。因为人员与部门为多对多双向管理,所以这里是用的方法是使用字符串拼接直接删除member memberService.remove(deleted); } catch (Exception e){ addFieldError("deleteMember","删除人员失败!"); } return INPUT; } public void validateDeleteMemberSubmit(){ if (deletedLine==null) addFieldError("deleted","请输入要删除者ID!"); else { deleted = deletedLine.split(","); if (deleted == null | deleted[0] == null) { addFieldError("deleted", "输入删除者ID格式有误"); } else for (String id:deleted){ if (!memberService.exist(id)){ addFieldError("deleted","被删除者有的不为member"); break; } } } } @Action( value="resetPasswordSubmit", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 修改id为needreset的member密码为defaultPassword= "111111" */ public String resetPasswordSubmit(){ newToken = tokenUtil.tokenCheck(this, session, token); try { Member curmember=memberService.get(needreset.trim()); System.out.println("修改前的密码加密:"+curmember.getPassword()); curmember.setPassword(defaultPassword); memberService.update(curmember); System.out.println("重置后的密码加密:"+memberService.get(needreset.trim()).getPassword()); jsonresult.put("resetresult",true); } catch (Exception e){ addFieldError("resetPassword","密码重置失败!"); } return INPUT; } @Action( value="fetchMemberInfo", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 取当前操作者的信息,即((Person)session.get(loginKey)).getID()的id */ public String fetchMemberInfo(){ try { this.id=((Person)session.get(loginKey)).getID(); Member curMember= memberService.get(id); jsonresult.put("curPerson",curMember); return INPUT; } catch (Exception e){ addFieldError("fetchMemberInfo","成员获取失败!"); return INPUT; } } @Action( value="modifyInfo", results={ @Result(name="input", type="json", params={"ignoreHierarchy", "false"}), } ) /** * 修改Member类型对象并保存 */ public String modifyInfo(){ newToken = tokenUtil.tokenCheck(this, session, token); try { id= ((Person)session.get(loginKey)).getID(); Member member_on; member_on=memberService.get(id); if (member_on==null){ addFieldError("fetchPersonInfo","您的id不存在!"); return INPUT;} member_on.setQQ(QQ); member_on.setGender(gender); member_on.setPhoneNumber(phoneNumber); Calendar calendar=Calendar.getInstance(); calendar.setTime(simpleDateFormat.parse(birthday)); member_on.setBirthday(calendar); personService.update(member_on); System.out.println(member_on); } catch (Exception e){ e.printStackTrace(); addFieldError("fetchPersonInfo","修改用户信息失败!"); } return INPUT; } public void validateModifyInfo(){ if (name==null || name.equals("")) { addFieldError("name", "请输入您的姓名!"); } else { if (!registerUtil.isValid(RegisterCheck.Type.NAME,name)) { addFieldError("name", "请输入正确的姓名信息!"); } } if (phoneNumber==null || phoneNumber.equals("")) { addFieldError("phoneNumber", "请告诉我们您的手机号以方便联系您。"); } else { if (!registerUtil.isValid(RegisterCheck.Type.PHONE_NUMBER,phoneNumber)) { addFieldError("phoneNumber", "请输入有效的大陆手机号码!"); } } if (QQ==null || QQ.equals("")) { addFieldError("QQ", "请告诉我们您的QQ号以方便日后您与社团其他成员的互动。"); } else { if (!registerUtil.isValid(RegisterCheck.Type.QQ,QQ)) { addFieldError("QQ", "您的QQ号输入有误,请检查并重新输入!"); } } //西安交通大学招生简章规定,少年班的入学年龄不得低于14岁 Calendar curtime = Calendar.getInstance(); if (birthday.equals("")) { addFieldError("birthday", "请输入您的生日以便社团成员为您庆祝生日!"); } else { if(!registerUtil.isValid(RegisterCheck.Type.BIRTHDAY,birthday)){ addFieldError("birthday", "您输入的生日已经超越极限啦!您是来逗逼的吧!"); } } return; } @Override public void setSession(Map<String, Object> map) { this.session=map; } public String getReadyMemberId() { return readyMemberId; } public void setReadyMemberId(String readyMemberId) { this.readyMemberId = readyMemberId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public String getDeletedLine() { return deletedLine; } public void setDeletedLine(String deletedLine) { this.deletedLine = deletedLine; } public void setName(String name) { this.name = name; } @JSON(serialize = false) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public int getDept() { return dept; } public void setDept(int dept) { this.dept = dept; } public String getOldpassword() { return oldpassword; } public void setOldpassword(String oldpassword) { this.oldpassword = oldpassword; } @JSON(serialize = false) public String[] getDeleted() { return deleted; } public void setDeleted(String[] deleted) { this.deleted = deleted; } public Map<String, Object> getJsonresult() { return jsonresult; } public void setJsonresult(Map<String, Object> jsonresult) { this.jsonresult = jsonresult; } public String getNeedreset() { return needreset; } public void setNeedreset(String needreset) { this.needreset = needreset; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getQQ() { return QQ; } public void setQQ(String QQ) { this.QQ = QQ; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getReadyIntervieweeIdLine() { return readyIntervieweeIdLine; } public void setReadyIntervieweeIdLine(String readyIntervieweeIdLine) { this.readyIntervieweeIdLine = readyIntervieweeIdLine; } public String[] getReadyIntervieweeId() { return readyIntervieweeId; } public void setReadyIntervieweeId(String[] readyIntervieweeId) { this.readyIntervieweeId = readyIntervieweeId; } @Override public void setServletRequest(HttpServletRequest httpServletRequest) { this.request=httpServletRequest; } @Override public void setServletResponse(HttpServletResponse httpServletResponse) { this.response=httpServletResponse; } }
125416_18
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This class is a copy of SSHExec from Ant 1.8.1 sources to support RUNDECK specific * requirements (e.g., log verbosity). * * * @author Alex Honor <a href="mailto:[email protected]">[email protected]</a> * @version $Revision$ */ package org.rundeck.plugins.jsch.net; import com.dtolabs.rundeck.core.utils.SSHAgentProcess; import com.dtolabs.rundeck.plugins.PluginLogger; import com.jcraft.jsch.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.optional.ssh.SSHBase; import org.apache.tools.ant.taskdefs.optional.ssh.SSHUserInfo; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.KeepAliveOutputStream; import org.apache.tools.ant.util.TeeOutputStream; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Executes a command on a remote machine via ssh. * @since Ant 1.6 (created February 2, 2003) */ public class ExtSSHExec extends SSHBase implements SSHTaskBuilder.SSHExecInterface { private static final int BUFFER_SIZE = 8192; private static final int RETRY_INTERVAL = 500; /** the command to execute via ssh */ private String command = null; /** units are milliseconds, default is 0=infinite */ private long maxwait = 0; private long connectTimeout = 0; private long commandTimeout = 0; /** for waiting for the command to finish */ private Thread thread = null; private String outputProperty = null; // like <exec> private File outputFile = null; // like <exec> private String inputProperty = null; // like <exec> private File inputFile = null; // like <exec> private boolean append = false; // like <exec> private InputStream inputStream=null; private OutputStream secondaryStream=null; private DisconnectHolder disconnectHolder=null; private PluginLogger logger; private Resource commandResource = null; private List<Environment.Variable> envVars=null; private Boolean enableSSHAgent=false; private Integer ttlSSHAgent=0; private SSHAgentProcess sshAgentProcess=null; private String bindAddress; public static final String COMMAND_TIMEOUT_MESSAGE = "Timeout period exceeded, connection dropped."; public static final String CON_TIMEOUT_MESSAGE = "Connection timeout."; /** * Constructor for SSHExecTask. */ public ExtSSHExec() { super(); } /** * Sets the command to execute on the remote host. * * @param command The new command value */ public void setCommand(String command) { this.command = command; } /** * Sets a commandResource from a file * @param f the value to use. * @since Ant 1.7.1 */ public void setCommandResource(String f) { this.commandResource = new FileResource(new File(f)); } /** * The connection can be dropped after a specified number of * milliseconds. This is sometimes useful when a connection may be * flaky. Default is 0, which means &quot;wait forever&quot;. * * @param timeout The new timeout value in seconds */ public void setTimeout(long timeout) { maxwait = timeout; } public long getTimeout(){ return maxwait; } @Override public void setConnectTimeout(final long sshTimeout) { connectTimeout = sshTimeout; } @Override public long getConnectTimeout() { return connectTimeout; } @Override public void setCommandTimeout(final long sshTimeout) { commandTimeout = sshTimeout; } @Override public long getCommandTimeout() { return commandTimeout; } /** * If used, stores the output of the command to the given file. * * @param output The file to write to. */ public void setOutput(File output) { outputFile = output; } /** * If used, the content of the file is piped to the remote command * * @param input The file which provides the input data for the remote command */ public void setInput(File input) { inputFile = input; } /** * If used, the content of the property is piped to the remote command * * @param inputProperty The property which contains the input data for the remote command. */ public void setInputProperty(String inputProperty) { this.inputProperty = inputProperty; } /** * Determines if the output is appended to the file given in * <code>setOutput</code>. Default is false, that is, overwrite * the file. * * @param append True to append to an existing file, false to overwrite. */ public void setAppend(boolean append) { this.append = append; } /** * If set, the output of the command will be stored in the given property. * * @param property The name of the property in which the command output * will be stored. */ public void setOutputproperty(String property) { outputProperty = property; } private boolean allocatePty = false; private boolean passEnvVar = false; /** * Allocate a Pseudo-Terminal. * If set true, the SSH connection will be setup to run over an allocated pty. * @param b if true, allocate the pty. (default false */ public void setAllocatePty(boolean b) { allocatePty = b; } /** * Pass ENV_ rundeck variables. */ public void passEnvVar(boolean b) { passEnvVar = b; } private int exitStatus =-1; /** * @return exitStatus of the remote execution, after it has finished or failed. * The return value prior to retrieving the result will be -1. If that value is returned * after the task has executed, it indicates that an exception was thrown prior to retrieval * of the value. * */ public int getExitStatus(){ return exitStatus; } /** * Add an Env element * @param env element */ public void addEnv(final Environment.Variable env){ if(null==envVars) { envVars = new ArrayList<Environment.Variable>(); } envVars.add(env); } /** * @return the disconnectHolder */ public DisconnectHolder getDisconnectHolder() { return disconnectHolder; } /** * Set a disconnectHolder * @param disconnectHolder holder */ public void setDisconnectHolder(final DisconnectHolder disconnectHolder) { this.disconnectHolder = disconnectHolder; } public PluginLogger getPluginLogger() { return logger; } public void setPluginLogger(PluginLogger logger) { this.logger = logger; } public int getAntLogLevel() { return antLogLevel; } public void setAntLogLevel(int antLogLevel) { this.antLogLevel = antLogLevel; } public Map<String, String> getSshConfigSession() { return sshConfig; } public InputStream getSshKeyData() { return sshKeyData; } public SSHAgentProcess getSSHAgentProcess() { return this.sshAgentProcess; } public void setSSHAgentProcess(SSHAgentProcess sshAgentProcess) { this.sshAgentProcess = sshAgentProcess; } /** * Allows disconnecting the ssh connection */ public static interface Disconnectable{ /** * Disconnect */ public void disconnect(); } /** * Interface for receiving access to Disconnectable */ public static interface DisconnectHolder{ /** * Set disconnectable * @param disconnectable disconnectable */ public void setDisconnectable(Disconnectable disconnectable); } /** * Execute the command on the remote host. * * @exception BuildException Most likely a network error or bad parameter. */ public void execute() throws BuildException { if (getHost() == null) { throw new BuildException("Host is required."); } if (getUserInfo().getName() == null) { throw new BuildException("Username is required."); } if (getUserInfo().getKeyfile() == null && getUserInfo().getPassword() == null && getSshKeyData() == null) { throw new BuildException("Password or Keyfile is required."); } if (command == null && commandResource == null) { throw new BuildException("Command or commandResource is required."); } if (inputFile != null && inputProperty != null) { throw new BuildException("You can't specify both inputFile and" + " inputProperty."); } if (inputFile != null && !inputFile.exists()) { throw new BuildException("The input file " + inputFile.getAbsolutePath() + " does not exist."); } Session session = null; StringBuffer output = new StringBuffer(); try { session = openSession(); if(null!=getDisconnectHolder()){ final Session sub=session; getDisconnectHolder().setDisconnectable(new Disconnectable() { public void disconnect() { sub.disconnect(); } }); } /* called once */ if (command != null) { executeCommand(session, command, output); } else { // read command resource and execute for each command try { BufferedReader br = new BufferedReader( new InputStreamReader(commandResource.getInputStream())); String cmd; while ((cmd = br.readLine()) != null) { executeCommand(session, cmd, output); output.append("\n"); } FileUtils.close(br); } catch (IOException e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } } } catch (JSchException e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } finally { try { if (null != this.sshAgentProcess) { this.sshAgentProcess.stopAgent(); } } catch (IOException e) { log( "Caught exception: " + e.getMessage(), Project.MSG_ERR); } if (outputProperty != null) { getProject().setNewProperty(outputProperty, output.toString()); } if (session != null && session.isConnected()) { session.disconnect(); } } } private void executeCommand(Session session, String cmd, StringBuffer sb) throws BuildException { final ByteArrayOutputStream out ; final OutputStream tee; final OutputStream teeout; if(null!=outputFile || null!=outputProperty){ out = new ByteArrayOutputStream(); }else{ out=null; } if(null!=getSecondaryStream() && null!=out) { teeout= new TeeOutputStream(out, getSecondaryStream()); } else if(null!= getSecondaryStream()){ teeout= getSecondaryStream(); }else if(null!=out){ teeout=out; }else{ teeout=null; } if(null!=teeout){ tee = new TeeOutputStream(teeout, new KeepAliveOutputStream(System.out)); }else{ tee= new KeepAliveOutputStream(System.out); } InputStream istream = null ; if (inputFile != null) { try { istream = new FileInputStream(inputFile) ; } catch (IOException e) { // because we checked the existence before, this one // shouldn't happen What if the file exists, but there // are no read permissions? log("Failed to read " + inputFile + " because of: " + e.getMessage(), Project.MSG_WARN); } } if (inputProperty != null) { String inputData = getProject().getProperty(inputProperty) ; if (inputData != null) { istream = new ByteArrayInputStream(inputData.getBytes()) ; } } if(getInputStream()!=null){ istream=getInputStream(); } long sshConTimeout = connectTimeout > 0 ? connectTimeout : maxwait; try { final ChannelExec channel; session.setTimeout((int) sshConTimeout); /* execute the command */ channel = (ChannelExec) session.openChannel("exec"); if(null != this.sshAgentProcess){ channel.setAgentForwarding(true); } channel.setCommand(cmd); channel.setOutputStream(tee); channel.setExtOutputStream(new KeepAliveOutputStream(System.err), true); if (istream != null) { channel.setInputStream(istream); } channel.setPty(allocatePty); /* set env vars if any are embedded */ if(null!=envVars && envVars.size()>0 && passEnvVar){ for(final Environment.Variable env:envVars) { channel.setEnv(env.getKey(), env.getValue()); } } //since jsch doesnt accept infinite in connection timeout we use a week of timeout instead of 0 int jschConTimeout = sshConTimeout>0?(int)sshConTimeout:604800000; channel.connect(jschConTimeout); // wait for it to finish thread = new Thread() { public void run() { while (!channel.isClosed()) { if (thread == null) { return; } try { sleep(RETRY_INTERVAL); } catch (Exception e) { // ignored } } } }; thread.start(); thread.join(commandTimeout); if (thread.isAlive()) { // ran out of time thread = null; if (getFailonerror()) { throw new BuildException(COMMAND_TIMEOUT_MESSAGE); } else { log(COMMAND_TIMEOUT_MESSAGE, Project.MSG_ERR); } } else { //success if (outputFile != null && null != out) { writeToFile(out.toString(), append, outputFile); } // this is the wrong test if the remote OS is OpenVMS, // but there doesn't seem to be a way to detect it. exitStatus = channel.getExitStatus(); int ec = channel.getExitStatus(); if (ec != 0) { String msg = "Remote command failed with exit status " + ec; if (getFailonerror()) { throw new BuildException(msg); } else { log(msg, Project.MSG_ERR); } } } } catch (BuildException e) { throw e; } catch (JSchException e) { if (e.getMessage().contains("session is down")) { if (getFailonerror()) { throw new BuildException(CON_TIMEOUT_MESSAGE, e); } else { log(CON_TIMEOUT_MESSAGE, Project.MSG_ERR); } } else { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } } catch (Exception e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } finally { if(null!=out){ sb.append(out.toString()); } FileUtils.close(istream); } } /** * Writes a string to a file. If destination file exists, it may be * overwritten depending on the "append" value. * * @param from string to write * @param to file to write to * @param append if true, append to existing file, else overwrite * @exception IOException on io error */ private void writeToFile(String from, boolean append, File to) throws IOException { FileWriter out = null; try { out = new FileWriter(to.getAbsolutePath(), append); StringReader in = new StringReader(from); char[] buffer = new char[BUFFER_SIZE]; int bytesRead; while (true) { bytesRead = in.read(buffer); if (bytesRead == -1) { break; } out.write(buffer, 0, bytesRead); } out.flush(); } finally { if (out != null) { out.close(); } } } private String knownHosts; private InputStream sshKeyData; @Override public void setSshKeyData(InputStream sshKeyData) { this.sshKeyData=sshKeyData; } /** * Sets the path to the file that has the identities of * all known hosts. This is used by SSH protocol to validate * the identity of the host. The default is * <i>${user.home}/.ssh/known_hosts</i>. * * @param knownHosts a path to the known hosts file. */ public void setKnownhosts(String knownHosts) { this.knownHosts = knownHosts; super.setKnownhosts(knownHosts); } private Map<String,String> sshConfig; @Override public void setSshConfigSession(Map<String, String> config) { this.sshConfig=config; } /** * Open an ssh seession. * * Copied from SSHBase 1.8.1 * @return the opened session * @throws JSchException on error */ protected Session openSession() throws JSchException { return SSHTaskBuilder.openSession(this); } private int antLogLevel=Project.MSG_INFO; public InputStream getInputStream() { return inputStream; } /** * Set an inputstream for pty input to the session * @param inputStream stream */ public void setInputStream(final InputStream inputStream) { this.inputStream = inputStream; } public OutputStream getSecondaryStream() { return secondaryStream; } /** * Set a secondary outputstream to read from the connection * @param secondaryStream secondary stream */ public void setSecondaryStream(final OutputStream secondaryStream) { this.secondaryStream = secondaryStream; } @Override public String getKeyfile() { return getUserInfo().getKeyfile(); } @Override public String getKnownhosts() { return knownHosts; } public SSHUserInfo getUserInfo(){ return super.getUserInfo(); } @Override public void setEnableSSHAgent(Boolean enableSSHAgent) { this.enableSSHAgent = enableSSHAgent; } @Override public Boolean getEnableSSHAgent() { return this.enableSSHAgent; } @Override public void setTtlSSHAgent(Integer ttlSSHAgent) { this.ttlSSHAgent = ttlSSHAgent; } @Override public Integer getTtlSSHAgent() { return this.ttlSSHAgent; } @Override public void setBindAddress(String bindAddress) { this.bindAddress=bindAddress; } @Override public String getBindAddress() { return bindAddress; } }
rundeck/rundeck
plugins/jsch-plugin/src/main/java/org/rundeck/plugins/jsch/net/ExtSSHExec.java
5,663
/** * Add an Env element * @param env element */
block_comment
nl
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This class is a copy of SSHExec from Ant 1.8.1 sources to support RUNDECK specific * requirements (e.g., log verbosity). * * * @author Alex Honor <a href="mailto:[email protected]">[email protected]</a> * @version $Revision$ */ package org.rundeck.plugins.jsch.net; import com.dtolabs.rundeck.core.utils.SSHAgentProcess; import com.dtolabs.rundeck.plugins.PluginLogger; import com.jcraft.jsch.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.optional.ssh.SSHBase; import org.apache.tools.ant.taskdefs.optional.ssh.SSHUserInfo; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.KeepAliveOutputStream; import org.apache.tools.ant.util.TeeOutputStream; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Executes a command on a remote machine via ssh. * @since Ant 1.6 (created February 2, 2003) */ public class ExtSSHExec extends SSHBase implements SSHTaskBuilder.SSHExecInterface { private static final int BUFFER_SIZE = 8192; private static final int RETRY_INTERVAL = 500; /** the command to execute via ssh */ private String command = null; /** units are milliseconds, default is 0=infinite */ private long maxwait = 0; private long connectTimeout = 0; private long commandTimeout = 0; /** for waiting for the command to finish */ private Thread thread = null; private String outputProperty = null; // like <exec> private File outputFile = null; // like <exec> private String inputProperty = null; // like <exec> private File inputFile = null; // like <exec> private boolean append = false; // like <exec> private InputStream inputStream=null; private OutputStream secondaryStream=null; private DisconnectHolder disconnectHolder=null; private PluginLogger logger; private Resource commandResource = null; private List<Environment.Variable> envVars=null; private Boolean enableSSHAgent=false; private Integer ttlSSHAgent=0; private SSHAgentProcess sshAgentProcess=null; private String bindAddress; public static final String COMMAND_TIMEOUT_MESSAGE = "Timeout period exceeded, connection dropped."; public static final String CON_TIMEOUT_MESSAGE = "Connection timeout."; /** * Constructor for SSHExecTask. */ public ExtSSHExec() { super(); } /** * Sets the command to execute on the remote host. * * @param command The new command value */ public void setCommand(String command) { this.command = command; } /** * Sets a commandResource from a file * @param f the value to use. * @since Ant 1.7.1 */ public void setCommandResource(String f) { this.commandResource = new FileResource(new File(f)); } /** * The connection can be dropped after a specified number of * milliseconds. This is sometimes useful when a connection may be * flaky. Default is 0, which means &quot;wait forever&quot;. * * @param timeout The new timeout value in seconds */ public void setTimeout(long timeout) { maxwait = timeout; } public long getTimeout(){ return maxwait; } @Override public void setConnectTimeout(final long sshTimeout) { connectTimeout = sshTimeout; } @Override public long getConnectTimeout() { return connectTimeout; } @Override public void setCommandTimeout(final long sshTimeout) { commandTimeout = sshTimeout; } @Override public long getCommandTimeout() { return commandTimeout; } /** * If used, stores the output of the command to the given file. * * @param output The file to write to. */ public void setOutput(File output) { outputFile = output; } /** * If used, the content of the file is piped to the remote command * * @param input The file which provides the input data for the remote command */ public void setInput(File input) { inputFile = input; } /** * If used, the content of the property is piped to the remote command * * @param inputProperty The property which contains the input data for the remote command. */ public void setInputProperty(String inputProperty) { this.inputProperty = inputProperty; } /** * Determines if the output is appended to the file given in * <code>setOutput</code>. Default is false, that is, overwrite * the file. * * @param append True to append to an existing file, false to overwrite. */ public void setAppend(boolean append) { this.append = append; } /** * If set, the output of the command will be stored in the given property. * * @param property The name of the property in which the command output * will be stored. */ public void setOutputproperty(String property) { outputProperty = property; } private boolean allocatePty = false; private boolean passEnvVar = false; /** * Allocate a Pseudo-Terminal. * If set true, the SSH connection will be setup to run over an allocated pty. * @param b if true, allocate the pty. (default false */ public void setAllocatePty(boolean b) { allocatePty = b; } /** * Pass ENV_ rundeck variables. */ public void passEnvVar(boolean b) { passEnvVar = b; } private int exitStatus =-1; /** * @return exitStatus of the remote execution, after it has finished or failed. * The return value prior to retrieving the result will be -1. If that value is returned * after the task has executed, it indicates that an exception was thrown prior to retrieval * of the value. * */ public int getExitStatus(){ return exitStatus; } /** * Add an Env<SUF>*/ public void addEnv(final Environment.Variable env){ if(null==envVars) { envVars = new ArrayList<Environment.Variable>(); } envVars.add(env); } /** * @return the disconnectHolder */ public DisconnectHolder getDisconnectHolder() { return disconnectHolder; } /** * Set a disconnectHolder * @param disconnectHolder holder */ public void setDisconnectHolder(final DisconnectHolder disconnectHolder) { this.disconnectHolder = disconnectHolder; } public PluginLogger getPluginLogger() { return logger; } public void setPluginLogger(PluginLogger logger) { this.logger = logger; } public int getAntLogLevel() { return antLogLevel; } public void setAntLogLevel(int antLogLevel) { this.antLogLevel = antLogLevel; } public Map<String, String> getSshConfigSession() { return sshConfig; } public InputStream getSshKeyData() { return sshKeyData; } public SSHAgentProcess getSSHAgentProcess() { return this.sshAgentProcess; } public void setSSHAgentProcess(SSHAgentProcess sshAgentProcess) { this.sshAgentProcess = sshAgentProcess; } /** * Allows disconnecting the ssh connection */ public static interface Disconnectable{ /** * Disconnect */ public void disconnect(); } /** * Interface for receiving access to Disconnectable */ public static interface DisconnectHolder{ /** * Set disconnectable * @param disconnectable disconnectable */ public void setDisconnectable(Disconnectable disconnectable); } /** * Execute the command on the remote host. * * @exception BuildException Most likely a network error or bad parameter. */ public void execute() throws BuildException { if (getHost() == null) { throw new BuildException("Host is required."); } if (getUserInfo().getName() == null) { throw new BuildException("Username is required."); } if (getUserInfo().getKeyfile() == null && getUserInfo().getPassword() == null && getSshKeyData() == null) { throw new BuildException("Password or Keyfile is required."); } if (command == null && commandResource == null) { throw new BuildException("Command or commandResource is required."); } if (inputFile != null && inputProperty != null) { throw new BuildException("You can't specify both inputFile and" + " inputProperty."); } if (inputFile != null && !inputFile.exists()) { throw new BuildException("The input file " + inputFile.getAbsolutePath() + " does not exist."); } Session session = null; StringBuffer output = new StringBuffer(); try { session = openSession(); if(null!=getDisconnectHolder()){ final Session sub=session; getDisconnectHolder().setDisconnectable(new Disconnectable() { public void disconnect() { sub.disconnect(); } }); } /* called once */ if (command != null) { executeCommand(session, command, output); } else { // read command resource and execute for each command try { BufferedReader br = new BufferedReader( new InputStreamReader(commandResource.getInputStream())); String cmd; while ((cmd = br.readLine()) != null) { executeCommand(session, cmd, output); output.append("\n"); } FileUtils.close(br); } catch (IOException e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } } } catch (JSchException e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } finally { try { if (null != this.sshAgentProcess) { this.sshAgentProcess.stopAgent(); } } catch (IOException e) { log( "Caught exception: " + e.getMessage(), Project.MSG_ERR); } if (outputProperty != null) { getProject().setNewProperty(outputProperty, output.toString()); } if (session != null && session.isConnected()) { session.disconnect(); } } } private void executeCommand(Session session, String cmd, StringBuffer sb) throws BuildException { final ByteArrayOutputStream out ; final OutputStream tee; final OutputStream teeout; if(null!=outputFile || null!=outputProperty){ out = new ByteArrayOutputStream(); }else{ out=null; } if(null!=getSecondaryStream() && null!=out) { teeout= new TeeOutputStream(out, getSecondaryStream()); } else if(null!= getSecondaryStream()){ teeout= getSecondaryStream(); }else if(null!=out){ teeout=out; }else{ teeout=null; } if(null!=teeout){ tee = new TeeOutputStream(teeout, new KeepAliveOutputStream(System.out)); }else{ tee= new KeepAliveOutputStream(System.out); } InputStream istream = null ; if (inputFile != null) { try { istream = new FileInputStream(inputFile) ; } catch (IOException e) { // because we checked the existence before, this one // shouldn't happen What if the file exists, but there // are no read permissions? log("Failed to read " + inputFile + " because of: " + e.getMessage(), Project.MSG_WARN); } } if (inputProperty != null) { String inputData = getProject().getProperty(inputProperty) ; if (inputData != null) { istream = new ByteArrayInputStream(inputData.getBytes()) ; } } if(getInputStream()!=null){ istream=getInputStream(); } long sshConTimeout = connectTimeout > 0 ? connectTimeout : maxwait; try { final ChannelExec channel; session.setTimeout((int) sshConTimeout); /* execute the command */ channel = (ChannelExec) session.openChannel("exec"); if(null != this.sshAgentProcess){ channel.setAgentForwarding(true); } channel.setCommand(cmd); channel.setOutputStream(tee); channel.setExtOutputStream(new KeepAliveOutputStream(System.err), true); if (istream != null) { channel.setInputStream(istream); } channel.setPty(allocatePty); /* set env vars if any are embedded */ if(null!=envVars && envVars.size()>0 && passEnvVar){ for(final Environment.Variable env:envVars) { channel.setEnv(env.getKey(), env.getValue()); } } //since jsch doesnt accept infinite in connection timeout we use a week of timeout instead of 0 int jschConTimeout = sshConTimeout>0?(int)sshConTimeout:604800000; channel.connect(jschConTimeout); // wait for it to finish thread = new Thread() { public void run() { while (!channel.isClosed()) { if (thread == null) { return; } try { sleep(RETRY_INTERVAL); } catch (Exception e) { // ignored } } } }; thread.start(); thread.join(commandTimeout); if (thread.isAlive()) { // ran out of time thread = null; if (getFailonerror()) { throw new BuildException(COMMAND_TIMEOUT_MESSAGE); } else { log(COMMAND_TIMEOUT_MESSAGE, Project.MSG_ERR); } } else { //success if (outputFile != null && null != out) { writeToFile(out.toString(), append, outputFile); } // this is the wrong test if the remote OS is OpenVMS, // but there doesn't seem to be a way to detect it. exitStatus = channel.getExitStatus(); int ec = channel.getExitStatus(); if (ec != 0) { String msg = "Remote command failed with exit status " + ec; if (getFailonerror()) { throw new BuildException(msg); } else { log(msg, Project.MSG_ERR); } } } } catch (BuildException e) { throw e; } catch (JSchException e) { if (e.getMessage().contains("session is down")) { if (getFailonerror()) { throw new BuildException(CON_TIMEOUT_MESSAGE, e); } else { log(CON_TIMEOUT_MESSAGE, Project.MSG_ERR); } } else { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } } catch (Exception e) { if (getFailonerror()) { throw new BuildException(e); } else { log("Caught exception: " + e.getMessage(), Project.MSG_ERR); } } finally { if(null!=out){ sb.append(out.toString()); } FileUtils.close(istream); } } /** * Writes a string to a file. If destination file exists, it may be * overwritten depending on the "append" value. * * @param from string to write * @param to file to write to * @param append if true, append to existing file, else overwrite * @exception IOException on io error */ private void writeToFile(String from, boolean append, File to) throws IOException { FileWriter out = null; try { out = new FileWriter(to.getAbsolutePath(), append); StringReader in = new StringReader(from); char[] buffer = new char[BUFFER_SIZE]; int bytesRead; while (true) { bytesRead = in.read(buffer); if (bytesRead == -1) { break; } out.write(buffer, 0, bytesRead); } out.flush(); } finally { if (out != null) { out.close(); } } } private String knownHosts; private InputStream sshKeyData; @Override public void setSshKeyData(InputStream sshKeyData) { this.sshKeyData=sshKeyData; } /** * Sets the path to the file that has the identities of * all known hosts. This is used by SSH protocol to validate * the identity of the host. The default is * <i>${user.home}/.ssh/known_hosts</i>. * * @param knownHosts a path to the known hosts file. */ public void setKnownhosts(String knownHosts) { this.knownHosts = knownHosts; super.setKnownhosts(knownHosts); } private Map<String,String> sshConfig; @Override public void setSshConfigSession(Map<String, String> config) { this.sshConfig=config; } /** * Open an ssh seession. * * Copied from SSHBase 1.8.1 * @return the opened session * @throws JSchException on error */ protected Session openSession() throws JSchException { return SSHTaskBuilder.openSession(this); } private int antLogLevel=Project.MSG_INFO; public InputStream getInputStream() { return inputStream; } /** * Set an inputstream for pty input to the session * @param inputStream stream */ public void setInputStream(final InputStream inputStream) { this.inputStream = inputStream; } public OutputStream getSecondaryStream() { return secondaryStream; } /** * Set a secondary outputstream to read from the connection * @param secondaryStream secondary stream */ public void setSecondaryStream(final OutputStream secondaryStream) { this.secondaryStream = secondaryStream; } @Override public String getKeyfile() { return getUserInfo().getKeyfile(); } @Override public String getKnownhosts() { return knownHosts; } public SSHUserInfo getUserInfo(){ return super.getUserInfo(); } @Override public void setEnableSSHAgent(Boolean enableSSHAgent) { this.enableSSHAgent = enableSSHAgent; } @Override public Boolean getEnableSSHAgent() { return this.enableSSHAgent; } @Override public void setTtlSSHAgent(Integer ttlSSHAgent) { this.ttlSSHAgent = ttlSSHAgent; } @Override public Integer getTtlSSHAgent() { return this.ttlSSHAgent; } @Override public void setBindAddress(String bindAddress) { this.bindAddress=bindAddress; } @Override public String getBindAddress() { return bindAddress; } }
11404_14
/* * Copyright (c) 2016-2017, Abel Briggs * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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. */ package net.runelite.api; /** * Utility class used for mapping animation IDs. * <p> * Note: This class is not complete and may not contain a specific animation * required. */ public final class AnimationID { public static final int IDLE = -1; public static final int HERBLORE_PESTLE_AND_MORTAR = 364; public static final int WOODCUTTING_BRONZE = 879; public static final int WOODCUTTING_IRON = 877; public static final int WOODCUTTING_STEEL = 875; public static final int WOODCUTTING_BLACK = 873; public static final int WOODCUTTING_MITHRIL = 871; public static final int WOODCUTTING_ADAMANT = 869; public static final int WOODCUTTING_RUNE = 867; public static final int WOODCUTTING_GILDED = 8303; public static final int WOODCUTTING_DRAGON = 2846; public static final int WOODCUTTING_DRAGON_OR = 24; public static final int WOODCUTTING_INFERNAL = 2117; public static final int WOODCUTTING_3A_AXE = 7264; public static final int WOODCUTTING_CRYSTAL = 8324; public static final int WOODCUTTING_TRAILBLAZER = 8778; // Same animation as Infernal axe (or) public static final int WOODCUTTING_2H_BRONZE = 10064; public static final int WOODCUTTING_2H_IRON = 10065; public static final int WOODCUTTING_2H_STEEL = 10066; public static final int WOODCUTTING_2H_BLACK = 10067; public static final int WOODCUTTING_2H_MITHRIL = 10068; public static final int WOODCUTTING_2H_ADAMANT = 10069; public static final int WOODCUTTING_2H_RUNE = 10070; public static final int WOODCUTTING_2H_DRAGON = 10071; public static final int WOODCUTTING_2H_CRYSTAL = 10072; public static final int WOODCUTTING_2H_CRYSTAL_INACTIVE = 10073; public static final int WOODCUTTING_2H_3A = 10074; public static final int WOODCUTTING_ENT_BRONZE = 3291; public static final int WOODCUTTING_ENT_IRON = 3290; public static final int WOODCUTTING_ENT_STEEL = 3289; public static final int WOODCUTTING_ENT_BLACK = 3288; public static final int WOODCUTTING_ENT_MITHRIL = 3287; public static final int WOODCUTTING_ENT_ADAMANT = 3286; public static final int WOODCUTTING_ENT_RUNE = 3285; public static final int WOODCUTTING_ENT_GILDED = 8305; public static final int WOODCUTTING_ENT_DRAGON = 3292; public static final int WOODCUTTING_ENT_DRAGON_OR = 23; public static final int WOODCUTTING_ENT_INFERNAL = 2116; public static final int WOODCUTTING_ENT_INFERNAL_OR = 8777; public static final int WOODCUTTING_ENT_3A = 7266; public static final int WOODCUTTING_ENT_CRYSTAL = 8323; public static final int WOODCUTTING_ENT_CRYSTAL_INACTIVE = 8327; public static final int WOODCUTTING_ENT_TRAILBLAZER = 8780; public static final int WOODCUTTING_ENT_2H_BRONZE = 10517; public static final int WOODCUTTING_ENT_2H_IRON = 10518; public static final int WOODCUTTING_ENT_2H_STEEL = 10519; public static final int WOODCUTTING_ENT_2H_BLACK = 10520; public static final int WOODCUTTING_ENT_2H_MITHRIL = 10521; public static final int WOODCUTTING_ENT_2H_ADAMANT = 10522; public static final int WOODCUTTING_ENT_2H_RUNE = 10523; public static final int WOODCUTTING_ENT_2H_DRAGON = 10524; public static final int WOODCUTTING_ENT_2H_CRYSTAL = 10525; public static final int WOODCUTTING_ENT_2H_CRYSTAL_INACTIVE = 10526; public static final int WOODCUTTING_ENT_2H_3A = 10527; public static final int CONSUMING = 829; // consuming consumables public static final int FIREMAKING = 733; public static final int FIREMAKING_FORESTERS_CAMPFIRE_ARCTIC_PINE = 10563; public static final int FIREMAKING_FORESTERS_CAMPFIRE_BLISTERWOOD = 10564; public static final int FIREMAKING_FORESTERS_CAMPFIRE_LOGS = 10565; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAGIC = 10566; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAHOGANY = 10567; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAPLE = 10568; public static final int FIREMAKING_FORESTERS_CAMPFIRE_OAK = 10569; public static final int FIREMAKING_FORESTERS_CAMPFIRE_REDWOOD = 10570; public static final int FIREMAKING_FORESTERS_CAMPFIRE_TEAK = 10571; public static final int FIREMAKING_FORESTERS_CAMPFIRE_WILLOW = 10572; public static final int FIREMAKING_FORESTERS_CAMPFIRE_YEW = 10573; public static final int DEATH = 836; public static final int COOKING_FIRE = 897; public static final int COOKING_RANGE = 896; public static final int COOKING_WINE = 7529; public static final int FLETCHING_BOW_CUTTING = 1248; public static final int HUNTER_LAY_BOXTRAP_BIRDSNARE = 5208; //same for laying bird snares and box traps public static final int HUNTER_LAY_DEADFALLTRAP = 5212; //setting up deadfall trap public static final int HUNTER_LAY_NETTRAP = 5215; //setting up net trap public static final int HUNTER_LAY_MANIACAL_MONKEY_BOULDER_TRAP = 7259; // setting up maniacal monkey boulder trap public static final int HUNTER_CHECK_BIRD_SNARE = 5207; public static final int HUNTER_CHECK_BOX_TRAP = 5212; public static final int HERBLORE_MAKE_TAR = 5249; public static final int FLETCHING_STRING_NORMAL_SHORTBOW = 6678; public static final int FLETCHING_STRING_NORMAL_LONGBOW = 6684; public static final int FLETCHING_STRING_OAK_SHORTBOW = 6679; public static final int FLETCHING_STRING_OAK_LONGBOW = 6685; public static final int FLETCHING_STRING_WILLOW_SHORTBOW = 6680; public static final int FLETCHING_STRING_WILLOW_LONGBOW = 6686; public static final int FLETCHING_STRING_MAPLE_SHORTBOW = 6681; public static final int FLETCHING_STRING_MAPLE_LONGBOW = 6687; public static final int FLETCHING_STRING_YEW_SHORTBOW = 6682; public static final int FLETCHING_STRING_YEW_LONGBOW = 6688; public static final int FLETCHING_STRING_MAGIC_SHORTBOW = 6683; public static final int FLETCHING_STRING_MAGIC_LONGBOW = 6689; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BRONZE_BOLT = 8472; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_IRON_BROAD_BOLT = 8473; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BLURITE_BOLT = 8474; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_STEEL_BOLT = 8475; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_MITHRIL_BOLT = 8476; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_ADAMANT_BOLT = 8477; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_RUNE_BOLT = 8478; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_DRAGON_BOLT = 8479; public static final int FLETCHING_ATTACH_HEADS = 8480; public static final int FLETCHING_ATTACH_FEATHERS_TO_ARROWSHAFT = 8481; public static final int GEM_CUTTING_OPAL = 890; public static final int GEM_CUTTING_JADE = 891; public static final int GEM_CUTTING_REDTOPAZ = 892; public static final int GEM_CUTTING_SAPPHIRE = 888; public static final int GEM_CUTTING_EMERALD = 889; public static final int GEM_CUTTING_RUBY = 887; public static final int GEM_CUTTING_DIAMOND = 886; public static final int GEM_CUTTING_AMETHYST = 6295; public static final int CRAFTING_LEATHER = 1249; public static final int CRAFTING_GLASSBLOWING = 884; public static final int CRAFTING_SPINNING = 894; public static final int CRAFTING_POTTERS_WHEEL = 883; public static final int CRAFTING_POTTERY_OVEN = 24975; public static final int CRAFTING_LOOM = 2270; public static final int SMITHING_SMELTING = 899; public static final int SMITHING_CANNONBALL = 827; //cball smithing uses this and SMITHING_SMELTING public static final int SMITHING_ANVIL = 898; public static final int SMITHING_IMCANDO_HAMMER = 8911; public static final int FISHING_BIG_NET = 620; public static final int FISHING_NET = 621; public static final int FISHING_POLE_CAST = 623; // pole is in the water public static final int FISHING_CAGE = 619; public static final int FISHING_HARPOON = 618; public static final int FISHING_BARBTAIL_HARPOON = 5108; public static final int FISHING_DRAGON_HARPOON = 7401; public static final int FISHING_DRAGON_HARPOON_OR = 88; public static final int FISHING_INFERNAL_HARPOON = 7402; public static final int FISHING_CRYSTAL_HARPOON = 8336; public static final int FISHING_TRAILBLAZER_HARPOON = 8784; // Same animation as Infernal harpoon (or) public static final int FISHING_OILY_ROD = 622; public static final int FISHING_KARAMBWAN = 1193; public static final int FISHING_CRUSHING_INFERNAL_EELS = 7553; public static final int FISHING_CRUSHING_INFERNAL_EELS_IMCANDO_HAMMER = 8969; public static final int FISHING_CUTTING_SACRED_EELS = 7151; public static final int FISHING_BAREHAND = 6709; public static final int FISHING_BAREHAND_WINDUP_1 = 6703; public static final int FISHING_BAREHAND_WINDUP_2 = 6704; public static final int FISHING_BAREHAND_CAUGHT_SHARK_1 = 6705; public static final int FISHING_BAREHAND_CAUGHT_SHARK_2 = 6706; public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_1 = 6707; public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_2 = 6708; public static final int FISHING_BAREHAND_CAUGHT_TUNA_1 = 6710; public static final int FISHING_BAREHAND_CAUGHT_TUNA_2 = 6711; public static final int FISHING_PEARL_ROD = 8188; public static final int FISHING_PEARL_FLY_ROD = 8189; public static final int FISHING_PEARL_BARBARIAN_ROD = 8190; public static final int FISHING_PEARL_ROD_2 = 8191; public static final int FISHING_PEARL_FLY_ROD_2 = 8192; public static final int FISHING_PEARL_BARBARIAN_ROD_2 = 8193; public static final int FISHING_PEARL_OILY_ROD = 6932; public static final int FISHING_BARBARIAN_ROD = 9350; public static final int MINING_BRONZE_PICKAXE = 625; public static final int MINING_IRON_PICKAXE = 626; public static final int MINING_STEEL_PICKAXE = 627; public static final int MINING_BLACK_PICKAXE = 3873; public static final int MINING_MITHRIL_PICKAXE = 629; public static final int MINING_ADAMANT_PICKAXE = 628; public static final int MINING_RUNE_PICKAXE = 624; public static final int MINING_GILDED_PICKAXE = 8313; public static final int MINING_DRAGON_PICKAXE = 7139; public static final int MINING_DRAGON_PICKAXE_UPGRADED = 642; public static final int MINING_DRAGON_PICKAXE_OR = 8346; public static final int MINING_DRAGON_PICKAXE_OR_TRAILBLAZER = 8887; public static final int MINING_INFERNAL_PICKAXE = 4482; public static final int MINING_3A_PICKAXE = 7283; public static final int MINING_CRYSTAL_PICKAXE = 8347; public static final int MINING_TRAILBLAZER_PICKAXE = 8787; // Same animation as Infernal pickaxe (or) public static final int MINING_TRAILBLAZER_PICKAXE_2 = 8788; public static final int MINING_TRAILBLAZER_PICKAXE_3 = 8789; public static final int MINING_MOTHERLODE_BRONZE = 6753; public static final int MINING_MOTHERLODE_IRON = 6754; public static final int MINING_MOTHERLODE_STEEL = 6755; public static final int MINING_MOTHERLODE_BLACK = 3866; public static final int MINING_MOTHERLODE_MITHRIL = 6757; public static final int MINING_MOTHERLODE_ADAMANT = 6756; public static final int MINING_MOTHERLODE_RUNE = 6752; public static final int MINING_MOTHERLODE_GILDED = 8312; public static final int MINING_MOTHERLODE_DRAGON = 6758; public static final int MINING_MOTHERLODE_DRAGON_UPGRADED = 335; public static final int MINING_MOTHERLODE_DRAGON_OR = 8344; public static final int MINING_MOTHERLODE_DRAGON_OR_TRAILBLAZER = 8886; public static final int MINING_MOTHERLODE_INFERNAL = 4481; public static final int MINING_MOTHERLODE_3A = 7282; public static final int MINING_MOTHERLODE_CRYSTAL = 8345; public static final int MINING_MOTHERLODE_TRAILBLAZER = 8786; // Same animation as Infernal pickaxe (or) public final static int MINING_CRASHEDSTAR_BRONZE = 6747; public final static int MINING_CRASHEDSTAR_IRON = 6748; public final static int MINING_CRASHEDSTAR_STEEL = 6749; public final static int MINING_CRASHEDSTAR_BLACK = 6108; public final static int MINING_CRASHEDSTAR_MITHRIL = 6751; public final static int MINING_CRASHEDSTAR_ADAMANT = 6750; public final static int MINING_CRASHEDSTAR_RUNE = 6746; public final static int MINING_CRASHEDSTAR_GILDED = 8314; public final static int MINING_CRASHEDSTAR_DRAGON = 7140; public final static int MINING_CRASHEDSTAR_DRAGON_UPGRADED = 643; public final static int MINING_CRASHEDSTAR_DRAGON_OR = 8349; public final static int MINING_CRASHEDSTAR_DRAGON_OR_TRAILBLAZER = 8888; public final static int MINING_CRASHEDSTAR_INFERNAL = 4483; public final static int MINING_CRASHEDSTAR_3A = 7284; public final static int MINING_CRASHEDSTAR_CRYSTAL = 8350; public static final int DENSE_ESSENCE_CHIPPING = 7201; public static final int DENSE_ESSENCE_CHISELING = 7202; public static final int HERBLORE_POTIONMAKING = 363; //used for both herb and secondary public static final int MAGIC_CHARGING_ORBS = 726; public static final int MAGIC_MAKE_TABLET = 4068; public static final int MAGIC_ENCHANTING_JEWELRY = 931; public static final int MAGIC_ENCHANTING_AMULET_1 = 719; // sapphire, opal, diamond public static final int MAGIC_ENCHANTING_AMULET_2 = 720; // emerald, jade, dragonstone public static final int MAGIC_ENCHANTING_AMULET_3 = 721; // ruby, topaz, onyx, zenyte public static final int MAGIC_ENCHANTING_BOLTS = 4462; public static final int BURYING_BONES = 827; public static final int USING_GILDED_ALTAR = 3705; public static final int LOOKING_INTO = 832; // Generic animation used for filling water vessels, Shades of Mort'ton, etc. public static final int DIG = 830; public static final int DEMONIC_GORILLA_MAGIC_ATTACK = 7225; public static final int DEMONIC_GORILLA_MELEE_ATTACK = 7226; public static final int DEMONIC_GORILLA_RANGED_ATTACK = 7227; public static final int DEMONIC_GORILLA_AOE_ATTACK = 7228; public static final int DEMONIC_GORILLA_PRAYER_SWITCH = 7228; public static final int DEMONIC_GORILLA_DEFEND = 7224; public static final int BOOK_HOME_TELEPORT_1 = 4847; public static final int BOOK_HOME_TELEPORT_2 = 4850; public static final int BOOK_HOME_TELEPORT_3 = 4853; public static final int BOOK_HOME_TELEPORT_4 = 4855; public static final int BOOK_HOME_TELEPORT_5 = 4857; public static final int COW_HOME_TELEPORT_1 = 1696; public static final int COW_HOME_TELEPORT_2 = 1697; public static final int COW_HOME_TELEPORT_3 = 1698; public static final int COW_HOME_TELEPORT_4 = 1699; public static final int COW_HOME_TELEPORT_5 = 1700; public static final int COW_HOME_TELEPORT_6 = 1701; public static final int LEAGUE_HOME_TELEPORT_1 = 8798; public static final int LEAGUE_HOME_TELEPORT_2 = 8799; public static final int LEAGUE_HOME_TELEPORT_3 = 8801; public static final int LEAGUE_HOME_TELEPORT_4 = 8803; public static final int LEAGUE_HOME_TELEPORT_5 = 8805; public static final int LEAGUE_HOME_TELEPORT_6 = 8807; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_1 = 9209; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_2 = 9210; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_3 = 9211; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_4 = 9212; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_5 = 9213; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_6 = 9214; public static final int RAID_LIGHT_ANIMATION = 3101; public static final int LOOTBEAM_ANIMATION = 9260; public static final int BLISTERWOOD_JUMP_SCARE = 2390; public static final int CONSTRUCTION = 3676; public static final int CONSTRUCTION_IMCANDO = 8912; public static final int SAND_COLLECTION = 895; public static final int PISCARILIUS_CRANE_REPAIR = 7199; public static final int HOME_MAKE_TABLET = 4067; public static final int DRAGONFIRE_SHIELD_SPECIAL = 6696; public static final int MILKING_COW = 2305; public static final int CHURN_MILK_SHORT = 2793; public static final int CHURN_MILK_MEDIUM = 2794; public static final int CHURN_MILK_LONG = 2795; public static final int CLEANING_SPECIMENS_1 = 6217; public static final int CLEANING_SPECIMENS_2 = 6459; // Ectofuntus animations public static final int ECTOFUNTUS_FILL_SLIME_BUCKET = 4471; public static final int ECTOFUNTUS_GRIND_BONES = 1648; public static final int ECTOFUNTUS_INSERT_BONES = 1649; public static final int ECTOFUNTUS_EMPTY_BIN = 1650; // NPC animations public static final int TZTOK_JAD_MAGIC_ATTACK = 2656; public static final int TZTOK_JAD_RANGE_ATTACK = 2652; public static final int HELLHOUND_DEFENCE = 6566; // Farming public static final int FARMING_HARVEST_FRUIT_TREE = 2280; public static final int FARMING_HARVEST_BUSH = 2281; public static final int FARMING_HARVEST_HERB = 2282; public static final int FARMING_USE_COMPOST = 2283; public static final int FARMING_CURE_WITH_POTION = 2288; public static final int FARMING_PLANT_SEED = 2291; public static final int FARMING_HARVEST_FLOWER = 2292; public static final int FARMING_MIX_ULTRACOMPOST = 7699; public static final int FARMING_HARVEST_ALLOTMENT = 830; // Lunar spellbook public static final int ENERGY_TRANSFER_VENGEANCE_OTHER = 4411; public static final int MAGIC_LUNAR_SHARED = 4413; // Utilized by Fertile Soil, Boost/Stat Potion Share, NPC Contact, Bake Pie public static final int MAGIC_LUNAR_CURE_PLANT = 4432; public static final int MAGIC_LUNAR_GEOMANCY = 7118; public static final int MAGIC_LUNAR_PLANK_MAKE = 6298; public static final int MAGIC_LUNAR_STRING_JEWELRY = 4412; // Arceuus spellbook public static final int MAGIC_ARCEUUS_RESURRECT_CROPS = 7118; // Battlestaff Crafting public static final int CRAFTING_BATTLESTAVES = 7531; // Death Animations public static final int CAVE_KRAKEN_DEATH = 3993; public static final int WIZARD_DEATH = 2553; public static final int GARGOYLE_DEATH = 1520; public static final int MARBLE_GARGOYLE_DEATH = 7813; public static final int LIZARD_DEATH = 2778; public static final int ROCKSLUG_DEATH = 1568; public static final int ZYGOMITE_DEATH = 3327; public static final int IMP_DEATH = 172; public static final int CORP_DEATH = 1676; public static final int VERZIK_P2_BLUE_NYLO_EXPLOSION = 7992; public static final int VERZIK_P2_GREEN_NYLO_EXPLOSION = 8000; public static final int VERZIK_P2_WHITE_NYLO_EXPLOSION = 8006; public static final int VERZIK_P2_PURPLE_NYLO_EXPLOSION = 8078; public static final int VERZIK_P2_RED_NYLO_EXPLOSION = 8097; // POH Animations public static final int INCENSE_BURNER = 3687; }
runelite/runelite
runelite-api/src/main/java/net/runelite/api/AnimationID.java
7,856
// emerald, jade, dragonstone
line_comment
nl
/* * Copyright (c) 2016-2017, Abel Briggs * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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. */ package net.runelite.api; /** * Utility class used for mapping animation IDs. * <p> * Note: This class is not complete and may not contain a specific animation * required. */ public final class AnimationID { public static final int IDLE = -1; public static final int HERBLORE_PESTLE_AND_MORTAR = 364; public static final int WOODCUTTING_BRONZE = 879; public static final int WOODCUTTING_IRON = 877; public static final int WOODCUTTING_STEEL = 875; public static final int WOODCUTTING_BLACK = 873; public static final int WOODCUTTING_MITHRIL = 871; public static final int WOODCUTTING_ADAMANT = 869; public static final int WOODCUTTING_RUNE = 867; public static final int WOODCUTTING_GILDED = 8303; public static final int WOODCUTTING_DRAGON = 2846; public static final int WOODCUTTING_DRAGON_OR = 24; public static final int WOODCUTTING_INFERNAL = 2117; public static final int WOODCUTTING_3A_AXE = 7264; public static final int WOODCUTTING_CRYSTAL = 8324; public static final int WOODCUTTING_TRAILBLAZER = 8778; // Same animation as Infernal axe (or) public static final int WOODCUTTING_2H_BRONZE = 10064; public static final int WOODCUTTING_2H_IRON = 10065; public static final int WOODCUTTING_2H_STEEL = 10066; public static final int WOODCUTTING_2H_BLACK = 10067; public static final int WOODCUTTING_2H_MITHRIL = 10068; public static final int WOODCUTTING_2H_ADAMANT = 10069; public static final int WOODCUTTING_2H_RUNE = 10070; public static final int WOODCUTTING_2H_DRAGON = 10071; public static final int WOODCUTTING_2H_CRYSTAL = 10072; public static final int WOODCUTTING_2H_CRYSTAL_INACTIVE = 10073; public static final int WOODCUTTING_2H_3A = 10074; public static final int WOODCUTTING_ENT_BRONZE = 3291; public static final int WOODCUTTING_ENT_IRON = 3290; public static final int WOODCUTTING_ENT_STEEL = 3289; public static final int WOODCUTTING_ENT_BLACK = 3288; public static final int WOODCUTTING_ENT_MITHRIL = 3287; public static final int WOODCUTTING_ENT_ADAMANT = 3286; public static final int WOODCUTTING_ENT_RUNE = 3285; public static final int WOODCUTTING_ENT_GILDED = 8305; public static final int WOODCUTTING_ENT_DRAGON = 3292; public static final int WOODCUTTING_ENT_DRAGON_OR = 23; public static final int WOODCUTTING_ENT_INFERNAL = 2116; public static final int WOODCUTTING_ENT_INFERNAL_OR = 8777; public static final int WOODCUTTING_ENT_3A = 7266; public static final int WOODCUTTING_ENT_CRYSTAL = 8323; public static final int WOODCUTTING_ENT_CRYSTAL_INACTIVE = 8327; public static final int WOODCUTTING_ENT_TRAILBLAZER = 8780; public static final int WOODCUTTING_ENT_2H_BRONZE = 10517; public static final int WOODCUTTING_ENT_2H_IRON = 10518; public static final int WOODCUTTING_ENT_2H_STEEL = 10519; public static final int WOODCUTTING_ENT_2H_BLACK = 10520; public static final int WOODCUTTING_ENT_2H_MITHRIL = 10521; public static final int WOODCUTTING_ENT_2H_ADAMANT = 10522; public static final int WOODCUTTING_ENT_2H_RUNE = 10523; public static final int WOODCUTTING_ENT_2H_DRAGON = 10524; public static final int WOODCUTTING_ENT_2H_CRYSTAL = 10525; public static final int WOODCUTTING_ENT_2H_CRYSTAL_INACTIVE = 10526; public static final int WOODCUTTING_ENT_2H_3A = 10527; public static final int CONSUMING = 829; // consuming consumables public static final int FIREMAKING = 733; public static final int FIREMAKING_FORESTERS_CAMPFIRE_ARCTIC_PINE = 10563; public static final int FIREMAKING_FORESTERS_CAMPFIRE_BLISTERWOOD = 10564; public static final int FIREMAKING_FORESTERS_CAMPFIRE_LOGS = 10565; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAGIC = 10566; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAHOGANY = 10567; public static final int FIREMAKING_FORESTERS_CAMPFIRE_MAPLE = 10568; public static final int FIREMAKING_FORESTERS_CAMPFIRE_OAK = 10569; public static final int FIREMAKING_FORESTERS_CAMPFIRE_REDWOOD = 10570; public static final int FIREMAKING_FORESTERS_CAMPFIRE_TEAK = 10571; public static final int FIREMAKING_FORESTERS_CAMPFIRE_WILLOW = 10572; public static final int FIREMAKING_FORESTERS_CAMPFIRE_YEW = 10573; public static final int DEATH = 836; public static final int COOKING_FIRE = 897; public static final int COOKING_RANGE = 896; public static final int COOKING_WINE = 7529; public static final int FLETCHING_BOW_CUTTING = 1248; public static final int HUNTER_LAY_BOXTRAP_BIRDSNARE = 5208; //same for laying bird snares and box traps public static final int HUNTER_LAY_DEADFALLTRAP = 5212; //setting up deadfall trap public static final int HUNTER_LAY_NETTRAP = 5215; //setting up net trap public static final int HUNTER_LAY_MANIACAL_MONKEY_BOULDER_TRAP = 7259; // setting up maniacal monkey boulder trap public static final int HUNTER_CHECK_BIRD_SNARE = 5207; public static final int HUNTER_CHECK_BOX_TRAP = 5212; public static final int HERBLORE_MAKE_TAR = 5249; public static final int FLETCHING_STRING_NORMAL_SHORTBOW = 6678; public static final int FLETCHING_STRING_NORMAL_LONGBOW = 6684; public static final int FLETCHING_STRING_OAK_SHORTBOW = 6679; public static final int FLETCHING_STRING_OAK_LONGBOW = 6685; public static final int FLETCHING_STRING_WILLOW_SHORTBOW = 6680; public static final int FLETCHING_STRING_WILLOW_LONGBOW = 6686; public static final int FLETCHING_STRING_MAPLE_SHORTBOW = 6681; public static final int FLETCHING_STRING_MAPLE_LONGBOW = 6687; public static final int FLETCHING_STRING_YEW_SHORTBOW = 6682; public static final int FLETCHING_STRING_YEW_LONGBOW = 6688; public static final int FLETCHING_STRING_MAGIC_SHORTBOW = 6683; public static final int FLETCHING_STRING_MAGIC_LONGBOW = 6689; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BRONZE_BOLT = 8472; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_IRON_BROAD_BOLT = 8473; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BLURITE_BOLT = 8474; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_STEEL_BOLT = 8475; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_MITHRIL_BOLT = 8476; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_ADAMANT_BOLT = 8477; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_RUNE_BOLT = 8478; public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_DRAGON_BOLT = 8479; public static final int FLETCHING_ATTACH_HEADS = 8480; public static final int FLETCHING_ATTACH_FEATHERS_TO_ARROWSHAFT = 8481; public static final int GEM_CUTTING_OPAL = 890; public static final int GEM_CUTTING_JADE = 891; public static final int GEM_CUTTING_REDTOPAZ = 892; public static final int GEM_CUTTING_SAPPHIRE = 888; public static final int GEM_CUTTING_EMERALD = 889; public static final int GEM_CUTTING_RUBY = 887; public static final int GEM_CUTTING_DIAMOND = 886; public static final int GEM_CUTTING_AMETHYST = 6295; public static final int CRAFTING_LEATHER = 1249; public static final int CRAFTING_GLASSBLOWING = 884; public static final int CRAFTING_SPINNING = 894; public static final int CRAFTING_POTTERS_WHEEL = 883; public static final int CRAFTING_POTTERY_OVEN = 24975; public static final int CRAFTING_LOOM = 2270; public static final int SMITHING_SMELTING = 899; public static final int SMITHING_CANNONBALL = 827; //cball smithing uses this and SMITHING_SMELTING public static final int SMITHING_ANVIL = 898; public static final int SMITHING_IMCANDO_HAMMER = 8911; public static final int FISHING_BIG_NET = 620; public static final int FISHING_NET = 621; public static final int FISHING_POLE_CAST = 623; // pole is in the water public static final int FISHING_CAGE = 619; public static final int FISHING_HARPOON = 618; public static final int FISHING_BARBTAIL_HARPOON = 5108; public static final int FISHING_DRAGON_HARPOON = 7401; public static final int FISHING_DRAGON_HARPOON_OR = 88; public static final int FISHING_INFERNAL_HARPOON = 7402; public static final int FISHING_CRYSTAL_HARPOON = 8336; public static final int FISHING_TRAILBLAZER_HARPOON = 8784; // Same animation as Infernal harpoon (or) public static final int FISHING_OILY_ROD = 622; public static final int FISHING_KARAMBWAN = 1193; public static final int FISHING_CRUSHING_INFERNAL_EELS = 7553; public static final int FISHING_CRUSHING_INFERNAL_EELS_IMCANDO_HAMMER = 8969; public static final int FISHING_CUTTING_SACRED_EELS = 7151; public static final int FISHING_BAREHAND = 6709; public static final int FISHING_BAREHAND_WINDUP_1 = 6703; public static final int FISHING_BAREHAND_WINDUP_2 = 6704; public static final int FISHING_BAREHAND_CAUGHT_SHARK_1 = 6705; public static final int FISHING_BAREHAND_CAUGHT_SHARK_2 = 6706; public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_1 = 6707; public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_2 = 6708; public static final int FISHING_BAREHAND_CAUGHT_TUNA_1 = 6710; public static final int FISHING_BAREHAND_CAUGHT_TUNA_2 = 6711; public static final int FISHING_PEARL_ROD = 8188; public static final int FISHING_PEARL_FLY_ROD = 8189; public static final int FISHING_PEARL_BARBARIAN_ROD = 8190; public static final int FISHING_PEARL_ROD_2 = 8191; public static final int FISHING_PEARL_FLY_ROD_2 = 8192; public static final int FISHING_PEARL_BARBARIAN_ROD_2 = 8193; public static final int FISHING_PEARL_OILY_ROD = 6932; public static final int FISHING_BARBARIAN_ROD = 9350; public static final int MINING_BRONZE_PICKAXE = 625; public static final int MINING_IRON_PICKAXE = 626; public static final int MINING_STEEL_PICKAXE = 627; public static final int MINING_BLACK_PICKAXE = 3873; public static final int MINING_MITHRIL_PICKAXE = 629; public static final int MINING_ADAMANT_PICKAXE = 628; public static final int MINING_RUNE_PICKAXE = 624; public static final int MINING_GILDED_PICKAXE = 8313; public static final int MINING_DRAGON_PICKAXE = 7139; public static final int MINING_DRAGON_PICKAXE_UPGRADED = 642; public static final int MINING_DRAGON_PICKAXE_OR = 8346; public static final int MINING_DRAGON_PICKAXE_OR_TRAILBLAZER = 8887; public static final int MINING_INFERNAL_PICKAXE = 4482; public static final int MINING_3A_PICKAXE = 7283; public static final int MINING_CRYSTAL_PICKAXE = 8347; public static final int MINING_TRAILBLAZER_PICKAXE = 8787; // Same animation as Infernal pickaxe (or) public static final int MINING_TRAILBLAZER_PICKAXE_2 = 8788; public static final int MINING_TRAILBLAZER_PICKAXE_3 = 8789; public static final int MINING_MOTHERLODE_BRONZE = 6753; public static final int MINING_MOTHERLODE_IRON = 6754; public static final int MINING_MOTHERLODE_STEEL = 6755; public static final int MINING_MOTHERLODE_BLACK = 3866; public static final int MINING_MOTHERLODE_MITHRIL = 6757; public static final int MINING_MOTHERLODE_ADAMANT = 6756; public static final int MINING_MOTHERLODE_RUNE = 6752; public static final int MINING_MOTHERLODE_GILDED = 8312; public static final int MINING_MOTHERLODE_DRAGON = 6758; public static final int MINING_MOTHERLODE_DRAGON_UPGRADED = 335; public static final int MINING_MOTHERLODE_DRAGON_OR = 8344; public static final int MINING_MOTHERLODE_DRAGON_OR_TRAILBLAZER = 8886; public static final int MINING_MOTHERLODE_INFERNAL = 4481; public static final int MINING_MOTHERLODE_3A = 7282; public static final int MINING_MOTHERLODE_CRYSTAL = 8345; public static final int MINING_MOTHERLODE_TRAILBLAZER = 8786; // Same animation as Infernal pickaxe (or) public final static int MINING_CRASHEDSTAR_BRONZE = 6747; public final static int MINING_CRASHEDSTAR_IRON = 6748; public final static int MINING_CRASHEDSTAR_STEEL = 6749; public final static int MINING_CRASHEDSTAR_BLACK = 6108; public final static int MINING_CRASHEDSTAR_MITHRIL = 6751; public final static int MINING_CRASHEDSTAR_ADAMANT = 6750; public final static int MINING_CRASHEDSTAR_RUNE = 6746; public final static int MINING_CRASHEDSTAR_GILDED = 8314; public final static int MINING_CRASHEDSTAR_DRAGON = 7140; public final static int MINING_CRASHEDSTAR_DRAGON_UPGRADED = 643; public final static int MINING_CRASHEDSTAR_DRAGON_OR = 8349; public final static int MINING_CRASHEDSTAR_DRAGON_OR_TRAILBLAZER = 8888; public final static int MINING_CRASHEDSTAR_INFERNAL = 4483; public final static int MINING_CRASHEDSTAR_3A = 7284; public final static int MINING_CRASHEDSTAR_CRYSTAL = 8350; public static final int DENSE_ESSENCE_CHIPPING = 7201; public static final int DENSE_ESSENCE_CHISELING = 7202; public static final int HERBLORE_POTIONMAKING = 363; //used for both herb and secondary public static final int MAGIC_CHARGING_ORBS = 726; public static final int MAGIC_MAKE_TABLET = 4068; public static final int MAGIC_ENCHANTING_JEWELRY = 931; public static final int MAGIC_ENCHANTING_AMULET_1 = 719; // sapphire, opal, diamond public static final int MAGIC_ENCHANTING_AMULET_2 = 720; // emerald, jade,<SUF> public static final int MAGIC_ENCHANTING_AMULET_3 = 721; // ruby, topaz, onyx, zenyte public static final int MAGIC_ENCHANTING_BOLTS = 4462; public static final int BURYING_BONES = 827; public static final int USING_GILDED_ALTAR = 3705; public static final int LOOKING_INTO = 832; // Generic animation used for filling water vessels, Shades of Mort'ton, etc. public static final int DIG = 830; public static final int DEMONIC_GORILLA_MAGIC_ATTACK = 7225; public static final int DEMONIC_GORILLA_MELEE_ATTACK = 7226; public static final int DEMONIC_GORILLA_RANGED_ATTACK = 7227; public static final int DEMONIC_GORILLA_AOE_ATTACK = 7228; public static final int DEMONIC_GORILLA_PRAYER_SWITCH = 7228; public static final int DEMONIC_GORILLA_DEFEND = 7224; public static final int BOOK_HOME_TELEPORT_1 = 4847; public static final int BOOK_HOME_TELEPORT_2 = 4850; public static final int BOOK_HOME_TELEPORT_3 = 4853; public static final int BOOK_HOME_TELEPORT_4 = 4855; public static final int BOOK_HOME_TELEPORT_5 = 4857; public static final int COW_HOME_TELEPORT_1 = 1696; public static final int COW_HOME_TELEPORT_2 = 1697; public static final int COW_HOME_TELEPORT_3 = 1698; public static final int COW_HOME_TELEPORT_4 = 1699; public static final int COW_HOME_TELEPORT_5 = 1700; public static final int COW_HOME_TELEPORT_6 = 1701; public static final int LEAGUE_HOME_TELEPORT_1 = 8798; public static final int LEAGUE_HOME_TELEPORT_2 = 8799; public static final int LEAGUE_HOME_TELEPORT_3 = 8801; public static final int LEAGUE_HOME_TELEPORT_4 = 8803; public static final int LEAGUE_HOME_TELEPORT_5 = 8805; public static final int LEAGUE_HOME_TELEPORT_6 = 8807; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_1 = 9209; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_2 = 9210; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_3 = 9211; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_4 = 9212; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_5 = 9213; public static final int SHATTERED_LEAGUE_HOME_TELEPORT_6 = 9214; public static final int RAID_LIGHT_ANIMATION = 3101; public static final int LOOTBEAM_ANIMATION = 9260; public static final int BLISTERWOOD_JUMP_SCARE = 2390; public static final int CONSTRUCTION = 3676; public static final int CONSTRUCTION_IMCANDO = 8912; public static final int SAND_COLLECTION = 895; public static final int PISCARILIUS_CRANE_REPAIR = 7199; public static final int HOME_MAKE_TABLET = 4067; public static final int DRAGONFIRE_SHIELD_SPECIAL = 6696; public static final int MILKING_COW = 2305; public static final int CHURN_MILK_SHORT = 2793; public static final int CHURN_MILK_MEDIUM = 2794; public static final int CHURN_MILK_LONG = 2795; public static final int CLEANING_SPECIMENS_1 = 6217; public static final int CLEANING_SPECIMENS_2 = 6459; // Ectofuntus animations public static final int ECTOFUNTUS_FILL_SLIME_BUCKET = 4471; public static final int ECTOFUNTUS_GRIND_BONES = 1648; public static final int ECTOFUNTUS_INSERT_BONES = 1649; public static final int ECTOFUNTUS_EMPTY_BIN = 1650; // NPC animations public static final int TZTOK_JAD_MAGIC_ATTACK = 2656; public static final int TZTOK_JAD_RANGE_ATTACK = 2652; public static final int HELLHOUND_DEFENCE = 6566; // Farming public static final int FARMING_HARVEST_FRUIT_TREE = 2280; public static final int FARMING_HARVEST_BUSH = 2281; public static final int FARMING_HARVEST_HERB = 2282; public static final int FARMING_USE_COMPOST = 2283; public static final int FARMING_CURE_WITH_POTION = 2288; public static final int FARMING_PLANT_SEED = 2291; public static final int FARMING_HARVEST_FLOWER = 2292; public static final int FARMING_MIX_ULTRACOMPOST = 7699; public static final int FARMING_HARVEST_ALLOTMENT = 830; // Lunar spellbook public static final int ENERGY_TRANSFER_VENGEANCE_OTHER = 4411; public static final int MAGIC_LUNAR_SHARED = 4413; // Utilized by Fertile Soil, Boost/Stat Potion Share, NPC Contact, Bake Pie public static final int MAGIC_LUNAR_CURE_PLANT = 4432; public static final int MAGIC_LUNAR_GEOMANCY = 7118; public static final int MAGIC_LUNAR_PLANK_MAKE = 6298; public static final int MAGIC_LUNAR_STRING_JEWELRY = 4412; // Arceuus spellbook public static final int MAGIC_ARCEUUS_RESURRECT_CROPS = 7118; // Battlestaff Crafting public static final int CRAFTING_BATTLESTAVES = 7531; // Death Animations public static final int CAVE_KRAKEN_DEATH = 3993; public static final int WIZARD_DEATH = 2553; public static final int GARGOYLE_DEATH = 1520; public static final int MARBLE_GARGOYLE_DEATH = 7813; public static final int LIZARD_DEATH = 2778; public static final int ROCKSLUG_DEATH = 1568; public static final int ZYGOMITE_DEATH = 3327; public static final int IMP_DEATH = 172; public static final int CORP_DEATH = 1676; public static final int VERZIK_P2_BLUE_NYLO_EXPLOSION = 7992; public static final int VERZIK_P2_GREEN_NYLO_EXPLOSION = 8000; public static final int VERZIK_P2_WHITE_NYLO_EXPLOSION = 8006; public static final int VERZIK_P2_PURPLE_NYLO_EXPLOSION = 8078; public static final int VERZIK_P2_RED_NYLO_EXPLOSION = 8097; // POH Animations public static final int INCENSE_BURNER = 3687; }
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,202
//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(); } }
60483_1
package com.company; import javax.swing.plaf.nimbus.State; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ProductDAOPsql implements ProductDAO{ private Connection connection; private OVChipkaartDAO ovChipkaartDAO; public ProductDAOPsql(Connection connection) { this.connection = connection; } @Override public void setOVChipkaartDAO(OVChipkaartDAO ovChipkaartDAO) { this.ovChipkaartDAO = ovChipkaartDAO; } @Override public boolean save(Product product) { boolean isSuccess = false; try { PreparedStatement insertProductPreparedStatement = connection.prepareStatement("INSERT INTO product (product_nummer, naam, beschrijving, prijs) VALUES(?, ?, ?, ?)"); insertProductPreparedStatement.setInt(1, product.getNummer()); insertProductPreparedStatement.setString(2, product.getNaam()); insertProductPreparedStatement.setString(3, product.getBeschrijving()); insertProductPreparedStatement.setDouble(4, product.getPrijs()); int resultSet = insertProductPreparedStatement.executeUpdate(); if(resultSet > 0) { for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { PreparedStatement insertRelationPreparedStatement = connection.prepareStatement("INSERT INTO ov_chipkaart_product (kaart_nummer, product_nummer, last_update) VALUES(?, ?, now())"); insertRelationPreparedStatement.setInt(1, ovChipkaart.getKaartnummer()); insertRelationPreparedStatement.setInt(2, product.getNummer()); insertRelationPreparedStatement.execute(); insertRelationPreparedStatement.close(); } isSuccess = true; } insertProductPreparedStatement.close(); }catch(SQLException ex) { System.err.println("[SQLException] Opslaan van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public boolean update(Product product) { boolean isSuccess = false; try { //UPDATE product PreparedStatement preparedStatement = connection.prepareStatement("UPDATE product SET naam=?, beschrijving=?, prijs=? WHERE product_nummer=?"); preparedStatement.setString(1, product.getNaam()); preparedStatement.setString(2, product.getBeschrijving()); preparedStatement.setDouble(3, product.getPrijs()); preparedStatement.setInt(4, product.getNummer()); int resultSet = preparedStatement.executeUpdate(); preparedStatement.close(); if(resultSet > 0) { isSuccess = true; } //Verwijder relaties die niet meer bestaan Statement ovChipkaartenNummersStatement = connection.createStatement(); ResultSet ovChipkaartenNummers = ovChipkaartenNummersStatement.executeQuery("SELECT kaart_nummer FROM ov_chipkaart_product WHERE product_nummer=" + product.getNummer()); List<Integer> kaartnummers = new ArrayList<>(); while(ovChipkaartenNummers.next()) { kaartnummers.add(ovChipkaartenNummers.getInt("kaart_nummer")); } for(int kaartNummer : kaartnummers) { boolean isFound = false; for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { if(ovChipkaart.getKaartnummer() == kaartNummer) { isFound = true; break; } } //Als ovchipkaart_nummer (uit database) niet voorkomt in product.getOvChipkaarten(); if(!isFound) { //Verwijder relatie PreparedStatement deleteRelationStatement = connection.prepareStatement("DELETE FROM ov_chipkaart_product WHERE kaart_nummer=? AND product_nummer=?"); deleteRelationStatement.setInt(1, kaartNummer); deleteRelationStatement.setInt(2, product.getNummer()); deleteRelationStatement.executeUpdate(); deleteRelationStatement.close(); } } //INSERT relaties als niet bestaat for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { boolean isFound = false; for(int kaartNummer : kaartnummers) { if(ovChipkaart.getKaartnummer() == kaartNummer) { isFound = true; break; } } if(!isFound) { PreparedStatement updateRelationStatement = connection.prepareStatement("INSERT INTO ov_chipkaart_product (kaart_nummer, product_nummer) VALUES (?, ?)"); updateRelationStatement.setInt(1, ovChipkaart.getKaartnummer()); updateRelationStatement.setInt(2, product.getNummer()); updateRelationStatement.executeUpdate(); updateRelationStatement.close(); } } }catch(SQLException ex) { System.err.println("[SQLException] Updaten van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public boolean delete(Product product) { boolean isSuccess = false; try { // Delete relation (OVChipkaart - Product) PreparedStatement deleteRelationStatement = connection.prepareStatement("DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"); deleteRelationStatement.setInt(1, product.getNummer()); deleteRelationStatement.executeUpdate(); deleteRelationStatement.close(); // Delete product PreparedStatement deleteProductStatement = connection.prepareStatement("DELETE FROM product WHERE product_nummer=?"); deleteProductStatement.setInt(1, product.getNummer()); int resultSet = deleteProductStatement.executeUpdate(); if(resultSet > 0) { isSuccess = true; } deleteProductStatement.close(); }catch(SQLException ex) { System.err.println("[SQLException] Verwijderen van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) { List<Product> producten = new ArrayList<>(); try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT product.product_nummer, product.naam, product.beschrijving, product.prijs FROM ov_chipkaart_product JOIN product ON ov_chipkaart_product.product_nummer = product.product_nummer WHERE ov_chipkaart_product.kaart_nummer = ?"); preparedStatement.setInt(1, ovChipkaart.getKaartnummer()); ResultSet products = preparedStatement.executeQuery(); //Haal alle producten op while (products.next()) { int productNummer = products.getInt("product_nummer"); String naam = products.getString("naam"); String beschrijving = products.getString("beschrijving"); double prijs = products.getDouble("prijs"); Product product = new Product(productNummer, naam, beschrijving, prijs); producten.add(product); } }catch(SQLException ex) { System.err.println("Er is iets fout gegaan bij het ophalen van alle producten: " + ex.getMessage()); } return producten; } @Override public List<Product> findAll() { List<Product> producten = new ArrayList<>(); try { Statement statement = connection.createStatement(); ResultSet products = statement.executeQuery("SELECT * FROM product"); //Haal alle producten op while (products.next()) { int productNummer = products.getInt("product_nummer"); String naam = products.getString("naam"); String beschrijving = products.getString("beschrijving"); double prijs = products.getDouble("prijs"); Product product = new Product(productNummer, naam, beschrijving, prijs); List<OVChipkaart> ovChipkaarten = ovChipkaartDAO.findByProduct(product); for(OVChipkaart ovChipkaart : ovChipkaarten) { product.voegOvChipkaartToe(ovChipkaart); } producten.add(product); } statement.close(); products.close(); }catch(SQLException ex) { System.err.println("Er is iets fout gegaan bij het ophalen van alle producten: " + ex.getMessage()); } return producten; } }
rvdriest/DP_OV-Chipkaart
src/com/company/ProductDAOPsql.java
2,400
//Als ovchipkaart_nummer (uit database) niet voorkomt in product.getOvChipkaarten();
line_comment
nl
package com.company; import javax.swing.plaf.nimbus.State; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ProductDAOPsql implements ProductDAO{ private Connection connection; private OVChipkaartDAO ovChipkaartDAO; public ProductDAOPsql(Connection connection) { this.connection = connection; } @Override public void setOVChipkaartDAO(OVChipkaartDAO ovChipkaartDAO) { this.ovChipkaartDAO = ovChipkaartDAO; } @Override public boolean save(Product product) { boolean isSuccess = false; try { PreparedStatement insertProductPreparedStatement = connection.prepareStatement("INSERT INTO product (product_nummer, naam, beschrijving, prijs) VALUES(?, ?, ?, ?)"); insertProductPreparedStatement.setInt(1, product.getNummer()); insertProductPreparedStatement.setString(2, product.getNaam()); insertProductPreparedStatement.setString(3, product.getBeschrijving()); insertProductPreparedStatement.setDouble(4, product.getPrijs()); int resultSet = insertProductPreparedStatement.executeUpdate(); if(resultSet > 0) { for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { PreparedStatement insertRelationPreparedStatement = connection.prepareStatement("INSERT INTO ov_chipkaart_product (kaart_nummer, product_nummer, last_update) VALUES(?, ?, now())"); insertRelationPreparedStatement.setInt(1, ovChipkaart.getKaartnummer()); insertRelationPreparedStatement.setInt(2, product.getNummer()); insertRelationPreparedStatement.execute(); insertRelationPreparedStatement.close(); } isSuccess = true; } insertProductPreparedStatement.close(); }catch(SQLException ex) { System.err.println("[SQLException] Opslaan van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public boolean update(Product product) { boolean isSuccess = false; try { //UPDATE product PreparedStatement preparedStatement = connection.prepareStatement("UPDATE product SET naam=?, beschrijving=?, prijs=? WHERE product_nummer=?"); preparedStatement.setString(1, product.getNaam()); preparedStatement.setString(2, product.getBeschrijving()); preparedStatement.setDouble(3, product.getPrijs()); preparedStatement.setInt(4, product.getNummer()); int resultSet = preparedStatement.executeUpdate(); preparedStatement.close(); if(resultSet > 0) { isSuccess = true; } //Verwijder relaties die niet meer bestaan Statement ovChipkaartenNummersStatement = connection.createStatement(); ResultSet ovChipkaartenNummers = ovChipkaartenNummersStatement.executeQuery("SELECT kaart_nummer FROM ov_chipkaart_product WHERE product_nummer=" + product.getNummer()); List<Integer> kaartnummers = new ArrayList<>(); while(ovChipkaartenNummers.next()) { kaartnummers.add(ovChipkaartenNummers.getInt("kaart_nummer")); } for(int kaartNummer : kaartnummers) { boolean isFound = false; for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { if(ovChipkaart.getKaartnummer() == kaartNummer) { isFound = true; break; } } //Als ovchipkaart_nummer<SUF> if(!isFound) { //Verwijder relatie PreparedStatement deleteRelationStatement = connection.prepareStatement("DELETE FROM ov_chipkaart_product WHERE kaart_nummer=? AND product_nummer=?"); deleteRelationStatement.setInt(1, kaartNummer); deleteRelationStatement.setInt(2, product.getNummer()); deleteRelationStatement.executeUpdate(); deleteRelationStatement.close(); } } //INSERT relaties als niet bestaat for(OVChipkaart ovChipkaart : product.getOvChipkaarten()) { boolean isFound = false; for(int kaartNummer : kaartnummers) { if(ovChipkaart.getKaartnummer() == kaartNummer) { isFound = true; break; } } if(!isFound) { PreparedStatement updateRelationStatement = connection.prepareStatement("INSERT INTO ov_chipkaart_product (kaart_nummer, product_nummer) VALUES (?, ?)"); updateRelationStatement.setInt(1, ovChipkaart.getKaartnummer()); updateRelationStatement.setInt(2, product.getNummer()); updateRelationStatement.executeUpdate(); updateRelationStatement.close(); } } }catch(SQLException ex) { System.err.println("[SQLException] Updaten van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public boolean delete(Product product) { boolean isSuccess = false; try { // Delete relation (OVChipkaart - Product) PreparedStatement deleteRelationStatement = connection.prepareStatement("DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"); deleteRelationStatement.setInt(1, product.getNummer()); deleteRelationStatement.executeUpdate(); deleteRelationStatement.close(); // Delete product PreparedStatement deleteProductStatement = connection.prepareStatement("DELETE FROM product WHERE product_nummer=?"); deleteProductStatement.setInt(1, product.getNummer()); int resultSet = deleteProductStatement.executeUpdate(); if(resultSet > 0) { isSuccess = true; } deleteProductStatement.close(); }catch(SQLException ex) { System.err.println("[SQLException] Verwijderen van product niet gelukt: " + ex.getMessage()); } return isSuccess; } @Override public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) { List<Product> producten = new ArrayList<>(); try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT product.product_nummer, product.naam, product.beschrijving, product.prijs FROM ov_chipkaart_product JOIN product ON ov_chipkaart_product.product_nummer = product.product_nummer WHERE ov_chipkaart_product.kaart_nummer = ?"); preparedStatement.setInt(1, ovChipkaart.getKaartnummer()); ResultSet products = preparedStatement.executeQuery(); //Haal alle producten op while (products.next()) { int productNummer = products.getInt("product_nummer"); String naam = products.getString("naam"); String beschrijving = products.getString("beschrijving"); double prijs = products.getDouble("prijs"); Product product = new Product(productNummer, naam, beschrijving, prijs); producten.add(product); } }catch(SQLException ex) { System.err.println("Er is iets fout gegaan bij het ophalen van alle producten: " + ex.getMessage()); } return producten; } @Override public List<Product> findAll() { List<Product> producten = new ArrayList<>(); try { Statement statement = connection.createStatement(); ResultSet products = statement.executeQuery("SELECT * FROM product"); //Haal alle producten op while (products.next()) { int productNummer = products.getInt("product_nummer"); String naam = products.getString("naam"); String beschrijving = products.getString("beschrijving"); double prijs = products.getDouble("prijs"); Product product = new Product(productNummer, naam, beschrijving, prijs); List<OVChipkaart> ovChipkaarten = ovChipkaartDAO.findByProduct(product); for(OVChipkaart ovChipkaart : ovChipkaarten) { product.voegOvChipkaartToe(ovChipkaart); } producten.add(product); } statement.close(); products.close(); }catch(SQLException ex) { System.err.println("Er is iets fout gegaan bij het ophalen van alle producten: " + ex.getMessage()); } return producten; } }
22642_1
package Database; import Model.Cause; import java.sql.*; import java.util.ArrayList; public class CauseDAO { public ArrayList<String> getAllPossibleCauses() { //MOET HIER GEEN METHODE IN DIE DUPLICATES VERWIJDERT? Heb 'DISTINCT' toegevoegd bij select hiervoor? Connection con = null; try { con = DBHandler.getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql = "SELECT causeName " + "FROM cause"; ResultSet srs = stmt.executeQuery(sql); ArrayList<String> causes = new ArrayList<>(); while (srs.next()) causes.add(srs.getString("causeName")); return causes; } catch (DBException dbe) { dbe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return null; } public void saveCause (Cause cause) { Connection con = null; try { con = DBHandler.getConnection(); // INSERT String sqlInsert = "INSERT into cause " + "(causeName) " + "VALUES (?)"; //System.out.println(sql); PreparedStatement insertStm = con.prepareStatement(sqlInsert); insertStm.setString(1, cause.getCauseName()); insertStm.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } } //DeleteCause, als we deze houden moeten we ook een saveCause toevoegen!! public void deleteCause(Cause cause) { Connection con = null; try { con = DBHandler.getConnection(); String sql ="DELETE FROM cause " + "WHERE causeName = ?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,cause.getCauseName()); stmt.executeUpdate(); } catch (DBException dbe) { dbe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } }
rwultepu/ISproject
src/Database/CauseDAO.java
606
//DeleteCause, als we deze houden moeten we ook een saveCause toevoegen!!
line_comment
nl
package Database; import Model.Cause; import java.sql.*; import java.util.ArrayList; public class CauseDAO { public ArrayList<String> getAllPossibleCauses() { //MOET HIER GEEN METHODE IN DIE DUPLICATES VERWIJDERT? Heb 'DISTINCT' toegevoegd bij select hiervoor? Connection con = null; try { con = DBHandler.getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql = "SELECT causeName " + "FROM cause"; ResultSet srs = stmt.executeQuery(sql); ArrayList<String> causes = new ArrayList<>(); while (srs.next()) causes.add(srs.getString("causeName")); return causes; } catch (DBException dbe) { dbe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return null; } public void saveCause (Cause cause) { Connection con = null; try { con = DBHandler.getConnection(); // INSERT String sqlInsert = "INSERT into cause " + "(causeName) " + "VALUES (?)"; //System.out.println(sql); PreparedStatement insertStm = con.prepareStatement(sqlInsert); insertStm.setString(1, cause.getCauseName()); insertStm.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } } //DeleteCause, als<SUF> public void deleteCause(Cause cause) { Connection con = null; try { con = DBHandler.getConnection(); String sql ="DELETE FROM cause " + "WHERE causeName = ?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,cause.getCauseName()); stmt.executeUpdate(); } catch (DBException dbe) { dbe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } }
214383_27
/***************************** AVLBaum.java *********************************/ //import AlgoTools.IO; /** Ein AVLBaum ist ein SuchBaum, bei dem alle Knoten ausgeglichen * sind. Das heisst, die Hoehe aller Teilbaeume unterscheidet sich * maximal um eins. */ package db.avltree; public class AVLBaum extends SuchBaum { private int balance; // Balance public AVLBaum() { // erzeugt leeren AVLBaum balance = 0; } private static class Status { // Innere Klasse zur Uebergabe eines // Status in der Rekursion boolean unbal; // unbal ist true, wenn beim Einfue- // gen ein Sohn groesser geworden ist Status () { // Konstruktor der inneren Klasse unbal = false; // Element noch nicht eingefuegt => } // noch keine Unausgeglichenheit } public String toString() { // fuer Ausgabe: Inhalt(Balance) return inhalt + "(" + balance + ")"; } public boolean insert(Comparable x) throws Exception {// fuegt x in den AVLBaum ein: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion insertAVL return insertAVL(x, new Status()); } private boolean insertAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode zum // Einfuegen (rekursiv) boolean eingefuegt; if (empty()) { // Blatt: Hier kann eingefuegt werden inhalt = x; // Inhalt setzen links = new AVLBaum(); // Neuer leerer AVLBaum links rechts = new AVLBaum(); // Neuer leerer AVLBaum rechts s.unbal = true; // Dieser Teilbaum wurde groesser return true; // Einfuegen erfolgreich und } // dieser Teilbaum groesser else if (((Comparable) value()).compareTo(x) == 0) // Element schon im AVLBaum return false; else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => eingefuegt = ((AVLBaum) left()).insertAVL(x, s); // linker Teilbaum if (s.unbal) { // Linker Teilbaum wurde groesser switch (balance) { case 1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = -1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) links).balance == -1) rotateLL(); else rotateLR(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } else { // Element ist groesser => eingefuegt = ((AVLBaum) right()).insertAVL(x, s);// rechter Teilbaum if (s.unbal) { // Rechter Teilbaum wurde groesser switch (balance) { case -1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = 1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) rechts).balance == 1) rotateRR(); else rotateRL(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } return eingefuegt; // Keine Rotation => Ergebnis zurueck } public void rotateLL() { //IO.println("LL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) rechts; // und rechten Teilbaum // Idee: Inhalt von a1 in die Wurzel links = a1.links; // Setze neuen linken Sohn rechts = a1; // Setze neuen rechten Sohn a1.links = a1.rechts; // Setze dessen linken a1.rechts = a2; // und rechten Sohn Object tmp = a1.inhalt; // Inhalt von rechts (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) rechts).balance = 0; // rechter Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateLR() { //IO.println("LR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) a1.rechts; // und dessen rechten Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.rechts = a2.links; // Setze Soehne von a2 a2.links = a2.rechts; a2.rechts = rechts; rechts = a2; // a2 wird neuer rechter Sohn Object tmp = inhalt; // Inhalt von rechts (==a2) inhalt = rechts.inhalt; // wird mit Wurzel rechts.inhalt = tmp; // getauscht if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; balance = 0; // Wurzel balanciert } public void rotateRR() { //IO.println("RR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten AVLBaum a2 = (AVLBaum) links; // und linken Teilbaum // Idee: Inhalt von a1 in die Wurzel rechts = a1.rechts; // Setze neuen rechten Sohn links = a1; // Setze neuen linken Sohn a1.rechts = a1.links; // Setze dessen rechten a1.links = a2; // und linken Sohn Object tmp = a1.inhalt; // Inhalt von links (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) links).balance = 0; // linker Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateRL() { //IO.println("RL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten Sohn AVLBaum a2 = (AVLBaum) a1.links; // und dessen linken Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.links = a2.rechts; a2.rechts = a2.links; // Setze Soehne von a2 a2.links = links; links = a2; // a2 wird neuer linker Sohn Object tmp = inhalt; // Inhalt von links (==a2) inhalt = links.inhalt; // wird mit Wurzel links.inhalt = tmp; // getauscht if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; balance = 0; // Wurzel balanciert } @Override public boolean delete(Comparable x) throws Exception {// loescht x im AVLBaum: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion deleteAVL return deleteAVL(x, new Status()); } private boolean deleteAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode // zum Loeschen (rekursiv); true, wenn erfolgreich boolean geloescht; // true, wenn geloescht wurde if (empty()) { // Blatt: Element nicht gefunden return false; // => Einfuegen erfolglos } else if (((Comparable) value()).compareTo(x) < 0) { // Element x ist groesser => // Suche rechts weiter geloescht = ((AVLBaum) rechts).deleteAVL(x, s); if (s.unbal == true) balance2(s); // Gleiche ggf. aus return geloescht; } else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => // Suche links weiter geloescht = ((AVLBaum) links).deleteAVL(x, s); if (s.unbal == true) balance1(s); // Gleiche ggf. aus return geloescht; } else { // Element gefunden if (rechts.empty()) { // Kein rechter Sohn inhalt = links.inhalt; // ersetze Knoten durch linken Sohn links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else if (links.empty()) { // Kein linker Sohn inhalt = rechts.inhalt; // ersetze Knoten durch rechten Sohn rechts = rechts.rechts; // Kein rechter Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else { // Beide Soehne vorhanden inhalt = ((AVLBaum) links).del(s); // Rufe del() auf if (s.unbal) { // Gleiche Unbalance aus balance1(s); } } return true; // Loeschen erfolgreich } } private Object del(Status s) { // Sucht Ersatz fuer gel. Objekt Object ersatz; // Das Ersatz-Objekt if (!rechts.empty()) { // Suche groessten Sohn im Teilbaum ersatz = ((AVLBaum) rechts).del(s); if (s.unbal) // Gleicht ggf. Unbalance aus balance2(s); } else { // Tausche mit geloeschtem Knoten ersatz = inhalt; // Merke Ersatz und inhalt = links.inhalt; // ersetze Knoten durch linken Sohn. links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Teilbaum wurde kuerzer } return ersatz; // Gib Ersatz-Objekt zurueck } private void balance1(Status s) { // Unbalance, weil linker Ast kuerzer switch (balance) { case -1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = 1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) rechts).balance; //Merke Balance des rechten Sohns if (b >= 0) { rotateRR(); if (b == 0) { // Gleiche neue Balancen an balance = -1; ((AVLBaum) links).balance = 1; s.unbal = false; } } else rotateRL(); break; } } private void balance2(Status s) { // Unbalance, weil recht. Ast kuerzer switch (balance) { case 1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = -1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) links).balance; // Merke Balance des linken Sohns if (b <= 0) { rotateLL(); if (b == 0) { // Gleiche neue Balancen an balance = 1; ((AVLBaum) rechts).balance = -1; s.unbal = false; } } else rotateLR(); break; } } }
sPyOpenSource/os
src/db/avltree/AVLBaum.java
4,085
// Element ist groesser =>
line_comment
nl
/***************************** AVLBaum.java *********************************/ //import AlgoTools.IO; /** Ein AVLBaum ist ein SuchBaum, bei dem alle Knoten ausgeglichen * sind. Das heisst, die Hoehe aller Teilbaeume unterscheidet sich * maximal um eins. */ package db.avltree; public class AVLBaum extends SuchBaum { private int balance; // Balance public AVLBaum() { // erzeugt leeren AVLBaum balance = 0; } private static class Status { // Innere Klasse zur Uebergabe eines // Status in der Rekursion boolean unbal; // unbal ist true, wenn beim Einfue- // gen ein Sohn groesser geworden ist Status () { // Konstruktor der inneren Klasse unbal = false; // Element noch nicht eingefuegt => } // noch keine Unausgeglichenheit } public String toString() { // fuer Ausgabe: Inhalt(Balance) return inhalt + "(" + balance + ")"; } public boolean insert(Comparable x) throws Exception {// fuegt x in den AVLBaum ein: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion insertAVL return insertAVL(x, new Status()); } private boolean insertAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode zum // Einfuegen (rekursiv) boolean eingefuegt; if (empty()) { // Blatt: Hier kann eingefuegt werden inhalt = x; // Inhalt setzen links = new AVLBaum(); // Neuer leerer AVLBaum links rechts = new AVLBaum(); // Neuer leerer AVLBaum rechts s.unbal = true; // Dieser Teilbaum wurde groesser return true; // Einfuegen erfolgreich und } // dieser Teilbaum groesser else if (((Comparable) value()).compareTo(x) == 0) // Element schon im AVLBaum return false; else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => eingefuegt = ((AVLBaum) left()).insertAVL(x, s); // linker Teilbaum if (s.unbal) { // Linker Teilbaum wurde groesser switch (balance) { case 1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = -1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) links).balance == -1) rotateLL(); else rotateLR(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } else { // Element ist<SUF> eingefuegt = ((AVLBaum) right()).insertAVL(x, s);// rechter Teilbaum if (s.unbal) { // Rechter Teilbaum wurde groesser switch (balance) { case -1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = 1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) rechts).balance == 1) rotateRR(); else rotateRL(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } return eingefuegt; // Keine Rotation => Ergebnis zurueck } public void rotateLL() { //IO.println("LL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) rechts; // und rechten Teilbaum // Idee: Inhalt von a1 in die Wurzel links = a1.links; // Setze neuen linken Sohn rechts = a1; // Setze neuen rechten Sohn a1.links = a1.rechts; // Setze dessen linken a1.rechts = a2; // und rechten Sohn Object tmp = a1.inhalt; // Inhalt von rechts (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) rechts).balance = 0; // rechter Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateLR() { //IO.println("LR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) a1.rechts; // und dessen rechten Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.rechts = a2.links; // Setze Soehne von a2 a2.links = a2.rechts; a2.rechts = rechts; rechts = a2; // a2 wird neuer rechter Sohn Object tmp = inhalt; // Inhalt von rechts (==a2) inhalt = rechts.inhalt; // wird mit Wurzel rechts.inhalt = tmp; // getauscht if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; balance = 0; // Wurzel balanciert } public void rotateRR() { //IO.println("RR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten AVLBaum a2 = (AVLBaum) links; // und linken Teilbaum // Idee: Inhalt von a1 in die Wurzel rechts = a1.rechts; // Setze neuen rechten Sohn links = a1; // Setze neuen linken Sohn a1.rechts = a1.links; // Setze dessen rechten a1.links = a2; // und linken Sohn Object tmp = a1.inhalt; // Inhalt von links (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) links).balance = 0; // linker Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateRL() { //IO.println("RL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten Sohn AVLBaum a2 = (AVLBaum) a1.links; // und dessen linken Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.links = a2.rechts; a2.rechts = a2.links; // Setze Soehne von a2 a2.links = links; links = a2; // a2 wird neuer linker Sohn Object tmp = inhalt; // Inhalt von links (==a2) inhalt = links.inhalt; // wird mit Wurzel links.inhalt = tmp; // getauscht if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; balance = 0; // Wurzel balanciert } @Override public boolean delete(Comparable x) throws Exception {// loescht x im AVLBaum: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion deleteAVL return deleteAVL(x, new Status()); } private boolean deleteAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode // zum Loeschen (rekursiv); true, wenn erfolgreich boolean geloescht; // true, wenn geloescht wurde if (empty()) { // Blatt: Element nicht gefunden return false; // => Einfuegen erfolglos } else if (((Comparable) value()).compareTo(x) < 0) { // Element x ist groesser => // Suche rechts weiter geloescht = ((AVLBaum) rechts).deleteAVL(x, s); if (s.unbal == true) balance2(s); // Gleiche ggf. aus return geloescht; } else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => // Suche links weiter geloescht = ((AVLBaum) links).deleteAVL(x, s); if (s.unbal == true) balance1(s); // Gleiche ggf. aus return geloescht; } else { // Element gefunden if (rechts.empty()) { // Kein rechter Sohn inhalt = links.inhalt; // ersetze Knoten durch linken Sohn links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else if (links.empty()) { // Kein linker Sohn inhalt = rechts.inhalt; // ersetze Knoten durch rechten Sohn rechts = rechts.rechts; // Kein rechter Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else { // Beide Soehne vorhanden inhalt = ((AVLBaum) links).del(s); // Rufe del() auf if (s.unbal) { // Gleiche Unbalance aus balance1(s); } } return true; // Loeschen erfolgreich } } private Object del(Status s) { // Sucht Ersatz fuer gel. Objekt Object ersatz; // Das Ersatz-Objekt if (!rechts.empty()) { // Suche groessten Sohn im Teilbaum ersatz = ((AVLBaum) rechts).del(s); if (s.unbal) // Gleicht ggf. Unbalance aus balance2(s); } else { // Tausche mit geloeschtem Knoten ersatz = inhalt; // Merke Ersatz und inhalt = links.inhalt; // ersetze Knoten durch linken Sohn. links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Teilbaum wurde kuerzer } return ersatz; // Gib Ersatz-Objekt zurueck } private void balance1(Status s) { // Unbalance, weil linker Ast kuerzer switch (balance) { case -1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = 1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) rechts).balance; //Merke Balance des rechten Sohns if (b >= 0) { rotateRR(); if (b == 0) { // Gleiche neue Balancen an balance = -1; ((AVLBaum) links).balance = 1; s.unbal = false; } } else rotateRL(); break; } } private void balance2(Status s) { // Unbalance, weil recht. Ast kuerzer switch (balance) { case 1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = -1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) links).balance; // Merke Balance des linken Sohns if (b <= 0) { rotateLL(); if (b == 0) { // Gleiche neue Balancen an balance = 1; ((AVLBaum) rechts).balance = -1; s.unbal = false; } } else rotateLR(); break; } } }
201663_30
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2017-Present 8x8, 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 org.jitsi.jicofo.jibri; import edu.umd.cs.findbugs.annotations.*; import org.jetbrains.annotations.Nullable; import org.jitsi.jicofo.*; import org.jitsi.jicofo.xmpp.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import org.jetbrains.annotations.*; import org.jitsi.utils.logging2.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas * * This is not meant to be `public`, but has to be exposed because of compatibility with kotlin (JibriStats.kt takes * a parameter type that exposes JibriSession and it can not be restricted to java's "package private"). */ public class JibriSession { /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(Status status) { return Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. * TODO: Fix the inconsistent synchronization */ @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for events from the {@link JibriDetector}. */ private final JibriDetectorEventHandler jibriEventHandler = new JibriDetectorEventHandler(); /** * Current Jibri recording status. */ private Status jibriStatus = Status.UNDEFINED; private final Logger logger; /** * The listener which will be notified about status changes of this session. */ private final StateListener stateListener; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link AbstractXMPPConnection} instance used to send/listen for XMPP packets. */ private final AbstractXMPPConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; @NotNull private final JibriStats stats = JibriStats.getGlobalStats(); /** * Creates new {@link JibriSession} instance. * @param stateListener the listener to be notified about this session state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( StateListener stateListener, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, AbstractXMPPConnection connection, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.stateListener = stateListener; this.roomName = roomName; this.initiator = initiator; this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; jibriDetector.addHandler(jibriEventHandler); logger = new LoggerImpl(getClass().getName(), logLevelDelegate.getLevel()); } /** * Used internally to call * {@link StateListener#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } stateListener.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException.AllBusy(); } throw new StartException.NotAvailable(); } try { logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); if (!(e instanceof StartException.OneBusy)) { jibriDetector.memberHadTransientError(jibriJid); } if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException.InternalServerError(); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; jibriDetector.removeHandler(jibriEventHandler); } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status Status status = iq.getStatus(); if (!Status.UNDEFINED.equals(status)) { logger.info("Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) throws SmackException.NotConnectedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = UtilKt.sendIqAndGetResponse(xmpp, startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException.UnexpectedResponse(); } JibriIq jibriIq = (JibriIq) reply; if (isBusyResponse(jibriIq)) { logger.info("Jibri " + jibriIq.getFrom() + " was busy"); throw new StartException.OneBusy(); } if (!isPendingResponse(jibriIq)) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException.UnexpectedResponse(); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = TaskPools.getScheduledPool().schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.warn("Failed to fall back to another Jibri, this session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface StateListener { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, Status newStatus, FailureReason failureReason); } static public abstract class StartException extends Exception { public StartException(String message) { super(message); } static public class AllBusy extends StartException { public AllBusy() { super("All jibri instances are busy"); } } static public class InternalServerError extends StartException { public InternalServerError() { super("Internal server error"); } } static public class NotAvailable extends StartException { public NotAvailable() { super("No Jibris available"); } } static public class UnexpectedResponse extends StartException { public UnexpectedResponse() { super("Unexpected response"); } } static public class OneBusy extends StartException { public OneBusy() { super("This Jibri instance was busy"); } } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } private class JibriDetectorEventHandler implements JibriDetector.EventHandler { @Override public void instanceOffline(Jid jid) { if (jid.equals(currentJibriJid)) { logger.warn(nickname() + " went offline: " + jid + " for room: " + roomName); handleJibriStatusUpdate( jid, Status.OFF, FailureReason.ERROR, true); } } } /** * Returns true if the given IQ represens a busy response from Jibri */ private boolean isBusyResponse(JibriIq iq) { return Status.OFF.equals(iq.getStatus()) && iq.isFailure() && FailureReason.BUSY.equals(iq.getFailureReason()); } private boolean isPendingResponse(JibriIq iq) { return Status.PENDING.equals(iq.getStatus()); } }
saal-core/blync-jicofo
src/main/java/org/jitsi/jicofo/jibri/JibriSession.java
7,967
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2017-Present 8x8, 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 org.jitsi.jicofo.jibri; import edu.umd.cs.findbugs.annotations.*; import org.jetbrains.annotations.Nullable; import org.jitsi.jicofo.*; import org.jitsi.jicofo.xmpp.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import org.jetbrains.annotations.*; import org.jitsi.utils.logging2.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas * * This is not meant to be `public`, but has to be exposed because of compatibility with kotlin (JibriStats.kt takes * a parameter type that exposes JibriSession and it can not be restricted to java's "package private"). */ public class JibriSession { /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(Status status) { return Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. * TODO: Fix the inconsistent synchronization */ @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for events from the {@link JibriDetector}. */ private final JibriDetectorEventHandler jibriEventHandler = new JibriDetectorEventHandler(); /** * Current Jibri recording status. */ private Status jibriStatus = Status.UNDEFINED; private final Logger logger; /** * The listener which will be notified about status changes of this session. */ private final StateListener stateListener; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link AbstractXMPPConnection} instance used to send/listen for XMPP packets. */ private final AbstractXMPPConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; @NotNull private final JibriStats stats = JibriStats.getGlobalStats(); /** * Creates new {@link JibriSession} instance. * @param stateListener the listener to be notified about this session state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( StateListener stateListener, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, AbstractXMPPConnection connection, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.stateListener = stateListener; this.roomName = roomName; this.initiator = initiator; this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; jibriDetector.addHandler(jibriEventHandler); logger = new LoggerImpl(getClass().getName(), logLevelDelegate.getLevel()); } /** * Used internally to call * {@link StateListener#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } stateListener.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException.AllBusy(); } throw new StartException.NotAvailable(); } try { logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); if (!(e instanceof StartException.OneBusy)) { jibriDetector.memberHadTransientError(jibriJid); } if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException.InternalServerError(); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; jibriDetector.removeHandler(jibriEventHandler); } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status Status status = iq.getStatus(); if (!Status.UNDEFINED.equals(status)) { logger.info("Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) throws SmackException.NotConnectedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = UtilKt.sendIqAndGetResponse(xmpp, startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException.UnexpectedResponse(); } JibriIq jibriIq = (JibriIq) reply; if (isBusyResponse(jibriIq)) { logger.info("Jibri " + jibriIq.getFrom() + " was busy"); throw new StartException.OneBusy(); } if (!isPendingResponse(jibriIq)) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException.UnexpectedResponse(); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = TaskPools.getScheduledPool().schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.warn("Failed to fall back to another Jibri, this session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface StateListener { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, Status newStatus, FailureReason failureReason); } static public abstract class StartException extends Exception { public StartException(String message) { super(message); } static public class AllBusy extends StartException { public AllBusy() { super("All jibri instances are busy"); } } static public class InternalServerError extends StartException { public InternalServerError() { super("Internal server error"); } } static public class NotAvailable extends StartException { public NotAvailable() { super("No Jibris available"); } } static public class UnexpectedResponse extends StartException { public UnexpectedResponse() { super("Unexpected response"); } } static public class OneBusy extends StartException { public OneBusy() { super("This Jibri instance was busy"); } } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } private class JibriDetectorEventHandler implements JibriDetector.EventHandler { @Override public void instanceOffline(Jid jid) { if (jid.equals(currentJibriJid)) { logger.warn(nickname() + " went offline: " + jid + " for room: " + roomName); handleJibriStatusUpdate( jid, Status.OFF, FailureReason.ERROR, true); } } } /** * Returns true if the given IQ represens a busy response from Jibri */ private boolean isBusyResponse(JibriIq iq) { return Status.OFF.equals(iq.getStatus()) && iq.isFailure() && FailureReason.BUSY.equals(iq.getFailureReason()); } private boolean isPendingResponse(JibriIq iq) { return Status.PENDING.equals(iq.getStatus()); } }
19607_1
package nl.bitsentools.eindprojectbackendmetabo.utils; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import org.springframework.stereotype.Service; import java.security.Key; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.userdetails.UserDetails; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @Service public class JwtUtil { private final static String SECRET_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // TODO vul hier je super geheime sleutel in nu aaaa maar id dat genoeg???*/; private Key getSigningKey() { byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY); return Keys.hmacShaKeyFor(keyBytes); } public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } private Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { final Claims claims = extractAllClaims(token); return claimsResolver.apply(claims); } private Claims extractAllClaims(String token) { return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return createToken(claims, userDetails.getUsername()); } private String createToken(Map<String, Object> claims, String subject) { return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30L)) //TODO: de JWT vervalt nu na 24 uur. Nu aangepast naar 30L. .signWith(getSigningKey() ,SignatureAlgorithm.HS256) .compact(); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } }
saarryp/BA-EindProject-Metabo
src/main/java/nl/bitsentools/eindprojectbackendmetabo/utils/JwtUtil.java
718
//TODO: de JWT vervalt nu na 24 uur. Nu aangepast naar 30L.
line_comment
nl
package nl.bitsentools.eindprojectbackendmetabo.utils; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import org.springframework.stereotype.Service; import java.security.Key; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.userdetails.UserDetails; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @Service public class JwtUtil { private final static String SECRET_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // TODO vul hier je super geheime sleutel in nu aaaa maar id dat genoeg???*/; private Key getSigningKey() { byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY); return Keys.hmacShaKeyFor(keyBytes); } public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } private Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { final Claims claims = extractAllClaims(token); return claimsResolver.apply(claims); } private Claims extractAllClaims(String token) { return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return createToken(claims, userDetails.getUsername()); } private String createToken(Map<String, Object> claims, String subject) { return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30L)) //TODO: de<SUF> .signWith(getSigningKey() ,SignatureAlgorithm.HS256) .compact(); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } }
130863_33
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.clas.modules; import java.awt.Color; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.clas.view.DetectorShape2D; import org.clas.viewer.FTCalibrationModule; import org.clas.viewer.FTDetector; import org.jlab.clas.pdg.PhysicsConstants; import org.jlab.clas.physics.Particle; import org.jlab.detector.calib.utils.CalibrationConstants; import org.jlab.groot.base.ColorPalette; import org.jlab.groot.data.H1F; import org.jlab.groot.group.DataGroup; import org.jlab.io.base.DataBank; import org.jlab.io.base.DataEvent; import org.jlab.groot.math.F1D; import org.jlab.groot.fitter.DataFitter; import org.jlab.groot.data.GraphErrors; import org.jlab.groot.data.H2F; import org.jlab.utils.groups.IndexedList; /** * * @author devita */ public class FTEnergyCalibration extends FTCalibrationModule { // analysis realted info double nsPerSample=4; double LSB = 0.4884; double clusterEnergyThr = 500.0;// Vertical selection int clusterSizeThr = 9;// Vertical selection // double singleChThr = 0.00;// Single channel selection MeV // double signalThr =0.0; // double simSignalThr=0.00;// Threshold used for simulated events in MeV // double startTime = 124.25;//ns // double ftcalDistance =1898; //mm // double timeshift =0;// ns // double crystal_size = 15.3;//mm double charge2e = 15.3/6.005; //MeV // double crystal_length = 200;//mm // double shower_depth = 65; // double light_speed = 150; //cm/ns // double c = 29.97; //cm/ns public FTEnergyCalibration(FTDetector d, String name) { super(d, name, "offset:offset_error:resolution",3); } @Override public void resetEventListener() { H1F hpi0sum = new H1F("hpi0sum", 100,0., 300.); hpi0sum.setTitleX("M (MeV)"); hpi0sum.setTitleY("Counts"); hpi0sum.setTitle("2#gamma invariant mass"); hpi0sum.setFillColor(3); H1F hpi0sum_calib = new H1F("hpi0sum_calib", 100,0., 300.); hpi0sum_calib.setTitleX("M (MeV)"); hpi0sum_calib.setTitleY("counts"); hpi0sum_calib.setTitle("2#gamma invariant mass"); hpi0sum_calib.setFillColor(44); H2F hmassangle = new H2F("hmassangle", 100, 0., 300., 100, 0., 6.); hmassangle.setTitleX("M (MeV)"); hmassangle.setTitleY("Angle (deg)"); hmassangle.setTitle("Angle vs. Mass"); for (int key : this.getDetector().getDetectorComponents()) { // initializa calibration constant table this.getCalibrationTable().addEntry(1, 1, key); // initialize data group H1F hpi0 = new H1F("hpi0_" + key, 100,0., 300.); hpi0.setTitleX("M (MeV)"); hpi0.setTitleY("Counts"); hpi0.setTitle("Component " + key); H1F hpi0_calib = new H1F("hpi0_calib_" + key, 100,0., 300.); hpi0_calib.setTitleX("M (MeV)"); hpi0_calib.setTitleY("Counts"); hpi0_calib.setTitle("Component " + key); H2F hcal2d = new H2F("hcal2d_" + key, 100, 0, 5000, 100, 0, 5000); hcal2d.setTitleX("Calculated Energy (MeV)"); hcal2d.setTitleY("Measured Energy (MeV)"); hcal2d.setTitle("Component " + key); H1F hcal = new H1F("hcal_" + key, 100, 0, 2); hcal.setTitleX("Correction Factor"); hcal.setTitleY("Counts"); hcal.setTitle("Component " + key); H1F htime_calib = new H1F("htime_calib_" + key, 300, -15.0, 15.0); htime_calib.setTitleX("Time (ns)"); htime_calib.setTitleY("Counts"); htime_calib.setTitle("Component " + key); htime_calib.setFillColor(44); htime_calib.setLineColor(24); F1D ftime = new F1D("ftime_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.); ftime.setParameter(0, 0.0); ftime.setParameter(1, 0.0); ftime.setParameter(2, 2.0); ftime.setLineColor(24); ftime.setLineWidth(2); // ftime.setLineColor(2); // ftime.setLineStyle(1); DataGroup dg = new DataGroup(3, 2); dg.addDataSet(hpi0sum , 0); dg.addDataSet(hpi0sum_calib, 0); dg.addDataSet(hmassangle, 1); dg.addDataSet(hpi0, 3); dg.addDataSet(hpi0_calib, 3); dg.addDataSet(hcal2d, 4); dg.addDataSet(hcal, 5); // dg.addDataSet(ftime, 3); this.getDataGroup().add(dg, 1, 1, key); } getCalibrationTable().fireTableDataChanged(); } @Override public List<CalibrationConstants> getCalibrationConstants() { return Arrays.asList(getCalibrationTable()); } public int getNEvents(int isec, int ilay, int icomp) { return this.getDataGroup().getItem(1, 1, icomp).getH1F("hpi0_" + icomp).getEntries(); } public void processEvent(DataEvent event) { // loop over FTCAL reconstructed cluster if (event.hasBank("FTCAL::clusters") && event.hasBank("FTCAL::adc")) { ArrayList<Particle> ftParticles = new ArrayList(); DataBank clusterFTCAL = event.getBank("FTCAL::clusters");//if(recFTCAL.rows()>1)System.out.println(" recFTCAL.rows() "+recFTCAL.rows()); DataBank adcFTCAL = event.getBank("FTCAL::adc"); for (int loop = 0; loop < clusterFTCAL.rows(); loop++) { int key = getDetector().getComponent(clusterFTCAL.getFloat("x", loop), clusterFTCAL.getFloat("y", loop)); int size = clusterFTCAL.getShort("size", loop); double x = clusterFTCAL.getFloat("x", loop); double y = clusterFTCAL.getFloat("y", loop); double z = clusterFTCAL.getFloat("z", loop); double energy = 1e3 * clusterFTCAL.getFloat("energy", loop); double energyR = 1e3 * clusterFTCAL.getFloat("recEnergy", loop); double path = Math.sqrt(x*x+y*y+z*z); double energySeed=0; for(int k=0; k<adcFTCAL.rows(); k++) { double energyK = ((double) adcFTCAL.getInt("ADC", k))*(LSB*nsPerSample/50)*charge2e; if(key == adcFTCAL.getInt("component", k) && energyK>energySeed) energySeed = energyK; } Particle recParticle = new Particle(22, energy*x/path, energy*y/path, energy*z/path, 0,0,0); recParticle.setProperty("key",(double) key); recParticle.setProperty("energySeed",energySeed); if(energyR>this.clusterEnergyThr && size>this.clusterSizeThr) ftParticles.add(recParticle); } if(ftParticles.size()>=2) { for (int i1 = 0; i1 < ftParticles.size(); i1++) { for (int i2 = i1 + 1; i2 < ftParticles.size(); i2++) { int key1 = (int) ftParticles.get(i1).getProperty("key"); int key2 = (int) ftParticles.get(i2).getProperty("key"); Particle partGamma1 = ftParticles.get(i1); Particle partGamma2 = ftParticles.get(i2); Particle partPi0 = new Particle(); partPi0.copy(partGamma1); partPi0.combine(partGamma2, +1); double invmass = Math.sqrt(partPi0.mass2()); double x = (partGamma1.p() - partGamma2.p()) / (partGamma1.p() + partGamma2.p()); double angle = Math.toDegrees(Math.acos(partGamma1.cosTheta(partGamma2))); this.getDataGroup().getItem(1, 1, key1).getH1F("hpi0sum").fill(invmass); this.getDataGroup().getItem(1, 1, key1).getH2F("hmassangle").fill(invmass, angle); this.getDataGroup().getItem(1, 1, key2).getH1F("hpi0sum").fill(invmass); this.getDataGroup().getItem(1, 1, key2).getH2F("hmassangle").fill(invmass, angle); if(angle>1.) { double ecal1 = Math.pow(PhysicsConstants.massPionNeutral()*1.0E3,2)/(2*partGamma2.p()*(1-Math.cos(Math.toRadians(angle))))-(partGamma1.p()-partGamma1.getProperty("energySeed")); double ecal2 = Math.pow(PhysicsConstants.massPionNeutral()*1.0E3,2)/(2*partGamma1.p()*(1-Math.cos(Math.toRadians(angle))))-(partGamma2.p()-partGamma2.getProperty("energySeed")); // ecal1=partPi0.mass2()/(2*partGamma1.p()*partGamma2.p()*(1-partGamma1.cosTheta(partGamma2))); // System.out.println(ecal1 + " " + partGamma1.p()+ " " + partGamma1.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key1).getH1F("hpi0_" + key1).fill(invmass); this.getDataGroup().getItem(1, 1, key1).getH2F("hcal2d_" + key1).fill(ecal1,partGamma1.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key1).getH1F("hcal_" + key1).fill(partGamma1.getProperty("energySeed")/ecal1); this.getDataGroup().getItem(1, 1, key2).getH1F("hpi0_" + key2).fill(invmass); this.getDataGroup().getItem(1, 1, key2).getH2F("hcal2d_" + key2).fill(ecal2,partGamma2.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key2).getH1F("hcal_" + key2).fill(partGamma2.getProperty("energySeed")/ecal2); } } } } } } public void analyze() { // System.out.println("Analyzing"); // for (int key : this.getDetector().getDetectorComponents()) { // this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").reset(); // } // for (int key : this.getDetector().getDetectorComponents()) { // H1F htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_" + key); // F1D ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_" + key); // this.initTimeGaussFitPar(ftime,htime); // DataFitter.fit(ftime,htime,"LQ"); // // this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").addPoint(key, ftime.getParameter(1), 0, ftime.parameter(1).error()); // // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(1), "offset", 1, 1, key); // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).parameter(1).error(), "offset_error", 1, 1, key); // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(2), "resolution" , 1, 1, key); // } // getCalibrationTable().fireTableDataChanged(); } private void initTimeGaussFitPar(F1D ftime, H1F htime) { double hAmp = htime.getBinContent(htime.getMaximumBin()); double hMean = htime.getAxis().getBinCenter(htime.getMaximumBin()); double hRMS = 2; //ns double rangeMin = (hMean - (0.8*hRMS)); double rangeMax = (hMean + (0.2*hRMS)); double pm = (hMean*3.)/100.0; ftime.setRange(rangeMin, rangeMax); ftime.setParameter(0, hAmp); ftime.setParLimits(0, hAmp*0.8, hAmp*1.2); ftime.setParameter(1, hMean); ftime.setParLimits(1, hMean-pm, hMean+(pm)); ftime.setParameter(2, 0.2); ftime.setParLimits(2, 0.1*hRMS, 0.8*hRMS); } @Override public Color getColor(DetectorShape2D dsd) { // show summary int sector = dsd.getDescriptor().getSector(); int layer = dsd.getDescriptor().getLayer(); int key = dsd.getDescriptor().getComponent(); ColorPalette palette = new ColorPalette(); Color col = new Color(100, 100, 100); if (this.getDetector().hasComponent(key)) { int nent = this.getNEvents(sector, layer, key); if (nent > 0) { col = palette.getColor3D(nent, this.getnProcessed(), true); } } // col = new Color(100, 0, 0); return col; } // @Override // public void processShape(DetectorShape2D dsd) { // // plot histos for the specific component // int sector = dsd.getDescriptor().getSector(); // int layer = dsd.getDescriptor().getLayer(); // int paddle = dsd.getDescriptor().getComponent(); // System.out.println("Selected shape " + sector + " " + layer + " " + paddle); // IndexedList<DataGroup> group = this.getDataGroup(); // // if(group.hasItem(sector,layer,paddle)==true){ // this.getCanvas().clear(); // this.getCanvas().divide(2, 2); // this.getCanvas().cd(0); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htsum")); // this.getCanvas().cd(1); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getGraph("gtoffsets")); // this.getCanvas().cd(2); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htime_wide_" + paddle)); // this.getCanvas().cd(3); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htime_" + paddle)); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getF1D("ftime_" + paddle),"same"); //// this.getCanvas().draw(this.getDataGroup().getItem(sector,layer,paddle)); //// this.getCanvas().update(); // } else { // System.out.println(" ERROR: can not find the data group"); // } // } @Override public void timerUpdate() { this.analyze(); } }
sadhi003/clas12calibration-ft
ftCalCalib/src/main/java/org/clas/modules/FTEnergyCalibration.java
4,894
// int paddle = dsd.getDescriptor().getComponent();
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.clas.modules; import java.awt.Color; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.clas.view.DetectorShape2D; import org.clas.viewer.FTCalibrationModule; import org.clas.viewer.FTDetector; import org.jlab.clas.pdg.PhysicsConstants; import org.jlab.clas.physics.Particle; import org.jlab.detector.calib.utils.CalibrationConstants; import org.jlab.groot.base.ColorPalette; import org.jlab.groot.data.H1F; import org.jlab.groot.group.DataGroup; import org.jlab.io.base.DataBank; import org.jlab.io.base.DataEvent; import org.jlab.groot.math.F1D; import org.jlab.groot.fitter.DataFitter; import org.jlab.groot.data.GraphErrors; import org.jlab.groot.data.H2F; import org.jlab.utils.groups.IndexedList; /** * * @author devita */ public class FTEnergyCalibration extends FTCalibrationModule { // analysis realted info double nsPerSample=4; double LSB = 0.4884; double clusterEnergyThr = 500.0;// Vertical selection int clusterSizeThr = 9;// Vertical selection // double singleChThr = 0.00;// Single channel selection MeV // double signalThr =0.0; // double simSignalThr=0.00;// Threshold used for simulated events in MeV // double startTime = 124.25;//ns // double ftcalDistance =1898; //mm // double timeshift =0;// ns // double crystal_size = 15.3;//mm double charge2e = 15.3/6.005; //MeV // double crystal_length = 200;//mm // double shower_depth = 65; // double light_speed = 150; //cm/ns // double c = 29.97; //cm/ns public FTEnergyCalibration(FTDetector d, String name) { super(d, name, "offset:offset_error:resolution",3); } @Override public void resetEventListener() { H1F hpi0sum = new H1F("hpi0sum", 100,0., 300.); hpi0sum.setTitleX("M (MeV)"); hpi0sum.setTitleY("Counts"); hpi0sum.setTitle("2#gamma invariant mass"); hpi0sum.setFillColor(3); H1F hpi0sum_calib = new H1F("hpi0sum_calib", 100,0., 300.); hpi0sum_calib.setTitleX("M (MeV)"); hpi0sum_calib.setTitleY("counts"); hpi0sum_calib.setTitle("2#gamma invariant mass"); hpi0sum_calib.setFillColor(44); H2F hmassangle = new H2F("hmassangle", 100, 0., 300., 100, 0., 6.); hmassangle.setTitleX("M (MeV)"); hmassangle.setTitleY("Angle (deg)"); hmassangle.setTitle("Angle vs. Mass"); for (int key : this.getDetector().getDetectorComponents()) { // initializa calibration constant table this.getCalibrationTable().addEntry(1, 1, key); // initialize data group H1F hpi0 = new H1F("hpi0_" + key, 100,0., 300.); hpi0.setTitleX("M (MeV)"); hpi0.setTitleY("Counts"); hpi0.setTitle("Component " + key); H1F hpi0_calib = new H1F("hpi0_calib_" + key, 100,0., 300.); hpi0_calib.setTitleX("M (MeV)"); hpi0_calib.setTitleY("Counts"); hpi0_calib.setTitle("Component " + key); H2F hcal2d = new H2F("hcal2d_" + key, 100, 0, 5000, 100, 0, 5000); hcal2d.setTitleX("Calculated Energy (MeV)"); hcal2d.setTitleY("Measured Energy (MeV)"); hcal2d.setTitle("Component " + key); H1F hcal = new H1F("hcal_" + key, 100, 0, 2); hcal.setTitleX("Correction Factor"); hcal.setTitleY("Counts"); hcal.setTitle("Component " + key); H1F htime_calib = new H1F("htime_calib_" + key, 300, -15.0, 15.0); htime_calib.setTitleX("Time (ns)"); htime_calib.setTitleY("Counts"); htime_calib.setTitle("Component " + key); htime_calib.setFillColor(44); htime_calib.setLineColor(24); F1D ftime = new F1D("ftime_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.); ftime.setParameter(0, 0.0); ftime.setParameter(1, 0.0); ftime.setParameter(2, 2.0); ftime.setLineColor(24); ftime.setLineWidth(2); // ftime.setLineColor(2); // ftime.setLineStyle(1); DataGroup dg = new DataGroup(3, 2); dg.addDataSet(hpi0sum , 0); dg.addDataSet(hpi0sum_calib, 0); dg.addDataSet(hmassangle, 1); dg.addDataSet(hpi0, 3); dg.addDataSet(hpi0_calib, 3); dg.addDataSet(hcal2d, 4); dg.addDataSet(hcal, 5); // dg.addDataSet(ftime, 3); this.getDataGroup().add(dg, 1, 1, key); } getCalibrationTable().fireTableDataChanged(); } @Override public List<CalibrationConstants> getCalibrationConstants() { return Arrays.asList(getCalibrationTable()); } public int getNEvents(int isec, int ilay, int icomp) { return this.getDataGroup().getItem(1, 1, icomp).getH1F("hpi0_" + icomp).getEntries(); } public void processEvent(DataEvent event) { // loop over FTCAL reconstructed cluster if (event.hasBank("FTCAL::clusters") && event.hasBank("FTCAL::adc")) { ArrayList<Particle> ftParticles = new ArrayList(); DataBank clusterFTCAL = event.getBank("FTCAL::clusters");//if(recFTCAL.rows()>1)System.out.println(" recFTCAL.rows() "+recFTCAL.rows()); DataBank adcFTCAL = event.getBank("FTCAL::adc"); for (int loop = 0; loop < clusterFTCAL.rows(); loop++) { int key = getDetector().getComponent(clusterFTCAL.getFloat("x", loop), clusterFTCAL.getFloat("y", loop)); int size = clusterFTCAL.getShort("size", loop); double x = clusterFTCAL.getFloat("x", loop); double y = clusterFTCAL.getFloat("y", loop); double z = clusterFTCAL.getFloat("z", loop); double energy = 1e3 * clusterFTCAL.getFloat("energy", loop); double energyR = 1e3 * clusterFTCAL.getFloat("recEnergy", loop); double path = Math.sqrt(x*x+y*y+z*z); double energySeed=0; for(int k=0; k<adcFTCAL.rows(); k++) { double energyK = ((double) adcFTCAL.getInt("ADC", k))*(LSB*nsPerSample/50)*charge2e; if(key == adcFTCAL.getInt("component", k) && energyK>energySeed) energySeed = energyK; } Particle recParticle = new Particle(22, energy*x/path, energy*y/path, energy*z/path, 0,0,0); recParticle.setProperty("key",(double) key); recParticle.setProperty("energySeed",energySeed); if(energyR>this.clusterEnergyThr && size>this.clusterSizeThr) ftParticles.add(recParticle); } if(ftParticles.size()>=2) { for (int i1 = 0; i1 < ftParticles.size(); i1++) { for (int i2 = i1 + 1; i2 < ftParticles.size(); i2++) { int key1 = (int) ftParticles.get(i1).getProperty("key"); int key2 = (int) ftParticles.get(i2).getProperty("key"); Particle partGamma1 = ftParticles.get(i1); Particle partGamma2 = ftParticles.get(i2); Particle partPi0 = new Particle(); partPi0.copy(partGamma1); partPi0.combine(partGamma2, +1); double invmass = Math.sqrt(partPi0.mass2()); double x = (partGamma1.p() - partGamma2.p()) / (partGamma1.p() + partGamma2.p()); double angle = Math.toDegrees(Math.acos(partGamma1.cosTheta(partGamma2))); this.getDataGroup().getItem(1, 1, key1).getH1F("hpi0sum").fill(invmass); this.getDataGroup().getItem(1, 1, key1).getH2F("hmassangle").fill(invmass, angle); this.getDataGroup().getItem(1, 1, key2).getH1F("hpi0sum").fill(invmass); this.getDataGroup().getItem(1, 1, key2).getH2F("hmassangle").fill(invmass, angle); if(angle>1.) { double ecal1 = Math.pow(PhysicsConstants.massPionNeutral()*1.0E3,2)/(2*partGamma2.p()*(1-Math.cos(Math.toRadians(angle))))-(partGamma1.p()-partGamma1.getProperty("energySeed")); double ecal2 = Math.pow(PhysicsConstants.massPionNeutral()*1.0E3,2)/(2*partGamma1.p()*(1-Math.cos(Math.toRadians(angle))))-(partGamma2.p()-partGamma2.getProperty("energySeed")); // ecal1=partPi0.mass2()/(2*partGamma1.p()*partGamma2.p()*(1-partGamma1.cosTheta(partGamma2))); // System.out.println(ecal1 + " " + partGamma1.p()+ " " + partGamma1.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key1).getH1F("hpi0_" + key1).fill(invmass); this.getDataGroup().getItem(1, 1, key1).getH2F("hcal2d_" + key1).fill(ecal1,partGamma1.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key1).getH1F("hcal_" + key1).fill(partGamma1.getProperty("energySeed")/ecal1); this.getDataGroup().getItem(1, 1, key2).getH1F("hpi0_" + key2).fill(invmass); this.getDataGroup().getItem(1, 1, key2).getH2F("hcal2d_" + key2).fill(ecal2,partGamma2.getProperty("energySeed")); this.getDataGroup().getItem(1, 1, key2).getH1F("hcal_" + key2).fill(partGamma2.getProperty("energySeed")/ecal2); } } } } } } public void analyze() { // System.out.println("Analyzing"); // for (int key : this.getDetector().getDetectorComponents()) { // this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").reset(); // } // for (int key : this.getDetector().getDetectorComponents()) { // H1F htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_" + key); // F1D ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_" + key); // this.initTimeGaussFitPar(ftime,htime); // DataFitter.fit(ftime,htime,"LQ"); // // this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").addPoint(key, ftime.getParameter(1), 0, ftime.parameter(1).error()); // // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(1), "offset", 1, 1, key); // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).parameter(1).error(), "offset_error", 1, 1, key); // getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(2), "resolution" , 1, 1, key); // } // getCalibrationTable().fireTableDataChanged(); } private void initTimeGaussFitPar(F1D ftime, H1F htime) { double hAmp = htime.getBinContent(htime.getMaximumBin()); double hMean = htime.getAxis().getBinCenter(htime.getMaximumBin()); double hRMS = 2; //ns double rangeMin = (hMean - (0.8*hRMS)); double rangeMax = (hMean + (0.2*hRMS)); double pm = (hMean*3.)/100.0; ftime.setRange(rangeMin, rangeMax); ftime.setParameter(0, hAmp); ftime.setParLimits(0, hAmp*0.8, hAmp*1.2); ftime.setParameter(1, hMean); ftime.setParLimits(1, hMean-pm, hMean+(pm)); ftime.setParameter(2, 0.2); ftime.setParLimits(2, 0.1*hRMS, 0.8*hRMS); } @Override public Color getColor(DetectorShape2D dsd) { // show summary int sector = dsd.getDescriptor().getSector(); int layer = dsd.getDescriptor().getLayer(); int key = dsd.getDescriptor().getComponent(); ColorPalette palette = new ColorPalette(); Color col = new Color(100, 100, 100); if (this.getDetector().hasComponent(key)) { int nent = this.getNEvents(sector, layer, key); if (nent > 0) { col = palette.getColor3D(nent, this.getnProcessed(), true); } } // col = new Color(100, 0, 0); return col; } // @Override // public void processShape(DetectorShape2D dsd) { // // plot histos for the specific component // int sector = dsd.getDescriptor().getSector(); // int layer = dsd.getDescriptor().getLayer(); // int paddle<SUF> // System.out.println("Selected shape " + sector + " " + layer + " " + paddle); // IndexedList<DataGroup> group = this.getDataGroup(); // // if(group.hasItem(sector,layer,paddle)==true){ // this.getCanvas().clear(); // this.getCanvas().divide(2, 2); // this.getCanvas().cd(0); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htsum")); // this.getCanvas().cd(1); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getGraph("gtoffsets")); // this.getCanvas().cd(2); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htime_wide_" + paddle)); // this.getCanvas().cd(3); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getH1F("htime_" + paddle)); // this.getCanvas().draw(this.getDataGroup().getItem(1,1,paddle).getF1D("ftime_" + paddle),"same"); //// this.getCanvas().draw(this.getDataGroup().getItem(sector,layer,paddle)); //// this.getCanvas().update(); // } else { // System.out.println(" ERROR: can not find the data group"); // } // } @Override public void timerUpdate() { this.analyze(); } }
116118_31
package fuzzingengine; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import java.lang.reflect.*; import atlasdsl.Component; import atlasdsl.Computer; import atlasdsl.Message; import atlasdsl.Mission; import atlasdsl.Robot; import carsspecific.ros.carsqueue.ROSTopicUpdate; import fuzzingengine.FuzzingSimMapping.VariableDirection; import fuzzingengine.FuzzingSimMapping.VariableSpecification; import fuzzingengine.grammar.FuzzingCondition; import fuzzingengine.grammar.FuzzingConditionStartEnd; import fuzzingengine.grammar.FuzzingConditionStartSpec; import fuzzingengine.operations.EventFuzzingOperation; import fuzzingengine.operations.FuzzingOperation; import fuzzingengine.operations.ValueFuzzingOperation; import middleware.core.*; import middleware.logging.ATLASLog; public class FuzzingEngine<E> { Mission m; FuzzingConfig confs = new FuzzingConfig(); FuzzingSimMapping fuzzingspec = new FuzzingSimMapping(); PriorityQueue<FutureEvent<E>> delayedEvents = new PriorityQueue<FutureEvent<E>>(); // The count of active fuzzing operations private int activeFuzzingOperationMax = 0; // The last time at which the active fuzzing operations were tracked private double activeFuzzingOperationLastTime = 0.0; private final double FUZZING_OPERATION_TRACKING_TIME_STEP = 1.0; public FuzzingEngine(Mission m) { this.m = m; } private List<String> getVehicles(String vehicleList) throws MissingRobot { if (vehicleList.toUpperCase().equals("ALL")) { return m.getAllRobotAndComputerNames(); } else if (vehicleList.equals("")) { return m.getAllRobotAndComputerNames(); } else { List<String> vehicleNames = Arrays.asList(vehicleList.split("\\|")); // Check for the missing robots in the model return vehicleNames; } } public void addFuzzingKeyOperation(String fuzzingKey, String vehicleNameList, Object groupNum, double startTime, double endTime, FuzzingOperation op) throws MissingRobot { VariableSpecification vr = fuzzingspec.getRecordForKey(fuzzingKey); if (vr == null) { System.out.println("!!!!!! addFuzzingKeyOperation - key " + fuzzingKey + " not found in fuzzing spec - ignoring !!!!!"); } else { List<String> vehicles = getVehicles(vehicleNameList); FuzzingKeySelectionRecord fr = new FuzzingKeySelectionRecord(fuzzingKey, vr.getReflectionName_opt(), vr.getComponent(), vr.getRegexp(), groupNum, op, vehicles, startTime, endTime); confs.addKeyRecord(fr); } } public void addFuzzingKeyOperation(String fuzzingKey, String vehicleNameList, Object groupNum, FuzzingTimeSpecification spec, FuzzingOperation op) throws MissingRobot { VariableSpecification vr = fuzzingspec.getRecordForKey(fuzzingKey); if (vr == null) { System.out.println("!!!!!! addFuzzingKeyOperation - key " + fuzzingKey + " not found in fuzzing spec - ignoring !!!!!"); } else { List<String> vehicles = getVehicles(vehicleNameList); FuzzingKeySelectionRecord fr = new FuzzingKeySelectionRecord(fuzzingKey, vr.getReflectionName_opt(), vr.getComponent(), vr.getRegexp(), groupNum, op, vehicles, spec); confs.addKeyRecord(fr); } } // private void addFuzzingComponentOperation(String componentName, FuzzingOperation op, String vehicleNameList) // throws MissingRobot { // List<String> vehicles = getVehicles(vehicleNameList); // FuzzingComponentSelectionRecord cr = new FuzzingComponentSelectionRecord(componentName, op, vehicles); // confs.addComponentRecord(cr); // } public void addFuzzingMessageOperation(String messageName, String messageFieldName, int groupNum, double startTime, double endTime, FuzzingOperation op) throws InvalidMessage { Message msg = m.getMessage(messageName); if (msg == null) { throw new InvalidMessage(messageName, "Message not in model"); } else { String primedKeyName = messageFieldName + "'"; VariableSpecification vr = fuzzingspec.getRecordForKey(primedKeyName); if (vr == null) { throw new InvalidMessage(messageName, "Simmapping key not present for message field name " + messageFieldName); } else { // TODO: handle case where the given message is not defined in the mission FuzzingMessageSelectionRecord mr = new FuzzingMessageSelectionRecord(messageFieldName, msg, op); List<String> participants = new ArrayList<String>(); for (Component cFrom : msg.getFrom()) { if (cFrom instanceof Robot) { participants.add(((Robot) cFrom).getName()); } else { participants.add(((Computer) cFrom).getName()); } } FuzzingKeySelectionRecord kr = new FuzzingKeySelectionRecord(primedKeyName, Optional.of(messageFieldName), vr.getComponent(), vr.getRegexp(), groupNum, op, participants, startTime, endTime); // For all dests, have to set them as a participant for the fuzzing key record List<Component> cDests = msg.getTo(); for (Component c : cDests) { String destName; if (c instanceof Computer) { Computer comp = (Computer) c; destName = comp.getName(); kr.addParticipant(destName); System.out.println("Adding participant " + destName); } } for (Component c : cDests) { String destName; if (c instanceof Robot) { Robot r = (Robot) c; destName = r.getName(); kr.addParticipant(destName); } } confs.addKeyRecord(kr); confs.addMessageRecord(mr); } } } // // need to test: look up the key in simmodel, is its specific component set as // // active // private Optional<FuzzingOperation> getOperationByInboundComponentAndVehicle(String key, String vehicle) { // VariableSpecification vr = fuzzingspec.getRecordForKey(key); // if (vr != null) { // Optional<String> comp = vr.getComponent(); // if (comp.isPresent()) { // return confs.getOperationByOutboundComponentAndVehicle(comp.get(), vehicle); // } // } // // return Optional.empty(); // } public Optional<String> getKeyOrTopic(E event) { if (event instanceof KeyValueUpdate) { KeyValueUpdate kv = (KeyValueUpdate) event; return Optional.of(kv.getKey()); } if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; return Optional.of(rtu.getTopicName()); } return Optional.empty(); } // public List<FuzzingOperation> shouldFuzzCARSEvent(E event, double time) { // List<FuzzingOperation> res = new ArrayList<FuzzingOperation>(); // if (event instanceof KeyValueUpdate) { // KeyValueUpdate cv = (KeyValueUpdate) event; // String vehicle = cv.getVehicleName(); // String key = cv.getKey(); // ATLASLog.logFuzzing("shouldFuzzCARSEvent called on vehicle " + vehicle + " - key " + key); // Optional<FuzzingOperation> op_o = confs.getOperationByKeyAndVehicle(key, vehicle, time); // if (op_o.isPresent()) { // res.add(op_o.get()); // } // } // // if (event instanceof ROSTopicUpdate) { // ROSTopicUpdate rtu = (ROSTopicUpdate) event; // String vehicle = rtu.getVehicleName(); // String key = rtu.getTopicName(); // Optional<FuzzingOperation> op_o = confs.getOperationByKeyAndVehicle(key, vehicle, time); // if (op_o.isPresent()) { // FuzzingOperation op = op_o.get(); // ATLASLog.logFuzzing("shouldFuzzCARSEvent yes on vehicle " + vehicle + " - key " + key + " - found fuzzing operation " + op); // res.add(op); // } else { // ATLASLog.logFuzzing("shouldFuzzCARSEvent no on vehicle " + vehicle + " - key " + key); // } // } // // return res; // } public List<ActiveFuzzingInfo> getActiveFuzzingForEvent(E event, double time) { List<ActiveFuzzingInfo> res = new ArrayList<ActiveFuzzingInfo>(); if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; String vehicle = cv.getVehicleName(); String key = cv.getKey(); ATLASLog.logFuzzing("shouldFuzzCARSEvent called on vehicle " + vehicle + " - key " + key); List<FuzzingKeySelectionRecord> recs = confs.getRecordsByKeyAndVehicle(key, vehicle, time); for (FuzzingKeySelectionRecord fr : recs) { res.add(new ActiveFuzzingInfo(fr)); } } if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; String vehicle = rtu.getVehicleName(); String key = rtu.getTopicName(); List<FuzzingKeySelectionRecord> recs = confs.getRecordsByKeyAndVehicle(key, vehicle, time); for (FuzzingKeySelectionRecord fr : recs) { FuzzingOperation op = fr.getOperation(); ATLASLog.logFuzzing("shouldFuzzCARSEvent yes on vehicle " + vehicle + " - key " + key + " - found fuzzing operation " + op); res.add(new ActiveFuzzingInfo(fr)); } } return res; } public Optional<String> shouldReflectBackToCARS(E event) { if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; String k = cv.getKey(); return fuzzingspec.getReflectionKey(k); } // TODO: some values may only need to be reflected back if they were fuzzed. // This needs to be configured in the model if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; String k = rtu.getTopicName(); return fuzzingspec.getReflectionKey(k); } return Optional.empty(); } public static String replaceGroup(Pattern p, String source, int groupToReplace, ValueFuzzingOperation op) throws FuzzingEngineMatchFailure { Matcher m = p.matcher(source); if (!m.find()) { throw new FuzzingEngineMatchFailure(p, source); } else { String v = m.group(groupToReplace); String newV = op.fuzzTransformString(v); return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), newV).toString(); } } private JsonObject insertValue(JsonObject source, String key, String value) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add(key, value); source.entrySet(). forEach(e -> builder.add(e.getKey(), e.getValue())); return builder.build(); } public boolean jsonStructureNotSupplied(Optional<Object> jsonStructure) { if (!jsonStructure.isPresent()) { return true; } else { Object o = jsonStructure.get(); if (o instanceof String) { String s = (String)o; if (s.isEmpty()) { return true; } else { return false; } } else { return false; } } } public Optional<E> fuzzTransformEvent(Optional<E> event_o, ActiveFuzzingInfo fi) { FuzzingOperation op = fi.getOperation(); if (op.isEventBased()) { EventFuzzingOperation eop = (EventFuzzingOperation)op; return eop.fuzzTransformPotentialEvent(event_o); } else { if (event_o.isPresent()) { E event = event_o.get(); if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; KeyValueUpdate newUpdate = new KeyValueUpdate(cv); ValueFuzzingOperation vop = (ValueFuzzingOperation) op; String key = cv.getKey(); String v = cv.getValue(); String newValue = v; Optional<Map.Entry<Pattern, Object>> regexp_sel = fi.getPatternAndGroupStructure(); if (!regexp_sel.isPresent()) { newValue = vop.fuzzTransformString(v); } else { Pattern p = regexp_sel.get().getKey(); // TODO: check this is an integer Integer groupNum = (Integer)regexp_sel.get().getValue(); try { newValue = replaceGroup(p, v, groupNum, vop); } catch (FuzzingEngineMatchFailure e) { ATLASLog.logFuzzing("FuzzingEngineMatchFailure - " + event + e); } } newUpdate.setValue(newValue); return Optional.of((E)newUpdate); } else if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate)event; //ROSTopicUpdate newRTU = new ROSTopicUpdate(rtu); ValueFuzzingOperation vop = (ValueFuzzingOperation)op; String key = rtu.getTopicName(); JsonObject js = rtu.getJSON(); JsonObject newValue = js; Optional<Object> jsonStructure = fi.getJSONStructure(); // This selects if there is structure defined to the JSON key in the CSV file... if (jsonStructureNotSupplied(jsonStructure)) { // If there is // no structure defined in the CSV file, pass the entire structure to fuzz // This fuzzes the JSON object as a string representation, re-parses it String fuzzed = vop.fuzzTransformString(js.toString()); JsonReader jsonReader = Json.createReader(new StringReader(fuzzed)); newValue = jsonReader.readObject(); jsonReader.close(); } else { // There is structure... extract it String jsonSpec = (String)jsonStructure.get(); System.out.println("jsonSpec = " + jsonSpec); String [] fields = jsonSpec.split("\\."); newValue = JSONExtras.fuzzReplacement(js, fields, vop); } // Create the new fuzzed topic update by replacing the JSON ROSTopicUpdate modifiedRTU = new ROSTopicUpdate(rtu, newValue); ATLASLog.logFuzzing("modified ROSTopicUpdate original=" + js + "\nnewValue = " + newValue); return Optional.of((E)modifiedRTU); } else { return event_o; } } else return event_o; } } public FuzzingSimMapping getSimMapping() { return fuzzingspec; } public FuzzingConfig getConfig() { return confs; } public FuzzingSimMapping getSpec() { return fuzzingspec; } public HashMap<String, String> getVariables() { // Need to return: any variables from components enabled for binary fuzzing // With either the component enabled for fuzzing // Or the individual variable enabled HashMap<String, String> vars = new HashMap<String, String>(); // for (confs.getAllKeysByComponent(component)) { // confs.getAllKeysByComponent // } return vars; } public void setSimMapping(FuzzingSimMapping simMapping) { this.fuzzingspec = simMapping; } public List<String> getMessageKeys(String robotName, VariableDirection dir) { return confs.getMessageKeys(robotName, dir); } public Optional<FuzzingOperation> loadOperation(String className, String params) { try { Class<?> c = Class.forName("fuzzingengine.operations." + className); System.out.println("className for operation " + className); Method method = c.getDeclaredMethod("createFromParamString", String.class); Object res = method.invoke(null, params); if (res instanceof FuzzingOperation) { return Optional.of((FuzzingOperation) res); } else { return Optional.empty(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return Optional.empty(); } private FuzzingTimeSpecification createTimeSpec(String key, String startSpec, String endSpec) { if (key.equals("KEYCONDSTART")) { // This is a start cond, end time spec System.out.println("startSpec=" + startSpec); System.out.println("endSpec=" + endSpec); double end = Double.parseDouble(endSpec); FuzzingCondition startCond = FuzzingCondition.parseCSVString(startSpec); try { startCond.doConversion(); } catch (UnrecognisedComparison | UnrecognisedTreeNode e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedUnOp e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedBinOp e) { // TODO Auto-generated catch block e.printStackTrace(); } return new FuzzingConditionStartSpec(startCond, end); } if (key.equals("KEYCONDBOTH")) { // This is a start-end time spec System.out.println("startSpec=" + startSpec); System.out.println("endSpec=" + endSpec); FuzzingCondition startCond = FuzzingCondition.parseCSVString(startSpec); FuzzingCondition endCond = FuzzingCondition.parseCSVString(endSpec); try { startCond.doConversion(); endCond.doConversion(); } catch (UnrecognisedComparison | UnrecognisedTreeNode e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedUnOp e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedBinOp e) { // TODO Auto-generated catch block e.printStackTrace(); } return new FuzzingConditionStartEnd(startCond, endCond); } // Otherwise, assume a start-end time spec double start = Double.parseDouble(startSpec); double end = Double.parseDouble(endSpec); return new FuzzingFixedTimeSpecification(start, end); } public void setupFromFuzzingFile(String fileName, Mission m) { System.out.println("setupFromFuzzingFile - " + fileName); try { Files.readAllLines(Paths.get(fileName)).forEach(line -> { System.out.println("line="+line); if (line.length() > 0 && line.charAt(0) != '#') { String fields[] = line.split(","); System.out.println("0 - " + fields[0]); int i = 0; for (final String token : fields) { if (!token.isEmpty()) { System.out.println("Token:" + i + " " + token); } i++; } // Scan for key record in file if (fields[0].toUpperCase().contains("KEY")) { System.out.println("KEY based fuzzing"); String varName = fields[1]; FuzzingTimeSpecification spec = createTimeSpec(fields[0], fields[2], fields[3]); //double startTime = Double.parseDouble(fields[2]); //double endTime = Double.parseDouble(fields[3]); String vehicleNames = fields[4]; String fieldSpec = fields[5]; String opClass = fields[6]; String params = fields[7]; System.out.println("params = " + params); Optional<FuzzingOperation> op_o = loadOperation(opClass, params); if (op_o.isPresent()) { FuzzingOperation op = op_o.get(); try { addFuzzingKeyOperation(varName, vehicleNames, fieldSpec, spec, op); System.out.println("Installing fuzzing operation for " + varName + " - " + op); } catch (MissingRobot e) { System.out.println("Missing robot: name = " + e.getName()); e.printStackTrace(); } } } // TODO: component records no longer supported // // Scan for component record in file // if (fields[0].toUpperCase().equals("COMPONENT")) { // // TODO: parse the vehicle names from here // String componentName = fields[1]; // String vehicleNames = fields[2]; // String dirString = fields[3]; // // TODO: not using the direction string yet // String opClass = fields[4]; // String params = fields[5]; // Optional<FuzzingOperation> op_o = loadOperation(opClass, params); // if (op_o.isPresent()) { // FuzzingOperation op = op_o.get(); // try { // addFuzzingComponentOperation(componentName, op, vehicleNames); // } catch (MissingRobot e) { // e.printStackTrace(); // } // System.out.println( // "Installing fuzzing operation for component " + componentName + " - " + op); // } // } // Scan for message if (fields[0].toUpperCase().equals("MESSAGE")) { String messageName = fields[1]; double startTime = Double.parseDouble(fields[2]); double endTime = Double.parseDouble(fields[3]); String messageFieldName = fields[4]; Integer groupNum = Integer.valueOf(fields[5]); String opClass = fields[6]; String params = fields[7]; Optional<FuzzingOperation> op_o = loadOperation(opClass, params); if (op_o.isPresent()) { FuzzingOperation op = op_o.get(); // Where to get the regexp for the message fields? - in the model try { addFuzzingMessageOperation(messageName, messageFieldName, groupNum, startTime, endTime, op); } catch (InvalidMessage e) { System.out .println("Invalid message name: " + e.getMessageName() + " - " + e.getReason()); e.printStackTrace(); // TODO: raise exception to indicate the conversion failed } System.out.println("Installing fuzzing operation for " + messageName + ":" + messageFieldName + " - " + op); } } } }); } catch (NoSuchFileException ex) { System.out.println("Fuzzing file " + fileName + " not found - performing a null fuzzing experiment"); } catch (IOException ex) { ex.printStackTrace(); } } // This gets the explicitly selected keys upon this component public Map<String, String> getAllChanges(String component) { Map<String, String> inOut = new HashMap<String, String>(); List<FuzzingKeySelectionRecord> recs = getConfig().getAllKeysByComponent(component); for (FuzzingKeySelectionRecord kr : recs) { if (kr.getReflectionKey().isPresent()) { inOut.put(kr.getKey(), kr.getReflectionKey().get()); } } return inOut; } // This gets the keys upon this component defined in the simmapping public Map<String, String> getAllChangesDefinedOn(String component) { Map<String, String> inOut = new HashMap<String, String>(); Set<VariableSpecification> recs = getSimMapping().getRecordsUponComponent(component); for (VariableSpecification vr : recs) { inOut.put(vr.getVariable(), vr.getReflectionName()); } return inOut; } public void addToQueue(E e, double releaseTime, Optional<String> reflectBackName) { // TODO: define comparators for the release time delayedEvents.add(new FutureEvent(e, releaseTime, reflectBackName)); } public List<FutureEvent<E>> pollEventsReady(double byTime) { List<FutureEvent<E>> res = new ArrayList<FutureEvent<E>>(); FutureEvent<E> fe = delayedEvents.peek(); if (fe != null) { if (fe.getPendingTime() < byTime) { FutureEvent<E> feRemoved = delayedEvents.remove(); res.add(feRemoved); } } return res; } public Set<String> getAllKeys() { return confs.getAllKeys(); } public Set<FuzzingKeySelectionRecord> getAllEnvironmentalKeys() { Set<FuzzingKeySelectionRecord> frToUse = confs.getAllKeyRecords().stream() .filter(r -> keyIsEnvironmental(r.getKey())) .collect(Collectors.toSet()); return frToUse; } private boolean keyIsEnvironmental(String key) { VariableSpecification vs = fuzzingspec.getRecordForKey(key); Optional<String> c_o = vs.getComponent(); if (c_o.isPresent()) { String cname = c_o.get(); return fuzzingspec.isEnviromental(cname); } else { return false; } } public String getFilenameForKey(String key) { // TODO: Base simulator path + config path + key name VariableSpecification vs = fuzzingspec.getRecordForKey(key); Optional<String> path_o = vs.getPath(); if (path_o.isPresent()) { String path = path_o.get(); return path + "/" + key; } else { // If there is no component path, treat the key as absolute return key; } } public List<String> getAllLaunchFilesPaths() { return fuzzingspec.getAllLaunchFilesPaths(); } public void registerActiveOperations(double time, List<ActiveFuzzingInfo> ifs) { // This assumes there is at least one operation per second int activeCount = ifs.size(); activeFuzzingOperationMax = Math.max(activeFuzzingOperationMax, activeCount); if (time > (activeFuzzingOperationLastTime + FUZZING_OPERATION_TRACKING_TIME_STEP)) { // Log the active fuzzing operations at this timestep ATLASLog.logActiveFuzzingMetrics(time,activeFuzzingOperationMax); activeFuzzingOperationLastTime = time; activeFuzzingOperationMax = 0; } } }
safemuv/safefuzz
middleware-java/src/fuzzingengine/FuzzingEngine.java
7,797
// FuzzingOperation op = op_o.get();
line_comment
nl
package fuzzingengine; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import java.lang.reflect.*; import atlasdsl.Component; import atlasdsl.Computer; import atlasdsl.Message; import atlasdsl.Mission; import atlasdsl.Robot; import carsspecific.ros.carsqueue.ROSTopicUpdate; import fuzzingengine.FuzzingSimMapping.VariableDirection; import fuzzingengine.FuzzingSimMapping.VariableSpecification; import fuzzingengine.grammar.FuzzingCondition; import fuzzingengine.grammar.FuzzingConditionStartEnd; import fuzzingengine.grammar.FuzzingConditionStartSpec; import fuzzingengine.operations.EventFuzzingOperation; import fuzzingengine.operations.FuzzingOperation; import fuzzingengine.operations.ValueFuzzingOperation; import middleware.core.*; import middleware.logging.ATLASLog; public class FuzzingEngine<E> { Mission m; FuzzingConfig confs = new FuzzingConfig(); FuzzingSimMapping fuzzingspec = new FuzzingSimMapping(); PriorityQueue<FutureEvent<E>> delayedEvents = new PriorityQueue<FutureEvent<E>>(); // The count of active fuzzing operations private int activeFuzzingOperationMax = 0; // The last time at which the active fuzzing operations were tracked private double activeFuzzingOperationLastTime = 0.0; private final double FUZZING_OPERATION_TRACKING_TIME_STEP = 1.0; public FuzzingEngine(Mission m) { this.m = m; } private List<String> getVehicles(String vehicleList) throws MissingRobot { if (vehicleList.toUpperCase().equals("ALL")) { return m.getAllRobotAndComputerNames(); } else if (vehicleList.equals("")) { return m.getAllRobotAndComputerNames(); } else { List<String> vehicleNames = Arrays.asList(vehicleList.split("\\|")); // Check for the missing robots in the model return vehicleNames; } } public void addFuzzingKeyOperation(String fuzzingKey, String vehicleNameList, Object groupNum, double startTime, double endTime, FuzzingOperation op) throws MissingRobot { VariableSpecification vr = fuzzingspec.getRecordForKey(fuzzingKey); if (vr == null) { System.out.println("!!!!!! addFuzzingKeyOperation - key " + fuzzingKey + " not found in fuzzing spec - ignoring !!!!!"); } else { List<String> vehicles = getVehicles(vehicleNameList); FuzzingKeySelectionRecord fr = new FuzzingKeySelectionRecord(fuzzingKey, vr.getReflectionName_opt(), vr.getComponent(), vr.getRegexp(), groupNum, op, vehicles, startTime, endTime); confs.addKeyRecord(fr); } } public void addFuzzingKeyOperation(String fuzzingKey, String vehicleNameList, Object groupNum, FuzzingTimeSpecification spec, FuzzingOperation op) throws MissingRobot { VariableSpecification vr = fuzzingspec.getRecordForKey(fuzzingKey); if (vr == null) { System.out.println("!!!!!! addFuzzingKeyOperation - key " + fuzzingKey + " not found in fuzzing spec - ignoring !!!!!"); } else { List<String> vehicles = getVehicles(vehicleNameList); FuzzingKeySelectionRecord fr = new FuzzingKeySelectionRecord(fuzzingKey, vr.getReflectionName_opt(), vr.getComponent(), vr.getRegexp(), groupNum, op, vehicles, spec); confs.addKeyRecord(fr); } } // private void addFuzzingComponentOperation(String componentName, FuzzingOperation op, String vehicleNameList) // throws MissingRobot { // List<String> vehicles = getVehicles(vehicleNameList); // FuzzingComponentSelectionRecord cr = new FuzzingComponentSelectionRecord(componentName, op, vehicles); // confs.addComponentRecord(cr); // } public void addFuzzingMessageOperation(String messageName, String messageFieldName, int groupNum, double startTime, double endTime, FuzzingOperation op) throws InvalidMessage { Message msg = m.getMessage(messageName); if (msg == null) { throw new InvalidMessage(messageName, "Message not in model"); } else { String primedKeyName = messageFieldName + "'"; VariableSpecification vr = fuzzingspec.getRecordForKey(primedKeyName); if (vr == null) { throw new InvalidMessage(messageName, "Simmapping key not present for message field name " + messageFieldName); } else { // TODO: handle case where the given message is not defined in the mission FuzzingMessageSelectionRecord mr = new FuzzingMessageSelectionRecord(messageFieldName, msg, op); List<String> participants = new ArrayList<String>(); for (Component cFrom : msg.getFrom()) { if (cFrom instanceof Robot) { participants.add(((Robot) cFrom).getName()); } else { participants.add(((Computer) cFrom).getName()); } } FuzzingKeySelectionRecord kr = new FuzzingKeySelectionRecord(primedKeyName, Optional.of(messageFieldName), vr.getComponent(), vr.getRegexp(), groupNum, op, participants, startTime, endTime); // For all dests, have to set them as a participant for the fuzzing key record List<Component> cDests = msg.getTo(); for (Component c : cDests) { String destName; if (c instanceof Computer) { Computer comp = (Computer) c; destName = comp.getName(); kr.addParticipant(destName); System.out.println("Adding participant " + destName); } } for (Component c : cDests) { String destName; if (c instanceof Robot) { Robot r = (Robot) c; destName = r.getName(); kr.addParticipant(destName); } } confs.addKeyRecord(kr); confs.addMessageRecord(mr); } } } // // need to test: look up the key in simmodel, is its specific component set as // // active // private Optional<FuzzingOperation> getOperationByInboundComponentAndVehicle(String key, String vehicle) { // VariableSpecification vr = fuzzingspec.getRecordForKey(key); // if (vr != null) { // Optional<String> comp = vr.getComponent(); // if (comp.isPresent()) { // return confs.getOperationByOutboundComponentAndVehicle(comp.get(), vehicle); // } // } // // return Optional.empty(); // } public Optional<String> getKeyOrTopic(E event) { if (event instanceof KeyValueUpdate) { KeyValueUpdate kv = (KeyValueUpdate) event; return Optional.of(kv.getKey()); } if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; return Optional.of(rtu.getTopicName()); } return Optional.empty(); } // public List<FuzzingOperation> shouldFuzzCARSEvent(E event, double time) { // List<FuzzingOperation> res = new ArrayList<FuzzingOperation>(); // if (event instanceof KeyValueUpdate) { // KeyValueUpdate cv = (KeyValueUpdate) event; // String vehicle = cv.getVehicleName(); // String key = cv.getKey(); // ATLASLog.logFuzzing("shouldFuzzCARSEvent called on vehicle " + vehicle + " - key " + key); // Optional<FuzzingOperation> op_o = confs.getOperationByKeyAndVehicle(key, vehicle, time); // if (op_o.isPresent()) { // res.add(op_o.get()); // } // } // // if (event instanceof ROSTopicUpdate) { // ROSTopicUpdate rtu = (ROSTopicUpdate) event; // String vehicle = rtu.getVehicleName(); // String key = rtu.getTopicName(); // Optional<FuzzingOperation> op_o = confs.getOperationByKeyAndVehicle(key, vehicle, time); // if (op_o.isPresent()) { // FuzzingOperation op<SUF> // ATLASLog.logFuzzing("shouldFuzzCARSEvent yes on vehicle " + vehicle + " - key " + key + " - found fuzzing operation " + op); // res.add(op); // } else { // ATLASLog.logFuzzing("shouldFuzzCARSEvent no on vehicle " + vehicle + " - key " + key); // } // } // // return res; // } public List<ActiveFuzzingInfo> getActiveFuzzingForEvent(E event, double time) { List<ActiveFuzzingInfo> res = new ArrayList<ActiveFuzzingInfo>(); if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; String vehicle = cv.getVehicleName(); String key = cv.getKey(); ATLASLog.logFuzzing("shouldFuzzCARSEvent called on vehicle " + vehicle + " - key " + key); List<FuzzingKeySelectionRecord> recs = confs.getRecordsByKeyAndVehicle(key, vehicle, time); for (FuzzingKeySelectionRecord fr : recs) { res.add(new ActiveFuzzingInfo(fr)); } } if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; String vehicle = rtu.getVehicleName(); String key = rtu.getTopicName(); List<FuzzingKeySelectionRecord> recs = confs.getRecordsByKeyAndVehicle(key, vehicle, time); for (FuzzingKeySelectionRecord fr : recs) { FuzzingOperation op = fr.getOperation(); ATLASLog.logFuzzing("shouldFuzzCARSEvent yes on vehicle " + vehicle + " - key " + key + " - found fuzzing operation " + op); res.add(new ActiveFuzzingInfo(fr)); } } return res; } public Optional<String> shouldReflectBackToCARS(E event) { if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; String k = cv.getKey(); return fuzzingspec.getReflectionKey(k); } // TODO: some values may only need to be reflected back if they were fuzzed. // This needs to be configured in the model if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate) event; String k = rtu.getTopicName(); return fuzzingspec.getReflectionKey(k); } return Optional.empty(); } public static String replaceGroup(Pattern p, String source, int groupToReplace, ValueFuzzingOperation op) throws FuzzingEngineMatchFailure { Matcher m = p.matcher(source); if (!m.find()) { throw new FuzzingEngineMatchFailure(p, source); } else { String v = m.group(groupToReplace); String newV = op.fuzzTransformString(v); return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), newV).toString(); } } private JsonObject insertValue(JsonObject source, String key, String value) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add(key, value); source.entrySet(). forEach(e -> builder.add(e.getKey(), e.getValue())); return builder.build(); } public boolean jsonStructureNotSupplied(Optional<Object> jsonStructure) { if (!jsonStructure.isPresent()) { return true; } else { Object o = jsonStructure.get(); if (o instanceof String) { String s = (String)o; if (s.isEmpty()) { return true; } else { return false; } } else { return false; } } } public Optional<E> fuzzTransformEvent(Optional<E> event_o, ActiveFuzzingInfo fi) { FuzzingOperation op = fi.getOperation(); if (op.isEventBased()) { EventFuzzingOperation eop = (EventFuzzingOperation)op; return eop.fuzzTransformPotentialEvent(event_o); } else { if (event_o.isPresent()) { E event = event_o.get(); if (event instanceof KeyValueUpdate) { KeyValueUpdate cv = (KeyValueUpdate) event; KeyValueUpdate newUpdate = new KeyValueUpdate(cv); ValueFuzzingOperation vop = (ValueFuzzingOperation) op; String key = cv.getKey(); String v = cv.getValue(); String newValue = v; Optional<Map.Entry<Pattern, Object>> regexp_sel = fi.getPatternAndGroupStructure(); if (!regexp_sel.isPresent()) { newValue = vop.fuzzTransformString(v); } else { Pattern p = regexp_sel.get().getKey(); // TODO: check this is an integer Integer groupNum = (Integer)regexp_sel.get().getValue(); try { newValue = replaceGroup(p, v, groupNum, vop); } catch (FuzzingEngineMatchFailure e) { ATLASLog.logFuzzing("FuzzingEngineMatchFailure - " + event + e); } } newUpdate.setValue(newValue); return Optional.of((E)newUpdate); } else if (event instanceof ROSTopicUpdate) { ROSTopicUpdate rtu = (ROSTopicUpdate)event; //ROSTopicUpdate newRTU = new ROSTopicUpdate(rtu); ValueFuzzingOperation vop = (ValueFuzzingOperation)op; String key = rtu.getTopicName(); JsonObject js = rtu.getJSON(); JsonObject newValue = js; Optional<Object> jsonStructure = fi.getJSONStructure(); // This selects if there is structure defined to the JSON key in the CSV file... if (jsonStructureNotSupplied(jsonStructure)) { // If there is // no structure defined in the CSV file, pass the entire structure to fuzz // This fuzzes the JSON object as a string representation, re-parses it String fuzzed = vop.fuzzTransformString(js.toString()); JsonReader jsonReader = Json.createReader(new StringReader(fuzzed)); newValue = jsonReader.readObject(); jsonReader.close(); } else { // There is structure... extract it String jsonSpec = (String)jsonStructure.get(); System.out.println("jsonSpec = " + jsonSpec); String [] fields = jsonSpec.split("\\."); newValue = JSONExtras.fuzzReplacement(js, fields, vop); } // Create the new fuzzed topic update by replacing the JSON ROSTopicUpdate modifiedRTU = new ROSTopicUpdate(rtu, newValue); ATLASLog.logFuzzing("modified ROSTopicUpdate original=" + js + "\nnewValue = " + newValue); return Optional.of((E)modifiedRTU); } else { return event_o; } } else return event_o; } } public FuzzingSimMapping getSimMapping() { return fuzzingspec; } public FuzzingConfig getConfig() { return confs; } public FuzzingSimMapping getSpec() { return fuzzingspec; } public HashMap<String, String> getVariables() { // Need to return: any variables from components enabled for binary fuzzing // With either the component enabled for fuzzing // Or the individual variable enabled HashMap<String, String> vars = new HashMap<String, String>(); // for (confs.getAllKeysByComponent(component)) { // confs.getAllKeysByComponent // } return vars; } public void setSimMapping(FuzzingSimMapping simMapping) { this.fuzzingspec = simMapping; } public List<String> getMessageKeys(String robotName, VariableDirection dir) { return confs.getMessageKeys(robotName, dir); } public Optional<FuzzingOperation> loadOperation(String className, String params) { try { Class<?> c = Class.forName("fuzzingengine.operations." + className); System.out.println("className for operation " + className); Method method = c.getDeclaredMethod("createFromParamString", String.class); Object res = method.invoke(null, params); if (res instanceof FuzzingOperation) { return Optional.of((FuzzingOperation) res); } else { return Optional.empty(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return Optional.empty(); } private FuzzingTimeSpecification createTimeSpec(String key, String startSpec, String endSpec) { if (key.equals("KEYCONDSTART")) { // This is a start cond, end time spec System.out.println("startSpec=" + startSpec); System.out.println("endSpec=" + endSpec); double end = Double.parseDouble(endSpec); FuzzingCondition startCond = FuzzingCondition.parseCSVString(startSpec); try { startCond.doConversion(); } catch (UnrecognisedComparison | UnrecognisedTreeNode e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedUnOp e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedBinOp e) { // TODO Auto-generated catch block e.printStackTrace(); } return new FuzzingConditionStartSpec(startCond, end); } if (key.equals("KEYCONDBOTH")) { // This is a start-end time spec System.out.println("startSpec=" + startSpec); System.out.println("endSpec=" + endSpec); FuzzingCondition startCond = FuzzingCondition.parseCSVString(startSpec); FuzzingCondition endCond = FuzzingCondition.parseCSVString(endSpec); try { startCond.doConversion(); endCond.doConversion(); } catch (UnrecognisedComparison | UnrecognisedTreeNode e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedUnOp e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecognisedBinOp e) { // TODO Auto-generated catch block e.printStackTrace(); } return new FuzzingConditionStartEnd(startCond, endCond); } // Otherwise, assume a start-end time spec double start = Double.parseDouble(startSpec); double end = Double.parseDouble(endSpec); return new FuzzingFixedTimeSpecification(start, end); } public void setupFromFuzzingFile(String fileName, Mission m) { System.out.println("setupFromFuzzingFile - " + fileName); try { Files.readAllLines(Paths.get(fileName)).forEach(line -> { System.out.println("line="+line); if (line.length() > 0 && line.charAt(0) != '#') { String fields[] = line.split(","); System.out.println("0 - " + fields[0]); int i = 0; for (final String token : fields) { if (!token.isEmpty()) { System.out.println("Token:" + i + " " + token); } i++; } // Scan for key record in file if (fields[0].toUpperCase().contains("KEY")) { System.out.println("KEY based fuzzing"); String varName = fields[1]; FuzzingTimeSpecification spec = createTimeSpec(fields[0], fields[2], fields[3]); //double startTime = Double.parseDouble(fields[2]); //double endTime = Double.parseDouble(fields[3]); String vehicleNames = fields[4]; String fieldSpec = fields[5]; String opClass = fields[6]; String params = fields[7]; System.out.println("params = " + params); Optional<FuzzingOperation> op_o = loadOperation(opClass, params); if (op_o.isPresent()) { FuzzingOperation op = op_o.get(); try { addFuzzingKeyOperation(varName, vehicleNames, fieldSpec, spec, op); System.out.println("Installing fuzzing operation for " + varName + " - " + op); } catch (MissingRobot e) { System.out.println("Missing robot: name = " + e.getName()); e.printStackTrace(); } } } // TODO: component records no longer supported // // Scan for component record in file // if (fields[0].toUpperCase().equals("COMPONENT")) { // // TODO: parse the vehicle names from here // String componentName = fields[1]; // String vehicleNames = fields[2]; // String dirString = fields[3]; // // TODO: not using the direction string yet // String opClass = fields[4]; // String params = fields[5]; // Optional<FuzzingOperation> op_o = loadOperation(opClass, params); // if (op_o.isPresent()) { // FuzzingOperation op = op_o.get(); // try { // addFuzzingComponentOperation(componentName, op, vehicleNames); // } catch (MissingRobot e) { // e.printStackTrace(); // } // System.out.println( // "Installing fuzzing operation for component " + componentName + " - " + op); // } // } // Scan for message if (fields[0].toUpperCase().equals("MESSAGE")) { String messageName = fields[1]; double startTime = Double.parseDouble(fields[2]); double endTime = Double.parseDouble(fields[3]); String messageFieldName = fields[4]; Integer groupNum = Integer.valueOf(fields[5]); String opClass = fields[6]; String params = fields[7]; Optional<FuzzingOperation> op_o = loadOperation(opClass, params); if (op_o.isPresent()) { FuzzingOperation op = op_o.get(); // Where to get the regexp for the message fields? - in the model try { addFuzzingMessageOperation(messageName, messageFieldName, groupNum, startTime, endTime, op); } catch (InvalidMessage e) { System.out .println("Invalid message name: " + e.getMessageName() + " - " + e.getReason()); e.printStackTrace(); // TODO: raise exception to indicate the conversion failed } System.out.println("Installing fuzzing operation for " + messageName + ":" + messageFieldName + " - " + op); } } } }); } catch (NoSuchFileException ex) { System.out.println("Fuzzing file " + fileName + " not found - performing a null fuzzing experiment"); } catch (IOException ex) { ex.printStackTrace(); } } // This gets the explicitly selected keys upon this component public Map<String, String> getAllChanges(String component) { Map<String, String> inOut = new HashMap<String, String>(); List<FuzzingKeySelectionRecord> recs = getConfig().getAllKeysByComponent(component); for (FuzzingKeySelectionRecord kr : recs) { if (kr.getReflectionKey().isPresent()) { inOut.put(kr.getKey(), kr.getReflectionKey().get()); } } return inOut; } // This gets the keys upon this component defined in the simmapping public Map<String, String> getAllChangesDefinedOn(String component) { Map<String, String> inOut = new HashMap<String, String>(); Set<VariableSpecification> recs = getSimMapping().getRecordsUponComponent(component); for (VariableSpecification vr : recs) { inOut.put(vr.getVariable(), vr.getReflectionName()); } return inOut; } public void addToQueue(E e, double releaseTime, Optional<String> reflectBackName) { // TODO: define comparators for the release time delayedEvents.add(new FutureEvent(e, releaseTime, reflectBackName)); } public List<FutureEvent<E>> pollEventsReady(double byTime) { List<FutureEvent<E>> res = new ArrayList<FutureEvent<E>>(); FutureEvent<E> fe = delayedEvents.peek(); if (fe != null) { if (fe.getPendingTime() < byTime) { FutureEvent<E> feRemoved = delayedEvents.remove(); res.add(feRemoved); } } return res; } public Set<String> getAllKeys() { return confs.getAllKeys(); } public Set<FuzzingKeySelectionRecord> getAllEnvironmentalKeys() { Set<FuzzingKeySelectionRecord> frToUse = confs.getAllKeyRecords().stream() .filter(r -> keyIsEnvironmental(r.getKey())) .collect(Collectors.toSet()); return frToUse; } private boolean keyIsEnvironmental(String key) { VariableSpecification vs = fuzzingspec.getRecordForKey(key); Optional<String> c_o = vs.getComponent(); if (c_o.isPresent()) { String cname = c_o.get(); return fuzzingspec.isEnviromental(cname); } else { return false; } } public String getFilenameForKey(String key) { // TODO: Base simulator path + config path + key name VariableSpecification vs = fuzzingspec.getRecordForKey(key); Optional<String> path_o = vs.getPath(); if (path_o.isPresent()) { String path = path_o.get(); return path + "/" + key; } else { // If there is no component path, treat the key as absolute return key; } } public List<String> getAllLaunchFilesPaths() { return fuzzingspec.getAllLaunchFilesPaths(); } public void registerActiveOperations(double time, List<ActiveFuzzingInfo> ifs) { // This assumes there is at least one operation per second int activeCount = ifs.size(); activeFuzzingOperationMax = Math.max(activeFuzzingOperationMax, activeCount); if (time > (activeFuzzingOperationLastTime + FUZZING_OPERATION_TRACKING_TIME_STEP)) { // Log the active fuzzing operations at this timestep ATLASLog.logActiveFuzzingMetrics(time,activeFuzzingOperationMax); activeFuzzingOperationLastTime = time; activeFuzzingOperationMax = 0; } } }
83529_2
package com.in28minutes.rest.webservices.restfulwebservices.helloworld; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; // REST API @RestController public class HelloWorldController { private MessageSource messageSource; public HelloWorldController(MessageSource messageSource) { this.messageSource = messageSource; } // /hello-world @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("hello world"); } @GetMapping(path = "/hello-world/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean("hello " + name); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized() { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage("good.morning.message", null, "Default Message", locale); // return "Hello World"; // 1: // 2: // - Example: `en` - English (Good Morning) // - Example: `nl` - Dutch (Goedemorgen) // - Example: `fr` - French (Bonjour) // - Example: `de` - Deutsch (Guten Morgen) } }
sahuankit010/Spring-Project
restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java
452
// - Example: `nl` - Dutch (Goedemorgen)
line_comment
nl
package com.in28minutes.rest.webservices.restfulwebservices.helloworld; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; // REST API @RestController public class HelloWorldController { private MessageSource messageSource; public HelloWorldController(MessageSource messageSource) { this.messageSource = messageSource; } // /hello-world @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("hello world"); } @GetMapping(path = "/hello-world/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean("hello " + name); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized() { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage("good.morning.message", null, "Default Message", locale); // return "Hello World"; // 1: // 2: // - Example: `en` - English (Good Morning) // - Example:<SUF> // - Example: `fr` - French (Bonjour) // - Example: `de` - Deutsch (Guten Morgen) } }
20332_19
package hackathon.com.sansad; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import hackathon.com.sansad.models.api.Data; import hackathon.com.sansad.models.api.Session; import hackathon.com.sansad.models.chat.Chat; import hackathon.com.sansad.models.chat.Messages; import hackathon.com.sansad.models.home.Notificationn; import hackathon.com.sansad.models.home.Offer; import hackathon.com.sansad.models.places.Places; import hackathon.com.sansad.models.user.User; import java.util.ArrayList; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ADDRESS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ADMIN; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_DESCRIPTION; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_FEATURED; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ID; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_IMAGE_LINK; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LATITUDE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LOCATION; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LONGITUDE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_MIN_COST; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_NAME; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_NO_RATINGS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_PHONE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_POPULAR; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_RATING; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_RECOMMENDED; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_STATUS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_TYPE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_VIEWS; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_EMAIL; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_GENDER; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_IMAGE; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_NAME; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_SESSION; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_TOKEN; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_USERNAME; public class SQLiteDBHelper extends SQLiteOpenHelper { // All Static variables // Database Version //last increased on 10th march 2016. Don't(preferably) increment unless a release was pushed before current day private static final int DATABASE_VERSION = 5; // Database Name private static final String DATABASE_LEUK = "sansad"; // Login table name private static final String TABLE_USER = "users"; private static final String TABLE_PLACES = "places"; ; public SQLiteDBHelper(Context context) { super(context, DATABASE_LEUK, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "(" + COLUMN_USER_NAME + " TEXT NOT NULL, " + COLUMN_USER_USERNAME + " TEXT PRIMARY KEY, " + COLUMN_USER_EMAIL + " TEXT NOT NULL, " + COLUMN_USER_GENDER + " TEXT NOT NULL, " + COLUMN_USER_IMAGE + " TEXT, " + COLUMN_USER_SESSION + " TEXT NOT NULL, " + COLUMN_USER_TOKEN + " TEXT NOT NULL " + ")"; String CREATE_PLACES_TABLE = "CREATE TABLE " + TABLE_PLACES + "(" + COLUMN_PLACE_ID + " TEXT PRIMARY KEY NOT NULL, " + COLUMN_PLACE_NAME + " TEXT , " + COLUMN_PLACE_TYPE + " TEXT NOT NULL, " + COLUMN_PLACE_MIN_COST + " TEXT, " + COLUMN_PLACE_RATING + " TEXT, " + COLUMN_PLACE_DESCRIPTION + " TEXT NOT NULL, " + COLUMN_PLACE_ADDRESS + " TEXT, " + COLUMN_PLACE_LOCATION + " TEXT, " + COLUMN_PLACE_IMAGE_LINK + " TEXT NOT NULL, " + COLUMN_PLACE_LATITUDE + " TEXT, " + COLUMN_PLACE_LONGITUDE + " TEXT, " + COLUMN_PLACE_PHONE + " TEXT, " + COLUMN_PLACE_FEATURED + " TEXT, " + COLUMN_PLACE_POPULAR + " TEXT, " + COLUMN_PLACE_RECOMMENDED + " TEXT, " + COLUMN_PLACE_NO_RATINGS + " TEXT, " + COLUMN_PLACE_ADMIN + " TEXT, " + COLUMN_PLACE_VIEWS + " TEXT, " + COLUMN_PLACE_STATUS + " TEXT " + ")"; db.execSQL(CREATE_LOGIN_TABLE); Log.d("database", "user created"); db.execSQL(CREATE_PLACES_TABLE); Log.d("database", "places created"); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER); db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLACES); // Create tables again onCreate(db); } /** * Storing user details in database */ public void addUser(String name, String username, String email, String gender, String phone, String location, String image, String level, String totalCredits, String remainingCredits, int maxCredits, String session, String token) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_USER_NAME, name); // Name values.put(COLUMN_USER_USERNAME, username); // Username values.put(COLUMN_USER_EMAIL, email); // Email values.put(COLUMN_USER_GENDER, gender); // Gender values.put(COLUMN_USER_IMAGE, image); // Image values.put(COLUMN_USER_SESSION, session); // Session ID values.put(COLUMN_USER_TOKEN, token); // Token // Inserting Row db.insert(TABLE_USER, null, values); db.close(); // Closing database connection } /** * Getting user data from database */ public Data getUserDetails() { String selectQuery = "SELECT * FROM " + TABLE_USER; Data data = new Data(); User user = new User(); Session session = new Session(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // Move to first row cursor.moveToFirst(); if (cursor.getCount() > 0) { user.setName(cursor.getString(0)); user.setUsername(cursor.getString(1)); user.setEmail(cursor.getString(2)); user.setGender(cursor.getString(3)); user.setProfileImg(cursor.getString(4)); session.setSessionid(cursor.getString(5)); session.setToken(cursor.getString(6)); data.setSession(session); data.setUser(user); } cursor.close(); db.close(); return data; } /** * Update user data in database */ public void updateUserDetails(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_USER_NAME, user.getName()); // Name values.put(COLUMN_USER_GENDER, user.getGender()); // Gender db.update(TABLE_USER, values, COLUMN_USER_USERNAME + "=\'" + user.getUsername() + "\'", null); } /** * Getting user login status return true if rows are there in table */ public int getRowCount() { String countQuery = "SELECT * FROM " + TABLE_USER; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); int rowCount = cursor.getCount(); db.close(); cursor.close(); // return row count return rowCount; } /** * Storing places in the database */ public void addPlace(Places place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_PLACE_ID, place.getId()); values.put(COLUMN_PLACE_NAME, place.getName()); // Place Name values.put(COLUMN_PLACE_TYPE, place.getType()); // Place Type values.put(COLUMN_PLACE_MIN_COST, place.getMinimumSpending()); // Place minimum spending values.put(COLUMN_PLACE_RATING, place.getRating()); // Place Rating values.put(COLUMN_PLACE_DESCRIPTION, place.getDescription()); // Place Description values.put(COLUMN_PLACE_ADDRESS, place.getAddress()); // Place Address values.put(COLUMN_PLACE_LOCATION, place.getLocation()); // Place Location values.put(COLUMN_PLACE_IMAGE_LINK, place.getPhotoLink()); // Place image link values.put(COLUMN_PLACE_LATITUDE, place.getLatitude()); // Place Location values.put(COLUMN_PLACE_LONGITUDE, place.getLongitude()); // Place Location values.put(COLUMN_PLACE_PHONE, place.getPhone()); // Place phone values.put(COLUMN_PLACE_FEATURED, place.getFeatured()); // Place phone values.put(COLUMN_PLACE_POPULAR, place.getPopular()); // Place phone values.put(COLUMN_PLACE_RECOMMENDED, place.getRecommended()); // Place phone values.put(COLUMN_PLACE_NO_RATINGS, place.getNoOfRatings()); // Place phone values.put(COLUMN_PLACE_ADMIN, place.getLeukAdmin()); // Place phone values.put(COLUMN_PLACE_VIEWS, place.getViews());//Place views values.put(COLUMN_PLACE_STATUS, place.getStatus()); // Place phone // Inserting Row db.insert(TABLE_PLACES, null, values); Log.d("database", "added place" + place.getName()); db.close(); // Closing database connection } public void addPlaces(ArrayList<Places> placesArrayList) { SQLiteDatabase db = this.getWritableDatabase(); db.beginTransaction(); Log.d("bulk insert start", System.currentTimeMillis() + ""); for (Places place : placesArrayList) { ContentValues values = new ContentValues(); values.put(COLUMN_PLACE_ID, place.getId()); values.put(COLUMN_PLACE_NAME, place.getName()); // Place Name values.put(COLUMN_PLACE_TYPE, place.getType()); // Place Type values.put(COLUMN_PLACE_MIN_COST, place.getMinimumSpending()); // Place minimum spending values.put(COLUMN_PLACE_RATING, place.getRating()); // Place Rating values.put(COLUMN_PLACE_DESCRIPTION, place.getDescription()); // Place Description values.put(COLUMN_PLACE_ADDRESS, place.getAddress()); // Place Address values.put(COLUMN_PLACE_LOCATION, place.getLocation()); // Place Location values.put(COLUMN_PLACE_IMAGE_LINK, place.getPhotoLink()); // Place image link values.put(COLUMN_PLACE_LATITUDE, place.getLatitude()); // Place Location values.put(COLUMN_PLACE_LONGITUDE, place.getLongitude()); // Place Location values.put(COLUMN_PLACE_PHONE, place.getPhone()); // Place phone values.put(COLUMN_PLACE_FEATURED, place.getFeatured()); // Place phone values.put(COLUMN_PLACE_POPULAR, place.getPopular()); // Place phone values.put(COLUMN_PLACE_RECOMMENDED, place.getRecommended()); // Place phone values.put(COLUMN_PLACE_NO_RATINGS, place.getNoOfRatings()); // Place phone values.put(COLUMN_PLACE_ADMIN, place.getLeukAdmin()); // Place phone values.put(COLUMN_PLACE_VIEWS, place.getViews());//Place views values.put(COLUMN_PLACE_STATUS, place.getStatus()); // Place phone // Inserting Row db.insert(TABLE_PLACES, null, values); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); Log.d("bulk insert end", System.currentTimeMillis() + ""); } public ArrayList<Places> getAllPlaces() { String placeTypeQuery = "SELECT * FROM " + TABLE_PLACES + " ORDER BY " + COLUMN_PLACE_FEATURED + " DESC," + COLUMN_PLACE_POPULAR + " DESC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(placeTypeQuery, null); ArrayList<Places> places = new ArrayList<>(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); Places place = new Places(); place.setId(cursor.getString(0)); place.setName(cursor.getString(1)); place.setType(cursor.getString(2)); place.setMinimumSpending(cursor.getString(3)); place.setRating(cursor.getString(4)); place.setDescription(cursor.getString(5)); place.setAddress(cursor.getString(6)); place.setLocation(cursor.getString(7)); place.setPhotoLink(cursor.getString(8)); place.setLatitude(cursor.getString(9)); place.setLongitude(cursor.getString(10)); place.setPhone(cursor.getString(11)); place.setFeatured(cursor.getString(12)); place.setPopular(cursor.getString(13)); place.setRecommended(cursor.getString(14)); place.setNoOfRatings(cursor.getString(15)); place.setLeukAdmin(cursor.getString(16)); place.setViews(cursor.getString(17)); place.setStatus(cursor.getString(18)); places.add(place); } return places; } /** * Re crate database Delete all tables and create them again */ public void resetTables() { SQLiteDatabase db = this.getWritableDatabase(); // Delete All Rows db.delete(TABLE_USER, null, null); db.close(); } public void resetPlacesTable() { SQLiteDatabase db = this.getWritableDatabase(); // Delete All Rows try { db.delete(TABLE_PLACES, null, null); } catch (Exception e) { } db.close(); } public void deletePlacesFromType(String category) { String deleteFromType = "DELETE FROM " + TABLE_PLACES + " WHERE " + COLUMN_PLACE_TYPE + " ='" + category + "'"; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(deleteFromType); db.close(); } }
saiabishek1/Sansad
app/src/main/java/hackathon/com/sansad/SQLiteDBHelper.java
4,471
// Delete All Rows
line_comment
nl
package hackathon.com.sansad; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import hackathon.com.sansad.models.api.Data; import hackathon.com.sansad.models.api.Session; import hackathon.com.sansad.models.chat.Chat; import hackathon.com.sansad.models.chat.Messages; import hackathon.com.sansad.models.home.Notificationn; import hackathon.com.sansad.models.home.Offer; import hackathon.com.sansad.models.places.Places; import hackathon.com.sansad.models.user.User; import java.util.ArrayList; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ADDRESS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ADMIN; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_DESCRIPTION; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_FEATURED; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_ID; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_IMAGE_LINK; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LATITUDE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LOCATION; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_LONGITUDE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_MIN_COST; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_NAME; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_NO_RATINGS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_PHONE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_POPULAR; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_RATING; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_RECOMMENDED; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_STATUS; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_TYPE; import static hackathon.com.sansad.resources.Constants.COLUMN_PLACE_VIEWS; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_EMAIL; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_GENDER; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_IMAGE; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_NAME; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_SESSION; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_TOKEN; import static hackathon.com.sansad.resources.Constants.COLUMN_USER_USERNAME; public class SQLiteDBHelper extends SQLiteOpenHelper { // All Static variables // Database Version //last increased on 10th march 2016. Don't(preferably) increment unless a release was pushed before current day private static final int DATABASE_VERSION = 5; // Database Name private static final String DATABASE_LEUK = "sansad"; // Login table name private static final String TABLE_USER = "users"; private static final String TABLE_PLACES = "places"; ; public SQLiteDBHelper(Context context) { super(context, DATABASE_LEUK, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "(" + COLUMN_USER_NAME + " TEXT NOT NULL, " + COLUMN_USER_USERNAME + " TEXT PRIMARY KEY, " + COLUMN_USER_EMAIL + " TEXT NOT NULL, " + COLUMN_USER_GENDER + " TEXT NOT NULL, " + COLUMN_USER_IMAGE + " TEXT, " + COLUMN_USER_SESSION + " TEXT NOT NULL, " + COLUMN_USER_TOKEN + " TEXT NOT NULL " + ")"; String CREATE_PLACES_TABLE = "CREATE TABLE " + TABLE_PLACES + "(" + COLUMN_PLACE_ID + " TEXT PRIMARY KEY NOT NULL, " + COLUMN_PLACE_NAME + " TEXT , " + COLUMN_PLACE_TYPE + " TEXT NOT NULL, " + COLUMN_PLACE_MIN_COST + " TEXT, " + COLUMN_PLACE_RATING + " TEXT, " + COLUMN_PLACE_DESCRIPTION + " TEXT NOT NULL, " + COLUMN_PLACE_ADDRESS + " TEXT, " + COLUMN_PLACE_LOCATION + " TEXT, " + COLUMN_PLACE_IMAGE_LINK + " TEXT NOT NULL, " + COLUMN_PLACE_LATITUDE + " TEXT, " + COLUMN_PLACE_LONGITUDE + " TEXT, " + COLUMN_PLACE_PHONE + " TEXT, " + COLUMN_PLACE_FEATURED + " TEXT, " + COLUMN_PLACE_POPULAR + " TEXT, " + COLUMN_PLACE_RECOMMENDED + " TEXT, " + COLUMN_PLACE_NO_RATINGS + " TEXT, " + COLUMN_PLACE_ADMIN + " TEXT, " + COLUMN_PLACE_VIEWS + " TEXT, " + COLUMN_PLACE_STATUS + " TEXT " + ")"; db.execSQL(CREATE_LOGIN_TABLE); Log.d("database", "user created"); db.execSQL(CREATE_PLACES_TABLE); Log.d("database", "places created"); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER); db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLACES); // Create tables again onCreate(db); } /** * Storing user details in database */ public void addUser(String name, String username, String email, String gender, String phone, String location, String image, String level, String totalCredits, String remainingCredits, int maxCredits, String session, String token) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_USER_NAME, name); // Name values.put(COLUMN_USER_USERNAME, username); // Username values.put(COLUMN_USER_EMAIL, email); // Email values.put(COLUMN_USER_GENDER, gender); // Gender values.put(COLUMN_USER_IMAGE, image); // Image values.put(COLUMN_USER_SESSION, session); // Session ID values.put(COLUMN_USER_TOKEN, token); // Token // Inserting Row db.insert(TABLE_USER, null, values); db.close(); // Closing database connection } /** * Getting user data from database */ public Data getUserDetails() { String selectQuery = "SELECT * FROM " + TABLE_USER; Data data = new Data(); User user = new User(); Session session = new Session(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // Move to first row cursor.moveToFirst(); if (cursor.getCount() > 0) { user.setName(cursor.getString(0)); user.setUsername(cursor.getString(1)); user.setEmail(cursor.getString(2)); user.setGender(cursor.getString(3)); user.setProfileImg(cursor.getString(4)); session.setSessionid(cursor.getString(5)); session.setToken(cursor.getString(6)); data.setSession(session); data.setUser(user); } cursor.close(); db.close(); return data; } /** * Update user data in database */ public void updateUserDetails(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_USER_NAME, user.getName()); // Name values.put(COLUMN_USER_GENDER, user.getGender()); // Gender db.update(TABLE_USER, values, COLUMN_USER_USERNAME + "=\'" + user.getUsername() + "\'", null); } /** * Getting user login status return true if rows are there in table */ public int getRowCount() { String countQuery = "SELECT * FROM " + TABLE_USER; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); int rowCount = cursor.getCount(); db.close(); cursor.close(); // return row count return rowCount; } /** * Storing places in the database */ public void addPlace(Places place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_PLACE_ID, place.getId()); values.put(COLUMN_PLACE_NAME, place.getName()); // Place Name values.put(COLUMN_PLACE_TYPE, place.getType()); // Place Type values.put(COLUMN_PLACE_MIN_COST, place.getMinimumSpending()); // Place minimum spending values.put(COLUMN_PLACE_RATING, place.getRating()); // Place Rating values.put(COLUMN_PLACE_DESCRIPTION, place.getDescription()); // Place Description values.put(COLUMN_PLACE_ADDRESS, place.getAddress()); // Place Address values.put(COLUMN_PLACE_LOCATION, place.getLocation()); // Place Location values.put(COLUMN_PLACE_IMAGE_LINK, place.getPhotoLink()); // Place image link values.put(COLUMN_PLACE_LATITUDE, place.getLatitude()); // Place Location values.put(COLUMN_PLACE_LONGITUDE, place.getLongitude()); // Place Location values.put(COLUMN_PLACE_PHONE, place.getPhone()); // Place phone values.put(COLUMN_PLACE_FEATURED, place.getFeatured()); // Place phone values.put(COLUMN_PLACE_POPULAR, place.getPopular()); // Place phone values.put(COLUMN_PLACE_RECOMMENDED, place.getRecommended()); // Place phone values.put(COLUMN_PLACE_NO_RATINGS, place.getNoOfRatings()); // Place phone values.put(COLUMN_PLACE_ADMIN, place.getLeukAdmin()); // Place phone values.put(COLUMN_PLACE_VIEWS, place.getViews());//Place views values.put(COLUMN_PLACE_STATUS, place.getStatus()); // Place phone // Inserting Row db.insert(TABLE_PLACES, null, values); Log.d("database", "added place" + place.getName()); db.close(); // Closing database connection } public void addPlaces(ArrayList<Places> placesArrayList) { SQLiteDatabase db = this.getWritableDatabase(); db.beginTransaction(); Log.d("bulk insert start", System.currentTimeMillis() + ""); for (Places place : placesArrayList) { ContentValues values = new ContentValues(); values.put(COLUMN_PLACE_ID, place.getId()); values.put(COLUMN_PLACE_NAME, place.getName()); // Place Name values.put(COLUMN_PLACE_TYPE, place.getType()); // Place Type values.put(COLUMN_PLACE_MIN_COST, place.getMinimumSpending()); // Place minimum spending values.put(COLUMN_PLACE_RATING, place.getRating()); // Place Rating values.put(COLUMN_PLACE_DESCRIPTION, place.getDescription()); // Place Description values.put(COLUMN_PLACE_ADDRESS, place.getAddress()); // Place Address values.put(COLUMN_PLACE_LOCATION, place.getLocation()); // Place Location values.put(COLUMN_PLACE_IMAGE_LINK, place.getPhotoLink()); // Place image link values.put(COLUMN_PLACE_LATITUDE, place.getLatitude()); // Place Location values.put(COLUMN_PLACE_LONGITUDE, place.getLongitude()); // Place Location values.put(COLUMN_PLACE_PHONE, place.getPhone()); // Place phone values.put(COLUMN_PLACE_FEATURED, place.getFeatured()); // Place phone values.put(COLUMN_PLACE_POPULAR, place.getPopular()); // Place phone values.put(COLUMN_PLACE_RECOMMENDED, place.getRecommended()); // Place phone values.put(COLUMN_PLACE_NO_RATINGS, place.getNoOfRatings()); // Place phone values.put(COLUMN_PLACE_ADMIN, place.getLeukAdmin()); // Place phone values.put(COLUMN_PLACE_VIEWS, place.getViews());//Place views values.put(COLUMN_PLACE_STATUS, place.getStatus()); // Place phone // Inserting Row db.insert(TABLE_PLACES, null, values); } db.setTransactionSuccessful(); db.endTransaction(); db.close(); Log.d("bulk insert end", System.currentTimeMillis() + ""); } public ArrayList<Places> getAllPlaces() { String placeTypeQuery = "SELECT * FROM " + TABLE_PLACES + " ORDER BY " + COLUMN_PLACE_FEATURED + " DESC," + COLUMN_PLACE_POPULAR + " DESC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(placeTypeQuery, null); ArrayList<Places> places = new ArrayList<>(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); Places place = new Places(); place.setId(cursor.getString(0)); place.setName(cursor.getString(1)); place.setType(cursor.getString(2)); place.setMinimumSpending(cursor.getString(3)); place.setRating(cursor.getString(4)); place.setDescription(cursor.getString(5)); place.setAddress(cursor.getString(6)); place.setLocation(cursor.getString(7)); place.setPhotoLink(cursor.getString(8)); place.setLatitude(cursor.getString(9)); place.setLongitude(cursor.getString(10)); place.setPhone(cursor.getString(11)); place.setFeatured(cursor.getString(12)); place.setPopular(cursor.getString(13)); place.setRecommended(cursor.getString(14)); place.setNoOfRatings(cursor.getString(15)); place.setLeukAdmin(cursor.getString(16)); place.setViews(cursor.getString(17)); place.setStatus(cursor.getString(18)); places.add(place); } return places; } /** * Re crate database Delete all tables and create them again */ public void resetTables() { SQLiteDatabase db = this.getWritableDatabase(); // Delete All<SUF> db.delete(TABLE_USER, null, null); db.close(); } public void resetPlacesTable() { SQLiteDatabase db = this.getWritableDatabase(); // Delete All Rows try { db.delete(TABLE_PLACES, null, null); } catch (Exception e) { } db.close(); } public void deletePlacesFromType(String category) { String deleteFromType = "DELETE FROM " + TABLE_PLACES + " WHERE " + COLUMN_PLACE_TYPE + " ='" + category + "'"; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(deleteFromType); db.close(); } }
19609_12
package android.topdown.game; import android.gameengine.icadroids.objects.GameObject; import android.util.Log; public class Zombie extends LivingEntity { private int damage; private static int[] blockedTiles = { Level.ID_WALL }; //static pointer shared by all zombies private static Player player; private int numMoves, move; private boolean noticedPlayer; /** * @param hp amount of health point this zombie will have * @param speed the speed this zombie will have * @param damage the damage this zombie will be able to give per attack * @param player a pointer to the current player so the zombie can eat his brains */ public Zombie(int hp, double speed, int damage, Player player) { super(blockedTiles, hp, speed); this.damage = damage; Zombie.player = player; setSprite(getSpriteName()); numMoves = move = 0; noticedPlayer = false; } //chooses a random zombie sprite private String getSpriteName() { switch ((int) (Math.random() * 3 + 1)) { case 1: return "zombie1"; case 2: return "zombie2"; case 3: return "zombie3"; default: return "zombie4"; } } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#update() */ public void update() { super.update(); zombieNavigation(); if (playerWithin(12)) makeSound(); } //make a random sound private void makeSound() { if ((int) (Math.random() * 200) == 0) switch ((int) (Math.random() * 20)) { case 0: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT); break; case 1: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT2); break; case 2: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT3); break; case 3: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN1); break; case 4: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN2); break; case 5: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN3); break; case 6: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN4); break; } } //decide how to move private void zombieNavigation() { if ((seesPlayer() && playerWithin(8)) || playerWithin(3) || noticedPlayer) { clearRandom(); if (turnTowardPlayer()) { moveForward(); } if (!playerWithin(12)) noticedPlayer = false; } else { randomMove(); } } //clear the random move counter private void clearRandom() { numMoves = move = 0; } //move somewhere at random private void randomMove() { if (numMoves == 0) {// shit verzinnen numMoves = (int) (Math.random() * 20) + 20; move = (int) (Math.random() * 12); } else {// we moeten de huidige move nog een keer doen numMoves--; switch (move) { case 0: moveForward(); break; case 1: moveBackward(); break; case 2: rotate(4f); break; case 3: rotate(-4f); break; } } } //turn towards the player private boolean turnTowardPlayer() { int angle = getAngleToPlayer(); if (!(angle < 10 || angle > 350)) { if (angle <= 180) {// speler is rechts van ons rotate(7.5f); } else if (angle > 180) {// speler is links van ons rotate(-7.5f); } } if (angle < 20 || angle > 340) {// speler is dicht bij genoeg return true; } return false; } //returns true if the player is in front of the zombie private boolean seesPlayer() { if (getAngleToPlayer() > 320 || getAngleToPlayer() < 40) { return true; } return false; } //returns true if the player is within a certain amount of tiles private boolean playerWithin(int tiles) { float zx = getCenterX(); float zy = getCenterY(); float px = player.getCenterX(); float py = player.getCenterY(); int dy = Math.round(Math.abs(zy - py)); int dx = Math.round(Math.abs(zx - px)); if (Math.sqrt(dx * dx + dy * dy) < Level.TILE_SIZE * tiles) return true; return false; } //returns the angle to the player private int getAngleToPlayer() { float zx = getCenterX(); float zy = getCenterY(); float px = player.getCenterX(); float py = player.getCenterY(); double rot = getRotation(); double angle = Math.toDegrees(Math.atan2(zy - py, zx - px)); if (angle + (270 - rot) < 0) angle += (270 - rot) + 360; else if (angle + (270 - rot) > 360) angle += (270 - rot) - 360; else angle += (270 - rot); return (int) Math.round(angle); } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#objectCollision(android.gameengine.icadroids.objects.GameObject) */ @Override protected void objectCollision(GameObject g) { if (g instanceof Bullet) { hurt(((Bullet) g).getDamage()); g.deleteThisGameObject(); switch ((int) (Math.random() * 3)) { case 1: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT); break; case 2: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT2); break; default: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT3); } if (!noticedPlayer) noticedPlayer = !noticedPlayer; Log.i("collision", "zombievsbullet"); } else if (g instanceof Zombie && !g.equals(this)) { rotate((float) (Math.random() * 7.5f - 3.75)); } } /** * @return the amount of damage this zombie can do per attack */ public int getDamage() { return damage; } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#die() */ @Override public void die() { super.die(); Game.ZombieDeath(); switch ((int) (Math.random() * 40)) { case 2: SoundLib.play(SoundLib.FERDI_JIJGAATDOOD); break; case 3: SoundLib.play(SoundLib.FERDI_PUNCHINBALLS); break; case 4: SoundLib.play(SoundLib.FERDI_TAKEITLIKEABOSS); break; case 5: SoundLib.play(SoundLib.FERDI_THATSUREWASEASY); break; case 6: SoundLib.play(SoundLib.FERDI_TASTYBACONSTRIPS); break; case 7: SoundLib.play(SoundLib.FERDI_BANAAN); break; case 8: SoundLib.play(SoundLib.FERDI_BANAAN2); break; case 9: SoundLib.play(SoundLib.FERDI_BANAAN3); break; case 10: SoundLib.play(SoundLib.FERDI_BANAAN4); break; case 11: SoundLib.play(SoundLib.FERDI_BITCHPLEASE2); break; case 12: SoundLib.play(SoundLib.FERDI_ZONDERSOUND); break; default: if ((int) (Math.random() * 2) == 0) SoundLib.play(SoundLib.FERDI_HA); else SoundLib.play(SoundLib.FERDI_HMM); } Game.addPoints(25); } }
saifsultanc/Android-Top-Down-Game
ICA_DROID/src/android/topdown/game/Zombie.java
2,441
// speler is dicht bij genoeg
line_comment
nl
package android.topdown.game; import android.gameengine.icadroids.objects.GameObject; import android.util.Log; public class Zombie extends LivingEntity { private int damage; private static int[] blockedTiles = { Level.ID_WALL }; //static pointer shared by all zombies private static Player player; private int numMoves, move; private boolean noticedPlayer; /** * @param hp amount of health point this zombie will have * @param speed the speed this zombie will have * @param damage the damage this zombie will be able to give per attack * @param player a pointer to the current player so the zombie can eat his brains */ public Zombie(int hp, double speed, int damage, Player player) { super(blockedTiles, hp, speed); this.damage = damage; Zombie.player = player; setSprite(getSpriteName()); numMoves = move = 0; noticedPlayer = false; } //chooses a random zombie sprite private String getSpriteName() { switch ((int) (Math.random() * 3 + 1)) { case 1: return "zombie1"; case 2: return "zombie2"; case 3: return "zombie3"; default: return "zombie4"; } } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#update() */ public void update() { super.update(); zombieNavigation(); if (playerWithin(12)) makeSound(); } //make a random sound private void makeSound() { if ((int) (Math.random() * 200) == 0) switch ((int) (Math.random() * 20)) { case 0: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT); break; case 1: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT2); break; case 2: SoundLib.play(SoundLib.ZOMBIE_ZOMGRUNT3); break; case 3: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN1); break; case 4: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN2); break; case 5: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN3); break; case 6: SoundLib.play(SoundLib.ZOMBIE_ZOMMOAN4); break; } } //decide how to move private void zombieNavigation() { if ((seesPlayer() && playerWithin(8)) || playerWithin(3) || noticedPlayer) { clearRandom(); if (turnTowardPlayer()) { moveForward(); } if (!playerWithin(12)) noticedPlayer = false; } else { randomMove(); } } //clear the random move counter private void clearRandom() { numMoves = move = 0; } //move somewhere at random private void randomMove() { if (numMoves == 0) {// shit verzinnen numMoves = (int) (Math.random() * 20) + 20; move = (int) (Math.random() * 12); } else {// we moeten de huidige move nog een keer doen numMoves--; switch (move) { case 0: moveForward(); break; case 1: moveBackward(); break; case 2: rotate(4f); break; case 3: rotate(-4f); break; } } } //turn towards the player private boolean turnTowardPlayer() { int angle = getAngleToPlayer(); if (!(angle < 10 || angle > 350)) { if (angle <= 180) {// speler is rechts van ons rotate(7.5f); } else if (angle > 180) {// speler is links van ons rotate(-7.5f); } } if (angle < 20 || angle > 340) {// speler is<SUF> return true; } return false; } //returns true if the player is in front of the zombie private boolean seesPlayer() { if (getAngleToPlayer() > 320 || getAngleToPlayer() < 40) { return true; } return false; } //returns true if the player is within a certain amount of tiles private boolean playerWithin(int tiles) { float zx = getCenterX(); float zy = getCenterY(); float px = player.getCenterX(); float py = player.getCenterY(); int dy = Math.round(Math.abs(zy - py)); int dx = Math.round(Math.abs(zx - px)); if (Math.sqrt(dx * dx + dy * dy) < Level.TILE_SIZE * tiles) return true; return false; } //returns the angle to the player private int getAngleToPlayer() { float zx = getCenterX(); float zy = getCenterY(); float px = player.getCenterX(); float py = player.getCenterY(); double rot = getRotation(); double angle = Math.toDegrees(Math.atan2(zy - py, zx - px)); if (angle + (270 - rot) < 0) angle += (270 - rot) + 360; else if (angle + (270 - rot) > 360) angle += (270 - rot) - 360; else angle += (270 - rot); return (int) Math.round(angle); } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#objectCollision(android.gameengine.icadroids.objects.GameObject) */ @Override protected void objectCollision(GameObject g) { if (g instanceof Bullet) { hurt(((Bullet) g).getDamage()); g.deleteThisGameObject(); switch ((int) (Math.random() * 3)) { case 1: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT); break; case 2: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT2); break; default: SoundLib.play(SoundLib.ZOMBIE_ZOMSHORT3); } if (!noticedPlayer) noticedPlayer = !noticedPlayer; Log.i("collision", "zombievsbullet"); } else if (g instanceof Zombie && !g.equals(this)) { rotate((float) (Math.random() * 7.5f - 3.75)); } } /** * @return the amount of damage this zombie can do per attack */ public int getDamage() { return damage; } /* (non-Javadoc) * @see android.topdown.game.LivingEntity#die() */ @Override public void die() { super.die(); Game.ZombieDeath(); switch ((int) (Math.random() * 40)) { case 2: SoundLib.play(SoundLib.FERDI_JIJGAATDOOD); break; case 3: SoundLib.play(SoundLib.FERDI_PUNCHINBALLS); break; case 4: SoundLib.play(SoundLib.FERDI_TAKEITLIKEABOSS); break; case 5: SoundLib.play(SoundLib.FERDI_THATSUREWASEASY); break; case 6: SoundLib.play(SoundLib.FERDI_TASTYBACONSTRIPS); break; case 7: SoundLib.play(SoundLib.FERDI_BANAAN); break; case 8: SoundLib.play(SoundLib.FERDI_BANAAN2); break; case 9: SoundLib.play(SoundLib.FERDI_BANAAN3); break; case 10: SoundLib.play(SoundLib.FERDI_BANAAN4); break; case 11: SoundLib.play(SoundLib.FERDI_BITCHPLEASE2); break; case 12: SoundLib.play(SoundLib.FERDI_ZONDERSOUND); break; default: if ((int) (Math.random() * 2) == 0) SoundLib.play(SoundLib.FERDI_HA); else SoundLib.play(SoundLib.FERDI_HMM); } Game.addPoints(25); } }
23517_0
package org.example.h12; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) // tot waar moet de annotatie behouden blijven? public @interface Bram { String[] value() default ""; int age() default 0; }
sajanssens/bd2020-live-code
javase/src/main/java/org/example/h12/Bram.java
119
// tot waar moet de annotatie behouden blijven?
line_comment
nl
package org.example.h12; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) // tot waar<SUF> public @interface Bram { String[] value() default ""; int age() default 0; }
107567_1
package javabd.slides.h12_annotations; import java.lang.annotation.*; // @Documented // Deze annotatie moet NIET getoond worden in de javadoc van het element waar hij op staat: @Retention(RetentionPolicy.RUNTIME) // Tot waar wordt deze annotatie meegenomen? SOURCE: alleen in source, niet in gecompileerde class en ook niet at runtime beschikbaar. @Target(ElementType.METHOD) // deze annotatie mag op een method public @interface MyAnnotation2 { String value() default "Hello2"; }
sajanssens/bd2023
blok1/src/main/java/javabd/slides/h12_annotations/MyAnnotation2.java
142
// Tot waar wordt deze annotatie meegenomen? SOURCE: alleen in source, niet in gecompileerde class en ook niet at runtime beschikbaar.
line_comment
nl
package javabd.slides.h12_annotations; import java.lang.annotation.*; // @Documented // Deze annotatie moet NIET getoond worden in de javadoc van het element waar hij op staat: @Retention(RetentionPolicy.RUNTIME) // Tot waar<SUF> @Target(ElementType.METHOD) // deze annotatie mag op een method public @interface MyAnnotation2 { String value() default "Hello2"; }
188193_64
/** * Copyright (c) 2008-2012 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-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.sakaiproject.profile2.util; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.imageio.ImageIO; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.text.WordUtils; import org.imgscalr.Scalr; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.api.FormattedText; import lombok.extern.slf4j.Slf4j; @Slf4j public class ProfileUtils { /** * Check content type against allowed types. only JPEG,GIF and PNG are support at the moment * * @param contentType string of the content type determined by some image parser */ public static boolean checkContentTypeForProfileImage(String contentType) { ArrayList<String> allowedTypes = new ArrayList<String>(); allowedTypes.add("image/jpeg"); allowedTypes.add("image/gif"); allowedTypes.add("image/png"); //Adding MIME types that Internet Explorer returns PRFL-98 allowedTypes.add("image/x-png"); allowedTypes.add("image/pjpeg"); allowedTypes.add("image/jpg"); //add more here as required, BUT also add them below. //You will need to check ImageIO for the informal names. if(allowedTypes.contains(contentType)) { return true; } return false; } /** * Helper to get the informal format name that is used by ImageIO. * We have access to the mimetype so we can map them. * * <p>If no valid mapping is found, it will default to "jpg". * * @param mimeType the mimetype of the original image, eg image/jpeg */ public static String getInformalFormatForMimeType(String mimeType){ Map<String,String> formats = new HashMap<String,String>(); formats.put("image/jpeg", "jpg"); formats.put("image/gif", "gif"); formats.put("image/png", "png"); formats.put("image/x-png", "png"); formats.put("image/pjpeg", "jpg"); formats.put("image/jpg", "jpg"); String format = formats.get(mimeType); if(format != null) { return format; } return "jpg"; } public static byte[] scaleImage(byte[] imageData, int maxSize, String mimeType) { InputStream in = null; try { in = new ByteArrayInputStream(imageData); return scaleImage(in, maxSize, mimeType); } finally { if (in != null) { try { in.close(); log.debug("Image stream closed."); } catch (IOException e) { log.error("Error closing image stream: ", e); } } } } /** * Scale an image so it is fit within a give width and height, whilst maintaining its original proportions * * @param imageData bytes of the original image * @param maxSize maximum dimension in px */ public static byte[] scaleImage(InputStream in, int maxSize, String mimeType) { byte[] scaledImageBytes = null; try { //convert original image to inputstream //original buffered image BufferedImage originalImage = ImageIO.read(in); //scale the image using the imgscalr library BufferedImage scaledImage = Scalr.resize(originalImage, maxSize); //convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos); baos.flush(); scaledImageBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { log.error("Scaling image failed.", e); } return scaledImageBytes; } /** * Convert a Date into a String according to format, or, if format * is set to null, do a current locale based conversion. * * @param date date to convert * @param format format in SimpleDateFormat syntax. Set to null to force as locale based conversion. */ public static String convertDateToString(Date date, String format) { if(date == null || "".equals(format)) { throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()"); } String dateStr = null; if(format != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateStr = dateFormat.format(date); } else { // Since no specific format has been specced, we use the user's locale. Locale userLocale = (new ResourceLoader()).getLocale(); DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale); dateStr = formatter.format(date); } if(log.isDebugEnabled()) { log.debug("Profile.convertDateToString(): Input date: " + date.toString()); log.debug("Profile.convertDateToString(): Converted date string: " + dateStr); } return dateStr; } /** * Convert a string into a Date object (reverse of above * * @param dateStr date string to convert * @param format format of the input date in SimpleDateFormat syntax */ public static Date convertStringToDate(String dateStr, String format) { if("".equals(dateStr) || "".equals(format)) { throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()"); } SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { Date date = dateFormat.parse(dateStr); log.debug("Profile.convertStringToDate(): Input date string: " + dateStr); log.debug("Profile.convertStringToDate(): Converted date: " + date.toString()); return date; } catch (ParseException e) { log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage()); return null; } } /** * Strip the year from a given date (actually just sets it to 1) * * @param date original date * @return */ public static Date stripYear(Date date){ return DateUtils.setYears(date, 1); } /** * Get the localised name of the day (ie Monday for en, Maandag for nl) * @param day int according to Calendar.DAY_OF_WEEK * @param locale locale to render dayname in * @return */ public static String getDayName(int day, Locale locale) { //localised daynames String dayNames[] = new DateFormatSymbols(locale).getWeekdays(); String dayName = null; try { dayName = dayNames[day]; } catch (Exception e) { log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage()); } return dayName; } /** * Convert a string to propercase. ie This Is Proper Text * @param input string to be formatted * @return */ public static String toProperCase(String input) { return WordUtils.capitalizeFully(input); } /** * Convert a date into a field like "just then, 2 minutes ago, 4 hours ago, yesterday, on sunday, etc" * * @param date date to convert */ public static String convertDateForStatus(Date date) { //current time Calendar currentCal = Calendar.getInstance(); long currentTimeMillis = currentCal.getTimeInMillis(); //posting time long postingTimeMillis = date.getTime(); //difference int diff = (int)(currentTimeMillis - postingTimeMillis); Locale locale = getUserPreferredLocale(); //log.info("currentDate:" + currentTimeMillis); //log.info("postingDate:" + postingTimeMillis); //log.info("diff:" + diff); int MILLIS_IN_SECOND = 1000; int MILLIS_IN_MINUTE = 1000 * 60; int MILLIS_IN_HOUR = 1000 * 60 * 60; int MILLIS_IN_DAY = 1000 * 60 * 60 * 24; int MILLIS_IN_WEEK = 1000 * 60 * 60 * 24 * 7; if(diff < MILLIS_IN_SECOND) { //less than a second return Messages.getString("Label.just_then"); } else if (diff < MILLIS_IN_MINUTE) { //less than a minute, calc seconds int numSeconds = diff/MILLIS_IN_SECOND; if(numSeconds == 1) { //one sec return Messages.getString("Label.second_ago", new Object[] {numSeconds}); } else { //more than one sec return Messages.getString("Label.seconds_ago", new Object[] {numSeconds}); } } else if (diff < MILLIS_IN_HOUR) { //less than an hour, calc minutes int numMinutes = diff/MILLIS_IN_MINUTE; if(numMinutes == 1) { //one minute return Messages.getString("Label.minute_ago", new Object[] {numMinutes}); } else { //more than one minute return Messages.getString("Label.minutes_ago", new Object[] {numMinutes}); } } else if (diff < MILLIS_IN_DAY) { //less than a day, calc hours int numHours = diff/MILLIS_IN_HOUR; if(numHours == 1) { //one hour return Messages.getString("Label.hour_ago", new Object[] {numHours}); } else { //more than one hour return Messages.getString("Label.hours_ago", new Object[] {numHours}); } } else if (diff < MILLIS_IN_WEEK) { //less than a week, calculate days int numDays = diff/MILLIS_IN_DAY; //now calculate which day it was if(numDays == 1) { return Messages.getString("Label.yesterday"); } else { //set calendar and get day of week Calendar postingCal = Calendar.getInstance(); postingCal.setTimeInMillis(postingTimeMillis); int postingDay = postingCal.get(Calendar.DAY_OF_WEEK); //set to localised value: 'on Wednesday' for example String dayName = getDayName(postingDay,locale); if(dayName != null) { return Messages.getString("Label.on", new Object[] {toProperCase(dayName)}); } } } else { //over a week ago, we want it blank though. } return null; } /** * Gets the users preferred locale, either from the user's session or Sakai preferences and returns it * This depends on Sakai's ResourceLoader. * * @return */ public static Locale getUserPreferredLocale() { ResourceLoader rl = new ResourceLoader(); return rl.getLocale(); } /** * Gets the users preferred orientation, either from the user's session or Sakai preferences and returns it * This depends on Sakai's ResourceLoader. * * @return */ public static String getUserPreferredOrientation() { ResourceLoader rl = new ResourceLoader(); return rl.getOrientation(rl.getLocale()); } /** * Creates a full profile event reference for a given reference * @param ref * @return */ public static String createEventRef(String ref) { return "/profile/"+ref; } /** * Method for getting a value from a map based on the given key, but if it does not exist, use the given default * @param map * @param key * @param defaultValue * @return */ public static Object getValueFromMapOrDefault(Map<?,?> map, Object key, Object defaultValue) { return (map.containsKey(key) ? map.get(key) : defaultValue); } /** * Method to chop a String into it's parts based on the separator and return as a List. Useful for multi valued Sakai properties * @param str the String to split * @param separator separator character * @return */ public static List<String> getListFromString(String str, char separator) { String[] items = StringUtils.split(str, separator); return Arrays.asList(items); } /** * Processes HTML and escapes evils tags like &lt;script&gt;, also converts newlines to proper HTML breaks. * @param s * @return */ public static String processHtml(String s){ return ComponentManager.get(FormattedText.class).processFormattedText(s, new StringBuilder(), true, false); } /** * Strips string of HTML and returns plain text. * * @param s * @return */ public static String stripHtml(String s) { return ComponentManager.get(FormattedText.class).convertFormattedTextToPlaintext(s); } /** * Strips string of HTML, escaping anything that is left to return plain text. * * <p>Deals better with poorly formed HTML than just stripHtml and is best for XSS protection, not for storing actual data. * * @param s The string to process * @return */ public static String stripAndCleanHtml(String s) { //Attempt to strip HTML. This doesn't work on poorly formatted HTML though String stripped = ComponentManager.get(FormattedText.class).convertFormattedTextToPlaintext(s); //so we escape anything that is left return StringEscapeUtils.escapeHtml4(stripped); } /** * Strips html/xml tags from a string and returns the cleaned version. * * @param text any text (if this is null or empty then the input text is returned unchanged) * @param smartSpacing if true then try to make the text represent the intent of the html, * trims out duplicate spaces, converts block type html into a space, etc., * else just removes html tags and leaves all other parts of the string intact, * NOTE: false is also slightly faster * @param stripEscapeSequences if true, strips out any escape sequences such as '&nbsp;' * @return the cleaned string * @see #convertFormattedTextToPlaintext(String) for alternative mechanism */ public static String stripHtmlFromText(String text, boolean smartSpacing, boolean stripEscapeSequences) { return ComponentManager.get(FormattedText.class).stripHtmlFromText(text, smartSpacing, stripEscapeSequences); } /** * Trims text to the given maximum number of displayed characters. * Supports HTML and preserves formatting. * * @param s the string * @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags. * @param isHtml is the string HTML? * @return */ public static String truncate(String s, int maxNumOfChars, boolean isHtml) { if (StringUtils.isBlank(s)) { return ""; } //html if(isHtml) { StringBuilder trimmedHtml = new StringBuilder(); ComponentManager.get(FormattedText.class).trimFormattedText(s, maxNumOfChars, trimmedHtml); return trimmedHtml.toString(); } //plain text return StringUtils.substring(s, 0, maxNumOfChars); } /** * Trims and abbreviates text to the given maximum number of displayed * characters (less 3 characters, in case "..." must be appended). * Supports HTML and preserves formatting. * * @param s the string * @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags. * @param isHtml is the string HTML? * @return */ public static String truncateAndAbbreviate(String s, int maxNumOfChars, boolean isHtml) { if (StringUtils.isBlank(s)) { return ""; } //html if(isHtml) { StringBuilder trimmedHtml = new StringBuilder(); boolean trimmed = ComponentManager.get(FormattedText.class).trimFormattedText(s, maxNumOfChars - 3, trimmedHtml); if (trimmed) { int index = trimmedHtml.lastIndexOf("</"); if (-1 != index) { trimmedHtml.insert(index, "..."); } else { trimmedHtml.append("..."); } } return trimmedHtml.toString(); } //plain text return StringUtils.abbreviate(s, maxNumOfChars); } /** * Generate a UUID * @return */ public static String generateUuid() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } /** * Returns the SkypeMe URL for the specified Skype username. * * @param skypeUsername * @return the SkypeMe URL for the specified Skype username. */ public static String getSkypeMeURL(String skypeUsername) { return "skype:" + skypeUsername + "?call"; } /** * Remove duplicates from a list, order is not retained. * * @param list list of objects to clean */ public static <T> void removeDuplicates(List<T> list){ Set<T> set = new HashSet<T>(); set.addAll(list); list.clear(); list.addAll(set); } /** * Remove duplicates from a list, order is retained. * * @param list list of objects to clean */ public static <T> void removeDuplicatesWithOrder(List<T> list) { Set<T> set = new HashSet<T> (); List<T> newList = new ArrayList<T>(); for(T e: list) { if (set.add(e)) { newList.add(e); } } list.clear(); list.addAll(newList); } /** * Calculate an MD5 hash of a string * @param s String to hash * @return MD5 hash as a String */ public static String calculateMD5(String s){ return DigestUtils.md5Hex(s); } /** * Creates a square avatar image by taking a segment out of the centre of the original image and resizing to the appropriate dimensions * * @param imageData original bytes of the image * @param mimeType mimetype of image * @return */ public static byte[] createAvatar(byte[] imageData, String mimeType) { InputStream in = null; byte[] outputBytes = null; try { //convert original image to inputstream in = new ByteArrayInputStream(imageData); //original buffered image BufferedImage originalImage = ImageIO.read(in); //OPTION 1 //determine the smaller side of the image and use that as the size of the cropped square //to be taken out of the centre //then resize to the avatar size =80 square. int smallestSide = originalImage.getWidth(); if(originalImage.getHeight() < originalImage.getWidth()) { smallestSide = originalImage.getHeight(); } if(log.isDebugEnabled()){ log.debug("smallestSide:" + smallestSide); } int startX = (originalImage.getWidth() / 2) - (smallestSide/2); int startY = (originalImage.getHeight() / 2) - (smallestSide/2); //OPTION 2 (unused) //determine a percentage of the original image which we want to keep, say 90%. //then figure out the dimensions of the box and crop to that. //then resize to the avatar size =80 square. //int percentWidth = (originalImage.getWidth() / 100) * 90; //int startX = (originalImage.getWidth() / 2) - (percentWidth/2); //int percentHeight = (originalImage.getHeight() / 100) * 90; //int startY = (originalImage.getHeight() / 2) - (percentHeight/2); //log.debug("percentWidth:" + percentWidth); //log.debug("percentHeight:" + percentHeight); //so it is square, we can only use one dimension for both side, so choose the smaller one //int croppedSize = percentWidth; //if(percentHeight < percentWidth) { // croppedSize = percentHeight; //} //log.debug("croppedSize:" + croppedSize); if(log.isDebugEnabled()){ log.debug("originalImage.getWidth():" + originalImage.getWidth()); log.debug("originalImage.getHeight():" + originalImage.getHeight()); log.debug("startX:" + startX); log.debug("startY:" + startY); } //crop to these bounds and starting positions BufferedImage croppedImage = Scalr.crop(originalImage, startX, startY, smallestSide, smallestSide); //now resize it to the desired avatar size BufferedImage scaledImage = Scalr.resize(croppedImage, 80); //convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos); baos.flush(); outputBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { log.error("Cropping and scaling image failed.", e); } finally { if (in != null) { try { in.close(); log.debug("Image stream closed."); } catch (IOException e) { log.error("Error closing image stream: ", e); } } } return outputBytes; } }
sakaiproject/sakai
profile2/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java
6,575
//int startY = (originalImage.getHeight() / 2) - (percentHeight/2);
line_comment
nl
/** * Copyright (c) 2008-2012 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-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.sakaiproject.profile2.util; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.imageio.ImageIO; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.text.WordUtils; import org.imgscalr.Scalr; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.api.FormattedText; import lombok.extern.slf4j.Slf4j; @Slf4j public class ProfileUtils { /** * Check content type against allowed types. only JPEG,GIF and PNG are support at the moment * * @param contentType string of the content type determined by some image parser */ public static boolean checkContentTypeForProfileImage(String contentType) { ArrayList<String> allowedTypes = new ArrayList<String>(); allowedTypes.add("image/jpeg"); allowedTypes.add("image/gif"); allowedTypes.add("image/png"); //Adding MIME types that Internet Explorer returns PRFL-98 allowedTypes.add("image/x-png"); allowedTypes.add("image/pjpeg"); allowedTypes.add("image/jpg"); //add more here as required, BUT also add them below. //You will need to check ImageIO for the informal names. if(allowedTypes.contains(contentType)) { return true; } return false; } /** * Helper to get the informal format name that is used by ImageIO. * We have access to the mimetype so we can map them. * * <p>If no valid mapping is found, it will default to "jpg". * * @param mimeType the mimetype of the original image, eg image/jpeg */ public static String getInformalFormatForMimeType(String mimeType){ Map<String,String> formats = new HashMap<String,String>(); formats.put("image/jpeg", "jpg"); formats.put("image/gif", "gif"); formats.put("image/png", "png"); formats.put("image/x-png", "png"); formats.put("image/pjpeg", "jpg"); formats.put("image/jpg", "jpg"); String format = formats.get(mimeType); if(format != null) { return format; } return "jpg"; } public static byte[] scaleImage(byte[] imageData, int maxSize, String mimeType) { InputStream in = null; try { in = new ByteArrayInputStream(imageData); return scaleImage(in, maxSize, mimeType); } finally { if (in != null) { try { in.close(); log.debug("Image stream closed."); } catch (IOException e) { log.error("Error closing image stream: ", e); } } } } /** * Scale an image so it is fit within a give width and height, whilst maintaining its original proportions * * @param imageData bytes of the original image * @param maxSize maximum dimension in px */ public static byte[] scaleImage(InputStream in, int maxSize, String mimeType) { byte[] scaledImageBytes = null; try { //convert original image to inputstream //original buffered image BufferedImage originalImage = ImageIO.read(in); //scale the image using the imgscalr library BufferedImage scaledImage = Scalr.resize(originalImage, maxSize); //convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos); baos.flush(); scaledImageBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { log.error("Scaling image failed.", e); } return scaledImageBytes; } /** * Convert a Date into a String according to format, or, if format * is set to null, do a current locale based conversion. * * @param date date to convert * @param format format in SimpleDateFormat syntax. Set to null to force as locale based conversion. */ public static String convertDateToString(Date date, String format) { if(date == null || "".equals(format)) { throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()"); } String dateStr = null; if(format != null) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateStr = dateFormat.format(date); } else { // Since no specific format has been specced, we use the user's locale. Locale userLocale = (new ResourceLoader()).getLocale(); DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale); dateStr = formatter.format(date); } if(log.isDebugEnabled()) { log.debug("Profile.convertDateToString(): Input date: " + date.toString()); log.debug("Profile.convertDateToString(): Converted date string: " + dateStr); } return dateStr; } /** * Convert a string into a Date object (reverse of above * * @param dateStr date string to convert * @param format format of the input date in SimpleDateFormat syntax */ public static Date convertStringToDate(String dateStr, String format) { if("".equals(dateStr) || "".equals(format)) { throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()"); } SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { Date date = dateFormat.parse(dateStr); log.debug("Profile.convertStringToDate(): Input date string: " + dateStr); log.debug("Profile.convertStringToDate(): Converted date: " + date.toString()); return date; } catch (ParseException e) { log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage()); return null; } } /** * Strip the year from a given date (actually just sets it to 1) * * @param date original date * @return */ public static Date stripYear(Date date){ return DateUtils.setYears(date, 1); } /** * Get the localised name of the day (ie Monday for en, Maandag for nl) * @param day int according to Calendar.DAY_OF_WEEK * @param locale locale to render dayname in * @return */ public static String getDayName(int day, Locale locale) { //localised daynames String dayNames[] = new DateFormatSymbols(locale).getWeekdays(); String dayName = null; try { dayName = dayNames[day]; } catch (Exception e) { log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage()); } return dayName; } /** * Convert a string to propercase. ie This Is Proper Text * @param input string to be formatted * @return */ public static String toProperCase(String input) { return WordUtils.capitalizeFully(input); } /** * Convert a date into a field like "just then, 2 minutes ago, 4 hours ago, yesterday, on sunday, etc" * * @param date date to convert */ public static String convertDateForStatus(Date date) { //current time Calendar currentCal = Calendar.getInstance(); long currentTimeMillis = currentCal.getTimeInMillis(); //posting time long postingTimeMillis = date.getTime(); //difference int diff = (int)(currentTimeMillis - postingTimeMillis); Locale locale = getUserPreferredLocale(); //log.info("currentDate:" + currentTimeMillis); //log.info("postingDate:" + postingTimeMillis); //log.info("diff:" + diff); int MILLIS_IN_SECOND = 1000; int MILLIS_IN_MINUTE = 1000 * 60; int MILLIS_IN_HOUR = 1000 * 60 * 60; int MILLIS_IN_DAY = 1000 * 60 * 60 * 24; int MILLIS_IN_WEEK = 1000 * 60 * 60 * 24 * 7; if(diff < MILLIS_IN_SECOND) { //less than a second return Messages.getString("Label.just_then"); } else if (diff < MILLIS_IN_MINUTE) { //less than a minute, calc seconds int numSeconds = diff/MILLIS_IN_SECOND; if(numSeconds == 1) { //one sec return Messages.getString("Label.second_ago", new Object[] {numSeconds}); } else { //more than one sec return Messages.getString("Label.seconds_ago", new Object[] {numSeconds}); } } else if (diff < MILLIS_IN_HOUR) { //less than an hour, calc minutes int numMinutes = diff/MILLIS_IN_MINUTE; if(numMinutes == 1) { //one minute return Messages.getString("Label.minute_ago", new Object[] {numMinutes}); } else { //more than one minute return Messages.getString("Label.minutes_ago", new Object[] {numMinutes}); } } else if (diff < MILLIS_IN_DAY) { //less than a day, calc hours int numHours = diff/MILLIS_IN_HOUR; if(numHours == 1) { //one hour return Messages.getString("Label.hour_ago", new Object[] {numHours}); } else { //more than one hour return Messages.getString("Label.hours_ago", new Object[] {numHours}); } } else if (diff < MILLIS_IN_WEEK) { //less than a week, calculate days int numDays = diff/MILLIS_IN_DAY; //now calculate which day it was if(numDays == 1) { return Messages.getString("Label.yesterday"); } else { //set calendar and get day of week Calendar postingCal = Calendar.getInstance(); postingCal.setTimeInMillis(postingTimeMillis); int postingDay = postingCal.get(Calendar.DAY_OF_WEEK); //set to localised value: 'on Wednesday' for example String dayName = getDayName(postingDay,locale); if(dayName != null) { return Messages.getString("Label.on", new Object[] {toProperCase(dayName)}); } } } else { //over a week ago, we want it blank though. } return null; } /** * Gets the users preferred locale, either from the user's session or Sakai preferences and returns it * This depends on Sakai's ResourceLoader. * * @return */ public static Locale getUserPreferredLocale() { ResourceLoader rl = new ResourceLoader(); return rl.getLocale(); } /** * Gets the users preferred orientation, either from the user's session or Sakai preferences and returns it * This depends on Sakai's ResourceLoader. * * @return */ public static String getUserPreferredOrientation() { ResourceLoader rl = new ResourceLoader(); return rl.getOrientation(rl.getLocale()); } /** * Creates a full profile event reference for a given reference * @param ref * @return */ public static String createEventRef(String ref) { return "/profile/"+ref; } /** * Method for getting a value from a map based on the given key, but if it does not exist, use the given default * @param map * @param key * @param defaultValue * @return */ public static Object getValueFromMapOrDefault(Map<?,?> map, Object key, Object defaultValue) { return (map.containsKey(key) ? map.get(key) : defaultValue); } /** * Method to chop a String into it's parts based on the separator and return as a List. Useful for multi valued Sakai properties * @param str the String to split * @param separator separator character * @return */ public static List<String> getListFromString(String str, char separator) { String[] items = StringUtils.split(str, separator); return Arrays.asList(items); } /** * Processes HTML and escapes evils tags like &lt;script&gt;, also converts newlines to proper HTML breaks. * @param s * @return */ public static String processHtml(String s){ return ComponentManager.get(FormattedText.class).processFormattedText(s, new StringBuilder(), true, false); } /** * Strips string of HTML and returns plain text. * * @param s * @return */ public static String stripHtml(String s) { return ComponentManager.get(FormattedText.class).convertFormattedTextToPlaintext(s); } /** * Strips string of HTML, escaping anything that is left to return plain text. * * <p>Deals better with poorly formed HTML than just stripHtml and is best for XSS protection, not for storing actual data. * * @param s The string to process * @return */ public static String stripAndCleanHtml(String s) { //Attempt to strip HTML. This doesn't work on poorly formatted HTML though String stripped = ComponentManager.get(FormattedText.class).convertFormattedTextToPlaintext(s); //so we escape anything that is left return StringEscapeUtils.escapeHtml4(stripped); } /** * Strips html/xml tags from a string and returns the cleaned version. * * @param text any text (if this is null or empty then the input text is returned unchanged) * @param smartSpacing if true then try to make the text represent the intent of the html, * trims out duplicate spaces, converts block type html into a space, etc., * else just removes html tags and leaves all other parts of the string intact, * NOTE: false is also slightly faster * @param stripEscapeSequences if true, strips out any escape sequences such as '&nbsp;' * @return the cleaned string * @see #convertFormattedTextToPlaintext(String) for alternative mechanism */ public static String stripHtmlFromText(String text, boolean smartSpacing, boolean stripEscapeSequences) { return ComponentManager.get(FormattedText.class).stripHtmlFromText(text, smartSpacing, stripEscapeSequences); } /** * Trims text to the given maximum number of displayed characters. * Supports HTML and preserves formatting. * * @param s the string * @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags. * @param isHtml is the string HTML? * @return */ public static String truncate(String s, int maxNumOfChars, boolean isHtml) { if (StringUtils.isBlank(s)) { return ""; } //html if(isHtml) { StringBuilder trimmedHtml = new StringBuilder(); ComponentManager.get(FormattedText.class).trimFormattedText(s, maxNumOfChars, trimmedHtml); return trimmedHtml.toString(); } //plain text return StringUtils.substring(s, 0, maxNumOfChars); } /** * Trims and abbreviates text to the given maximum number of displayed * characters (less 3 characters, in case "..." must be appended). * Supports HTML and preserves formatting. * * @param s the string * @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags. * @param isHtml is the string HTML? * @return */ public static String truncateAndAbbreviate(String s, int maxNumOfChars, boolean isHtml) { if (StringUtils.isBlank(s)) { return ""; } //html if(isHtml) { StringBuilder trimmedHtml = new StringBuilder(); boolean trimmed = ComponentManager.get(FormattedText.class).trimFormattedText(s, maxNumOfChars - 3, trimmedHtml); if (trimmed) { int index = trimmedHtml.lastIndexOf("</"); if (-1 != index) { trimmedHtml.insert(index, "..."); } else { trimmedHtml.append("..."); } } return trimmedHtml.toString(); } //plain text return StringUtils.abbreviate(s, maxNumOfChars); } /** * Generate a UUID * @return */ public static String generateUuid() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } /** * Returns the SkypeMe URL for the specified Skype username. * * @param skypeUsername * @return the SkypeMe URL for the specified Skype username. */ public static String getSkypeMeURL(String skypeUsername) { return "skype:" + skypeUsername + "?call"; } /** * Remove duplicates from a list, order is not retained. * * @param list list of objects to clean */ public static <T> void removeDuplicates(List<T> list){ Set<T> set = new HashSet<T>(); set.addAll(list); list.clear(); list.addAll(set); } /** * Remove duplicates from a list, order is retained. * * @param list list of objects to clean */ public static <T> void removeDuplicatesWithOrder(List<T> list) { Set<T> set = new HashSet<T> (); List<T> newList = new ArrayList<T>(); for(T e: list) { if (set.add(e)) { newList.add(e); } } list.clear(); list.addAll(newList); } /** * Calculate an MD5 hash of a string * @param s String to hash * @return MD5 hash as a String */ public static String calculateMD5(String s){ return DigestUtils.md5Hex(s); } /** * Creates a square avatar image by taking a segment out of the centre of the original image and resizing to the appropriate dimensions * * @param imageData original bytes of the image * @param mimeType mimetype of image * @return */ public static byte[] createAvatar(byte[] imageData, String mimeType) { InputStream in = null; byte[] outputBytes = null; try { //convert original image to inputstream in = new ByteArrayInputStream(imageData); //original buffered image BufferedImage originalImage = ImageIO.read(in); //OPTION 1 //determine the smaller side of the image and use that as the size of the cropped square //to be taken out of the centre //then resize to the avatar size =80 square. int smallestSide = originalImage.getWidth(); if(originalImage.getHeight() < originalImage.getWidth()) { smallestSide = originalImage.getHeight(); } if(log.isDebugEnabled()){ log.debug("smallestSide:" + smallestSide); } int startX = (originalImage.getWidth() / 2) - (smallestSide/2); int startY = (originalImage.getHeight() / 2) - (smallestSide/2); //OPTION 2 (unused) //determine a percentage of the original image which we want to keep, say 90%. //then figure out the dimensions of the box and crop to that. //then resize to the avatar size =80 square. //int percentWidth = (originalImage.getWidth() / 100) * 90; //int startX = (originalImage.getWidth() / 2) - (percentWidth/2); //int percentHeight = (originalImage.getHeight() / 100) * 90; //int startY<SUF> //log.debug("percentWidth:" + percentWidth); //log.debug("percentHeight:" + percentHeight); //so it is square, we can only use one dimension for both side, so choose the smaller one //int croppedSize = percentWidth; //if(percentHeight < percentWidth) { // croppedSize = percentHeight; //} //log.debug("croppedSize:" + croppedSize); if(log.isDebugEnabled()){ log.debug("originalImage.getWidth():" + originalImage.getWidth()); log.debug("originalImage.getHeight():" + originalImage.getHeight()); log.debug("startX:" + startX); log.debug("startY:" + startY); } //crop to these bounds and starting positions BufferedImage croppedImage = Scalr.crop(originalImage, startX, startY, smallestSide, smallestSide); //now resize it to the desired avatar size BufferedImage scaledImage = Scalr.resize(croppedImage, 80); //convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos); baos.flush(); outputBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { log.error("Cropping and scaling image failed.", e); } finally { if (in != null) { try { in.close(); log.debug("Image stream closed."); } catch (IOException e) { log.error("Error closing image stream: ", e); } } } return outputBytes; } }
152299_5
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DlgAbout.java * * Created on 23 Jun 10, 19:03:08 */ package kepegawaian; import fungsi.batasInput; import fungsi.koneksiDB; import fungsi.validasi; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.FileInputStream; import java.util.Properties; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker.State; import static javafx.concurrent.Worker.State.FAILED; import javafx.embed.swing.JFXPanel; import javafx.print.PageLayout; import javafx.print.PageOrientation; import javafx.print.Paper; import javafx.print.Printer; import javafx.print.PrinterJob; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.transform.Scale; import javafx.scene.web.PopupFeatures; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Callback; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; /** * * @author perpustakaan */ public class DlgRiwayatPendidikan extends javax.swing.JDialog { private final JFXPanel jfxPanel = new JFXPanel(); private WebEngine engine; private final JLabel lblStatus = new JLabel(); private final JTextField txtURL = new JTextField(); private final JProgressBar progressBar = new JProgressBar(); private final Properties prop = new Properties(); private final validasi Valid=new validasi(); public DlgRiwayatPendidikan(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); initComponents2(); TCari.setDocument(new batasInput((byte)100).getKata(TCari)); if(koneksiDB.CARICEPAT().equals("aktif")){ TCari.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } @Override public void removeUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } @Override public void changedUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } }); } } private void initComponents2() { txtURL.addActionListener((ActionEvent e) -> { loadURL(txtURL.getText()); }); progressBar.setPreferredSize(new Dimension(150, 18)); progressBar.setStringPainted(true); panel.add(jfxPanel, BorderLayout.CENTER); internalFrame1.add(panel); } private void createScene() { Platform.runLater(new Runnable() { public void run() { WebView view = new WebView(); engine = view.getEngine(); engine.setJavaScriptEnabled(true); engine.setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() { @Override public WebEngine call(PopupFeatures p) { Stage stage = new Stage(StageStyle.TRANSPARENT); return view.getEngine(); } }); engine.titleProperty().addListener((ObservableValue<? extends String> observable, String oldValue, final String newValue) -> { SwingUtilities.invokeLater(() -> { DlgRiwayatPendidikan.this.setTitle(newValue); }); }); engine.setOnStatusChanged((final WebEvent<String> event) -> { SwingUtilities.invokeLater(() -> { lblStatus.setText(event.getData()); }); }); engine.getLoadWorker().workDoneProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) -> { SwingUtilities.invokeLater(() -> { progressBar.setValue(newValue.intValue()); }); }); engine.getLoadWorker().exceptionProperty().addListener((ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) -> { if (engine.getLoadWorker().getState() == FAILED) { SwingUtilities.invokeLater(() -> { JOptionPane.showMessageDialog( panel, (value != null) ? engine.getLocation() + "\n" + value.getMessage() : engine.getLocation() + "\nUnexpected Catatan.", "Loading Catatan...", JOptionPane.ERROR_MESSAGE); }); } }); engine.locationProperty().addListener((ObservableValue<? extends String> ov, String oldValue, final String newValue) -> { SwingUtilities.invokeLater(() -> { txtURL.setText(newValue); }); }); engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue ov, State oldState, State newState) { if (newState == State.SUCCEEDED) { try { prop.loadFromXML(new FileInputStream("setting/database.xml")); if(engine.getLocation().replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/","").contains("penggajian/pages")){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Valid.panggilUrl(engine.getLocation().replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/","").replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+"/"+prop.getProperty("HYBRIDWEB")+"/","")); engine.executeScript("history.back()"); setCursor(Cursor.getDefaultCursor()); } } catch (Exception ex) { System.out.println("Notifikasi : "+ex); } } } }); jfxPanel.setScene(new Scene(view)); } }); } public void loadURL(String url) { try { createScene(); } catch (Exception e) { } Platform.runLater(() -> { try { engine.load(url); }catch (Exception exception) { engine.load(url); } }); } public void CloseScane(){ Platform.setImplicitExit(false); } public void print(final Node node) { Printer printer = Printer.getDefaultPrinter(); PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT); double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth(); double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight(); node.getTransforms().add(new Scale(scaleX, scaleY)); PrinterJob job = PrinterJob.createPrinterJob(); if (job != null) { boolean success = job.printPage(node); if (success) { job.endJob(); } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { internalFrame1 = new widget.InternalFrame(); panelGlass5 = new widget.panelisi(); jLabel6 = new widget.Label(); TCari = new widget.TextBox(); BtnCari = new widget.Button(); BtnAll = new widget.Button(); jLabel7 = new widget.Label(); BtnKeluar = new widget.Button(); panel = new widget.panelisi(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("::[ About Program ]::"); setUndecorated(true); setResizable(false); addWindowStateListener(new java.awt.event.WindowStateListener() { public void windowStateChanged(java.awt.event.WindowEvent evt) { formWindowStateChanged(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); internalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(240, 245, 235)), "::[ Riwayat Pendidikan ]::", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(50,50,50))); // NOI18N internalFrame1.setName("internalFrame1"); // NOI18N internalFrame1.setLayout(new java.awt.BorderLayout(1, 1)); panelGlass5.setName("panelGlass5"); // NOI18N panelGlass5.setPreferredSize(new java.awt.Dimension(55, 55)); panelGlass5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 9)); jLabel6.setText("Key Word :"); jLabel6.setName("jLabel6"); // NOI18N jLabel6.setPreferredSize(new java.awt.Dimension(65, 23)); panelGlass5.add(jLabel6); TCari.setName("TCari"); // NOI18N TCari.setPreferredSize(new java.awt.Dimension(460, 23)); TCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { TCariKeyTyped(evt); } public void keyPressed(java.awt.event.KeyEvent evt) { TCariKeyPressed(evt); } }); panelGlass5.add(TCari); BtnCari.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/accept.png"))); // NOI18N BtnCari.setMnemonic('2'); BtnCari.setToolTipText("Alt+2"); BtnCari.setName("BtnCari"); // NOI18N BtnCari.setPreferredSize(new java.awt.Dimension(28, 23)); BtnCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnCariActionPerformed(evt); } }); BtnCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnCariKeyPressed(evt); } }); panelGlass5.add(BtnCari); BtnAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/Search-16x16.png"))); // NOI18N BtnAll.setMnemonic('M'); BtnAll.setToolTipText("Alt+M"); BtnAll.setName("BtnAll"); // NOI18N BtnAll.setPreferredSize(new java.awt.Dimension(28, 23)); BtnAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAllActionPerformed(evt); } }); BtnAll.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnAllKeyPressed(evt); } }); panelGlass5.add(BtnAll); jLabel7.setName("jLabel7"); // NOI18N jLabel7.setPreferredSize(new java.awt.Dimension(30, 23)); panelGlass5.add(jLabel7); BtnKeluar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/exit.png"))); // NOI18N BtnKeluar.setMnemonic('K'); BtnKeluar.setText("Keluar"); BtnKeluar.setToolTipText("Alt+K"); BtnKeluar.setName("BtnKeluar"); // NOI18N BtnKeluar.setPreferredSize(new java.awt.Dimension(100, 30)); BtnKeluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnKeluarActionPerformed(evt); } }); BtnKeluar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnKeluarKeyPressed(evt); } }); panelGlass5.add(BtnKeluar); internalFrame1.add(panelGlass5, java.awt.BorderLayout.PAGE_END); panel.setName("panel"); // NOI18N panel.setLayout(new java.awt.BorderLayout()); internalFrame1.add(panel, java.awt.BorderLayout.CENTER); getContentPane().add(internalFrame1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed Platform.setImplicitExit(false); }//GEN-LAST:event_formWindowClosed private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged if(this.isActive()==false){ Platform.setImplicitExit(false); } }//GEN-LAST:event_formWindowStateChanged private void TCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TCariKeyTyped if(evt.getKeyCode()==KeyEvent.VK_ENTER){ BtnCariActionPerformed(null); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_DOWN){ BtnCari.requestFocus(); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_UP){ BtnKeluar.requestFocus(); } }//GEN-LAST:event_TCariKeyTyped private void TCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_ENTER){ BtnCariActionPerformed(null); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_DOWN){ BtnCari.requestFocus(); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_UP){ BtnKeluar.requestFocus(); } }//GEN-LAST:event_TCariKeyPressed private void BtnCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCariActionPerformed try { if(engine.getLocation().contains("ListRiwayatPendidikan")){ loadURL("http://" +koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/"+"penggajian/index.php?act=ListRiwayatPendidikan&action=LIHAT&keyword="+TCari.getText().replaceAll(" ","_")); } } catch (Exception ex) { System.out.println("Notifikasi : "+ex); } }//GEN-LAST:event_BtnCariActionPerformed private void BtnCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnCariActionPerformed(null); }else{ Valid.pindah(evt, TCari, BtnAll); } }//GEN-LAST:event_BtnCariKeyPressed private void BtnAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAllActionPerformed TCari.setText(""); BtnCariActionPerformed(null); }//GEN-LAST:event_BtnAllActionPerformed private void BtnAllKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnAllKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnAllActionPerformed(null); }else{ Valid.pindah(evt,TCari, BtnKeluar); } }//GEN-LAST:event_BtnAllKeyPressed private void BtnKeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnKeluarActionPerformed dispose(); }//GEN-LAST:event_BtnKeluarActionPerformed private void BtnKeluarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnKeluarKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ dispose(); }else{Valid.pindah(evt,BtnKeluar,TCari);} }//GEN-LAST:event_BtnKeluarKeyPressed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { DlgRiwayatPendidikan dialog = new DlgRiwayatPendidikan(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private widget.Button BtnAll; private widget.Button BtnCari; private widget.Button BtnKeluar; private widget.TextBox TCari; private widget.InternalFrame internalFrame1; private widget.Label jLabel6; private widget.Label jLabel7; private widget.panelisi panel; private widget.panelisi panelGlass5; // End of variables declaration//GEN-END:variables }
salimmulyana/SIMKESKhanza-FKTP
src/kepegawaian/DlgRiwayatPendidikan.java
5,646
//" +koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/"+"penggajian/index.php?act=ListRiwayatPendidikan&action=LIHAT&keyword="+TCari.getText().replaceAll(" ","_"));
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DlgAbout.java * * Created on 23 Jun 10, 19:03:08 */ package kepegawaian; import fungsi.batasInput; import fungsi.koneksiDB; import fungsi.validasi; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.FileInputStream; import java.util.Properties; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker.State; import static javafx.concurrent.Worker.State.FAILED; import javafx.embed.swing.JFXPanel; import javafx.print.PageLayout; import javafx.print.PageOrientation; import javafx.print.Paper; import javafx.print.Printer; import javafx.print.PrinterJob; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.transform.Scale; import javafx.scene.web.PopupFeatures; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Callback; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; /** * * @author perpustakaan */ public class DlgRiwayatPendidikan extends javax.swing.JDialog { private final JFXPanel jfxPanel = new JFXPanel(); private WebEngine engine; private final JLabel lblStatus = new JLabel(); private final JTextField txtURL = new JTextField(); private final JProgressBar progressBar = new JProgressBar(); private final Properties prop = new Properties(); private final validasi Valid=new validasi(); public DlgRiwayatPendidikan(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); initComponents2(); TCari.setDocument(new batasInput((byte)100).getKata(TCari)); if(koneksiDB.CARICEPAT().equals("aktif")){ TCari.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } @Override public void removeUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } @Override public void changedUpdate(DocumentEvent e) { if(TCari.getText().length()>2){ BtnCariActionPerformed(null); } } }); } } private void initComponents2() { txtURL.addActionListener((ActionEvent e) -> { loadURL(txtURL.getText()); }); progressBar.setPreferredSize(new Dimension(150, 18)); progressBar.setStringPainted(true); panel.add(jfxPanel, BorderLayout.CENTER); internalFrame1.add(panel); } private void createScene() { Platform.runLater(new Runnable() { public void run() { WebView view = new WebView(); engine = view.getEngine(); engine.setJavaScriptEnabled(true); engine.setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() { @Override public WebEngine call(PopupFeatures p) { Stage stage = new Stage(StageStyle.TRANSPARENT); return view.getEngine(); } }); engine.titleProperty().addListener((ObservableValue<? extends String> observable, String oldValue, final String newValue) -> { SwingUtilities.invokeLater(() -> { DlgRiwayatPendidikan.this.setTitle(newValue); }); }); engine.setOnStatusChanged((final WebEvent<String> event) -> { SwingUtilities.invokeLater(() -> { lblStatus.setText(event.getData()); }); }); engine.getLoadWorker().workDoneProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) -> { SwingUtilities.invokeLater(() -> { progressBar.setValue(newValue.intValue()); }); }); engine.getLoadWorker().exceptionProperty().addListener((ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) -> { if (engine.getLoadWorker().getState() == FAILED) { SwingUtilities.invokeLater(() -> { JOptionPane.showMessageDialog( panel, (value != null) ? engine.getLocation() + "\n" + value.getMessage() : engine.getLocation() + "\nUnexpected Catatan.", "Loading Catatan...", JOptionPane.ERROR_MESSAGE); }); } }); engine.locationProperty().addListener((ObservableValue<? extends String> ov, String oldValue, final String newValue) -> { SwingUtilities.invokeLater(() -> { txtURL.setText(newValue); }); }); engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue ov, State oldState, State newState) { if (newState == State.SUCCEEDED) { try { prop.loadFromXML(new FileInputStream("setting/database.xml")); if(engine.getLocation().replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/","").contains("penggajian/pages")){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Valid.panggilUrl(engine.getLocation().replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/","").replaceAll("http://"+koneksiDB.HOSTHYBRIDWEB()+"/"+prop.getProperty("HYBRIDWEB")+"/","")); engine.executeScript("history.back()"); setCursor(Cursor.getDefaultCursor()); } } catch (Exception ex) { System.out.println("Notifikasi : "+ex); } } } }); jfxPanel.setScene(new Scene(view)); } }); } public void loadURL(String url) { try { createScene(); } catch (Exception e) { } Platform.runLater(() -> { try { engine.load(url); }catch (Exception exception) { engine.load(url); } }); } public void CloseScane(){ Platform.setImplicitExit(false); } public void print(final Node node) { Printer printer = Printer.getDefaultPrinter(); PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT); double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth(); double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight(); node.getTransforms().add(new Scale(scaleX, scaleY)); PrinterJob job = PrinterJob.createPrinterJob(); if (job != null) { boolean success = job.printPage(node); if (success) { job.endJob(); } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { internalFrame1 = new widget.InternalFrame(); panelGlass5 = new widget.panelisi(); jLabel6 = new widget.Label(); TCari = new widget.TextBox(); BtnCari = new widget.Button(); BtnAll = new widget.Button(); jLabel7 = new widget.Label(); BtnKeluar = new widget.Button(); panel = new widget.panelisi(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("::[ About Program ]::"); setUndecorated(true); setResizable(false); addWindowStateListener(new java.awt.event.WindowStateListener() { public void windowStateChanged(java.awt.event.WindowEvent evt) { formWindowStateChanged(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); internalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(240, 245, 235)), "::[ Riwayat Pendidikan ]::", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(50,50,50))); // NOI18N internalFrame1.setName("internalFrame1"); // NOI18N internalFrame1.setLayout(new java.awt.BorderLayout(1, 1)); panelGlass5.setName("panelGlass5"); // NOI18N panelGlass5.setPreferredSize(new java.awt.Dimension(55, 55)); panelGlass5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 9)); jLabel6.setText("Key Word :"); jLabel6.setName("jLabel6"); // NOI18N jLabel6.setPreferredSize(new java.awt.Dimension(65, 23)); panelGlass5.add(jLabel6); TCari.setName("TCari"); // NOI18N TCari.setPreferredSize(new java.awt.Dimension(460, 23)); TCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { TCariKeyTyped(evt); } public void keyPressed(java.awt.event.KeyEvent evt) { TCariKeyPressed(evt); } }); panelGlass5.add(TCari); BtnCari.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/accept.png"))); // NOI18N BtnCari.setMnemonic('2'); BtnCari.setToolTipText("Alt+2"); BtnCari.setName("BtnCari"); // NOI18N BtnCari.setPreferredSize(new java.awt.Dimension(28, 23)); BtnCari.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnCariActionPerformed(evt); } }); BtnCari.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnCariKeyPressed(evt); } }); panelGlass5.add(BtnCari); BtnAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/Search-16x16.png"))); // NOI18N BtnAll.setMnemonic('M'); BtnAll.setToolTipText("Alt+M"); BtnAll.setName("BtnAll"); // NOI18N BtnAll.setPreferredSize(new java.awt.Dimension(28, 23)); BtnAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAllActionPerformed(evt); } }); BtnAll.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnAllKeyPressed(evt); } }); panelGlass5.add(BtnAll); jLabel7.setName("jLabel7"); // NOI18N jLabel7.setPreferredSize(new java.awt.Dimension(30, 23)); panelGlass5.add(jLabel7); BtnKeluar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/picture/exit.png"))); // NOI18N BtnKeluar.setMnemonic('K'); BtnKeluar.setText("Keluar"); BtnKeluar.setToolTipText("Alt+K"); BtnKeluar.setName("BtnKeluar"); // NOI18N BtnKeluar.setPreferredSize(new java.awt.Dimension(100, 30)); BtnKeluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnKeluarActionPerformed(evt); } }); BtnKeluar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { BtnKeluarKeyPressed(evt); } }); panelGlass5.add(BtnKeluar); internalFrame1.add(panelGlass5, java.awt.BorderLayout.PAGE_END); panel.setName("panel"); // NOI18N panel.setLayout(new java.awt.BorderLayout()); internalFrame1.add(panel, java.awt.BorderLayout.CENTER); getContentPane().add(internalFrame1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed Platform.setImplicitExit(false); }//GEN-LAST:event_formWindowClosed private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged if(this.isActive()==false){ Platform.setImplicitExit(false); } }//GEN-LAST:event_formWindowStateChanged private void TCariKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TCariKeyTyped if(evt.getKeyCode()==KeyEvent.VK_ENTER){ BtnCariActionPerformed(null); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_DOWN){ BtnCari.requestFocus(); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_UP){ BtnKeluar.requestFocus(); } }//GEN-LAST:event_TCariKeyTyped private void TCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_ENTER){ BtnCariActionPerformed(null); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_DOWN){ BtnCari.requestFocus(); }else if(evt.getKeyCode()==KeyEvent.VK_PAGE_UP){ BtnKeluar.requestFocus(); } }//GEN-LAST:event_TCariKeyPressed private void BtnCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCariActionPerformed try { if(engine.getLocation().contains("ListRiwayatPendidikan")){ loadURL("http://" +koneksiDB.HOSTHYBRIDWEB()+":"+prop.getProperty("PORTWEB")+"/"+prop.getProperty("HYBRIDWEB")+"/"+"penggajian/index.php?act=ListRiwayatPendidikan&action=LIHAT&keyword="+TCari.getText().replaceAll("<SUF> } } catch (Exception ex) { System.out.println("Notifikasi : "+ex); } }//GEN-LAST:event_BtnCariActionPerformed private void BtnCariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnCariKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnCariActionPerformed(null); }else{ Valid.pindah(evt, TCari, BtnAll); } }//GEN-LAST:event_BtnCariKeyPressed private void BtnAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAllActionPerformed TCari.setText(""); BtnCariActionPerformed(null); }//GEN-LAST:event_BtnAllActionPerformed private void BtnAllKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnAllKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ BtnAllActionPerformed(null); }else{ Valid.pindah(evt,TCari, BtnKeluar); } }//GEN-LAST:event_BtnAllKeyPressed private void BtnKeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnKeluarActionPerformed dispose(); }//GEN-LAST:event_BtnKeluarActionPerformed private void BtnKeluarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_BtnKeluarKeyPressed if(evt.getKeyCode()==KeyEvent.VK_SPACE){ dispose(); }else{Valid.pindah(evt,BtnKeluar,TCari);} }//GEN-LAST:event_BtnKeluarKeyPressed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { DlgRiwayatPendidikan dialog = new DlgRiwayatPendidikan(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private widget.Button BtnAll; private widget.Button BtnCari; private widget.Button BtnKeluar; private widget.TextBox TCari; private widget.InternalFrame internalFrame1; private widget.Label jLabel6; private widget.Label jLabel7; private widget.panelisi panel; private widget.panelisi panelGlass5; // End of variables declaration//GEN-END:variables }
99507_13
/** * Created Dec 13, 2007 */ package com.crawljax.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Utility class that contains methods used by Crawljax and some plugin to deal with XPath * resolving, constructing etc. * * @author mesbah * @version $Id: XPathHelper.java 421 2010-09-10 15:03:03Z amesbah $ */ public final class XPathHelper { /** * */ private static final String FULL_XPATH_CACHE = "FULL_XPATH_CACHE"; private static final int MAX_SEARCH_LOOPS = 10000; private XPathHelper() { } /** * Reverse Engineers an XPath Expression of a given Node in the DOM. * * @param node * the given node. * @return string xpath expression (e.g., "/html[1]/body[1]/div[3]"). */ public static String getXPathExpression(Node node) { Object xpathCache = node.getUserData(FULL_XPATH_CACHE); if (xpathCache != null) { return xpathCache.toString(); } Node parent = node.getParentNode(); if ((parent == null) || parent.getNodeName().contains("#document")) { String xPath = "/" + node.getNodeName() + "[1]"; node.setUserData(FULL_XPATH_CACHE, xPath, null); return xPath; } StringBuffer buffer = new StringBuffer(); if (parent != node) { buffer.append(getXPathExpression(parent)); buffer.append("/"); } buffer.append(node.getNodeName()); List<Node> mySiblings = getSiblings(parent, node); for (int i = 0; i < mySiblings.size(); i++) { Node el = mySiblings.get(i); if (el.equals(node)) { buffer.append("["); buffer.append(Integer.toString(i + 1)); buffer.append("]"); // Found so break; break; } } String xPath = buffer.toString(); node.setUserData(FULL_XPATH_CACHE, xPath, null); return xPath; } /** * Get siblings of the same type as element from parent. * * @param parent * parent node. * @param element * element. * @return List of sibling (from element) under parent */ public static List<Node> getSiblings(Node parent, Node element) { List<Node> result = new ArrayList<Node>(); NodeList list = parent.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node el = list.item(i); if (el.getNodeName().equals(element.getNodeName())) { result.add(el); } } return result; } /** * Returns the list of nodes which match the expression xpathExpr in the String domStr. * * @param domStr * the string of the document to search in * @param xpathExpr * the xpath query * @author cor-paul * @return the list of nodes which match the query * @throws Exception * On erorr. */ public static NodeList evaluateXpathExpression(String domStr, String xpathExpr) throws Exception { Document dom = Helper.getDocument(domStr); return evaluateXpathExpression(dom, xpathExpr); } /** * Returns the list of nodes which match the expression xpathExpr in the Document dom. * * @param dom * the Document to search in * @param xpathExpr * the xpath query * @author cor-paul * @return the list of nodes which match the query * @throws XPathExpressionException * On error. */ public static NodeList evaluateXpathExpression(Document dom, String xpathExpr) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xpathExpr); Object result = expr.evaluate(dom, XPathConstants.NODESET); NodeList nodes = (NodeList) result; return nodes; } /** * Returns the XPaths of all nodes retrieved by xpathExpression. Example: //DIV[@id='foo'] * returns /HTM[1]/BODY[1]/DIV[2] * * @param dom * The dom. * @param xpathExpression * The expression to find the element. * @return list of XPaths retrieved by xpathExpression. */ public static List<String> getXpathForXPathExpressions(Document dom, String xpathExpression) { NodeList nodeList; try { nodeList = XPathHelper.evaluateXpathExpression(dom, xpathExpression); } catch (XPathExpressionException e) { return null; } List<String> result = new ArrayList<String>(); if (nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node n = nodeList.item(i); result.add(getXPathExpression(n)); } } return result; } /** * @param xpath * The xpath to format. * @return formatted xpath with tag names in uppercase and attributes in lowercase */ public static String formatXPath(String xpath) { String formatted = xpath; Pattern p = Pattern.compile("(/[a-z]+)"); Matcher m = p.matcher(xpath); while (m.find()) { formatted = m.replaceFirst(m.group().toUpperCase()); m = p.matcher(formatted); } p = Pattern.compile("(@[A-Z]+)"); m = p.matcher(formatted); while (m.find()) { formatted = m.replaceFirst(m.group().toLowerCase()); m = p.matcher(formatted); } return formatted; } /** * @param xpath * The xpath expression to find the last element of. * @return returns the last element in the xpath expression */ public static String getLastElementXPath(String xpath) { String[] elements = xpath.split("/"); for (int i = elements.length - 1; i >= 0; i--) { if (!elements[i].equals("") && elements[i].indexOf("()") == -1 && !elements[i].startsWith("@")) { return stripEndSquareBrackets(elements[i]); } } return ""; } /** * @param string * @return string without the before [ */ private static String stripEndSquareBrackets(String string) { if (string.indexOf("[") == -1) { return string; } else { return string.substring(0, string.indexOf("[")); } } /** * returns position of xpath element which match the expression xpath in the String dom. * * @param dom * the Document to search in * @param xpath * the xpath query * @author Danny * @return position of xpath element, if fails returns -1 **/ public static int getXPathLocation(String dom, String xpath) { dom = dom.toLowerCase(); xpath = xpath.toLowerCase(); String[] elements = xpath.split("/"); int pos = 0; int temp; int number; // System.out.println(xpath); for (String element : elements) { if (!element.equals("") && !element.startsWith("@") && element.indexOf("()") == -1) { if (element.indexOf("[") != -1) { try { number = Integer.parseInt(element.substring(element.indexOf("[") + 1, element.indexOf("]"))); } catch (Exception e) { return -1; } } else { number = 1; } // System.out.println("number: " + number); for (int i = 0; i < number; i++) { // find new open element temp = dom.indexOf("<" + stripEndSquareBrackets(element), pos); if (temp > -1) { pos = temp + 1; // if depth>1 then goto end of current element if (number > 1 && i < number - 1) { pos = getCloseElementLocation(dom, pos, stripEndSquareBrackets(element)); // pos = dom.indexOf("<" + // stripEndSquareBrackets(element), pos) + 1; } } } } } return pos - 1; } /** * @param dom * The dom string. * @param pos * Position where to start searching. * @param element * The element. * @return the position where the close element is */ public static int getCloseElementLocation(String dom, int pos, String element) { String[] elements = { "LINK", "META", "INPUT", "BR" }; List<String> singleElements = Arrays.asList(elements); if (singleElements.contains(element.toUpperCase())) { return dom.indexOf(">", pos) + 1; } // make sure not before the node int openElements = 1; int i = 0; dom = dom.toLowerCase(); element = element.toLowerCase(); String openElement = "<" + element; String closeElement = "</" + element; while (i < MAX_SEARCH_LOOPS) { if (dom.indexOf(openElement, pos) == -1 && dom.indexOf(closeElement, pos) == -1) { return -1; } // System.out.println("hierzo: " + dom.substring(pos)); if (dom.indexOf(openElement, pos) < dom.indexOf(closeElement, pos) && dom.indexOf(openElement, pos) != -1) { openElements++; pos = dom.indexOf(openElement, pos) + 1; // System.out.println("open: " + dom.substring(pos-1)); } else { openElements--; pos = dom.indexOf(closeElement, pos) + 1; // System.out.println("close: " + dom.substring(pos-1)); } // System.out.println(openElements); if (openElements == 0) { break; } i++; } // System.out.println("Finished: " + dom.substring(pos-1)); return pos - 1; } /** * @param dom * The dom. * @param xpath * The xpath expression. * @return the position where the close element is */ public static int getCloseElementLocation(String dom, String xpath) { return getCloseElementLocation(dom, getXPathLocation(dom, xpath) + 1, getLastElementXPath(xpath)); } /** * @param xpath * The xpath expression. * @return the xpath expression for only the element location. Leaves out the attributes and * text() */ public static String stripXPathToElement(String xpath) { if (xpath != null && !xpath.equals("")) { if (xpath.toLowerCase().indexOf("/text()") != -1) { xpath = xpath.substring(0, xpath.toLowerCase().indexOf("/text()")); } if (xpath.toLowerCase().indexOf("/comment()") != -1) { xpath = xpath.substring(0, xpath.toLowerCase().indexOf("/comment()")); } if (xpath.indexOf("@") != -1) { xpath = xpath.substring(0, xpath.indexOf("@") - 1); } } return xpath; } }
saltlab/JSNose
src/main/java/com/crawljax/util/XPathHelper.java
3,621
// find new open element
line_comment
nl
/** * Created Dec 13, 2007 */ package com.crawljax.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Utility class that contains methods used by Crawljax and some plugin to deal with XPath * resolving, constructing etc. * * @author mesbah * @version $Id: XPathHelper.java 421 2010-09-10 15:03:03Z amesbah $ */ public final class XPathHelper { /** * */ private static final String FULL_XPATH_CACHE = "FULL_XPATH_CACHE"; private static final int MAX_SEARCH_LOOPS = 10000; private XPathHelper() { } /** * Reverse Engineers an XPath Expression of a given Node in the DOM. * * @param node * the given node. * @return string xpath expression (e.g., "/html[1]/body[1]/div[3]"). */ public static String getXPathExpression(Node node) { Object xpathCache = node.getUserData(FULL_XPATH_CACHE); if (xpathCache != null) { return xpathCache.toString(); } Node parent = node.getParentNode(); if ((parent == null) || parent.getNodeName().contains("#document")) { String xPath = "/" + node.getNodeName() + "[1]"; node.setUserData(FULL_XPATH_CACHE, xPath, null); return xPath; } StringBuffer buffer = new StringBuffer(); if (parent != node) { buffer.append(getXPathExpression(parent)); buffer.append("/"); } buffer.append(node.getNodeName()); List<Node> mySiblings = getSiblings(parent, node); for (int i = 0; i < mySiblings.size(); i++) { Node el = mySiblings.get(i); if (el.equals(node)) { buffer.append("["); buffer.append(Integer.toString(i + 1)); buffer.append("]"); // Found so break; break; } } String xPath = buffer.toString(); node.setUserData(FULL_XPATH_CACHE, xPath, null); return xPath; } /** * Get siblings of the same type as element from parent. * * @param parent * parent node. * @param element * element. * @return List of sibling (from element) under parent */ public static List<Node> getSiblings(Node parent, Node element) { List<Node> result = new ArrayList<Node>(); NodeList list = parent.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node el = list.item(i); if (el.getNodeName().equals(element.getNodeName())) { result.add(el); } } return result; } /** * Returns the list of nodes which match the expression xpathExpr in the String domStr. * * @param domStr * the string of the document to search in * @param xpathExpr * the xpath query * @author cor-paul * @return the list of nodes which match the query * @throws Exception * On erorr. */ public static NodeList evaluateXpathExpression(String domStr, String xpathExpr) throws Exception { Document dom = Helper.getDocument(domStr); return evaluateXpathExpression(dom, xpathExpr); } /** * Returns the list of nodes which match the expression xpathExpr in the Document dom. * * @param dom * the Document to search in * @param xpathExpr * the xpath query * @author cor-paul * @return the list of nodes which match the query * @throws XPathExpressionException * On error. */ public static NodeList evaluateXpathExpression(Document dom, String xpathExpr) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xpathExpr); Object result = expr.evaluate(dom, XPathConstants.NODESET); NodeList nodes = (NodeList) result; return nodes; } /** * Returns the XPaths of all nodes retrieved by xpathExpression. Example: //DIV[@id='foo'] * returns /HTM[1]/BODY[1]/DIV[2] * * @param dom * The dom. * @param xpathExpression * The expression to find the element. * @return list of XPaths retrieved by xpathExpression. */ public static List<String> getXpathForXPathExpressions(Document dom, String xpathExpression) { NodeList nodeList; try { nodeList = XPathHelper.evaluateXpathExpression(dom, xpathExpression); } catch (XPathExpressionException e) { return null; } List<String> result = new ArrayList<String>(); if (nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node n = nodeList.item(i); result.add(getXPathExpression(n)); } } return result; } /** * @param xpath * The xpath to format. * @return formatted xpath with tag names in uppercase and attributes in lowercase */ public static String formatXPath(String xpath) { String formatted = xpath; Pattern p = Pattern.compile("(/[a-z]+)"); Matcher m = p.matcher(xpath); while (m.find()) { formatted = m.replaceFirst(m.group().toUpperCase()); m = p.matcher(formatted); } p = Pattern.compile("(@[A-Z]+)"); m = p.matcher(formatted); while (m.find()) { formatted = m.replaceFirst(m.group().toLowerCase()); m = p.matcher(formatted); } return formatted; } /** * @param xpath * The xpath expression to find the last element of. * @return returns the last element in the xpath expression */ public static String getLastElementXPath(String xpath) { String[] elements = xpath.split("/"); for (int i = elements.length - 1; i >= 0; i--) { if (!elements[i].equals("") && elements[i].indexOf("()") == -1 && !elements[i].startsWith("@")) { return stripEndSquareBrackets(elements[i]); } } return ""; } /** * @param string * @return string without the before [ */ private static String stripEndSquareBrackets(String string) { if (string.indexOf("[") == -1) { return string; } else { return string.substring(0, string.indexOf("[")); } } /** * returns position of xpath element which match the expression xpath in the String dom. * * @param dom * the Document to search in * @param xpath * the xpath query * @author Danny * @return position of xpath element, if fails returns -1 **/ public static int getXPathLocation(String dom, String xpath) { dom = dom.toLowerCase(); xpath = xpath.toLowerCase(); String[] elements = xpath.split("/"); int pos = 0; int temp; int number; // System.out.println(xpath); for (String element : elements) { if (!element.equals("") && !element.startsWith("@") && element.indexOf("()") == -1) { if (element.indexOf("[") != -1) { try { number = Integer.parseInt(element.substring(element.indexOf("[") + 1, element.indexOf("]"))); } catch (Exception e) { return -1; } } else { number = 1; } // System.out.println("number: " + number); for (int i = 0; i < number; i++) { // find new<SUF> temp = dom.indexOf("<" + stripEndSquareBrackets(element), pos); if (temp > -1) { pos = temp + 1; // if depth>1 then goto end of current element if (number > 1 && i < number - 1) { pos = getCloseElementLocation(dom, pos, stripEndSquareBrackets(element)); // pos = dom.indexOf("<" + // stripEndSquareBrackets(element), pos) + 1; } } } } } return pos - 1; } /** * @param dom * The dom string. * @param pos * Position where to start searching. * @param element * The element. * @return the position where the close element is */ public static int getCloseElementLocation(String dom, int pos, String element) { String[] elements = { "LINK", "META", "INPUT", "BR" }; List<String> singleElements = Arrays.asList(elements); if (singleElements.contains(element.toUpperCase())) { return dom.indexOf(">", pos) + 1; } // make sure not before the node int openElements = 1; int i = 0; dom = dom.toLowerCase(); element = element.toLowerCase(); String openElement = "<" + element; String closeElement = "</" + element; while (i < MAX_SEARCH_LOOPS) { if (dom.indexOf(openElement, pos) == -1 && dom.indexOf(closeElement, pos) == -1) { return -1; } // System.out.println("hierzo: " + dom.substring(pos)); if (dom.indexOf(openElement, pos) < dom.indexOf(closeElement, pos) && dom.indexOf(openElement, pos) != -1) { openElements++; pos = dom.indexOf(openElement, pos) + 1; // System.out.println("open: " + dom.substring(pos-1)); } else { openElements--; pos = dom.indexOf(closeElement, pos) + 1; // System.out.println("close: " + dom.substring(pos-1)); } // System.out.println(openElements); if (openElements == 0) { break; } i++; } // System.out.println("Finished: " + dom.substring(pos-1)); return pos - 1; } /** * @param dom * The dom. * @param xpath * The xpath expression. * @return the position where the close element is */ public static int getCloseElementLocation(String dom, String xpath) { return getCloseElementLocation(dom, getXPathLocation(dom, xpath) + 1, getLastElementXPath(xpath)); } /** * @param xpath * The xpath expression. * @return the xpath expression for only the element location. Leaves out the attributes and * text() */ public static String stripXPathToElement(String xpath) { if (xpath != null && !xpath.equals("")) { if (xpath.toLowerCase().indexOf("/text()") != -1) { xpath = xpath.substring(0, xpath.toLowerCase().indexOf("/text()")); } if (xpath.toLowerCase().indexOf("/comment()") != -1) { xpath = xpath.substring(0, xpath.toLowerCase().indexOf("/comment()")); } if (xpath.indexOf("@") != -1) { xpath = xpath.substring(0, xpath.indexOf("@") - 1); } } return xpath; } }
26668_1
public class Dossier { private String vluchtelingId; private boolean paspoortGetoond; private boolean asielAanvraagCompleet; private boolean rechterToegewezen; private boolean uitspraakRechter; private boolean toegelatenTotSamenleving; private boolean terugkeerNaarLandVanHerkomst; public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) { // Standaard waarden instellen this.vluchtelingId= vluchtelingId; this.paspoortGetoond = false; this.asielAanvraagCompleet = false; this.rechterToegewezen = false; this.uitspraakRechter = false; this.toegelatenTotSamenleving = false; this.terugkeerNaarLandVanHerkomst = false; } // Getters en setters voor de variabelen public String getVluchtelingId(){ return vluchtelingId; } public boolean isPaspoortGetoond() { return paspoortGetoond; } public void setPaspoortGetoond(boolean paspoortGetoond) { this.paspoortGetoond = paspoortGetoond; } public boolean isAsielAanvraagCompleet() { return asielAanvraagCompleet; } public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) { this.asielAanvraagCompleet = asielAanvraagCompleet; } public boolean isRechterToegewezen() { return rechterToegewezen; } public void setRechterToegewezen(boolean rechterToegewezen) { this.rechterToegewezen = rechterToegewezen; } public boolean isUitspraakRechter() { return uitspraakRechter; } public void setUitspraakRechter(boolean uitspraakRechter) { this.uitspraakRechter = uitspraakRechter; } public boolean isToegelatenTotSamenleving() { return toegelatenTotSamenleving; } public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) { this.toegelatenTotSamenleving = toegelatenTotSamenleving; } public boolean isTerugkeerNaarLandVanHerkomst() { return terugkeerNaarLandVanHerkomst; } public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) { this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst; } @Override public String toString() { return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s", paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId); } }
samuel2597/Portefolio-2
Dossier.java
1,029
// Getters en setters voor de variabelen
line_comment
nl
public class Dossier { private String vluchtelingId; private boolean paspoortGetoond; private boolean asielAanvraagCompleet; private boolean rechterToegewezen; private boolean uitspraakRechter; private boolean toegelatenTotSamenleving; private boolean terugkeerNaarLandVanHerkomst; public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) { // Standaard waarden instellen this.vluchtelingId= vluchtelingId; this.paspoortGetoond = false; this.asielAanvraagCompleet = false; this.rechterToegewezen = false; this.uitspraakRechter = false; this.toegelatenTotSamenleving = false; this.terugkeerNaarLandVanHerkomst = false; } // Getters en<SUF> public String getVluchtelingId(){ return vluchtelingId; } public boolean isPaspoortGetoond() { return paspoortGetoond; } public void setPaspoortGetoond(boolean paspoortGetoond) { this.paspoortGetoond = paspoortGetoond; } public boolean isAsielAanvraagCompleet() { return asielAanvraagCompleet; } public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) { this.asielAanvraagCompleet = asielAanvraagCompleet; } public boolean isRechterToegewezen() { return rechterToegewezen; } public void setRechterToegewezen(boolean rechterToegewezen) { this.rechterToegewezen = rechterToegewezen; } public boolean isUitspraakRechter() { return uitspraakRechter; } public void setUitspraakRechter(boolean uitspraakRechter) { this.uitspraakRechter = uitspraakRechter; } public boolean isToegelatenTotSamenleving() { return toegelatenTotSamenleving; } public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) { this.toegelatenTotSamenleving = toegelatenTotSamenleving; } public boolean isTerugkeerNaarLandVanHerkomst() { return terugkeerNaarLandVanHerkomst; } public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) { this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst; } @Override public String toString() { return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s", paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId); } }
44376_5
package com.example.sammy.bioscoop; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by Sammy on 3/29/18. */ public class FilmIDTask extends AsyncTask<String, Void, String> { private static final String TAG = "FilmIDTask"; private FilmIDAvailable listener = null; public FilmIDTask(FilmIDAvailable listener){ this.listener = listener; } @Override protected String doInBackground(String... params) { Log.d(TAG, "doInBackground: is called"); InputStream inputStream = null; int responsCode = -1; String itemUrl = params[0]; String response = ""; try { URL url = new URL(itemUrl); URLConnection urlConnection = url.openConnection(); if(!(urlConnection instanceof HttpURLConnection)){ return null; } HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.setAllowUserInteraction(false); httpConnection.setInstanceFollowRedirects(true); httpConnection.setRequestMethod("GET"); httpConnection.connect(); responsCode = httpConnection.getResponseCode(); if (responsCode == HttpURLConnection.HTTP_OK) { inputStream = httpConnection.getInputStream(); response = getStringFromInputStream(inputStream); } else { Log.e(TAG, "Error, invalid response"); } } catch (MalformedURLException e) { Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage()); return null; } catch (IOException e) { Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage()); return null; } // Hier eindigt deze methode. // Het resultaat gaat naar de onPostExecute methode. return response; } protected void onPostExecute(String response) { Log.i(TAG, "onPostExecute " + response); // Check of er een response is if(response == null || response == "") { Log.e(TAG, "onPostExecute kreeg een lege response!"); return; } // Het resultaat is in ons geval een stuk tekst in JSON formaat. // Daar moeten we de info die we willen tonen uit filteren (parsen). // Dat kan met een JSONObject. JSONObject jsonObject; try { // Top level json object jsonObject = new JSONObject(response); // Get all items and start looping JSONArray films = jsonObject.getJSONArray("results"); for(int idx = 0; idx < films.length(); idx++) { // array level objects and get user JSONObject film = films.getJSONObject(idx); int id = film.getInt("id"); Log.i(TAG, "Got item " + id); // call back listener.addMoviesID(id); } listener.callFilmID(); } catch( JSONException ex) { Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage()); } } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } }
samuelrafini/MovieApp
app/src/main/java/com/example/sammy/bioscoop/FilmIDTask.java
1,102
// Daar moeten we de info die we willen tonen uit filteren (parsen).
line_comment
nl
package com.example.sammy.bioscoop; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by Sammy on 3/29/18. */ public class FilmIDTask extends AsyncTask<String, Void, String> { private static final String TAG = "FilmIDTask"; private FilmIDAvailable listener = null; public FilmIDTask(FilmIDAvailable listener){ this.listener = listener; } @Override protected String doInBackground(String... params) { Log.d(TAG, "doInBackground: is called"); InputStream inputStream = null; int responsCode = -1; String itemUrl = params[0]; String response = ""; try { URL url = new URL(itemUrl); URLConnection urlConnection = url.openConnection(); if(!(urlConnection instanceof HttpURLConnection)){ return null; } HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.setAllowUserInteraction(false); httpConnection.setInstanceFollowRedirects(true); httpConnection.setRequestMethod("GET"); httpConnection.connect(); responsCode = httpConnection.getResponseCode(); if (responsCode == HttpURLConnection.HTTP_OK) { inputStream = httpConnection.getInputStream(); response = getStringFromInputStream(inputStream); } else { Log.e(TAG, "Error, invalid response"); } } catch (MalformedURLException e) { Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage()); return null; } catch (IOException e) { Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage()); return null; } // Hier eindigt deze methode. // Het resultaat gaat naar de onPostExecute methode. return response; } protected void onPostExecute(String response) { Log.i(TAG, "onPostExecute " + response); // Check of er een response is if(response == null || response == "") { Log.e(TAG, "onPostExecute kreeg een lege response!"); return; } // Het resultaat is in ons geval een stuk tekst in JSON formaat. // Daar moeten<SUF> // Dat kan met een JSONObject. JSONObject jsonObject; try { // Top level json object jsonObject = new JSONObject(response); // Get all items and start looping JSONArray films = jsonObject.getJSONArray("results"); for(int idx = 0; idx < films.length(); idx++) { // array level objects and get user JSONObject film = films.getJSONObject(idx); int id = film.getInt("id"); Log.i(TAG, "Got item " + id); // call back listener.addMoviesID(id); } listener.callFilmID(); } catch( JSONException ex) { Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage()); } } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } }
28800_0
package domain; import persistence.Marshalling; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; public class Ring { private String naam; private String letter; private int index; @XmlElementWrapper(name = "Tijdslots") @XmlElement(name = "Tijdslot") private final List<Tijdslot> tijdslots; @XmlIDREF @XmlElementWrapper(name = "Disciplines") @XmlElement(name = "Discipline") private final HashSet<Discipline> disciplines; public Ring(String ringNaam, String ringLetter, int ringIndex) { naam = ringNaam; letter = ringLetter; index = ringIndex; tijdslots = new ArrayList<>(); disciplines = new HashSet<>(); } public Ring(){ this("Ring zonder naam " + Math.random(), "", 0); } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } @XmlID @XmlAttribute(name = "id") public String getRef() { return "R"+ index; } public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); } public int getRingIndex() { return index; } public void setRingIndex(int ringIndex) { index = ringIndex; } @XmlTransient public List<Tijdslot> getTijdslots() { return tijdslots; } @XmlTransient public HashSet<Discipline> getDisciplines() { return disciplines;} public void addDiscipline(Discipline discipline) { disciplines.add(discipline); //tijdslots voor ring maken als ze nog niet bestaan if(tijdslots.size() == 0) { for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this); tijdslots.add(tijdslot); } } } public String getVerkorteNotatie() { return naam .replace("meisjes","") .replace("jongens","") .replace("gemengd",""); } @Override public String toString() { return naam + (letter != "" ? " " + letter : ""); } @Override public int hashCode() { return Objects.hash(getRingIndex()); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof Ring) { Ring other = (Ring) o; return getRingIndex() == other.getRingIndex(); } else { return false; } } }
samverstraete/klj-sf-planner
src/main/java/domain/Ring.java
822
//tijdslots voor ring maken als ze nog niet bestaan
line_comment
nl
package domain; import persistence.Marshalling; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; public class Ring { private String naam; private String letter; private int index; @XmlElementWrapper(name = "Tijdslots") @XmlElement(name = "Tijdslot") private final List<Tijdslot> tijdslots; @XmlIDREF @XmlElementWrapper(name = "Disciplines") @XmlElement(name = "Discipline") private final HashSet<Discipline> disciplines; public Ring(String ringNaam, String ringLetter, int ringIndex) { naam = ringNaam; letter = ringLetter; index = ringIndex; tijdslots = new ArrayList<>(); disciplines = new HashSet<>(); } public Ring(){ this("Ring zonder naam " + Math.random(), "", 0); } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } @XmlID @XmlAttribute(name = "id") public String getRef() { return "R"+ index; } public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); } public int getRingIndex() { return index; } public void setRingIndex(int ringIndex) { index = ringIndex; } @XmlTransient public List<Tijdslot> getTijdslots() { return tijdslots; } @XmlTransient public HashSet<Discipline> getDisciplines() { return disciplines;} public void addDiscipline(Discipline discipline) { disciplines.add(discipline); //tijdslots voor<SUF> if(tijdslots.size() == 0) { for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this); tijdslots.add(tijdslot); } } } public String getVerkorteNotatie() { return naam .replace("meisjes","") .replace("jongens","") .replace("gemengd",""); } @Override public String toString() { return naam + (letter != "" ? " " + letter : ""); } @Override public int hashCode() { return Objects.hash(getRingIndex()); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof Ring) { Ring other = (Ring) o; return getRingIndex() == other.getRingIndex(); } else { return false; } } }
46342_18
package replete.io.diff; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import replete.collections.Triple; import replete.hash.Md5Util; import replete.progress.FractionProgressMessage; import replete.ttc.DefaultTransparentTaskContext; import replete.ttc.TransparentTaskContext; import replete.ttc.TtcUtil; // Decided to create a separate utility class instead of // placing this functionality into FileUtil. It's perhaps // a little more convenient here, but debatable. public class DiffUtil { public static DiffResult diffDirs(File dir1, File dir2) { DirComparison comp = diffDirs(dir1, dir2, false, null, 0); return new DiffResult(dir1, dir2, comp); } public static DiffResult diffDirs(File dir1, File dir2, boolean ignoreCaseOk) { DirComparison comp = diffDirs(dir1, dir2, ignoreCaseOk, null, 0); return new DiffResult(dir1, dir2, comp); } public static DiffResult diffDirs(File dir1, File dir2, boolean ignoreCaseOk, DiffFileFilter filter) { DirComparison comp = diffDirs(dir1, dir2, ignoreCaseOk, filter, 0); return new DiffResult(dir1, dir2, comp); } private static DirComparison diffDirs(File dir1, File dir2, boolean ignoreCaseOk, DiffFileFilter filter, int level) { File[] paths1 = dir1.listFiles(); File[] paths2 = dir2.listFiles(); List<File> unmatchedPath2 = new ArrayList<>(Arrays.asList(paths2)); DirComparison diff = new DirComparison(); int p = 0; for(File path1 : paths1) { boolean isDir1 = path1.isDirectory(); boolean found = false; for(File path2 : paths2) { boolean match = path1.getName().equals(path2.getName()); boolean matchIc = path1.getName().equalsIgnoreCase(path2.getName()); boolean isDir2 = path2.isDirectory(); if(!path1.isDirectory() && !path1.isFile()) { throw new IllegalStateException(); } if(!path2.isDirectory() && !path2.isFile()) { throw new IllegalStateException(); } if(match || ignoreCaseOk && matchIc) { if(found) { throw new IllegalStateException("Already matched this path: " + path1 + ". Are you using ignoreCaseOk = true on Linux?"); } found = true; unmatchedPath2.remove(path2); boolean leftAccept = filter == null || filter.accept(DiffDirection.LEFT, path1); boolean rightAccept = filter == null || filter.accept(DiffDirection.RIGHT, path2); if(!leftAccept || !rightAccept) { break; } PathComparison pathDiff = new PathComparison( match != matchIc, isDir1 ? PathType.DIR : PathType.FILE, isDir2 ? PathType.DIR : PathType.FILE ); if(isDir1 && isDir2) { DirComparison dirDiff = diffDirs(path1, path2, ignoreCaseOk, filter, level + 1); pathDiff.setContentComparison(dirDiff); } else if(!isDir1 && !isDir2) { FileComparison fileDiff = diffFiles(path1, path2); pathDiff.setContentComparison(fileDiff); } diff.getResults().add( new Triple<>(path1, path2, pathDiff) ); } } if(!found) { if(filter == null || filter.accept(DiffDirection.LEFT, path1)) { PathComparison pathDiff = new PathComparison( false, isDir1 ? PathType.DIR : PathType.FILE, PathType.NONE ); diff.getResults().add( new Triple<>(path1, null, pathDiff) ); } } p++; TransparentTaskContext context = TtcUtil.getTtc(); if(context != null) { context.publishProgress(new FractionProgressMessage("Checked: " + path1, p, paths1.length)); } } for(File path2 : unmatchedPath2) { boolean isDir2 = path2.isDirectory(); if(filter == null || filter.accept(DiffDirection.RIGHT, path2)) { PathComparison pathDiff = new PathComparison( false, PathType.NONE, isDir2 ? PathType.DIR : PathType.FILE ); diff.getResults().add( new Triple<>(null, path2, pathDiff) ); } } return diff; } public static FileComparison diffFiles(File file1, File file2) { FileComparison diff = new FileComparison(); diff.setLeftLength(file1.length()); diff.setRightLength(file2.length()); // If the two files are the exact same size, then let's check // the bytes for equality. Here we'll be lazy and just use // a canned MD5 hash check for now, even if this opens the // possibility for the mythical hash collision to enable // erroneous behavior. if(file1.length() == file2.length()) { // Error handling here is somewhat rushed but makes sure that // problems reading the file (say it's locked or missing somehow) // don't stop the overall diffing process, which might be a long // one, and still highlight the issue in the final results. // Obviously a full solution would involve not bastardizing the // MD5 field but rather store file/dir access errors in another // part of the final diff results object. At the same time we // could review whether any other errors are possible (can they // happen when you try to list a directory's contents?). try { diff.setLeftMd5(Md5Util.getMd5(file1)); } catch(Exception e) { diff.setLeftMd5("ERROR-LEFT[" + e + "]"); } try { diff.setRightMd5(Md5Util.getMd5(file2)); } catch(Exception e) { diff.setRightMd5("ERROR-RIGHT[" + e + "]"); } } return diff; } ////////// // TEST // ////////// public static void main(String[] args) { // File d1 = new File("C:\\Users\\dtrumbo\\Desktop\\A\\jackson-core-asl-1.9.9"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\A\\jackson-all-1.9.9"); // File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\Avondale\\target\\avondale-3.5.0-SNAPSHOT"); // File d2 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\build\\deploy\\avondale-3.5.0"); // File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\avondale-3.5.0-SNAPSHOT"); // File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT\\bin\\lib\\replete-1.1.0-SNAPSHOT"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\avondale-3.5.0-SNAPSHOT\\bin\\lib\\replete-1.1.0-SNAPSHOT"); File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT"); File d2 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundlerMaven\\target\\avondale-bundler-3.5.0-SNAPSHOT"); TransparentTaskContext ttc = new DefaultTransparentTaskContext(); ttc.addProgressListener(e -> { System.out.println(e.getMessage()); }); TtcUtil.addTtc(ttc); DiffResult result = DiffUtil.diffDirs(d1, d2, false, null); DirComparison diff = result.getComparison(); ComparisonRenderOptions options = new ComparisonRenderOptions() .setIncludeSame(false) .setSortType(SortType.ALPHA_IC) .setLeftLabel("ABM") .setRightLabel("AV") ; String actual = diff.toString(0, options); System.out.println(d1 + " (Left) vs. " + d2 + " (Right) " + diff.getDiffCountLocal() + " Differences (" + diff.getDiffCountGlobal() + " Total)"); if(!diff.isDiff()) { System.out.println("<<< Identical >>>"); } System.out.println(actual); } }
sandialabs/replete
Replete/src/main/java/replete/io/diff/DiffUtil.java
2,586
// File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\Avondale\\target\\avondale-3.5.0-SNAPSHOT");
line_comment
nl
package replete.io.diff; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import replete.collections.Triple; import replete.hash.Md5Util; import replete.progress.FractionProgressMessage; import replete.ttc.DefaultTransparentTaskContext; import replete.ttc.TransparentTaskContext; import replete.ttc.TtcUtil; // Decided to create a separate utility class instead of // placing this functionality into FileUtil. It's perhaps // a little more convenient here, but debatable. public class DiffUtil { public static DiffResult diffDirs(File dir1, File dir2) { DirComparison comp = diffDirs(dir1, dir2, false, null, 0); return new DiffResult(dir1, dir2, comp); } public static DiffResult diffDirs(File dir1, File dir2, boolean ignoreCaseOk) { DirComparison comp = diffDirs(dir1, dir2, ignoreCaseOk, null, 0); return new DiffResult(dir1, dir2, comp); } public static DiffResult diffDirs(File dir1, File dir2, boolean ignoreCaseOk, DiffFileFilter filter) { DirComparison comp = diffDirs(dir1, dir2, ignoreCaseOk, filter, 0); return new DiffResult(dir1, dir2, comp); } private static DirComparison diffDirs(File dir1, File dir2, boolean ignoreCaseOk, DiffFileFilter filter, int level) { File[] paths1 = dir1.listFiles(); File[] paths2 = dir2.listFiles(); List<File> unmatchedPath2 = new ArrayList<>(Arrays.asList(paths2)); DirComparison diff = new DirComparison(); int p = 0; for(File path1 : paths1) { boolean isDir1 = path1.isDirectory(); boolean found = false; for(File path2 : paths2) { boolean match = path1.getName().equals(path2.getName()); boolean matchIc = path1.getName().equalsIgnoreCase(path2.getName()); boolean isDir2 = path2.isDirectory(); if(!path1.isDirectory() && !path1.isFile()) { throw new IllegalStateException(); } if(!path2.isDirectory() && !path2.isFile()) { throw new IllegalStateException(); } if(match || ignoreCaseOk && matchIc) { if(found) { throw new IllegalStateException("Already matched this path: " + path1 + ". Are you using ignoreCaseOk = true on Linux?"); } found = true; unmatchedPath2.remove(path2); boolean leftAccept = filter == null || filter.accept(DiffDirection.LEFT, path1); boolean rightAccept = filter == null || filter.accept(DiffDirection.RIGHT, path2); if(!leftAccept || !rightAccept) { break; } PathComparison pathDiff = new PathComparison( match != matchIc, isDir1 ? PathType.DIR : PathType.FILE, isDir2 ? PathType.DIR : PathType.FILE ); if(isDir1 && isDir2) { DirComparison dirDiff = diffDirs(path1, path2, ignoreCaseOk, filter, level + 1); pathDiff.setContentComparison(dirDiff); } else if(!isDir1 && !isDir2) { FileComparison fileDiff = diffFiles(path1, path2); pathDiff.setContentComparison(fileDiff); } diff.getResults().add( new Triple<>(path1, path2, pathDiff) ); } } if(!found) { if(filter == null || filter.accept(DiffDirection.LEFT, path1)) { PathComparison pathDiff = new PathComparison( false, isDir1 ? PathType.DIR : PathType.FILE, PathType.NONE ); diff.getResults().add( new Triple<>(path1, null, pathDiff) ); } } p++; TransparentTaskContext context = TtcUtil.getTtc(); if(context != null) { context.publishProgress(new FractionProgressMessage("Checked: " + path1, p, paths1.length)); } } for(File path2 : unmatchedPath2) { boolean isDir2 = path2.isDirectory(); if(filter == null || filter.accept(DiffDirection.RIGHT, path2)) { PathComparison pathDiff = new PathComparison( false, PathType.NONE, isDir2 ? PathType.DIR : PathType.FILE ); diff.getResults().add( new Triple<>(null, path2, pathDiff) ); } } return diff; } public static FileComparison diffFiles(File file1, File file2) { FileComparison diff = new FileComparison(); diff.setLeftLength(file1.length()); diff.setRightLength(file2.length()); // If the two files are the exact same size, then let's check // the bytes for equality. Here we'll be lazy and just use // a canned MD5 hash check for now, even if this opens the // possibility for the mythical hash collision to enable // erroneous behavior. if(file1.length() == file2.length()) { // Error handling here is somewhat rushed but makes sure that // problems reading the file (say it's locked or missing somehow) // don't stop the overall diffing process, which might be a long // one, and still highlight the issue in the final results. // Obviously a full solution would involve not bastardizing the // MD5 field but rather store file/dir access errors in another // part of the final diff results object. At the same time we // could review whether any other errors are possible (can they // happen when you try to list a directory's contents?). try { diff.setLeftMd5(Md5Util.getMd5(file1)); } catch(Exception e) { diff.setLeftMd5("ERROR-LEFT[" + e + "]"); } try { diff.setRightMd5(Md5Util.getMd5(file2)); } catch(Exception e) { diff.setRightMd5("ERROR-RIGHT[" + e + "]"); } } return diff; } ////////// // TEST // ////////// public static void main(String[] args) { // File d1 = new File("C:\\Users\\dtrumbo\\Desktop\\A\\jackson-core-asl-1.9.9"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\A\\jackson-all-1.9.9"); // File d1<SUF> // File d2 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\build\\deploy\\avondale-3.5.0"); // File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\avondale-3.5.0-SNAPSHOT"); // File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT\\bin\\lib\\replete-1.1.0-SNAPSHOT"); // File d2 = new File("C:\\Users\\dtrumbo\\Desktop\\avondale-3.5.0-SNAPSHOT\\bin\\lib\\replete-1.1.0-SNAPSHOT"); File d1 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundler\\target\\avondale-bundler-3.5.0-SNAPSHOT"); File d2 = new File("C:\\Users\\dtrumbo\\work\\eclipse-2\\AvondaleBundlerMaven\\target\\avondale-bundler-3.5.0-SNAPSHOT"); TransparentTaskContext ttc = new DefaultTransparentTaskContext(); ttc.addProgressListener(e -> { System.out.println(e.getMessage()); }); TtcUtil.addTtc(ttc); DiffResult result = DiffUtil.diffDirs(d1, d2, false, null); DirComparison diff = result.getComparison(); ComparisonRenderOptions options = new ComparisonRenderOptions() .setIncludeSame(false) .setSortType(SortType.ALPHA_IC) .setLeftLabel("ABM") .setRightLabel("AV") ; String actual = diff.toString(0, options); System.out.println(d1 + " (Left) vs. " + d2 + " (Right) " + diff.getDiffCountLocal() + " Differences (" + diff.getDiffCountGlobal() + " Total)"); if(!diff.isDiff()) { System.out.println("<<< Identical >>>"); } System.out.println(actual); } }
162599_2
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package be.kdg.repaircafe.backend.services.exceptions; /** * @author deketelw */ public class UserServiceException extends RuntimeException { // https://programmeren3-repaircafe.rhcloud.com/repair-cafe-applicatie/repair-cafe-frontend/presentation-layer/error-handling/ /** * Deze exception wordt gesmeten wanneer iets fout gaat met gebruikers * Bijvoorbeeld: fout password of foute gebruikersnaam * * @param message */ public UserServiceException(String message) { super(message); } }
sanming/teamgip2kdgbeFOUT
src/main/java/be/kdg/repaircafe/backend/services/exceptions/UserServiceException.java
195
/** * Deze exception wordt gesmeten wanneer iets fout gaat met gebruikers * Bijvoorbeeld: fout password of foute gebruikersnaam * * @param message */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package be.kdg.repaircafe.backend.services.exceptions; /** * @author deketelw */ public class UserServiceException extends RuntimeException { // https://programmeren3-repaircafe.rhcloud.com/repair-cafe-applicatie/repair-cafe-frontend/presentation-layer/error-handling/ /** * Deze exception wordt<SUF>*/ public UserServiceException(String message) { super(message); } }
151583_14
package pipe.controllers; import pipe.constants.GUIConstants; import pipe.controllers.application.PipeApplicationController; import pipe.gui.PetriNetTab; import pipe.historyActions.MultipleEdit; import pipe.historyActions.component.AddPetriNetObject; import pipe.utilities.gui.GuiUtils; import uk.ac.imperial.pipe.exceptions.PetriNetComponentException; import uk.ac.imperial.pipe.models.petrinet.*; import uk.ac.imperial.pipe.naming.MultipleNamer; import uk.ac.imperial.pipe.naming.PetriNetComponentNamer; import uk.ac.imperial.pipe.visitor.PasteVisitor; import uk.ac.imperial.pipe.visitor.component.PetriNetComponentVisitor; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.UndoableEdit; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Class to handle copy and paste functionality */ @SuppressWarnings("serial") public class CopyPasteManager extends javax.swing.JComponent implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.KeyListener { /** * Colour of rectangle displayed when pasting */ private static final Paint PASTE_COLOR = new Color(155, 155, 155, 100); /** * Colour of rectangle outline displayed when pasting */ private static final Color PASTE_COLOR_OUTLINE = new Color(155, 0, 0, 0); /** * Rectangle displayed which marks the outline of the objects to paste */ private final Rectangle pasteRectangle = new Rectangle(-1, -1); /** * Petri net tab where pasting takes place */ private final PetriNetTab petriNetTab; /** * Petri net pasting objects from/to */ private final PetriNet petriNet; /** * Main PIPE application controller */ private final PipeApplicationController applicationController; /** * Origin of the selected components to paste (top left corner) */ private final Point rectangleOrigin = new Point(); /** * Listener for undoable events being created */ private final UndoableEditListener listener; /** * pasteInProgres is true when pasteRectangle is visible (user is doing a * paste but still hasn't chosen the position where elements will be pasted). */ private boolean pasteInProgress = false; /** * Components to paste when paste is clicked. * These are set when copied */ private Collection<PetriNetComponent> pasteComponents = new ArrayList<>(); /** * Constructor * * @param listener undoable event listener, used to register undo events to * @param petriNetTab current Petri net tab * @param net underlying Petri net displayed on the Petri net tab * @param applicationController main application controller */ public CopyPasteManager(UndoableEditListener listener, PetriNetTab petriNetTab, PetriNet net, PipeApplicationController applicationController) { this.petriNetTab = petriNetTab; petriNet = net; this.applicationController = applicationController; addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); this.listener = listener; } /** * Creates new components for the petri net to copy when pasted * * @param selectedComponents components to copy */ public void copy(Collection<PetriNetComponent> selectedComponents) { pasteComponents.clear(); pasteComponents.addAll(selectedComponents); LocationVisitor locationVisitor = new LocationVisitor(); for (PetriNetComponent component : selectedComponents) { try { component.accept(locationVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } Location location = locationVisitor.location; pasteRectangle.setRect(location.left, location.top, location.right - location.left, location.bottom - location.top); rectangleOrigin.setLocation(location.left, location.top); } /** * Shows the paste rectangle on screen */ public void showPasteRectangle() { if (!pasteInProgress) { petriNetTab.add(this); requestFocusInWindow(); // if (zoom != petriNetTab.getZoom()) { // updateSize(pasteRectangle, zoom, petriNetTab.getZoom()); // zoom = petriNetTab.getZoom(); // } petriNetTab.setLayer(this, GUIConstants.SELECTION_LAYER_OFFSET); repaint(); pasteInProgress = true; updateBounds(); } } /** * Update the bounds which this object can be displayed at */ private void updateBounds() { if (pasteInProgress) { PetriNetTab activeTab = applicationController.getActiveTab(); setBounds(0, 0, activeTab.getWidth(), activeTab.getHeight()); } } /** * @return if it is possible to perform a paste action */ public boolean pasteEnabled() { return !pasteComponents.isEmpty(); } /** * Paints the paste rectangle onto the screen * * @param g paint graphics */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(PASTE_COLOR); g2d.fill(pasteRectangle); g2d.setXORMode(PASTE_COLOR_OUTLINE); g2d.draw(pasteRectangle); } /** * Dragging the mouse on the screen updates the location of the * paste rectangle * * @param e mouse drag event */ @Override public void mouseDragged(MouseEvent e) { if (pasteInProgress) { updateRect(e.getPoint()); } } /** * Changes the rectangles location to point * * @param point new top left point for rectangle */ private void updateRect(Point point) { pasteRectangle.setLocation(point); repaint(); updateBounds(); } /** * Moving the mouse on the screen updates the location of the * paste rectangle * * @param e mouse move event */ @Override public void mouseMoved(MouseEvent e) { if (pasteInProgress) { updateRect(e.getPoint()); } } /** * Noop action on click * * @param e mouse click event */ @Override public void mouseClicked(MouseEvent e) { //Not needed } /** * Performs the paste action * * @param e mouse pressed event */ @Override public void mousePressed(MouseEvent e) { petriNetTab.updatePreferredSize(); petriNetTab.setLayer(this, GUIConstants.LOWEST_LAYER_OFFSET); repaint(); if (pasteInProgress) { paste(petriNetTab); } } /** * Noop action * * @param e mouse released event */ @Override public void mouseReleased(MouseEvent e) { // Not needed } /** * Noop action * * @param e mouse entered event */ @Override public void mouseEntered(MouseEvent e) { // Not needed } /** * Noop action * * @param e mouse exited event */ @Override public void mouseExited(MouseEvent e) { // Not needed } /** * Paste pastes the new objects into the petriNet specified in consturction. * <p> * It first pastes the connectables, and then other components. This ordering is important * and will ensure that arcs are created with the right components. * </p> * @param petriNetTab petri net tab to paste items to */ private void paste(PetriNetTab petriNetTab) { pasteInProgress = false; petriNetTab.remove(this); if (pasteComponents.isEmpty()) { return; } int despX = pasteRectangle.x - rectangleOrigin.x; int despY = pasteRectangle.y - rectangleOrigin.y; MultipleNamer multipleNamer = new PetriNetComponentNamer(petriNet); PasteVisitor pasteVisitor = new PasteVisitor(petriNet, pasteComponents, multipleNamer, despX, despY); try { for (Connectable component : getConnectablesToPaste()) { component.accept(pasteVisitor); } for (PetriNetComponent component : getNonConnectablesToPaste()) { component.accept(pasteVisitor); } } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } createPasteHistoryItem(pasteVisitor.getCreatedComponents()); } /** * @return a collection of the connectable items to paste */ private Collection<Connectable> getConnectablesToPaste() { final Collection<Connectable> connectables = new LinkedList<>(); PetriNetComponentVisitor connectableVisitor = new PlaceTransitionVisitor() { @Override public void visit(Place place) { connectables.add(place); } @Override public void visit(Transition transition) { connectables.add(transition); } }; for (PetriNetComponent component : pasteComponents) { try { component.accept(connectableVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } return connectables; } /** * @return Petri net components that do not inherit from Connectable */ private Collection<PetriNetComponent> getNonConnectablesToPaste() { final Collection<PetriNetComponent> components = new LinkedList<>(); PetriNetComponentVisitor componentVisitor = new NonConnectableVisitor() { @Override public void visit(Token token) { components.add(token); } @Override public void visit(Annotation annotation) { components.add(annotation); } @Override public void visit(InboundArc inboundArc) { components.add(inboundArc); } @Override public void visit(OutboundArc outboundArc) { components.add(outboundArc); } }; for (PetriNetComponent component : pasteComponents) { try { component.accept(componentVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } return components; } /** * Creates a history item for the new components added to the petrinet * * @param createdComponents new components that have been created */ private void createPasteHistoryItem(Iterable<PetriNetComponent> createdComponents) { List<UndoableEdit> undoableEditList = new LinkedList<>(); for (PetriNetComponent component : createdComponents) { AddPetriNetObject addAction = new AddPetriNetObject(component, petriNet); undoableEditList.add(addAction); } listener.undoableEditHappened(new UndoableEditEvent(this, new MultipleEdit(undoableEditList))); } /** * Noop action * * @param e key typed event */ @Override public void keyTyped(KeyEvent e) { // Not needed } /** * Noop action * * @param e key pressed event */ @Override public void keyPressed(KeyEvent e) { // Not needed } /** * Noop action * * @param e key released event */ @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { cancelPaste(); } } /** * Cancel the paste. This will stop the paste rectangle being displayed but will * keep the copied items selected for future pastes */ public void cancelPaste() { PetriNetTab tab = applicationController.getActiveTab(); cancelPaste(tab); } /** * Cancel the paste. This will stop the paste rectangle being displayed but will * keep the copied items selected for future pastes * * @param view tab on which the paste is taking place */ void cancelPaste(PetriNetTab view) { pasteInProgress = false; view.repaint(); view.remove(this); } /** * Used for creating anonymous classes that only visit * Places and Transition */ private interface PlaceTransitionVisitor extends PlaceVisitor, TransitionVisitor { } /** * Used for creating anonymous classes that visit non connectable classes */ private interface NonConnectableVisitor extends AnnotationVisitor, ArcVisitor, TokenVisitor { } /** * Private class used to set the bounds of a selection rectangle * Needed to create a class so that the visitor can change the values */ private static class Location { /** * Bottom location */ private double bottom = 0; /** * Right of the rectangle */ private double right = 0; /** * Top of the rectangle */ private double top = Double.MAX_VALUE; /** * Left of the rectangle */ private double left = Double.MAX_VALUE; } /** * Used to set the bounds of the rectagle displayed when copy pasting */ private static class LocationVisitor implements PlaceTransitionVisitor { /** * Location of the rectangle */ private final Location location = new Location(); /** * Adjusts the bounds to include the position of the place * @param place */ @Override public void visit(Place place) { adjustLocation(place); } /** * Changes the bounds of the rectangle to include the connectable * @param connectable being bounded * @param <T> type of the connectable */ private <T extends Connectable> void adjustLocation(T connectable) { if (connectable.getX() < location.left) { location.left = connectable.getX(); } if (connectable.getX() + connectable.getWidth() > location.right) { location.right = connectable.getX() + connectable.getWidth(); } if (connectable.getY() < location.top) { location.top = connectable.getY(); } if (connectable.getY() + connectable.getHeight() > location.bottom) { location.bottom = connectable.getY() + connectable.getHeight(); } } /** * Adjusts the bounds of the rectangle to include the position of the transition * @param transition to be included in the bounds */ @Override public void visit(Transition transition) { adjustLocation(transition); } } }
sarahtattersall/PIPE
pipe-gui/src/main/java/pipe/controllers/CopyPasteManager.java
4,532
// if (zoom != petriNetTab.getZoom()) {
line_comment
nl
package pipe.controllers; import pipe.constants.GUIConstants; import pipe.controllers.application.PipeApplicationController; import pipe.gui.PetriNetTab; import pipe.historyActions.MultipleEdit; import pipe.historyActions.component.AddPetriNetObject; import pipe.utilities.gui.GuiUtils; import uk.ac.imperial.pipe.exceptions.PetriNetComponentException; import uk.ac.imperial.pipe.models.petrinet.*; import uk.ac.imperial.pipe.naming.MultipleNamer; import uk.ac.imperial.pipe.naming.PetriNetComponentNamer; import uk.ac.imperial.pipe.visitor.PasteVisitor; import uk.ac.imperial.pipe.visitor.component.PetriNetComponentVisitor; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.UndoableEdit; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Class to handle copy and paste functionality */ @SuppressWarnings("serial") public class CopyPasteManager extends javax.swing.JComponent implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.KeyListener { /** * Colour of rectangle displayed when pasting */ private static final Paint PASTE_COLOR = new Color(155, 155, 155, 100); /** * Colour of rectangle outline displayed when pasting */ private static final Color PASTE_COLOR_OUTLINE = new Color(155, 0, 0, 0); /** * Rectangle displayed which marks the outline of the objects to paste */ private final Rectangle pasteRectangle = new Rectangle(-1, -1); /** * Petri net tab where pasting takes place */ private final PetriNetTab petriNetTab; /** * Petri net pasting objects from/to */ private final PetriNet petriNet; /** * Main PIPE application controller */ private final PipeApplicationController applicationController; /** * Origin of the selected components to paste (top left corner) */ private final Point rectangleOrigin = new Point(); /** * Listener for undoable events being created */ private final UndoableEditListener listener; /** * pasteInProgres is true when pasteRectangle is visible (user is doing a * paste but still hasn't chosen the position where elements will be pasted). */ private boolean pasteInProgress = false; /** * Components to paste when paste is clicked. * These are set when copied */ private Collection<PetriNetComponent> pasteComponents = new ArrayList<>(); /** * Constructor * * @param listener undoable event listener, used to register undo events to * @param petriNetTab current Petri net tab * @param net underlying Petri net displayed on the Petri net tab * @param applicationController main application controller */ public CopyPasteManager(UndoableEditListener listener, PetriNetTab petriNetTab, PetriNet net, PipeApplicationController applicationController) { this.petriNetTab = petriNetTab; petriNet = net; this.applicationController = applicationController; addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); this.listener = listener; } /** * Creates new components for the petri net to copy when pasted * * @param selectedComponents components to copy */ public void copy(Collection<PetriNetComponent> selectedComponents) { pasteComponents.clear(); pasteComponents.addAll(selectedComponents); LocationVisitor locationVisitor = new LocationVisitor(); for (PetriNetComponent component : selectedComponents) { try { component.accept(locationVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } Location location = locationVisitor.location; pasteRectangle.setRect(location.left, location.top, location.right - location.left, location.bottom - location.top); rectangleOrigin.setLocation(location.left, location.top); } /** * Shows the paste rectangle on screen */ public void showPasteRectangle() { if (!pasteInProgress) { petriNetTab.add(this); requestFocusInWindow(); // if (zoom<SUF> // updateSize(pasteRectangle, zoom, petriNetTab.getZoom()); // zoom = petriNetTab.getZoom(); // } petriNetTab.setLayer(this, GUIConstants.SELECTION_LAYER_OFFSET); repaint(); pasteInProgress = true; updateBounds(); } } /** * Update the bounds which this object can be displayed at */ private void updateBounds() { if (pasteInProgress) { PetriNetTab activeTab = applicationController.getActiveTab(); setBounds(0, 0, activeTab.getWidth(), activeTab.getHeight()); } } /** * @return if it is possible to perform a paste action */ public boolean pasteEnabled() { return !pasteComponents.isEmpty(); } /** * Paints the paste rectangle onto the screen * * @param g paint graphics */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setPaint(PASTE_COLOR); g2d.fill(pasteRectangle); g2d.setXORMode(PASTE_COLOR_OUTLINE); g2d.draw(pasteRectangle); } /** * Dragging the mouse on the screen updates the location of the * paste rectangle * * @param e mouse drag event */ @Override public void mouseDragged(MouseEvent e) { if (pasteInProgress) { updateRect(e.getPoint()); } } /** * Changes the rectangles location to point * * @param point new top left point for rectangle */ private void updateRect(Point point) { pasteRectangle.setLocation(point); repaint(); updateBounds(); } /** * Moving the mouse on the screen updates the location of the * paste rectangle * * @param e mouse move event */ @Override public void mouseMoved(MouseEvent e) { if (pasteInProgress) { updateRect(e.getPoint()); } } /** * Noop action on click * * @param e mouse click event */ @Override public void mouseClicked(MouseEvent e) { //Not needed } /** * Performs the paste action * * @param e mouse pressed event */ @Override public void mousePressed(MouseEvent e) { petriNetTab.updatePreferredSize(); petriNetTab.setLayer(this, GUIConstants.LOWEST_LAYER_OFFSET); repaint(); if (pasteInProgress) { paste(petriNetTab); } } /** * Noop action * * @param e mouse released event */ @Override public void mouseReleased(MouseEvent e) { // Not needed } /** * Noop action * * @param e mouse entered event */ @Override public void mouseEntered(MouseEvent e) { // Not needed } /** * Noop action * * @param e mouse exited event */ @Override public void mouseExited(MouseEvent e) { // Not needed } /** * Paste pastes the new objects into the petriNet specified in consturction. * <p> * It first pastes the connectables, and then other components. This ordering is important * and will ensure that arcs are created with the right components. * </p> * @param petriNetTab petri net tab to paste items to */ private void paste(PetriNetTab petriNetTab) { pasteInProgress = false; petriNetTab.remove(this); if (pasteComponents.isEmpty()) { return; } int despX = pasteRectangle.x - rectangleOrigin.x; int despY = pasteRectangle.y - rectangleOrigin.y; MultipleNamer multipleNamer = new PetriNetComponentNamer(petriNet); PasteVisitor pasteVisitor = new PasteVisitor(petriNet, pasteComponents, multipleNamer, despX, despY); try { for (Connectable component : getConnectablesToPaste()) { component.accept(pasteVisitor); } for (PetriNetComponent component : getNonConnectablesToPaste()) { component.accept(pasteVisitor); } } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } createPasteHistoryItem(pasteVisitor.getCreatedComponents()); } /** * @return a collection of the connectable items to paste */ private Collection<Connectable> getConnectablesToPaste() { final Collection<Connectable> connectables = new LinkedList<>(); PetriNetComponentVisitor connectableVisitor = new PlaceTransitionVisitor() { @Override public void visit(Place place) { connectables.add(place); } @Override public void visit(Transition transition) { connectables.add(transition); } }; for (PetriNetComponent component : pasteComponents) { try { component.accept(connectableVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } return connectables; } /** * @return Petri net components that do not inherit from Connectable */ private Collection<PetriNetComponent> getNonConnectablesToPaste() { final Collection<PetriNetComponent> components = new LinkedList<>(); PetriNetComponentVisitor componentVisitor = new NonConnectableVisitor() { @Override public void visit(Token token) { components.add(token); } @Override public void visit(Annotation annotation) { components.add(annotation); } @Override public void visit(InboundArc inboundArc) { components.add(inboundArc); } @Override public void visit(OutboundArc outboundArc) { components.add(outboundArc); } }; for (PetriNetComponent component : pasteComponents) { try { component.accept(componentVisitor); } catch (PetriNetComponentException e) { GuiUtils.displayErrorMessage(null, e.getMessage()); } } return components; } /** * Creates a history item for the new components added to the petrinet * * @param createdComponents new components that have been created */ private void createPasteHistoryItem(Iterable<PetriNetComponent> createdComponents) { List<UndoableEdit> undoableEditList = new LinkedList<>(); for (PetriNetComponent component : createdComponents) { AddPetriNetObject addAction = new AddPetriNetObject(component, petriNet); undoableEditList.add(addAction); } listener.undoableEditHappened(new UndoableEditEvent(this, new MultipleEdit(undoableEditList))); } /** * Noop action * * @param e key typed event */ @Override public void keyTyped(KeyEvent e) { // Not needed } /** * Noop action * * @param e key pressed event */ @Override public void keyPressed(KeyEvent e) { // Not needed } /** * Noop action * * @param e key released event */ @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { cancelPaste(); } } /** * Cancel the paste. This will stop the paste rectangle being displayed but will * keep the copied items selected for future pastes */ public void cancelPaste() { PetriNetTab tab = applicationController.getActiveTab(); cancelPaste(tab); } /** * Cancel the paste. This will stop the paste rectangle being displayed but will * keep the copied items selected for future pastes * * @param view tab on which the paste is taking place */ void cancelPaste(PetriNetTab view) { pasteInProgress = false; view.repaint(); view.remove(this); } /** * Used for creating anonymous classes that only visit * Places and Transition */ private interface PlaceTransitionVisitor extends PlaceVisitor, TransitionVisitor { } /** * Used for creating anonymous classes that visit non connectable classes */ private interface NonConnectableVisitor extends AnnotationVisitor, ArcVisitor, TokenVisitor { } /** * Private class used to set the bounds of a selection rectangle * Needed to create a class so that the visitor can change the values */ private static class Location { /** * Bottom location */ private double bottom = 0; /** * Right of the rectangle */ private double right = 0; /** * Top of the rectangle */ private double top = Double.MAX_VALUE; /** * Left of the rectangle */ private double left = Double.MAX_VALUE; } /** * Used to set the bounds of the rectagle displayed when copy pasting */ private static class LocationVisitor implements PlaceTransitionVisitor { /** * Location of the rectangle */ private final Location location = new Location(); /** * Adjusts the bounds to include the position of the place * @param place */ @Override public void visit(Place place) { adjustLocation(place); } /** * Changes the bounds of the rectangle to include the connectable * @param connectable being bounded * @param <T> type of the connectable */ private <T extends Connectable> void adjustLocation(T connectable) { if (connectable.getX() < location.left) { location.left = connectable.getX(); } if (connectable.getX() + connectable.getWidth() > location.right) { location.right = connectable.getX() + connectable.getWidth(); } if (connectable.getY() < location.top) { location.top = connectable.getY(); } if (connectable.getY() + connectable.getHeight() > location.bottom) { location.bottom = connectable.getY() + connectable.getHeight(); } } /** * Adjusts the bounds of the rectangle to include the position of the transition * @param transition to be included in the bounds */ @Override public void visit(Transition transition) { adjustLocation(transition); } } }
200229_32
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, //in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, //in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, //in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german Massentrom TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }, //in german Heizung Betriebsart TYPE_HEATING_OPERATION_MODE { { command = "heating_operation_mode"; itemClass = NumberItem.class; } }, //in german Heizung Temperatur (Parallelverschiebung) TYPE_HEATING_TEMPERATURE { { command = "heating_temperature"; itemClass = NumberItem.class; } }, //in german Warmwasser Betriebsart TYPE_WARMWATER_OPERATION_MODE { { command = "warmwater_operation_mode"; itemClass = NumberItem.class; } }, //in german Warmwasser Temperatur TYPE_WARMWATER_TEMPERATURE { { command = "warmwater_temperature"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
sarvex/openhab
bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java
2,891
// in german Massentrom
line_comment
nl
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, //in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, //in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, //in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german<SUF> TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }, //in german Heizung Betriebsart TYPE_HEATING_OPERATION_MODE { { command = "heating_operation_mode"; itemClass = NumberItem.class; } }, //in german Heizung Temperatur (Parallelverschiebung) TYPE_HEATING_TEMPERATURE { { command = "heating_temperature"; itemClass = NumberItem.class; } }, //in german Warmwasser Betriebsart TYPE_WARMWATER_OPERATION_MODE { { command = "warmwater_operation_mode"; itemClass = NumberItem.class; } }, //in german Warmwasser Temperatur TYPE_WARMWATER_TEMPERATURE { { command = "warmwater_temperature"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
117578_8
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; /** * A ternary search algorithm is a technique in computer science for finding the * minimum or maximum of a unimodal function The algorithm determines either * that the minimum or maximum cannot be in the first third of the domain or * that it cannot be in the last third of the domain, then repeats on the * remaining third. * * <p> * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ public class TernarySearch implements SearchAlgorithm { /** * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @Override public <T extends Comparable<T>> int find(T[] arr, T value) { return ternarySearch(arr, value, 0, arr.length - 1); } /** * @param arr The **Sorted** array in which we will search the element. * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } /* First boundary: add 1/3 of length to start */ int mid1 = start + (end - start) / 3; /* Second boundary: add 2/3 of length to start */ int mid2 = start + 2 * (end - start) / 3; if (key.compareTo(arr[mid1]) == 0) { return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } public static void main(String[] args) { // just generate data Random r = new Random(); int size = 100; int maxElement = 100000; Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } }
satishppawar/Java
src/main/java/com/thealgorithms/searches/TernarySearch.java
1,008
// just generate data
line_comment
nl
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; /** * A ternary search algorithm is a technique in computer science for finding the * minimum or maximum of a unimodal function The algorithm determines either * that the minimum or maximum cannot be in the first third of the domain or * that it cannot be in the last third of the domain, then repeats on the * remaining third. * * <p> * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ public class TernarySearch implements SearchAlgorithm { /** * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @Override public <T extends Comparable<T>> int find(T[] arr, T value) { return ternarySearch(arr, value, 0, arr.length - 1); } /** * @param arr The **Sorted** array in which we will search the element. * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } /* First boundary: add 1/3 of length to start */ int mid1 = start + (end - start) / 3; /* Second boundary: add 2/3 of length to start */ int mid2 = start + 2 * (end - start) / 3; if (key.compareTo(arr[mid1]) == 0) { return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } public static void main(String[] args) { // just generate<SUF> Random r = new Random(); int size = 100; int maxElement = 100000; Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } }
30552_23
package nl.highco.thuglife; import java.io.IOException; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.Timer; import java.util.TimerTask; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import nl.saxion.act.playground.model.Game; import nl.saxion.act.playground.model.GameBoard; import nl.highco.thuglife.objects.*; import android.media.AudioManager; import android.media.MediaPlayer; public class ThugGame extends Game implements Observer { public static final String TAG = "thug game"; private MainActivity activity; private int money, score, wiet; private int highscore = 0; private int politieScore = 50; private MediaPlayer mPlayer; public boolean isPlaying = false; // map size private final static int MAP_WIDTH = 100; private final static int MAP_HIGHT = 100; // map private int[][] map; // player private Player player; private ArrayList<Police> politie = new ArrayList<Police>(); //handlers final Handler POLICEHANDLER = new Handler(); final Handler PLAYERHANDLER = new Handler(); // gameboard private GameBoard gameBoard; // timers private Timer policeTimer; private Timer playerTimer; public ThugGame(MainActivity activity) { super(new ThugGameboard(MAP_WIDTH, MAP_HIGHT)); this.activity = activity; // starts the game initGame(); // sets the game view to the game board ThugGameBoardView gameView = activity.getGameBoardView(); gameBoard = getGameBoard(); gameBoard.addObserver(this); gameView.setGameBoard(gameBoard); //Swipe controls///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// gameView.setOnTouchListener(new OnSwipeTouchListener(activity) { public void onSwipeTop() { Log.i("touchListener", "omhoog"); player.setRichtingOmhoog(); } public void onSwipeRight() { Log.i("touchListener", "rechts"); player.setRichtingRechts(); } public void onSwipeLeft() { Log.i("touchListener", "links"); player.setRichtingLinks(); } public void onSwipeBottom() { Log.i("touchListener", "onder"); player.setRichtingBeneden(); } public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // decides what kind of map format to use gameView.setFixedGridSize(gameBoard.getWidth(), gameBoard.getHeight()); } public void initGame() { // getting a map MapGenerator mapgen = new MapGenerator(); map = mapgen.getRandomMap(); // setting up the board GameBoard board = getGameBoard(); board.removeAllObjects(); // score , money en wiet naar 0 score = 0; money = 0; wiet = 10; // add player player = new Player(); board.addGameObject(player, 55, 50); // add shop board.addGameObject(new Shop(), 50, 60); // add wiet board.addGameObject(new Weed(), 42, 51); board.addGameObject(new Weed(), 80, 95); board.addGameObject(new Weed(), 75, 76); board.addGameObject(new Weed(), 31, 64); board.addGameObject(new Weed(), 98, 98); board.addGameObject(new Weed(), 83, 84); // add Police politie.clear(); Police p1 = new Police(); Police p2 = new Police(); Police p3 = new Police(); Police p4 = new Police(); Police p5 = new Police(); Police p6 = new Police(); board.addGameObject(p1, 28, 30); board.addGameObject(p2, 31, 38); board.addGameObject(p3, 46, 47); board.addGameObject(p4, 76, 34); board.addGameObject(p5, 84, 88); board.addGameObject(p6, 52, 63); politie.add(p1); politie.add(p2); politie.add(p3); politie.add(p4); politie.add(p5); politie.add(p6); // load walls onto the field for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_HIGHT; y++) { if (map[x][y] == 1) { if (board.getObject(x, y) == null) { board.addGameObject(new Wall(), x, y); } } } } board.updateView(); } // adds police on a random spot within the map public void addPolice() { int xSpot = randomX(); int ySpot = randomY(); if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26 && ySpot > 11) { politie.add(new Police()); getGameBoard().addGameObject(politie.get(politie.size() - 1), xSpot, ySpot); } else { addPolice(); } } // adds wiet on a random spot within the map public void addWietToMap() { int xSpot = randomX(); int ySpot = randomY(); if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26 && ySpot > 11) { getGameBoard().addGameObject(new Weed(), xSpot, ySpot); } else { addWietToMap(); } } public int randomX() { int randomX = (int) (Math.random() * MAP_WIDTH); return randomX; } public int randomY() { int randomY = (int) (Math.random() * MAP_HIGHT); return randomY; } public void enterShop() { activity.gotoShopView(); } //resets the game public void reset() { activity.resetShop(); initGame(); } /** * adds money to total of players' money * @param aantal amount of money to be added */ public void addMoney(int aantal) { money += aantal; gameBoard.updateView(); } /** * deducts money of total of players' money * @param aantal amount of money to be deducted */ public void deductMoney(int aantal) { money -= aantal; gameBoard.updateView(); } /** * adds 50 points to score when player collides with weed object */ public void updateScoreWCWW() { score += 50; if (score > highscore) { highscore = score; } gameBoard.updateView(); } /** * adds one weed to the weed variable */ public void addWiet() { wiet++; gameBoard.updateView(); } /** * deducts the weed according to the given value * @param aantal */ public void deductWiet(int aantal) { wiet -= aantal; gameBoard.updateView(); } /** * @return total amount of money the player has */ public int getMoney() { return money; } /** * @return total score the player has */ public int getScore() { return score; } /** * @return high score */ public int getHighscore() { return highscore; } /** * @return total amount of wiet the player has */ public int getWiet() { return wiet; } /** * @return the player object */ public Player getPlayer() { return player; } //Timer////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // police timer methods public void startPoliceTimer() { isPlaying = true; // maakt een timer die de handler en de runnable oproept elke halve // seconde. policeTimer = new Timer(); policeTimer.schedule(new TimerTask() { @Override public void run() { UpdateGUIPolice(); } }, 0, 250); } private void stopPoliceTimer() { policeTimer.cancel(); } // player timer methods public void startPlayerTimer(int speed) { isPlaying = true; // maakt een timer die de handler en de runnable oproept elke halve // seconde. playerTimer = new Timer(); playerTimer.schedule(new TimerTask() { @Override public void run() { UpdateGUIPlayer(); } }, 0, speed); } private void stopPlayerTimer() { playerTimer.cancel(); } // De runnable voor de police die je aan de handler meegeeft. final Runnable policeRunnable = new Runnable() { public void run() { for (int i = 0; i < politie.size(); i++) { politie.get(i).onUpdate(gameBoard); } gameBoard.updateView(); } }; // De runnable voor de player die je aan de handler meegeeft. final Runnable playerRunnable = new Runnable() { public void run() { player.onUpdate(gameBoard); } }; // Methode waarmee je de runnable aan de handler meegeeft. public void UpdateGUIPolice() { POLICEHANDLER.post(policeRunnable); } public void UpdateGUIPlayer() { PLAYERHANDLER.post(playerRunnable); } // kijken of player alive is private boolean isPlayerAlive() { if(player.getAliveState()){ return true; } return false; } // stops the timers public void stopTimers() { stopPlayerTimer(); stopPoliceTimer(); isPlaying = false; } public void update(Observable observable, Object data) { if (!isPlayerAlive()) { stopTimers(); activity.gotoGameOverScreen(); } activity.updateMoneyLabels(); activity.updateScoreLabel(); activity.updateWietLabels(); activity.updateHighscoreLabel(); //Voegt politie toe als de speler een wiet object opppakt. if (getScore() == politieScore) { addPolice(); policeMusic(); addWietToMap(); politieScore = politieScore + 50; } } //music for when the player picks up a wiet object private void policeMusic() { mPlayer = MediaPlayer.create(activity, R.raw.soundofdapolice); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mPlayer.start(); } }
saxion-speelveld/project
Source/ThugLife/src/nl/highco/thuglife/ThugGame.java
3,192
// maakt een timer die de handler en de runnable oproept elke halve
line_comment
nl
package nl.highco.thuglife; import java.io.IOException; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.Timer; import java.util.TimerTask; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import nl.saxion.act.playground.model.Game; import nl.saxion.act.playground.model.GameBoard; import nl.highco.thuglife.objects.*; import android.media.AudioManager; import android.media.MediaPlayer; public class ThugGame extends Game implements Observer { public static final String TAG = "thug game"; private MainActivity activity; private int money, score, wiet; private int highscore = 0; private int politieScore = 50; private MediaPlayer mPlayer; public boolean isPlaying = false; // map size private final static int MAP_WIDTH = 100; private final static int MAP_HIGHT = 100; // map private int[][] map; // player private Player player; private ArrayList<Police> politie = new ArrayList<Police>(); //handlers final Handler POLICEHANDLER = new Handler(); final Handler PLAYERHANDLER = new Handler(); // gameboard private GameBoard gameBoard; // timers private Timer policeTimer; private Timer playerTimer; public ThugGame(MainActivity activity) { super(new ThugGameboard(MAP_WIDTH, MAP_HIGHT)); this.activity = activity; // starts the game initGame(); // sets the game view to the game board ThugGameBoardView gameView = activity.getGameBoardView(); gameBoard = getGameBoard(); gameBoard.addObserver(this); gameView.setGameBoard(gameBoard); //Swipe controls///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// gameView.setOnTouchListener(new OnSwipeTouchListener(activity) { public void onSwipeTop() { Log.i("touchListener", "omhoog"); player.setRichtingOmhoog(); } public void onSwipeRight() { Log.i("touchListener", "rechts"); player.setRichtingRechts(); } public void onSwipeLeft() { Log.i("touchListener", "links"); player.setRichtingLinks(); } public void onSwipeBottom() { Log.i("touchListener", "onder"); player.setRichtingBeneden(); } public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // decides what kind of map format to use gameView.setFixedGridSize(gameBoard.getWidth(), gameBoard.getHeight()); } public void initGame() { // getting a map MapGenerator mapgen = new MapGenerator(); map = mapgen.getRandomMap(); // setting up the board GameBoard board = getGameBoard(); board.removeAllObjects(); // score , money en wiet naar 0 score = 0; money = 0; wiet = 10; // add player player = new Player(); board.addGameObject(player, 55, 50); // add shop board.addGameObject(new Shop(), 50, 60); // add wiet board.addGameObject(new Weed(), 42, 51); board.addGameObject(new Weed(), 80, 95); board.addGameObject(new Weed(), 75, 76); board.addGameObject(new Weed(), 31, 64); board.addGameObject(new Weed(), 98, 98); board.addGameObject(new Weed(), 83, 84); // add Police politie.clear(); Police p1 = new Police(); Police p2 = new Police(); Police p3 = new Police(); Police p4 = new Police(); Police p5 = new Police(); Police p6 = new Police(); board.addGameObject(p1, 28, 30); board.addGameObject(p2, 31, 38); board.addGameObject(p3, 46, 47); board.addGameObject(p4, 76, 34); board.addGameObject(p5, 84, 88); board.addGameObject(p6, 52, 63); politie.add(p1); politie.add(p2); politie.add(p3); politie.add(p4); politie.add(p5); politie.add(p6); // load walls onto the field for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_HIGHT; y++) { if (map[x][y] == 1) { if (board.getObject(x, y) == null) { board.addGameObject(new Wall(), x, y); } } } } board.updateView(); } // adds police on a random spot within the map public void addPolice() { int xSpot = randomX(); int ySpot = randomY(); if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26 && ySpot > 11) { politie.add(new Police()); getGameBoard().addGameObject(politie.get(politie.size() - 1), xSpot, ySpot); } else { addPolice(); } } // adds wiet on a random spot within the map public void addWietToMap() { int xSpot = randomX(); int ySpot = randomY(); if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26 && ySpot > 11) { getGameBoard().addGameObject(new Weed(), xSpot, ySpot); } else { addWietToMap(); } } public int randomX() { int randomX = (int) (Math.random() * MAP_WIDTH); return randomX; } public int randomY() { int randomY = (int) (Math.random() * MAP_HIGHT); return randomY; } public void enterShop() { activity.gotoShopView(); } //resets the game public void reset() { activity.resetShop(); initGame(); } /** * adds money to total of players' money * @param aantal amount of money to be added */ public void addMoney(int aantal) { money += aantal; gameBoard.updateView(); } /** * deducts money of total of players' money * @param aantal amount of money to be deducted */ public void deductMoney(int aantal) { money -= aantal; gameBoard.updateView(); } /** * adds 50 points to score when player collides with weed object */ public void updateScoreWCWW() { score += 50; if (score > highscore) { highscore = score; } gameBoard.updateView(); } /** * adds one weed to the weed variable */ public void addWiet() { wiet++; gameBoard.updateView(); } /** * deducts the weed according to the given value * @param aantal */ public void deductWiet(int aantal) { wiet -= aantal; gameBoard.updateView(); } /** * @return total amount of money the player has */ public int getMoney() { return money; } /** * @return total score the player has */ public int getScore() { return score; } /** * @return high score */ public int getHighscore() { return highscore; } /** * @return total amount of wiet the player has */ public int getWiet() { return wiet; } /** * @return the player object */ public Player getPlayer() { return player; } //Timer////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // police timer methods public void startPoliceTimer() { isPlaying = true; // maakt een timer die de handler en de runnable oproept elke halve // seconde. policeTimer = new Timer(); policeTimer.schedule(new TimerTask() { @Override public void run() { UpdateGUIPolice(); } }, 0, 250); } private void stopPoliceTimer() { policeTimer.cancel(); } // player timer methods public void startPlayerTimer(int speed) { isPlaying = true; // maakt een<SUF> // seconde. playerTimer = new Timer(); playerTimer.schedule(new TimerTask() { @Override public void run() { UpdateGUIPlayer(); } }, 0, speed); } private void stopPlayerTimer() { playerTimer.cancel(); } // De runnable voor de police die je aan de handler meegeeft. final Runnable policeRunnable = new Runnable() { public void run() { for (int i = 0; i < politie.size(); i++) { politie.get(i).onUpdate(gameBoard); } gameBoard.updateView(); } }; // De runnable voor de player die je aan de handler meegeeft. final Runnable playerRunnable = new Runnable() { public void run() { player.onUpdate(gameBoard); } }; // Methode waarmee je de runnable aan de handler meegeeft. public void UpdateGUIPolice() { POLICEHANDLER.post(policeRunnable); } public void UpdateGUIPlayer() { PLAYERHANDLER.post(playerRunnable); } // kijken of player alive is private boolean isPlayerAlive() { if(player.getAliveState()){ return true; } return false; } // stops the timers public void stopTimers() { stopPlayerTimer(); stopPoliceTimer(); isPlaying = false; } public void update(Observable observable, Object data) { if (!isPlayerAlive()) { stopTimers(); activity.gotoGameOverScreen(); } activity.updateMoneyLabels(); activity.updateScoreLabel(); activity.updateWietLabels(); activity.updateHighscoreLabel(); //Voegt politie toe als de speler een wiet object opppakt. if (getScore() == politieScore) { addPolice(); policeMusic(); addWietToMap(); politieScore = politieScore + 50; } } //music for when the player picks up a wiet object private void policeMusic() { mPlayer = MediaPlayer.create(activity, R.raw.soundofdapolice); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mPlayer.start(); } }
126156_0
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken hoe kenmerken toe te voegen? api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
sbnnl/documentatie
docs/100_producten/100_borgstelling/010_aanvragen-borgstelling/010_afhandelen-aanvraag-borgstelling/ArchiveerContractUseCase.java
794
//TODO: uitzoeken hoe kenmerken toe te voegen?
line_comment
nl
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken<SUF> api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
110941_4
package behavioural.memento.memento; /** * Klasse waarvan we de state changes willen bijhouden in de vorm van {@link Memento}s. */ public class Originator { private String state; /** * Methode om de state te zetten. * * @param state de nieuwe state */ public void setState(String state){ this.state = state; } /** * Methode om de huidige state op te halen * * @return de huidige state */ public String getState(){ return state; } /** * Methode om eem {@link Memento} aan te maken die de huidige state voorstelt. * * @return een Memento die de huidige state voorstelt */ public Memento saveStateToMemento(){ return new Memento(state); } /** * Methode om de huidige state te herstellen vanuit een eerder opgeslagen {@link Memento} * * @param memento de Memento waarmee we de huidige state herstellen */ public void restoreStateFromMemento(Memento memento){ state = memento.getSavedState(); } }
sbottelbergs/designpatterns
src/main/java/behavioural/memento/memento/Originator.java
335
/** * Methode om de huidige state te herstellen vanuit een eerder opgeslagen {@link Memento} * * @param memento de Memento waarmee we de huidige state herstellen */
block_comment
nl
package behavioural.memento.memento; /** * Klasse waarvan we de state changes willen bijhouden in de vorm van {@link Memento}s. */ public class Originator { private String state; /** * Methode om de state te zetten. * * @param state de nieuwe state */ public void setState(String state){ this.state = state; } /** * Methode om de huidige state op te halen * * @return de huidige state */ public String getState(){ return state; } /** * Methode om eem {@link Memento} aan te maken die de huidige state voorstelt. * * @return een Memento die de huidige state voorstelt */ public Memento saveStateToMemento(){ return new Memento(state); } /** * Methode om de<SUF>*/ public void restoreStateFromMemento(Memento memento){ state = memento.getSavedState(); } }
68733_18
package ddf.minim.ugens; import ddf.minim.UGen; /** * A Flanger is a specialized kind of delay that uses an LFO (low frequency * oscillator) to vary the amount of delay applied to each sample. This causes a * sweeping frequency kind of sound as the signal reinforces or cancels itself * in various ways. In particular the peaks and notches created in the frequency * spectrum are related to each other in a linear harmonic series. This causes * the spectrum to look like a comb. * <p> * Inputs for the Flanger are: * <ul> * <li>delay (in milliseconds): the minimum amount of delay applied to an incoming sample</li> * <li>rate (in Hz): the frequency of the LFO</li> * <li>depth (in milliseconds): the maximum amount of delay added onto delay by the LFO</li> * <li>feedback: how much of delayed signal should be fed back into the effect</li> * <li>dry: how much of the uneffected input should be included in the output</li> * <li>wet: how much of the effected signal should be included in the output</li> * </ul> * <p> * A more thorough description can be found on wikipedia: * http://en.wikipedia.org/wiki/Flanging * <p> * * @author Damien Di Fede * * @example Synthesis/flangerExample * * @related UGen */ public class Flanger extends UGen { /** * Where the input goes. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput audio; /** * How much does the flanger delay the incoming signal. Used as the low * value of the modulated delay amount. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput delay; /** * The frequency of the LFO applied to the delay. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput rate; /** * How many milliseconds the LFO increases the delay by at the maximum. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput depth; /** * How much of the flanged signal is fed back into the effect. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput feedback; /** * How much of the dry signal is added to the output. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput dry; /** * How much of the flanged signal is added to the output. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput wet; private float[] delayBuffer; private int outputFrame; private int bufferFrameLength; // //////////// // LFO // //////////// // where we will sample our waveform, moves between [0,1] private float step; // the step size we will use to advance our step private float stepSize; // what was our frequency from the last time we updated our step size // stashed so that we don't do more math than necessary private float prevFreq; // 1 / sampleRate, which is used to calculate stepSize private float oneOverSampleRate; /** * Construct a Flanger by specifying all initial values. * * @param delayLength * float: the minimum delay applied to incoming samples (in milliseconds) * @param lfoRate * float: the frequency of the the LFO * @param delayDepth * float: the maximum amount added to the delay by the LFO (in milliseconds) * @param feedbackAmplitude * float: the amount of the flanged signal fed back into the effect * @param dryAmplitude * float: the amount of incoming signal added to the output * @param wetAmplitude * float: the amount of the flanged signal added to the output */ public Flanger(float delayLength, float lfoRate, float delayDepth, float feedbackAmplitude, float dryAmplitude, float wetAmplitude) { audio = addAudio(); delay = addControl( delayLength ); rate = addControl( lfoRate ); depth = addControl( delayDepth ); feedback = addControl( feedbackAmplitude ); dry = addControl( dryAmplitude ); wet = addControl( wetAmplitude ); } private void resetBuffer() { int sampleCount = (int)( 100 * sampleRate() / 1000 ); delayBuffer = new float[sampleCount * audio.channelCount()]; outputFrame = 0; bufferFrameLength = sampleCount; } // clamps rate for us private float getRate() { float r = rate.getLastValue(); return r > 0.001f ? r : 0.001f; } protected void sampleRateChanged() { resetBuffer(); oneOverSampleRate = 1 / sampleRate(); // don't call updateStepSize because it checks for frequency change stepSize = getRate() * oneOverSampleRate; prevFreq = getRate(); // start at the lowest value step = 0.25f; } // updates our step size based on the current frequency private void updateStepSize() { float currFreq = getRate(); if ( prevFreq != currFreq ) { stepSize = currFreq * oneOverSampleRate; prevFreq = currFreq; } } protected void channelCountChanged() { resetBuffer(); } protected void uGenerate(float[] out) { // generate lfo value float lfo = Waves.SINE.value( step ); // modulate the delay amount using the lfo value. // we always modulate tp a max of 5ms above the input delay. float dep = depth.getLastValue() * 0.5f; float delMS = delay.getLastValue() + ( lfo * dep + dep ); // how many sample frames is that? int delFrame = (int)( delMS * sampleRate() / 1000 ); for ( int i = 0; i < out.length; ++i ) { int outputIndex = outputFrame * audio.channelCount() + i; float inSample = audio.getLastValues()[i]; float wetSample = delayBuffer[outputIndex]; // figure out where we need to place the delayed sample in our ring // buffer int delIndex = ( ( outputFrame + delFrame ) * audio.channelCount() + i ) % delayBuffer.length; delayBuffer[delIndex] = inSample + wetSample * feedback.getLastValue(); // the output sample is in plus wet, each scaled by amplitude inputs out[i] = inSample * dry.getLastValue() + wetSample * wet.getLastValue(); } // next output frame ++outputFrame; if ( outputFrame == bufferFrameLength ) { outputFrame = 0; } updateStepSize(); // step the LFO step += stepSize; if ( step > 1 ) { step -= 1; } } }
sbrichardson/OpenBCI_GUI
OpenBCI_GUI/libraries/minim/src/ddf/minim/ugens/Flanger.java
2,023
// generate lfo value
line_comment
nl
package ddf.minim.ugens; import ddf.minim.UGen; /** * A Flanger is a specialized kind of delay that uses an LFO (low frequency * oscillator) to vary the amount of delay applied to each sample. This causes a * sweeping frequency kind of sound as the signal reinforces or cancels itself * in various ways. In particular the peaks and notches created in the frequency * spectrum are related to each other in a linear harmonic series. This causes * the spectrum to look like a comb. * <p> * Inputs for the Flanger are: * <ul> * <li>delay (in milliseconds): the minimum amount of delay applied to an incoming sample</li> * <li>rate (in Hz): the frequency of the LFO</li> * <li>depth (in milliseconds): the maximum amount of delay added onto delay by the LFO</li> * <li>feedback: how much of delayed signal should be fed back into the effect</li> * <li>dry: how much of the uneffected input should be included in the output</li> * <li>wet: how much of the effected signal should be included in the output</li> * </ul> * <p> * A more thorough description can be found on wikipedia: * http://en.wikipedia.org/wiki/Flanging * <p> * * @author Damien Di Fede * * @example Synthesis/flangerExample * * @related UGen */ public class Flanger extends UGen { /** * Where the input goes. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput audio; /** * How much does the flanger delay the incoming signal. Used as the low * value of the modulated delay amount. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput delay; /** * The frequency of the LFO applied to the delay. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput rate; /** * How many milliseconds the LFO increases the delay by at the maximum. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput depth; /** * How much of the flanged signal is fed back into the effect. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput feedback; /** * How much of the dry signal is added to the output. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput dry; /** * How much of the flanged signal is added to the output. * * @example Synthesis/flangerExample * * @related Flanger * @related UGen.UGenInput */ public UGenInput wet; private float[] delayBuffer; private int outputFrame; private int bufferFrameLength; // //////////// // LFO // //////////// // where we will sample our waveform, moves between [0,1] private float step; // the step size we will use to advance our step private float stepSize; // what was our frequency from the last time we updated our step size // stashed so that we don't do more math than necessary private float prevFreq; // 1 / sampleRate, which is used to calculate stepSize private float oneOverSampleRate; /** * Construct a Flanger by specifying all initial values. * * @param delayLength * float: the minimum delay applied to incoming samples (in milliseconds) * @param lfoRate * float: the frequency of the the LFO * @param delayDepth * float: the maximum amount added to the delay by the LFO (in milliseconds) * @param feedbackAmplitude * float: the amount of the flanged signal fed back into the effect * @param dryAmplitude * float: the amount of incoming signal added to the output * @param wetAmplitude * float: the amount of the flanged signal added to the output */ public Flanger(float delayLength, float lfoRate, float delayDepth, float feedbackAmplitude, float dryAmplitude, float wetAmplitude) { audio = addAudio(); delay = addControl( delayLength ); rate = addControl( lfoRate ); depth = addControl( delayDepth ); feedback = addControl( feedbackAmplitude ); dry = addControl( dryAmplitude ); wet = addControl( wetAmplitude ); } private void resetBuffer() { int sampleCount = (int)( 100 * sampleRate() / 1000 ); delayBuffer = new float[sampleCount * audio.channelCount()]; outputFrame = 0; bufferFrameLength = sampleCount; } // clamps rate for us private float getRate() { float r = rate.getLastValue(); return r > 0.001f ? r : 0.001f; } protected void sampleRateChanged() { resetBuffer(); oneOverSampleRate = 1 / sampleRate(); // don't call updateStepSize because it checks for frequency change stepSize = getRate() * oneOverSampleRate; prevFreq = getRate(); // start at the lowest value step = 0.25f; } // updates our step size based on the current frequency private void updateStepSize() { float currFreq = getRate(); if ( prevFreq != currFreq ) { stepSize = currFreq * oneOverSampleRate; prevFreq = currFreq; } } protected void channelCountChanged() { resetBuffer(); } protected void uGenerate(float[] out) { // generate lfo<SUF> float lfo = Waves.SINE.value( step ); // modulate the delay amount using the lfo value. // we always modulate tp a max of 5ms above the input delay. float dep = depth.getLastValue() * 0.5f; float delMS = delay.getLastValue() + ( lfo * dep + dep ); // how many sample frames is that? int delFrame = (int)( delMS * sampleRate() / 1000 ); for ( int i = 0; i < out.length; ++i ) { int outputIndex = outputFrame * audio.channelCount() + i; float inSample = audio.getLastValues()[i]; float wetSample = delayBuffer[outputIndex]; // figure out where we need to place the delayed sample in our ring // buffer int delIndex = ( ( outputFrame + delFrame ) * audio.channelCount() + i ) % delayBuffer.length; delayBuffer[delIndex] = inSample + wetSample * feedback.getLastValue(); // the output sample is in plus wet, each scaled by amplitude inputs out[i] = inSample * dry.getLastValue() + wetSample * wet.getLastValue(); } // next output frame ++outputFrame; if ( outputFrame == bufferFrameLength ) { outputFrame = 0; } updateStepSize(); // step the LFO step += stepSize; if ( step > 1 ) { step -= 1; } } }
189836_3
/* * Copyright 2010 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.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "nl" locale. */ public class LocalizedNamesImpl_nl extends LocalizedNamesImpl { @Override public String[] loadLikelyRegionCodes() { return new String[] { "NL", "BE", }; } @Override public String[] loadSortedRegionCodes() { return new String[] { "AF", "AX", "AL", "DZ", "UM", "VI", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AC", "AU", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "VG", "BN", "BG", "BF", "BI", "KH", "CA", "IC", "KY", "CF", "EA", "CL", "CN", "CX", "CP", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CU", "CY", "DK", "DG", "DJ", "DM", "DO", "DE", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FX", "EU", "FO", "FK", "FJ", "PH", "FI", "FR", "TF", "GF", "PF", "GA", "GM", "GE", "GH", "GI", "GD", "GR", "GL", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "HN", "HU", "HK", "IE", "IS", "IN", "ID", "IQ", "IR", "IM", "IL", "IT", "CI", "JM", "JP", "YE", "JE", "JO", "CV", "CM", "KZ", "KE", "KG", "KI", "KW", "HR", "LA", "LS", "LV", "LB", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MV", "MY", "ML", "MT", "MA", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MZ", "MM", "NA", "NR", "NL", "AN", "NP", "NI", "NC", "NZ", "NE", "NG", "NU", "MP", "KP", "NO", "NF", "QO", "UG", "UA", "UZ", "OM", "AT", "TL", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "KN", "LC", "PM", "VC", "SB", "WS", "SM", "SA", "ST", "SN", "RS", "CS", "SC", "SL", "SG", "SH", "MF", "SI", "SK", "SD", "SO", "ES", "LK", "SR", "SJ", "SZ", "SY", "TJ", "TW", "TZ", "TH", "TG", "TK", "TO", "TT", "TA", "TD", "CZ", "TN", "TR", "TM", "TC", "TV", "UY", "VU", "VA", "VE", "AE", "US", "GB", "VN", "WF", "EH", "BY", "ZM", "ZW", "ZA", "GS", "KR", "SE", "CH", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("001", "Wereld"); namesMap.put("002", "Afrika"); namesMap.put("003", "Noord-Amerika"); namesMap.put("005", "Zuid-Amerika"); namesMap.put("009", "Oceanië"); namesMap.put("011", "West-Afrika"); namesMap.put("013", "Midden-Amerika"); namesMap.put("014", "Oost-Afrika"); namesMap.put("015", "Noord-Afrika"); namesMap.put("017", "Centraal-Afrika"); namesMap.put("018", "Zuidelijk Afrika"); namesMap.put("019", "Amerika"); namesMap.put("021", "Noordelijk Amerika"); namesMap.put("029", "Caribisch gebied"); namesMap.put("030", "Oost-Azië"); namesMap.put("034", "Zuid-Azië"); namesMap.put("035", "Zuidoost-Azië"); namesMap.put("039", "Zuid-Europa"); namesMap.put("053", "Australië en Nieuw-Zeeland"); namesMap.put("054", "Melanesië"); namesMap.put("057", "Micronesische regio"); namesMap.put("061", "Polynesië"); namesMap.put("062", "Zuidelijk Centraal-Azië"); namesMap.put("142", "Azië"); namesMap.put("143", "Centraal-Azië"); namesMap.put("145", "West-Azië"); namesMap.put("150", "Europa"); namesMap.put("151", "Oost-Europa"); namesMap.put("154", "Noord-Europa"); namesMap.put("155", "West-Europa"); namesMap.put("172", "Gemenebest van Onafhankelijke Staten"); namesMap.put("419", "Latijns-Amerika en het Caribisch gebied"); namesMap.put("830", "Kanaaleilanden"); namesMap.put("AC", "Ascension"); namesMap.put("AE", "Verenigde Arabische Emiraten"); namesMap.put("AG", "Antigua en Barbuda"); namesMap.put("AL", "Albanië"); namesMap.put("AM", "Armenië"); namesMap.put("AN", "Nederlandse Antillen"); namesMap.put("AR", "Argentinië"); namesMap.put("AS", "Amerikaans Samoa"); namesMap.put("AT", "Oostenrijk"); namesMap.put("AU", "Australië"); namesMap.put("AX", "Alandeilanden"); namesMap.put("AZ", "Azerbeidzjan"); namesMap.put("BA", "Bosnië en Herzegovina"); namesMap.put("BE", "België"); namesMap.put("BG", "Bulgarije"); namesMap.put("BH", "Bahrein"); namesMap.put("BR", "Brazilië"); namesMap.put("BS", "Bahama’s"); namesMap.put("BV", "Bouveteiland"); namesMap.put("BY", "Wit-Rusland"); namesMap.put("CC", "Cocoseilanden"); namesMap.put("CD", "Congo-Kinshasa"); namesMap.put("CF", "Centraal-Afrikaanse Republiek"); namesMap.put("CG", "Congo"); namesMap.put("CH", "Zwitserland"); namesMap.put("CI", "Ivoorkust"); namesMap.put("CK", "Cookeilanden"); namesMap.put("CL", "Chili"); namesMap.put("CM", "Kameroen"); namesMap.put("CP", "Clipperton"); namesMap.put("CS", "Servië en Montenegro"); namesMap.put("CV", "Kaapverdië"); namesMap.put("CX", "Christmaseiland"); namesMap.put("CZ", "Tsjechië"); namesMap.put("DE", "Duitsland"); namesMap.put("DK", "Denemarken"); namesMap.put("DO", "Dominicaanse Republiek"); namesMap.put("DZ", "Algerije"); namesMap.put("EA", "Ceuta en Melilla"); namesMap.put("EE", "Estland"); namesMap.put("EG", "Egypte"); namesMap.put("EH", "Westelijke Sahara"); namesMap.put("ES", "Spanje"); namesMap.put("ET", "Ethiopië"); namesMap.put("EU", "Europese Unie"); namesMap.put("FK", "Falklandeilanden"); namesMap.put("FM", "Micronesië"); namesMap.put("FO", "Faeröer"); namesMap.put("FR", "Frankrijk"); namesMap.put("FX", "Europese Frankrijk"); namesMap.put("GB", "Verenigd Koninkrijk"); namesMap.put("GE", "Georgië"); namesMap.put("GF", "Frans-Guyana"); namesMap.put("GL", "Groenland"); namesMap.put("GN", "Guinee"); namesMap.put("GQ", "Equatoriaal-Guinea"); namesMap.put("GR", "Griekenland"); namesMap.put("GS", "Zuid-Georgië en Zuidelijke Sandwicheilanden"); namesMap.put("GW", "Guinee-Bissau"); namesMap.put("HK", "Hongkong"); namesMap.put("HM", "Heard- en McDonaldeilanden"); namesMap.put("HR", "Kroatië"); namesMap.put("HT", "Haïti"); namesMap.put("HU", "Hongarije"); namesMap.put("IC", "Canarische Eilanden"); namesMap.put("ID", "Indonesië"); namesMap.put("IE", "Ierland"); namesMap.put("IL", "Israël"); namesMap.put("IO", "Britse Gebieden in de Indische Oceaan"); namesMap.put("IQ", "Irak"); namesMap.put("IS", "IJsland"); namesMap.put("IT", "Italië"); namesMap.put("JO", "Jordanië"); namesMap.put("KE", "Kenia"); namesMap.put("KG", "Kirgizië"); namesMap.put("KH", "Cambodja"); namesMap.put("KM", "Comoren"); namesMap.put("KN", "Saint Kitts en Nevis"); namesMap.put("KP", "Noord-Korea"); namesMap.put("KR", "Zuid-Korea"); namesMap.put("KW", "Koeweit"); namesMap.put("KY", "Caymaneilanden"); namesMap.put("KZ", "Kazachstan"); namesMap.put("LB", "Libanon"); namesMap.put("LT", "Litouwen"); namesMap.put("LU", "Luxemburg"); namesMap.put("LV", "Letland"); namesMap.put("LY", "Libië"); namesMap.put("MA", "Marokko"); namesMap.put("MD", "Moldavië"); namesMap.put("MF", "Sint-Maarten"); namesMap.put("MG", "Madagaskar"); namesMap.put("MH", "Marshalleilanden"); namesMap.put("MK", "Macedonië"); namesMap.put("MM", "Myanmar"); namesMap.put("MN", "Mongolië"); namesMap.put("MO", "Macao"); namesMap.put("MP", "Noordelijke Marianeneilanden"); namesMap.put("MR", "Mauritanië"); namesMap.put("MV", "Maldiven"); namesMap.put("MY", "Maleisië"); namesMap.put("NA", "Namibië"); namesMap.put("NC", "Nieuw-Caledonië"); namesMap.put("NF", "Norfolkeiland"); namesMap.put("NL", "Nederland"); namesMap.put("NO", "Noorwegen"); namesMap.put("NZ", "Nieuw-Zeeland"); namesMap.put("PF", "Frans-Polynesië"); namesMap.put("PG", "Papoea-Nieuw-Guinea"); namesMap.put("PH", "Filipijnen"); namesMap.put("PL", "Polen"); namesMap.put("PM", "Saint Pierre en Miquelon"); namesMap.put("PN", "Pitcairn"); namesMap.put("PS", "Palestijns Gebied"); namesMap.put("QO", "Oceanië (overige)"); namesMap.put("RO", "Roemenië"); namesMap.put("RS", "Servië"); namesMap.put("RU", "Rusland"); namesMap.put("SA", "Saoedi-Arabië"); namesMap.put("SB", "Salomonseilanden"); namesMap.put("SC", "Seychellen"); namesMap.put("SD", "Soedan"); namesMap.put("SE", "Zweden"); namesMap.put("SH", "Sint-Helena"); namesMap.put("SI", "Slovenië"); namesMap.put("SJ", "Svalbard en Jan Mayen"); namesMap.put("SK", "Slowakije"); namesMap.put("SO", "Somalië"); namesMap.put("ST", "Sao Tomé en Principe"); namesMap.put("SY", "Syrië"); namesMap.put("TC", "Turks- en Caicoseilanden"); namesMap.put("TD", "Tsjaad"); namesMap.put("TF", "Franse Gebieden in de zuidelijke Indische Oceaan"); namesMap.put("TJ", "Tadzjikistan"); namesMap.put("TL", "Oost-Timor"); namesMap.put("TN", "Tunesië"); namesMap.put("TR", "Turkije"); namesMap.put("TT", "Trinidad en Tobago"); namesMap.put("UA", "Oekraïne"); namesMap.put("UG", "Oeganda"); namesMap.put("UM", "Amerikaanse kleinere afgelegen eilanden"); namesMap.put("US", "Verenigde Staten"); namesMap.put("UZ", "Oezbekistan"); namesMap.put("VA", "Vaticaanstad"); namesMap.put("VC", "Saint Vincent en de Grenadines"); namesMap.put("VG", "Britse Maagdeneilanden"); namesMap.put("VI", "Amerikaanse Maagdeneilanden"); namesMap.put("WF", "Wallis en Futuna"); namesMap.put("YE", "Jemen"); namesMap.put("ZA", "Zuid-Afrika"); namesMap.put("ZZ", "Onbekend of onjuist gebied"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ return { "001": "Wereld", "002": "Afrika", "003": "Noord-Amerika", "005": "Zuid-Amerika", "009": "Oceanië", "011": "West-Afrika", "013": "Midden-Amerika", "014": "Oost-Afrika", "015": "Noord-Afrika", "017": "Centraal-Afrika", "018": "Zuidelijk Afrika", "019": "Amerika", "021": "Noordelijk Amerika", "029": "Caribisch gebied", "030": "Oost-Azië", "034": "Zuid-Azië", "035": "Zuidoost-Azië", "039": "Zuid-Europa", "053": "Australië en Nieuw-Zeeland", "054": "Melanesië", "057": "Micronesische regio", "061": "Polynesië", "062": "Zuidelijk Centraal-Azië", "142": "Azië", "143": "Centraal-Azië", "145": "West-Azië", "150": "Europa", "151": "Oost-Europa", "154": "Noord-Europa", "155": "West-Europa", "172": "Gemenebest van Onafhankelijke Staten", "419": "Latijns-Amerika en het Caribisch gebied", "830": "Kanaaleilanden", "AC": "Ascension", "AE": "Verenigde Arabische Emiraten", "AG": "Antigua en Barbuda", "AL": "Albanië", "AM": "Armenië", "AN": "Nederlandse Antillen", "AR": "Argentinië", "AS": "Amerikaans Samoa", "AT": "Oostenrijk", "AU": "Australië", "AX": "Alandeilanden", "AZ": "Azerbeidzjan", "BA": "Bosnië en Herzegovina", "BE": "België", "BG": "Bulgarije", "BH": "Bahrein", "BR": "Brazilië", "BS": "Bahama’s", "BV": "Bouveteiland", "BY": "Wit-Rusland", "CC": "Cocoseilanden", "CD": "Congo-Kinshasa", "CF": "Centraal-Afrikaanse Republiek", "CG": "Congo", "CH": "Zwitserland", "CI": "Ivoorkust", "CK": "Cookeilanden", "CL": "Chili", "CM": "Kameroen", "CP": "Clipperton", "CS": "Servië en Montenegro", "CV": "Kaapverdië", "CX": "Christmaseiland", "CZ": "Tsjechië", "DE": "Duitsland", "DK": "Denemarken", "DO": "Dominicaanse Republiek", "DZ": "Algerije", "EA": "Ceuta en Melilla", "EE": "Estland", "EG": "Egypte", "EH": "Westelijke Sahara", "ES": "Spanje", "ET": "Ethiopië", "EU": "Europese Unie", "FK": "Falklandeilanden", "FM": "Micronesië", "FO": "Faeröer", "FR": "Frankrijk", "FX": "Europese Frankrijk", "GB": "Verenigd Koninkrijk", "GE": "Georgië", "GF": "Frans-Guyana", "GL": "Groenland", "GN": "Guinee", "GQ": "Equatoriaal-Guinea", "GR": "Griekenland", "GS": "Zuid-Georgië en Zuidelijke Sandwicheilanden", "GW": "Guinee-Bissau", "HK": "Hongkong", "HM": "Heard- en McDonaldeilanden", "HR": "Kroatië", "HT": "Haïti", "HU": "Hongarije", "IC": "Canarische Eilanden", "ID": "Indonesië", "IE": "Ierland", "IL": "Israël", "IO": "Britse Gebieden in de Indische Oceaan", "IQ": "Irak", "IS": "IJsland", "IT": "Italië", "JO": "Jordanië", "KE": "Kenia", "KG": "Kirgizië", "KH": "Cambodja", "KM": "Comoren", "KN": "Saint Kitts en Nevis", "KP": "Noord-Korea", "KR": "Zuid-Korea", "KW": "Koeweit", "KY": "Caymaneilanden", "KZ": "Kazachstan", "LB": "Libanon", "LT": "Litouwen", "LU": "Luxemburg", "LV": "Letland", "LY": "Libië", "MA": "Marokko", "MD": "Moldavië", "MF": "Sint-Maarten", "MG": "Madagaskar", "MH": "Marshalleilanden", "MK": "Macedonië", "MM": "Myanmar", "MN": "Mongolië", "MO": "Macao", "MP": "Noordelijke Marianeneilanden", "MR": "Mauritanië", "MV": "Maldiven", "MY": "Maleisië", "NA": "Namibië", "NC": "Nieuw-Caledonië", "NF": "Norfolkeiland", "NL": "Nederland", "NO": "Noorwegen", "NZ": "Nieuw-Zeeland", "PF": "Frans-Polynesië", "PG": "Papoea-Nieuw-Guinea", "PH": "Filipijnen", "PL": "Polen", "PM": "Saint Pierre en Miquelon", "PN": "Pitcairn", "PS": "Palestijns Gebied", "QO": "Oceanië (overige)", "RO": "Roemenië", "RS": "Servië", "RU": "Rusland", "SA": "Saoedi-Arabië", "SB": "Salomonseilanden", "SC": "Seychellen", "SD": "Soedan", "SE": "Zweden", "SH": "Sint-Helena", "SI": "Slovenië", "SJ": "Svalbard en Jan Mayen", "SK": "Slowakije", "SO": "Somalië", "ST": "Sao Tomé en Principe", "SY": "Syrië", "TC": "Turks- en Caicoseilanden", "TD": "Tsjaad", "TF": "Franse Gebieden in de zuidelijke Indische Oceaan", "TJ": "Tadzjikistan", "TL": "Oost-Timor", "TN": "Tunesië", "TR": "Turkije", "TT": "Trinidad en Tobago", "UA": "Oekraïne", "UG": "Oeganda", "UM": "Amerikaanse kleinere afgelegen eilanden", "US": "Verenigde Staten", "UZ": "Oezbekistan", "VA": "Vaticaanstad", "VC": "Saint Vincent en de Grenadines", "VG": "Britse Maagdeneilanden", "VI": "Amerikaanse Maagdeneilanden", "WF": "Wallis en Futuna", "YE": "Jemen", "ZA": "Zuid-Afrika", "ZZ": "Onbekend of onjuist gebied" }; }-*/; }
scalagwt/scalagwt-gwt
user/src/com/google/gwt/i18n/client/impl/cldr/LocalizedNamesImpl_nl.java
6,984
/*-{ return { "001": "Wereld", "002": "Afrika", "003": "Noord-Amerika", "005": "Zuid-Amerika", "009": "Oceanië", "011": "West-Afrika", "013": "Midden-Amerika", "014": "Oost-Afrika", "015": "Noord-Afrika", "017": "Centraal-Afrika", "018": "Zuidelijk Afrika", "019": "Amerika", "021": "Noordelijk Amerika", "029": "Caribisch gebied", "030": "Oost-Azië", "034": "Zuid-Azië", "035": "Zuidoost-Azië", "039": "Zuid-Europa", "053": "Australië en Nieuw-Zeeland", "054": "Melanesië", "057": "Micronesische regio", "061": "Polynesië", "062": "Zuidelijk Centraal-Azië", "142": "Azië", "143": "Centraal-Azië", "145": "West-Azië", "150": "Europa", "151": "Oost-Europa", "154": "Noord-Europa", "155": "West-Europa", "172": "Gemenebest van Onafhankelijke Staten", "419": "Latijns-Amerika en het Caribisch gebied", "830": "Kanaaleilanden", "AC": "Ascension", "AE": "Verenigde Arabische Emiraten", "AG": "Antigua en Barbuda", "AL": "Albanië", "AM": "Armenië", "AN": "Nederlandse Antillen", "AR": "Argentinië", "AS": "Amerikaans Samoa", "AT": "Oostenrijk", "AU": "Australië", "AX": "Alandeilanden", "AZ": "Azerbeidzjan", "BA": "Bosnië en Herzegovina", "BE": "België", "BG": "Bulgarije", "BH": "Bahrein", "BR": "Brazilië", "BS": "Bahama’s", "BV": "Bouveteiland", "BY": "Wit-Rusland", "CC": "Cocoseilanden", "CD": "Congo-Kinshasa", "CF": "Centraal-Afrikaanse Republiek", "CG": "Congo", "CH": "Zwitserland", "CI": "Ivoorkust", "CK": "Cookeilanden", "CL": "Chili", "CM": "Kameroen", "CP": "Clipperton", "CS": "Servië en Montenegro", "CV": "Kaapverdië", "CX": "Christmaseiland", "CZ": "Tsjechië", "DE": "Duitsland", "DK": "Denemarken", "DO": "Dominicaanse Republiek", "DZ": "Algerije", "EA": "Ceuta en Melilla", "EE": "Estland", "EG": "Egypte", "EH": "Westelijke Sahara", "ES": "Spanje", "ET": "Ethiopië", "EU": "Europese Unie", "FK": "Falklandeilanden", "FM": "Micronesië", "FO": "Faeröer", "FR": "Frankrijk", "FX": "Europese Frankrijk", "GB": "Verenigd Koninkrijk", "GE": "Georgië", "GF": "Frans-Guyana", "GL": "Groenland", "GN": "Guinee", "GQ": "Equatoriaal-Guinea", "GR": "Griekenland", "GS": "Zuid-Georgië en Zuidelijke Sandwicheilanden", "GW": "Guinee-Bissau", "HK": "Hongkong", "HM": "Heard- en McDonaldeilanden", "HR": "Kroatië", "HT": "Haïti", "HU": "Hongarije", "IC": "Canarische Eilanden", "ID": "Indonesië", "IE": "Ierland", "IL": "Israël", "IO": "Britse Gebieden in de Indische Oceaan", "IQ": "Irak", "IS": "IJsland", "IT": "Italië", "JO": "Jordanië", "KE": "Kenia", "KG": "Kirgizië", "KH": "Cambodja", "KM": "Comoren", "KN": "Saint Kitts en Nevis", "KP": "Noord-Korea", "KR": "Zuid-Korea", "KW": "Koeweit", "KY": "Caymaneilanden", "KZ": "Kazachstan", "LB": "Libanon", "LT": "Litouwen", "LU": "Luxemburg", "LV": "Letland", "LY": "Libië", "MA": "Marokko", "MD": "Moldavië", "MF": "Sint-Maarten", "MG": "Madagaskar", "MH": "Marshalleilanden", "MK": "Macedonië", "MM": "Myanmar", "MN": "Mongolië", "MO": "Macao", "MP": "Noordelijke Marianeneilanden", "MR": "Mauritanië", "MV": "Maldiven", "MY": "Maleisië", "NA": "Namibië", "NC": "Nieuw-Caledonië", "NF": "Norfolkeiland", "NL": "Nederland", "NO": "Noorwegen", "NZ": "Nieuw-Zeeland", "PF": "Frans-Polynesië", "PG": "Papoea-Nieuw-Guinea", "PH": "Filipijnen", "PL": "Polen", "PM": "Saint Pierre en Miquelon", "PN": "Pitcairn", "PS": "Palestijns Gebied", "QO": "Oceanië (overige)", "RO": "Roemenië", "RS": "Servië", "RU": "Rusland", "SA": "Saoedi-Arabië", "SB": "Salomonseilanden", "SC": "Seychellen", "SD": "Soedan", "SE": "Zweden", "SH": "Sint-Helena", "SI": "Slovenië", "SJ": "Svalbard en Jan Mayen", "SK": "Slowakije", "SO": "Somalië", "ST": "Sao Tomé en Principe", "SY": "Syrië", "TC": "Turks- en Caicoseilanden", "TD": "Tsjaad", "TF": "Franse Gebieden in de zuidelijke Indische Oceaan", "TJ": "Tadzjikistan", "TL": "Oost-Timor", "TN": "Tunesië", "TR": "Turkije", "TT": "Trinidad en Tobago", "UA": "Oekraïne", "UG": "Oeganda", "UM": "Amerikaanse kleinere afgelegen eilanden", "US": "Verenigde Staten", "UZ": "Oezbekistan", "VA": "Vaticaanstad", "VC": "Saint Vincent en de Grenadines", "VG": "Britse Maagdeneilanden", "VI": "Amerikaanse Maagdeneilanden", "WF": "Wallis en Futuna", "YE": "Jemen", "ZA": "Zuid-Afrika", "ZZ": "Onbekend of onjuist gebied" }; }-*/
block_comment
nl
/* * Copyright 2010 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.gwt.i18n.client.impl.cldr; import com.google.gwt.core.client.JavaScriptObject; // DO NOT EDIT - GENERATED FROM CLDR DATA /** * Localized names for the "nl" locale. */ public class LocalizedNamesImpl_nl extends LocalizedNamesImpl { @Override public String[] loadLikelyRegionCodes() { return new String[] { "NL", "BE", }; } @Override public String[] loadSortedRegionCodes() { return new String[] { "AF", "AX", "AL", "DZ", "UM", "VI", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AC", "AU", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "VG", "BN", "BG", "BF", "BI", "KH", "CA", "IC", "KY", "CF", "EA", "CL", "CN", "CX", "CP", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CU", "CY", "DK", "DG", "DJ", "DM", "DO", "DE", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FX", "EU", "FO", "FK", "FJ", "PH", "FI", "FR", "TF", "GF", "PF", "GA", "GM", "GE", "GH", "GI", "GD", "GR", "GL", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "HN", "HU", "HK", "IE", "IS", "IN", "ID", "IQ", "IR", "IM", "IL", "IT", "CI", "JM", "JP", "YE", "JE", "JO", "CV", "CM", "KZ", "KE", "KG", "KI", "KW", "HR", "LA", "LS", "LV", "LB", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MV", "MY", "ML", "MT", "MA", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MZ", "MM", "NA", "NR", "NL", "AN", "NP", "NI", "NC", "NZ", "NE", "NG", "NU", "MP", "KP", "NO", "NF", "QO", "UG", "UA", "UZ", "OM", "AT", "TL", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "KN", "LC", "PM", "VC", "SB", "WS", "SM", "SA", "ST", "SN", "RS", "CS", "SC", "SL", "SG", "SH", "MF", "SI", "SK", "SD", "SO", "ES", "LK", "SR", "SJ", "SZ", "SY", "TJ", "TW", "TZ", "TH", "TG", "TK", "TO", "TT", "TA", "TD", "CZ", "TN", "TR", "TM", "TC", "TV", "UY", "VU", "VA", "VE", "AE", "US", "GB", "VN", "WF", "EH", "BY", "ZM", "ZW", "ZA", "GS", "KR", "SE", "CH", }; } @Override protected void loadNameMapJava() { super.loadNameMapJava(); namesMap.put("001", "Wereld"); namesMap.put("002", "Afrika"); namesMap.put("003", "Noord-Amerika"); namesMap.put("005", "Zuid-Amerika"); namesMap.put("009", "Oceanië"); namesMap.put("011", "West-Afrika"); namesMap.put("013", "Midden-Amerika"); namesMap.put("014", "Oost-Afrika"); namesMap.put("015", "Noord-Afrika"); namesMap.put("017", "Centraal-Afrika"); namesMap.put("018", "Zuidelijk Afrika"); namesMap.put("019", "Amerika"); namesMap.put("021", "Noordelijk Amerika"); namesMap.put("029", "Caribisch gebied"); namesMap.put("030", "Oost-Azië"); namesMap.put("034", "Zuid-Azië"); namesMap.put("035", "Zuidoost-Azië"); namesMap.put("039", "Zuid-Europa"); namesMap.put("053", "Australië en Nieuw-Zeeland"); namesMap.put("054", "Melanesië"); namesMap.put("057", "Micronesische regio"); namesMap.put("061", "Polynesië"); namesMap.put("062", "Zuidelijk Centraal-Azië"); namesMap.put("142", "Azië"); namesMap.put("143", "Centraal-Azië"); namesMap.put("145", "West-Azië"); namesMap.put("150", "Europa"); namesMap.put("151", "Oost-Europa"); namesMap.put("154", "Noord-Europa"); namesMap.put("155", "West-Europa"); namesMap.put("172", "Gemenebest van Onafhankelijke Staten"); namesMap.put("419", "Latijns-Amerika en het Caribisch gebied"); namesMap.put("830", "Kanaaleilanden"); namesMap.put("AC", "Ascension"); namesMap.put("AE", "Verenigde Arabische Emiraten"); namesMap.put("AG", "Antigua en Barbuda"); namesMap.put("AL", "Albanië"); namesMap.put("AM", "Armenië"); namesMap.put("AN", "Nederlandse Antillen"); namesMap.put("AR", "Argentinië"); namesMap.put("AS", "Amerikaans Samoa"); namesMap.put("AT", "Oostenrijk"); namesMap.put("AU", "Australië"); namesMap.put("AX", "Alandeilanden"); namesMap.put("AZ", "Azerbeidzjan"); namesMap.put("BA", "Bosnië en Herzegovina"); namesMap.put("BE", "België"); namesMap.put("BG", "Bulgarije"); namesMap.put("BH", "Bahrein"); namesMap.put("BR", "Brazilië"); namesMap.put("BS", "Bahama’s"); namesMap.put("BV", "Bouveteiland"); namesMap.put("BY", "Wit-Rusland"); namesMap.put("CC", "Cocoseilanden"); namesMap.put("CD", "Congo-Kinshasa"); namesMap.put("CF", "Centraal-Afrikaanse Republiek"); namesMap.put("CG", "Congo"); namesMap.put("CH", "Zwitserland"); namesMap.put("CI", "Ivoorkust"); namesMap.put("CK", "Cookeilanden"); namesMap.put("CL", "Chili"); namesMap.put("CM", "Kameroen"); namesMap.put("CP", "Clipperton"); namesMap.put("CS", "Servië en Montenegro"); namesMap.put("CV", "Kaapverdië"); namesMap.put("CX", "Christmaseiland"); namesMap.put("CZ", "Tsjechië"); namesMap.put("DE", "Duitsland"); namesMap.put("DK", "Denemarken"); namesMap.put("DO", "Dominicaanse Republiek"); namesMap.put("DZ", "Algerije"); namesMap.put("EA", "Ceuta en Melilla"); namesMap.put("EE", "Estland"); namesMap.put("EG", "Egypte"); namesMap.put("EH", "Westelijke Sahara"); namesMap.put("ES", "Spanje"); namesMap.put("ET", "Ethiopië"); namesMap.put("EU", "Europese Unie"); namesMap.put("FK", "Falklandeilanden"); namesMap.put("FM", "Micronesië"); namesMap.put("FO", "Faeröer"); namesMap.put("FR", "Frankrijk"); namesMap.put("FX", "Europese Frankrijk"); namesMap.put("GB", "Verenigd Koninkrijk"); namesMap.put("GE", "Georgië"); namesMap.put("GF", "Frans-Guyana"); namesMap.put("GL", "Groenland"); namesMap.put("GN", "Guinee"); namesMap.put("GQ", "Equatoriaal-Guinea"); namesMap.put("GR", "Griekenland"); namesMap.put("GS", "Zuid-Georgië en Zuidelijke Sandwicheilanden"); namesMap.put("GW", "Guinee-Bissau"); namesMap.put("HK", "Hongkong"); namesMap.put("HM", "Heard- en McDonaldeilanden"); namesMap.put("HR", "Kroatië"); namesMap.put("HT", "Haïti"); namesMap.put("HU", "Hongarije"); namesMap.put("IC", "Canarische Eilanden"); namesMap.put("ID", "Indonesië"); namesMap.put("IE", "Ierland"); namesMap.put("IL", "Israël"); namesMap.put("IO", "Britse Gebieden in de Indische Oceaan"); namesMap.put("IQ", "Irak"); namesMap.put("IS", "IJsland"); namesMap.put("IT", "Italië"); namesMap.put("JO", "Jordanië"); namesMap.put("KE", "Kenia"); namesMap.put("KG", "Kirgizië"); namesMap.put("KH", "Cambodja"); namesMap.put("KM", "Comoren"); namesMap.put("KN", "Saint Kitts en Nevis"); namesMap.put("KP", "Noord-Korea"); namesMap.put("KR", "Zuid-Korea"); namesMap.put("KW", "Koeweit"); namesMap.put("KY", "Caymaneilanden"); namesMap.put("KZ", "Kazachstan"); namesMap.put("LB", "Libanon"); namesMap.put("LT", "Litouwen"); namesMap.put("LU", "Luxemburg"); namesMap.put("LV", "Letland"); namesMap.put("LY", "Libië"); namesMap.put("MA", "Marokko"); namesMap.put("MD", "Moldavië"); namesMap.put("MF", "Sint-Maarten"); namesMap.put("MG", "Madagaskar"); namesMap.put("MH", "Marshalleilanden"); namesMap.put("MK", "Macedonië"); namesMap.put("MM", "Myanmar"); namesMap.put("MN", "Mongolië"); namesMap.put("MO", "Macao"); namesMap.put("MP", "Noordelijke Marianeneilanden"); namesMap.put("MR", "Mauritanië"); namesMap.put("MV", "Maldiven"); namesMap.put("MY", "Maleisië"); namesMap.put("NA", "Namibië"); namesMap.put("NC", "Nieuw-Caledonië"); namesMap.put("NF", "Norfolkeiland"); namesMap.put("NL", "Nederland"); namesMap.put("NO", "Noorwegen"); namesMap.put("NZ", "Nieuw-Zeeland"); namesMap.put("PF", "Frans-Polynesië"); namesMap.put("PG", "Papoea-Nieuw-Guinea"); namesMap.put("PH", "Filipijnen"); namesMap.put("PL", "Polen"); namesMap.put("PM", "Saint Pierre en Miquelon"); namesMap.put("PN", "Pitcairn"); namesMap.put("PS", "Palestijns Gebied"); namesMap.put("QO", "Oceanië (overige)"); namesMap.put("RO", "Roemenië"); namesMap.put("RS", "Servië"); namesMap.put("RU", "Rusland"); namesMap.put("SA", "Saoedi-Arabië"); namesMap.put("SB", "Salomonseilanden"); namesMap.put("SC", "Seychellen"); namesMap.put("SD", "Soedan"); namesMap.put("SE", "Zweden"); namesMap.put("SH", "Sint-Helena"); namesMap.put("SI", "Slovenië"); namesMap.put("SJ", "Svalbard en Jan Mayen"); namesMap.put("SK", "Slowakije"); namesMap.put("SO", "Somalië"); namesMap.put("ST", "Sao Tomé en Principe"); namesMap.put("SY", "Syrië"); namesMap.put("TC", "Turks- en Caicoseilanden"); namesMap.put("TD", "Tsjaad"); namesMap.put("TF", "Franse Gebieden in de zuidelijke Indische Oceaan"); namesMap.put("TJ", "Tadzjikistan"); namesMap.put("TL", "Oost-Timor"); namesMap.put("TN", "Tunesië"); namesMap.put("TR", "Turkije"); namesMap.put("TT", "Trinidad en Tobago"); namesMap.put("UA", "Oekraïne"); namesMap.put("UG", "Oeganda"); namesMap.put("UM", "Amerikaanse kleinere afgelegen eilanden"); namesMap.put("US", "Verenigde Staten"); namesMap.put("UZ", "Oezbekistan"); namesMap.put("VA", "Vaticaanstad"); namesMap.put("VC", "Saint Vincent en de Grenadines"); namesMap.put("VG", "Britse Maagdeneilanden"); namesMap.put("VI", "Amerikaanse Maagdeneilanden"); namesMap.put("WF", "Wallis en Futuna"); namesMap.put("YE", "Jemen"); namesMap.put("ZA", "Zuid-Afrika"); namesMap.put("ZZ", "Onbekend of onjuist gebied"); } @Override protected JavaScriptObject loadNameMapNative() { return overrideMap(super.loadNameMapNative(), loadMyNameMap()); } private native JavaScriptObject loadMyNameMap() /*-{ <SUF>*/; }
98335_1
/* * ReSTFS * ReSTFS Open API 3.0 Spec * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ch.cyberduck.core.eue.io.swagger.client.model; import java.util.Objects; import java.util.Arrays; import ch.cyberduck.core.eue.io.swagger.client.model.Shares; import ch.cyberduck.core.eue.io.swagger.client.model.UiGeo; import ch.cyberduck.core.eue.io.swagger.client.model.UiShare; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * Settings */ public class Settings { @JsonProperty("ui:geo") private UiGeo uigeo = null; @JsonProperty("ui:share") private UiShare uishare = null; @JsonProperty("shares") private Shares shares = null; public Settings uigeo(UiGeo uigeo) { this.uigeo = uigeo; return this; } /** * Get uigeo * @return uigeo **/ @Schema(description = "") public UiGeo getUigeo() { return uigeo; } public void setUigeo(UiGeo uigeo) { this.uigeo = uigeo; } public Settings uishare(UiShare uishare) { this.uishare = uishare; return this; } /** * Get uishare * @return uishare **/ @Schema(description = "") public UiShare getUishare() { return uishare; } public void setUishare(UiShare uishare) { this.uishare = uishare; } public Settings shares(Shares shares) { this.shares = shares; return this; } /** * Get shares * @return shares **/ @Schema(description = "") public Shares getShares() { return shares; } public void setShares(Shares shares) { this.shares = shares; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Settings settings = (Settings) o; return Objects.equals(this.uigeo, settings.uigeo) && Objects.equals(this.uishare, settings.uishare) && Objects.equals(this.shares, settings.shares); } @Override public int hashCode() { return Objects.hash(uigeo, uishare, shares); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Settings {\n"); sb.append(" uigeo: ").append(toIndentedString(uigeo)).append("\n"); sb.append(" uishare: ").append(toIndentedString(uishare)).append("\n"); sb.append(" shares: ").append(toIndentedString(shares)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
scaleway/cyberduck
eue/src/main/java/ch/cyberduck/core/eue/io/swagger/client/model/Settings.java
1,084
/** * Get uigeo * @return uigeo **/
block_comment
nl
/* * ReSTFS * ReSTFS Open API 3.0 Spec * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ch.cyberduck.core.eue.io.swagger.client.model; import java.util.Objects; import java.util.Arrays; import ch.cyberduck.core.eue.io.swagger.client.model.Shares; import ch.cyberduck.core.eue.io.swagger.client.model.UiGeo; import ch.cyberduck.core.eue.io.swagger.client.model.UiShare; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * Settings */ public class Settings { @JsonProperty("ui:geo") private UiGeo uigeo = null; @JsonProperty("ui:share") private UiShare uishare = null; @JsonProperty("shares") private Shares shares = null; public Settings uigeo(UiGeo uigeo) { this.uigeo = uigeo; return this; } /** * Get uigeo <SUF>*/ @Schema(description = "") public UiGeo getUigeo() { return uigeo; } public void setUigeo(UiGeo uigeo) { this.uigeo = uigeo; } public Settings uishare(UiShare uishare) { this.uishare = uishare; return this; } /** * Get uishare * @return uishare **/ @Schema(description = "") public UiShare getUishare() { return uishare; } public void setUishare(UiShare uishare) { this.uishare = uishare; } public Settings shares(Shares shares) { this.shares = shares; return this; } /** * Get shares * @return shares **/ @Schema(description = "") public Shares getShares() { return shares; } public void setShares(Shares shares) { this.shares = shares; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Settings settings = (Settings) o; return Objects.equals(this.uigeo, settings.uigeo) && Objects.equals(this.uishare, settings.uishare) && Objects.equals(this.shares, settings.shares); } @Override public int hashCode() { return Objects.hash(uigeo, uishare, shares); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Settings {\n"); sb.append(" uigeo: ").append(toIndentedString(uigeo)).append("\n"); sb.append(" uishare: ").append(toIndentedString(uishare)).append("\n"); sb.append(" shares: ").append(toIndentedString(shares)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
153082_8
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2024 sciview developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package sc.iview.ui; import net.miginfocom.swing.MigLayout; import org.scijava.Context; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.script.ScriptREPL; import org.scijava.ui.swing.script.OutputPane; import org.scijava.widget.UIComponent; import javax.script.ScriptContext; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; /** * A Swing UI pane for the SciJava scripting REPL. * * @author Curtis Rueden * @author Johannes Schindelin * @author Ulrik Guenther * @author Kyle Harrington */ public class REPLPane implements UIComponent<JComponent> { private final ScriptREPL repl; private final JSplitPane mainPane; private final OutputPane output; private final REPLEditor prompt; //private final VarsPane vars; @Parameter(required = false) private LogService log; /** * Constructs an interpreter UI pane for a SciJava scripting REPL. * * @param context The SciJava application context to use */ public REPLPane(final Context context) { context.inject(this); output = new OutputPane(log); final JScrollPane outputScroll = new JScrollPane(output); outputScroll.setPreferredSize(new Dimension(440, 400)); repl = new ScriptREPL(context, "Python (Jython)", output.getOutputStream()); repl.initialize(); final Writer writer = output.getOutputWriter(); final ScriptContext ctx = repl.getInterpreter().getEngine().getContext(); ctx.setErrorWriter(writer); ctx.setWriter(writer); //vars = new VarsPane(context, repl); //vars.setBorder(new EmptyBorder(0, 0, 8, 0)); //prompt = new REPLEditor(repl, vars, output); prompt = new REPLEditor(repl, null, output); context.inject(prompt); final JScrollPane promptScroll = new JScrollPane(prompt); final JPanel bottomPane = new JPanel(); bottomPane.setLayout(new MigLayout("ins 0", "[grow,fill][pref]", "[grow,fill,align top]")); bottomPane.add(promptScroll, "spany 2"); final JSplitPane outputAndPromptPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, outputScroll, bottomPane); outputAndPromptPane.setResizeWeight(1); // outputAndPromptPane.setDividerSize(2); // mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, vars, // outputAndPromptPane); // mainPane.setDividerSize(1); // mainPane.setDividerLocation(0); mainPane = outputAndPromptPane; } // -- InterpreterPane methods -- /** Gets the associated script REPL. * * @return REPL for use */ public ScriptREPL getREPL() { return repl; } /** Prints a message to the output panel. * * @param string to show in REPL */ public void print(final String string) { final Writer writer = output.getOutputWriter(); try { writer.write(string + "\n"); } catch (final IOException e) { e.printStackTrace(new PrintWriter(writer)); } } public void dispose() { output.close(); } // -- UIComponent methods -- @Override public JComponent getComponent() { return mainPane; } @Override public Class<JComponent> getComponentType() { return JComponent.class; } }
scenerygraphics/sciview
src/main/java/sc/iview/ui/REPLPane.java
1,515
// -- InterpreterPane methods --
line_comment
nl
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2024 sciview developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package sc.iview.ui; import net.miginfocom.swing.MigLayout; import org.scijava.Context; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.script.ScriptREPL; import org.scijava.ui.swing.script.OutputPane; import org.scijava.widget.UIComponent; import javax.script.ScriptContext; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; /** * A Swing UI pane for the SciJava scripting REPL. * * @author Curtis Rueden * @author Johannes Schindelin * @author Ulrik Guenther * @author Kyle Harrington */ public class REPLPane implements UIComponent<JComponent> { private final ScriptREPL repl; private final JSplitPane mainPane; private final OutputPane output; private final REPLEditor prompt; //private final VarsPane vars; @Parameter(required = false) private LogService log; /** * Constructs an interpreter UI pane for a SciJava scripting REPL. * * @param context The SciJava application context to use */ public REPLPane(final Context context) { context.inject(this); output = new OutputPane(log); final JScrollPane outputScroll = new JScrollPane(output); outputScroll.setPreferredSize(new Dimension(440, 400)); repl = new ScriptREPL(context, "Python (Jython)", output.getOutputStream()); repl.initialize(); final Writer writer = output.getOutputWriter(); final ScriptContext ctx = repl.getInterpreter().getEngine().getContext(); ctx.setErrorWriter(writer); ctx.setWriter(writer); //vars = new VarsPane(context, repl); //vars.setBorder(new EmptyBorder(0, 0, 8, 0)); //prompt = new REPLEditor(repl, vars, output); prompt = new REPLEditor(repl, null, output); context.inject(prompt); final JScrollPane promptScroll = new JScrollPane(prompt); final JPanel bottomPane = new JPanel(); bottomPane.setLayout(new MigLayout("ins 0", "[grow,fill][pref]", "[grow,fill,align top]")); bottomPane.add(promptScroll, "spany 2"); final JSplitPane outputAndPromptPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, outputScroll, bottomPane); outputAndPromptPane.setResizeWeight(1); // outputAndPromptPane.setDividerSize(2); // mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, vars, // outputAndPromptPane); // mainPane.setDividerSize(1); // mainPane.setDividerLocation(0); mainPane = outputAndPromptPane; } // -- InterpreterPane<SUF> /** Gets the associated script REPL. * * @return REPL for use */ public ScriptREPL getREPL() { return repl; } /** Prints a message to the output panel. * * @param string to show in REPL */ public void print(final String string) { final Writer writer = output.getOutputWriter(); try { writer.write(string + "\n"); } catch (final IOException e) { e.printStackTrace(new PrintWriter(writer)); } } public void dispose() { output.close(); } // -- UIComponent methods -- @Override public JComponent getComponent() { return mainPane; } @Override public Class<JComponent> getComponentType() { return JComponent.class; } }
125771_2
package cz.agents.agentdrive.simulator.lite.environment; import cz.agents.agentdrive.highway.environment.HighwayEnvironment; import cz.agents.agentdrive.highway.environment.SimulatorHandlers.PlanCallback; import cz.agents.agentdrive.highway.environment.roadnet.RoadNetworkRouter; import cz.agents.agentdrive.highway.environment.roadnet.XMLReader; import cz.agents.agentdrive.highway.environment.roadnet.network.RoadNetwork; import cz.agents.agentdrive.highway.storage.HighwayStorage; import cz.agents.agentdrive.highway.storage.RadarData; import cz.agents.agentdrive.highway.storage.RoadObject; import cz.agents.agentdrive.highway.storage.plan.Action; import cz.agents.agentdrive.highway.storage.plan.PlansOut; import cz.agents.agentdrive.highway.storage.plan.WPAction; import cz.agents.agentdrive.simulator.lite.storage.SimulatorEvent; import cz.agents.agentdrive.simulator.lite.storage.VehicleStorage; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Car; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Vehicle; import cz.agents.alite.common.event.Event; import cz.agents.alite.common.event.EventHandler; import cz.agents.alite.common.event.EventProcessor; import cz.agents.alite.common.event.EventProcessorEventType; import cz.agents.alite.configurator.Configurator; import cz.agents.alite.environment.eventbased.EventBasedEnvironment; import cz.agents.alite.simulation.SimulationEventType; import org.apache.log4j.Logger; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import java.util.*; /** * Class representing the environment of the simulation * <p/> * Created by wmatex on 3.7.14. */ public class SimulatorEnvironment extends EventBasedEnvironment { private static final Logger logger = Logger.getLogger(SimulatorEnvironment.class); /// All simulated vehicles private VehicleStorage vehicleStorage; private HighwayEnvironment highwayEnvironment; private RoadNetwork roadNetwork; private RadarData currentState = new RadarData(); private PlansOut plansOut = new PlansOut(); private PlanCallback planCallback = new PlanCallbackImp(); protected long timestep = Configurator.getParamInt("simulator.lite.timestep", 100); private int counter = 0; /// Time between updates static public final long UPDATE_STEP = 20; /// Time between communication updates static public final long COMM_STEP = 20; private static boolean perfectExecution = Configurator.getParamBool("simulator.lite.perfectExecution", true); /** * Create the environment, the storage and register event handlers */ public SimulatorEnvironment(final EventProcessor eventProcessor) { super(eventProcessor); vehicleStorage = new VehicleStorage(this); XMLReader xmlReader = new XMLReader(); roadNetwork = xmlReader.parseNetwork(Configurator.getParamString("simulator.net.folder", "nets/junction-big/")); RoadNetworkRouter.setRoadNet(roadNetwork); highwayEnvironment = new HighwayEnvironment(this.getEventProcessor(), roadNetwork); getEventProcessor().addEventHandler(new EventHandler() { @Override public EventProcessor getEventProcessor() { return eventProcessor; } @Override public void handleEvent(Event event) { // Start updating vehicles when the simulation starts if (event.isType(SimulationEventType.SIMULATION_STARTED)) { logger.info("SIMULATION STARTED"); if (Configurator.getParamBool("highway.dashboard.systemTime", false)) { highwayEnvironment.getStorage().setSTARTTIME(System.currentTimeMillis()); } else { highwayEnvironment.getStorage().setSTARTTIME(getEventProcessor().getCurrentTime()); } highwayEnvironment.getStorage().updateCars(new RadarData()); logger.debug("HighwayStorage: handled simulation START"); getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null); getEventProcessor().addEvent(SimulatorEvent.UPDATE, null, null, null); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null); } else if (event.isType(SimulatorEvent.COMMUNICATION_UPDATE)) { if (highwayEnvironment.getStorage().getCounter() > 0 && !perfectExecution) highwayEnvironment.getStorage().updateCars(vehicleStorage.generateRadarData()); if (highwayEnvironment.getStorage().getCounter() > 0 && perfectExecution) highwayEnvironment.getStorage().updateCars(highwayEnvironment.getStorage().getCurrentRadarData()); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null, Math.max(1, (long) (timestep * COMM_STEP))); } else if (event.isType(SimulatorEvent.TIMESTEP)) { if (!highwayEnvironment.getStorage().vehiclesForInsert.isEmpty() && highwayEnvironment.getStorage().getPosCurr().isEmpty()) highwayEnvironment.getStorage().updateCars(new RadarData()); if (HighwayStorage.isFinished) getEventProcessor().addEvent(EventProcessorEventType.STOP, null, null, null, timestep); else getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null, timestep); } } }); } private void acceptPlans(PlansOut plans) { logger.debug("Received plans: " + plans.getCarIds()); for (int carID : plans.getCarIds()) { logger.debug("Plan for car " + carID + ": " + plans.getPlan(carID)); // This is the init plan if (((WPAction) plans.getPlan(carID).iterator().next()).getSpeed() == -1) { vehicleStorage.removeVehicle(carID); } else { Vehicle vehicle = vehicleStorage.getVehicle(carID); if (vehicle == null) { // Get the first action containing car info WPAction action = (WPAction) plans.getPlan(carID).iterator().next(); if (plans.getPlan(carID).size() > 1) { Iterator<Action> iter = plans.getPlan(carID).iterator(); Point3f first = ((WPAction) iter.next()).getPosition(); Point3f second = ((WPAction) iter.next()).getPosition(); Vector3f heading = new Vector3f(second.x - first.x, second.y - first.y, second.z - first.z); heading.normalize(); vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), heading, (float) action.getSpeed() /*30.0f*/)); } else { vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), plans.getCurrStates().get(carID).getVelocity(), (float) action.getSpeed())); } } else { vehicle.getVelocityController().updatePlan(plans.getPlan(carID)); vehicle.setWayPoints(plans.getPlan(carID)); } } } } /** * Initialize the environment and add some vehicles */ public void init() { getEventProcessor().addEventHandler(vehicleStorage); } public VehicleStorage getStorage() { return vehicleStorage; } public RoadNetwork getRoadNetwork() { return roadNetwork; } public HighwayEnvironment getHighwayEnvironment() { return highwayEnvironment; } public PlanCallback getPlanCallback() { return planCallback; } class PlanCallbackImp extends PlanCallback { @Override public RadarData execute(PlansOut plans) { Map<Integer, RoadObject> currStates = plans.getCurrStates(); RadarData radarData = new RadarData(); if (Configurator.getParamBool("simulator.lite.perfectExecution", true)) { float duration = 0; float lastDuration = 0; double timest = Configurator.getParamDouble("highway.SimulatorLocal.timestep", 1.0); float timestep = (float) timest; boolean removeCar = false; for (Integer carID : plans.getCarIds()) { Collection<Action> plan = plans.getPlan(carID); RoadObject state = currStates.get(carID); Point3f lastPosition = state.getPosition(); Point3f myPosition = state.getPosition(); for (Action action : plan) { if (action.getClass().equals(WPAction.class)) { WPAction wpAction = (WPAction) action; if (wpAction.getSpeed() == -1) { myPosition = wpAction.getPosition(); removeCar = true; } if (wpAction.getSpeed() < 0.001) { duration += 0.10f; } else { myPosition = wpAction.getPosition(); lastDuration = (float) (wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed())); duration += wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed()); } // creating point between the waypoints if my duration is greater than the defined timestep if (duration >= timestep) { float remainingDuration = timestep - (duration - lastDuration); float ration = remainingDuration / lastDuration; float x = myPosition.x - lastPosition.x; float y = myPosition.y - lastPosition.y; float z = myPosition.z - lastPosition.z; Vector3f vec = new Vector3f(x, y, z); vec.scale(ration); myPosition = new Point3f(vec.x + 0 + lastPosition.x, vec.y + lastPosition.y, vec.z + lastPosition.z); break; } lastPosition = wpAction.getPosition(); } } if (removeCar) { if (Configurator.getParamBool("highway.dashboard.sumoSimulation", true)) { this.addToPlannedVehiclesToRemove(carID); } removeCar = false; } else { Vector3f vel = new Vector3f(state.getPosition()); vel.negate(); vel.add(myPosition); if (vel.length() < 0.0001) { vel = state.getVelocity(); vel.normalize(); vel.scale(0.0010f); } int lane = highwayEnvironment.getRoadNetwork().getClosestLane(myPosition).getIndex(); state = new RoadObject(carID, highwayEnvironment.getCurrentTime(), lane, myPosition, vel); radarData.add(state); duration = 0; } } currentState = radarData; } else { acceptPlans(plans); // let VehicleStorage apply plans from HighwayStorage } counter++; return radarData; } } }
schaemar/AgentDrive
src/main/java/cz/agents/agentdrive/simulator/lite/environment/SimulatorEnvironment.java
3,127
/// Time between updates
line_comment
nl
package cz.agents.agentdrive.simulator.lite.environment; import cz.agents.agentdrive.highway.environment.HighwayEnvironment; import cz.agents.agentdrive.highway.environment.SimulatorHandlers.PlanCallback; import cz.agents.agentdrive.highway.environment.roadnet.RoadNetworkRouter; import cz.agents.agentdrive.highway.environment.roadnet.XMLReader; import cz.agents.agentdrive.highway.environment.roadnet.network.RoadNetwork; import cz.agents.agentdrive.highway.storage.HighwayStorage; import cz.agents.agentdrive.highway.storage.RadarData; import cz.agents.agentdrive.highway.storage.RoadObject; import cz.agents.agentdrive.highway.storage.plan.Action; import cz.agents.agentdrive.highway.storage.plan.PlansOut; import cz.agents.agentdrive.highway.storage.plan.WPAction; import cz.agents.agentdrive.simulator.lite.storage.SimulatorEvent; import cz.agents.agentdrive.simulator.lite.storage.VehicleStorage; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Car; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Vehicle; import cz.agents.alite.common.event.Event; import cz.agents.alite.common.event.EventHandler; import cz.agents.alite.common.event.EventProcessor; import cz.agents.alite.common.event.EventProcessorEventType; import cz.agents.alite.configurator.Configurator; import cz.agents.alite.environment.eventbased.EventBasedEnvironment; import cz.agents.alite.simulation.SimulationEventType; import org.apache.log4j.Logger; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import java.util.*; /** * Class representing the environment of the simulation * <p/> * Created by wmatex on 3.7.14. */ public class SimulatorEnvironment extends EventBasedEnvironment { private static final Logger logger = Logger.getLogger(SimulatorEnvironment.class); /// All simulated vehicles private VehicleStorage vehicleStorage; private HighwayEnvironment highwayEnvironment; private RoadNetwork roadNetwork; private RadarData currentState = new RadarData(); private PlansOut plansOut = new PlansOut(); private PlanCallback planCallback = new PlanCallbackImp(); protected long timestep = Configurator.getParamInt("simulator.lite.timestep", 100); private int counter = 0; /// Time between<SUF> static public final long UPDATE_STEP = 20; /// Time between communication updates static public final long COMM_STEP = 20; private static boolean perfectExecution = Configurator.getParamBool("simulator.lite.perfectExecution", true); /** * Create the environment, the storage and register event handlers */ public SimulatorEnvironment(final EventProcessor eventProcessor) { super(eventProcessor); vehicleStorage = new VehicleStorage(this); XMLReader xmlReader = new XMLReader(); roadNetwork = xmlReader.parseNetwork(Configurator.getParamString("simulator.net.folder", "nets/junction-big/")); RoadNetworkRouter.setRoadNet(roadNetwork); highwayEnvironment = new HighwayEnvironment(this.getEventProcessor(), roadNetwork); getEventProcessor().addEventHandler(new EventHandler() { @Override public EventProcessor getEventProcessor() { return eventProcessor; } @Override public void handleEvent(Event event) { // Start updating vehicles when the simulation starts if (event.isType(SimulationEventType.SIMULATION_STARTED)) { logger.info("SIMULATION STARTED"); if (Configurator.getParamBool("highway.dashboard.systemTime", false)) { highwayEnvironment.getStorage().setSTARTTIME(System.currentTimeMillis()); } else { highwayEnvironment.getStorage().setSTARTTIME(getEventProcessor().getCurrentTime()); } highwayEnvironment.getStorage().updateCars(new RadarData()); logger.debug("HighwayStorage: handled simulation START"); getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null); getEventProcessor().addEvent(SimulatorEvent.UPDATE, null, null, null); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null); } else if (event.isType(SimulatorEvent.COMMUNICATION_UPDATE)) { if (highwayEnvironment.getStorage().getCounter() > 0 && !perfectExecution) highwayEnvironment.getStorage().updateCars(vehicleStorage.generateRadarData()); if (highwayEnvironment.getStorage().getCounter() > 0 && perfectExecution) highwayEnvironment.getStorage().updateCars(highwayEnvironment.getStorage().getCurrentRadarData()); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null, Math.max(1, (long) (timestep * COMM_STEP))); } else if (event.isType(SimulatorEvent.TIMESTEP)) { if (!highwayEnvironment.getStorage().vehiclesForInsert.isEmpty() && highwayEnvironment.getStorage().getPosCurr().isEmpty()) highwayEnvironment.getStorage().updateCars(new RadarData()); if (HighwayStorage.isFinished) getEventProcessor().addEvent(EventProcessorEventType.STOP, null, null, null, timestep); else getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null, timestep); } } }); } private void acceptPlans(PlansOut plans) { logger.debug("Received plans: " + plans.getCarIds()); for (int carID : plans.getCarIds()) { logger.debug("Plan for car " + carID + ": " + plans.getPlan(carID)); // This is the init plan if (((WPAction) plans.getPlan(carID).iterator().next()).getSpeed() == -1) { vehicleStorage.removeVehicle(carID); } else { Vehicle vehicle = vehicleStorage.getVehicle(carID); if (vehicle == null) { // Get the first action containing car info WPAction action = (WPAction) plans.getPlan(carID).iterator().next(); if (plans.getPlan(carID).size() > 1) { Iterator<Action> iter = plans.getPlan(carID).iterator(); Point3f first = ((WPAction) iter.next()).getPosition(); Point3f second = ((WPAction) iter.next()).getPosition(); Vector3f heading = new Vector3f(second.x - first.x, second.y - first.y, second.z - first.z); heading.normalize(); vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), heading, (float) action.getSpeed() /*30.0f*/)); } else { vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), plans.getCurrStates().get(carID).getVelocity(), (float) action.getSpeed())); } } else { vehicle.getVelocityController().updatePlan(plans.getPlan(carID)); vehicle.setWayPoints(plans.getPlan(carID)); } } } } /** * Initialize the environment and add some vehicles */ public void init() { getEventProcessor().addEventHandler(vehicleStorage); } public VehicleStorage getStorage() { return vehicleStorage; } public RoadNetwork getRoadNetwork() { return roadNetwork; } public HighwayEnvironment getHighwayEnvironment() { return highwayEnvironment; } public PlanCallback getPlanCallback() { return planCallback; } class PlanCallbackImp extends PlanCallback { @Override public RadarData execute(PlansOut plans) { Map<Integer, RoadObject> currStates = plans.getCurrStates(); RadarData radarData = new RadarData(); if (Configurator.getParamBool("simulator.lite.perfectExecution", true)) { float duration = 0; float lastDuration = 0; double timest = Configurator.getParamDouble("highway.SimulatorLocal.timestep", 1.0); float timestep = (float) timest; boolean removeCar = false; for (Integer carID : plans.getCarIds()) { Collection<Action> plan = plans.getPlan(carID); RoadObject state = currStates.get(carID); Point3f lastPosition = state.getPosition(); Point3f myPosition = state.getPosition(); for (Action action : plan) { if (action.getClass().equals(WPAction.class)) { WPAction wpAction = (WPAction) action; if (wpAction.getSpeed() == -1) { myPosition = wpAction.getPosition(); removeCar = true; } if (wpAction.getSpeed() < 0.001) { duration += 0.10f; } else { myPosition = wpAction.getPosition(); lastDuration = (float) (wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed())); duration += wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed()); } // creating point between the waypoints if my duration is greater than the defined timestep if (duration >= timestep) { float remainingDuration = timestep - (duration - lastDuration); float ration = remainingDuration / lastDuration; float x = myPosition.x - lastPosition.x; float y = myPosition.y - lastPosition.y; float z = myPosition.z - lastPosition.z; Vector3f vec = new Vector3f(x, y, z); vec.scale(ration); myPosition = new Point3f(vec.x + 0 + lastPosition.x, vec.y + lastPosition.y, vec.z + lastPosition.z); break; } lastPosition = wpAction.getPosition(); } } if (removeCar) { if (Configurator.getParamBool("highway.dashboard.sumoSimulation", true)) { this.addToPlannedVehiclesToRemove(carID); } removeCar = false; } else { Vector3f vel = new Vector3f(state.getPosition()); vel.negate(); vel.add(myPosition); if (vel.length() < 0.0001) { vel = state.getVelocity(); vel.normalize(); vel.scale(0.0010f); } int lane = highwayEnvironment.getRoadNetwork().getClosestLane(myPosition).getIndex(); state = new RoadObject(carID, highwayEnvironment.getCurrentTime(), lane, myPosition, vel); radarData.add(state); duration = 0; } } currentState = radarData; } else { acceptPlans(plans); // let VehicleStorage apply plans from HighwayStorage } counter++; return radarData; } } }
35715_17
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Alan Harder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.ConverterMatcher; import com.thoughtworks.xstream.converters.ConverterRegistry; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.core.ClassLoaderReference; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.util.Fields; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.ReaderWrapper; import com.thoughtworks.xstream.io.xml.StandardStaxDriver; import com.thoughtworks.xstream.mapper.CannotResolveClassException; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.security.AnyTypePermission; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.XmlFile; import hudson.diagnosis.OldDataMonitor; import hudson.model.Label; import hudson.model.Result; import hudson.model.Saveable; import hudson.remoting.ClassFilter; import hudson.util.xstream.ImmutableListConverter; import hudson.util.xstream.ImmutableMapConverter; import hudson.util.xstream.ImmutableSetConverter; import hudson.util.xstream.ImmutableSortedSetConverter; import hudson.util.xstream.MapperDelegate; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; import jenkins.util.xstream.SafeURLConverter; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * {@link XStream} customized in various ways for Jenkins’ needs. * Most importantly, integrates {@link RobustReflectionConverter}. */ public class XStream2 extends XStream { private static final Logger LOGGER = Logger.getLogger(XStream2.class.getName()); /** * Determine what is the value (in seconds) of the "collectionUpdateLimit" added by XStream * to protect against <a href="http://x-stream.github.io/CVE-2021-43859.html">CVE-2021-43859</a>. * It corresponds to the accumulated timeout when adding an item to a collection. * * Default: 5 seconds (in contrary to XStream default to 20 which is a bit too tolerant) * If negative: disable the DoS protection */ @Restricted(NoExternalUse.class) public static final String COLLECTION_UPDATE_LIMIT_PROPERTY_NAME = XStream2.class.getName() + ".collectionUpdateLimit"; private static final int COLLECTION_UPDATE_LIMIT_DEFAULT_VALUE = 5; private RobustReflectionConverter reflectionConverter; private final ThreadLocal<Boolean> oldData = new ThreadLocal<>(); private final @CheckForNull ClassOwnership classOwnership; private final Map<String, Class<?>> compatibilityAliases = new ConcurrentHashMap<>(); /** * Hook to insert {@link Mapper}s after they are created. */ private MapperInjectionPoint mapperInjectionPoint; /** * Convenience method so we only have to change the driver in one place * if we switch to something new in the future * * @return a new instance of the HierarchicalStreamDriver we want to use */ public static HierarchicalStreamDriver getDefaultDriver() { return new StaxDriver(); } private static class StaxDriver extends StandardStaxDriver { /* * The below two methods are copied from com.thoughtworks.xstream.io.xml.AbstractXppDriver to preserve * compatibility. */ @Override public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out, PrettyPrintWriter.XML_1_1, getNameCoder()); } @Override public HierarchicalStreamWriter createWriter(OutputStream out) { /* * While it is tempting to use StandardCharsets.UTF_8 here, this would break * hudson.util.XStream2EncodingTest#toXMLUnspecifiedEncoding. */ return createWriter(new OutputStreamWriter(out, Charset.defaultCharset())); } /* * The below two methods are copied from com.thoughtworks.xstream.io.xml.StaxDriver for Java 17 compatibility. */ @Override protected XMLInputFactory createInputFactory() { final XMLInputFactory instance = XMLInputFactory.newInstance(); instance.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); instance.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); return instance; } @Override protected XMLOutputFactory createOutputFactory() { return XMLOutputFactory.newInstance(); } } public XStream2() { super(getDefaultDriver()); init(); classOwnership = null; } public XStream2(HierarchicalStreamDriver hierarchicalStreamDriver) { super(hierarchicalStreamDriver); init(); classOwnership = null; } /** * @since 2.318 */ public XStream2(ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { super(reflectionProvider, driver, classLoaderReference, mapper, converterLookup, converterRegistry); init(); classOwnership = null; } XStream2(ClassOwnership classOwnership) { super(getDefaultDriver()); init(); this.classOwnership = classOwnership; } @Override public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { return unmarshal(reader, root, dataHolder, false); } /** * Variant of {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)} that nulls out non-{@code transient} instance fields not defined in the source when unmarshaling into an existing object. * <p>Typically useful when loading user-supplied XML files in place (non-null {@code root}) * where some reference-valued fields of the root object may have legitimate reasons for being null. * Without this mode, it is impossible to clear such fields in an existing instance, * since XStream has no notation for a null field value. * Even for primitive-valued fields, it is useful to guarantee * that unmarshaling will produce the same result as creating a new instance. * <p>Do <em>not</em> use in cases where the root objects defines fields (typically {@code final}) * which it expects to be {@link NonNull} unless you are prepared to restore default values for those fields. * @param nullOut whether to perform this special behavior; * false to use the stock XStream behavior of leaving unmentioned {@code root} fields untouched * @see XmlFile#unmarshalNullingOut * @see <a href="https://issues.jenkins.io/browse/JENKINS-21017">JENKINS-21017</a> * @since 2.99 */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder, boolean nullOut) { // init() is too early to do this // defensive because some use of XStream happens before plugins are initialized. Jenkins h = Jenkins.getInstanceOrNull(); if (h != null && h.pluginManager != null && h.pluginManager.uberClassLoader != null) { setClassLoader(h.pluginManager.uberClassLoader); } Object o; if (root == null || !nullOut) { o = super.unmarshal(reader, root, dataHolder); } else { Set<String> topLevelFields = new HashSet<>(); o = super.unmarshal(new ReaderWrapper(reader) { int depth; @Override public void moveUp() { if (--depth == 0) { topLevelFields.add(getNodeName()); } super.moveUp(); } @Override public void moveDown() { try { super.moveDown(); } finally { depth++; } } }, root, dataHolder); if (o == root && getConverterLookup().lookupConverterForType(o.getClass()) instanceof RobustReflectionConverter) { getReflectionProvider().visitSerializableFields(o, (String name, Class type, Class definedIn, Object value) -> { if (topLevelFields.contains(name)) { return; } Field f = Fields.find(definedIn, name); Object v; if (type.isPrimitive()) { // oddly not in com.thoughtworks.xstream.core.util.Primitives v = ReflectionUtils.getVmDefaultValueForPrimitiveType(type); if (v.equals(value)) { return; } } else { if (value == null) { return; } v = null; } LOGGER.log(Level.FINE, "JENKINS-21017: nulling out {0} in {1}", new Object[] {f, o}); Fields.write(f, o, v); }); } } if (oldData.get() != null) { oldData.remove(); if (o instanceof Saveable) OldDataMonitor.report((Saveable) o, "1.106"); } return o; } @Override protected void setupConverters() { super.setupConverters(); // replace default reflection converter reflectionConverter = new RobustReflectionConverter(getMapper(), JVM.newReflectionProvider(), new PluginClassOwnership()); registerConverter(reflectionConverter, PRIORITY_VERY_LOW + 1); } /** * Specifies that a given field of a given class should not be treated with laxity by {@link RobustCollectionConverter}. * @param clazz a class which we expect to hold a non-{@code transient} field * @param field a field name in that class * @since 2.85 this method can be used from outside core, before then it was restricted since initially added in 1.551 / 1.532.2 */ public void addCriticalField(Class<?> clazz, String field) { reflectionConverter.addCriticalField(clazz, field); } static String trimVersion(String version) { // TODO seems like there should be some trick with VersionNumber to do this return version.replaceFirst(" .+$", ""); } private void init() { int updateLimit = SystemProperties.getInteger(COLLECTION_UPDATE_LIMIT_PROPERTY_NAME, COLLECTION_UPDATE_LIMIT_DEFAULT_VALUE); this.setCollectionUpdateLimit(updateLimit); // list up types that should be marshalled out like a value, without referential integrity tracking. addImmutableType(Result.class, false); // http://www.openwall.com/lists/oss-security/2017/04/03/4 denyTypes(new Class[] { void.class, Void.class }); registerConverter(new RobustCollectionConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new RobustMapConverter(getMapper()), 10); registerConverter(new ImmutableMapConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableSortedSetConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableSetConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableListConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new CopyOnWriteMap.Tree.ConverterImpl(getMapper()), 10); // needs to override MapConverter registerConverter(new DescribableList.ConverterImpl(getMapper()), 10); // explicitly added to handle subtypes registerConverter(new Label.ConverterImpl(), 10); // SECURITY-637 against URL deserialization registerConverter(new SafeURLConverter(), 10); // this should come after all the XStream's default simpler converters, // but before reflection-based one kicks in. registerConverter(new AssociatedConverterImpl(this), -10); registerConverter(new BlacklistedTypesConverter(), PRIORITY_VERY_HIGH); // SECURITY-247 defense addPermission(AnyTypePermission.ANY); // covered by JEP-200, avoid securityWarningGiven registerConverter(new DynamicProxyConverter(getMapper(), new ClassLoaderReference(getClassLoader())) { // SECURITY-105 defense @Override public boolean canConvert(Class type) { return /* this precedes NullConverter */ type != null && super.canConvert(type); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new ConversionException("<dynamic-proxy> not supported"); } }, PRIORITY_VERY_HIGH); } @Override protected MapperWrapper wrapMapper(MapperWrapper next) { Mapper m = new CompatibilityMapper(new MapperWrapper(next) { @Override public String serializedClass(Class type) { if (type != null && ImmutableMap.class.isAssignableFrom(type)) return super.serializedClass(ImmutableMap.class); else if (type != null && ImmutableList.class.isAssignableFrom(type)) return super.serializedClass(ImmutableList.class); else return super.serializedClass(type); } }); mapperInjectionPoint = new MapperInjectionPoint(m); return mapperInjectionPoint; } public Mapper getMapperInjectionPoint() { return mapperInjectionPoint.getDelegate(); } /** * @deprecated Uses default encoding yet fails to write an encoding header. Prefer {@link #toXMLUTF8}. */ @Deprecated @Override public void toXML(Object obj, OutputStream out) { super.toXML(obj, out); } /** * Serializes to a byte stream. * Uses UTF-8 encoding and specifies that in the XML encoding declaration. * @since 1.504 */ public void toXMLUTF8(Object obj, OutputStream out) throws IOException { Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8); w.write("<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n"); toXML(obj, w); } /** * This method allows one to insert additional mappers after {@link XStream2} was created, * but because of the way XStream works internally, this needs to be done carefully. * Namely, * * <ol> * <li>You need to {@link #getMapperInjectionPoint()} wrap it, then put that back into {@link #setMapper(Mapper)}. * <li>The whole sequence needs to be synchronized against this object to avoid a concurrency issue. * </ol> */ public void setMapper(Mapper m) { mapperInjectionPoint.setDelegate(m); } static final class MapperInjectionPoint extends MapperDelegate { MapperInjectionPoint(Mapper wrapped) { super(wrapped); } public Mapper getDelegate() { return delegate; } public void setDelegate(Mapper m) { delegate = m; } } /** * Adds an alias in case class names change. * * Unlike {@link #alias(String, Class)}, which uses the registered alias name for writing XML, * this method registers an alias to be used only for the sake of reading from XML. This makes * this method usable for the situation when class names change. * * @param oldClassName * Fully qualified name of the old class name. * @param newClass * New class that's field-compatible with the given old class name. * @since 1.416 */ public void addCompatibilityAlias(String oldClassName, Class newClass) { compatibilityAliases.put(oldClassName, newClass); } /** * Prior to Hudson 1.106, XStream 1.1.x was used which encoded "$" in class names * as "-" instead of "_-" that is used now. Up through Hudson 1.348 compatibility * for old serialized data was maintained via {@link com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper}. * However, it was found (JENKINS-5768) that this caused fields with "__" to fail * deserialization due to double decoding. Now this class is used for compatibility. */ private class CompatibilityMapper extends MapperWrapper { private CompatibilityMapper(Mapper wrapped) { super(wrapped); } @Override public Class realClass(String elementName) { Class s = compatibilityAliases.get(elementName); if (s != null) return s; try { return super.realClass(elementName); } catch (CannotResolveClassException e) { // If a "-" is found, retry with mapping this to "$" if (elementName.indexOf('-') >= 0) try { Class c = super.realClass(elementName.replace('-', '$')); oldData.set(Boolean.TRUE); return c; } catch (CannotResolveClassException e2) { } // Throw original exception throw e; } } } /** * If a class defines a nested {@code ConverterImpl} subclass, use that as a {@link Converter}. * Its constructor may have XStream/XStream2 and/or Mapper parameters (or no params). */ private static final class AssociatedConverterImpl implements Converter { private final XStream xstream; private static final ClassValue<Class<? extends ConverterMatcher>> classCache = new ClassValue<Class<? extends ConverterMatcher>>() { @Override protected Class<? extends ConverterMatcher> computeValue(Class<?> type) { return computeConverterClass(type); } }; private final ConcurrentHashMap<Class<?>, Converter> cache = new ConcurrentHashMap<>(); private AssociatedConverterImpl(XStream xstream) { this.xstream = xstream; } @CheckForNull private Converter findConverter(@CheckForNull Class<?> t) { if (t == null) { return null; } Converter result = cache.computeIfAbsent(t, unused -> computeConverter(t)); // ConcurrentHashMap does not allow null, so use this object to represent null return result == this ? null : result; } @CheckForNull private static Class<? extends ConverterMatcher> computeConverterClass(@NonNull Class<?> t) { try { final ClassLoader classLoader = t.getClassLoader(); if (classLoader == null) { return null; } String name = t.getName() + "$ConverterImpl"; if (classLoader.getResource(name.replace('.', '/') + ".class") == null) { return null; } return classLoader.loadClass(name).asSubclass(ConverterMatcher.class); } catch (ClassNotFoundException e) { return null; } } @CheckForNull private Converter computeConverter(@NonNull Class<?> t) { Class<? extends ConverterMatcher> cl = classCache.get(t); if (cl == null) { // See above.. this object in cache represents null return this; } try { Constructor<?> c = cl.getConstructors()[0]; Class<?>[] p = c.getParameterTypes(); Object[] args = new Object[p.length]; for (int i = 0; i < p.length; i++) { if (p[i] == XStream.class || p[i] == XStream2.class) args[i] = xstream; else if (p[i] == Mapper.class) args[i] = xstream.getMapper(); else throw new InstantiationError("Unrecognized constructor parameter: " + p[i]); } ConverterMatcher cm = (ConverterMatcher) c.newInstance(args); return cm instanceof SingleValueConverter ? new SingleValueConverterWrapper((SingleValueConverter) cm) : (Converter) cm; } catch (IllegalAccessException e) { IllegalAccessError x = new IllegalAccessError(); x.initCause(e); throw x; } catch (InstantiationException | InvocationTargetException e) { InstantiationError x = new InstantiationError(); x.initCause(e); throw x; } } @Override public boolean canConvert(Class type) { return findConverter(type) != null; } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage") @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { findConverter(source.getClass()).marshal(source, writer, context); } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage") @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { return findConverter(context.getRequiredType()).unmarshal(reader, context); } } /** * Create a nested {@code ConverterImpl} subclass that extends this class to run some * callback code just after a type is unmarshalled by RobustReflectionConverter. * Example: <pre> public static class ConverterImpl extends XStream2.PassthruConverter&lt;MyType&gt; { * public ConverterImpl(XStream2 xstream) { super(xstream); } * {@literal @}Override protected void callback(MyType obj, UnmarshallingContext context) { * ... * </pre> */ public abstract static class PassthruConverter<T> implements Converter { private Converter converter; protected PassthruConverter(XStream2 xstream) { converter = xstream.reflectionConverter; } @Override public boolean canConvert(Class type) { // marshal/unmarshal called directly from AssociatedConverterImpl return false; } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { converter.marshal(source, writer, context); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Object obj = converter.unmarshal(reader, context); callback((T) obj, context); return obj; } protected abstract void callback(T obj, UnmarshallingContext context); } /** * Marks serialized classes as being owned by particular components. */ interface ClassOwnership { /** * Looks up the owner of a class, if any. * @param clazz a class which might be from a plugin * @return an identifier such as plugin name, or null */ @CheckForNull String ownerOf(Class<?> clazz); } class PluginClassOwnership implements ClassOwnership { private PluginManager pm; @Override public String ownerOf(Class<?> clazz) { if (classOwnership != null) { return classOwnership.ownerOf(clazz); } if (pm == null) { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null) { pm = j.getPluginManager(); } } if (pm == null) { return null; } // TODO: possibly recursively scan super class to discover dependencies PluginWrapper p = pm.whichPlugin(clazz); return p != null ? p.getShortName() + '@' + trimVersion(p.getVersion()) : null; } } private static class BlacklistedTypesConverter implements Converter { @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { throw new UnsupportedOperationException("Refusing to marshal " + source.getClass().getName() + " for security reasons; see https://www.jenkins.io/redirect/class-filter/"); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new ConversionException("Refusing to unmarshal " + reader.getNodeName() + " for security reasons; see https://www.jenkins.io/redirect/class-filter/"); } @Override public boolean canConvert(Class type) { if (type == null) { return false; } String name = type.getName(); // claim we can convert all the scary stuff so we can throw exceptions when attempting to do so return ClassFilter.DEFAULT.isBlacklisted(name) || ClassFilter.DEFAULT.isBlacklisted(type); } } }
scherler/jenkins
core/src/main/java/hudson/util/XStream2.java
7,407
// needs to override MapConverter
line_comment
nl
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Alan Harder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.ConverterMatcher; import com.thoughtworks.xstream.converters.ConverterRegistry; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.core.ClassLoaderReference; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.util.Fields; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.ReaderWrapper; import com.thoughtworks.xstream.io.xml.StandardStaxDriver; import com.thoughtworks.xstream.mapper.CannotResolveClassException; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.security.AnyTypePermission; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.XmlFile; import hudson.diagnosis.OldDataMonitor; import hudson.model.Label; import hudson.model.Result; import hudson.model.Saveable; import hudson.remoting.ClassFilter; import hudson.util.xstream.ImmutableListConverter; import hudson.util.xstream.ImmutableMapConverter; import hudson.util.xstream.ImmutableSetConverter; import hudson.util.xstream.ImmutableSortedSetConverter; import hudson.util.xstream.MapperDelegate; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; import jenkins.util.xstream.SafeURLConverter; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * {@link XStream} customized in various ways for Jenkins’ needs. * Most importantly, integrates {@link RobustReflectionConverter}. */ public class XStream2 extends XStream { private static final Logger LOGGER = Logger.getLogger(XStream2.class.getName()); /** * Determine what is the value (in seconds) of the "collectionUpdateLimit" added by XStream * to protect against <a href="http://x-stream.github.io/CVE-2021-43859.html">CVE-2021-43859</a>. * It corresponds to the accumulated timeout when adding an item to a collection. * * Default: 5 seconds (in contrary to XStream default to 20 which is a bit too tolerant) * If negative: disable the DoS protection */ @Restricted(NoExternalUse.class) public static final String COLLECTION_UPDATE_LIMIT_PROPERTY_NAME = XStream2.class.getName() + ".collectionUpdateLimit"; private static final int COLLECTION_UPDATE_LIMIT_DEFAULT_VALUE = 5; private RobustReflectionConverter reflectionConverter; private final ThreadLocal<Boolean> oldData = new ThreadLocal<>(); private final @CheckForNull ClassOwnership classOwnership; private final Map<String, Class<?>> compatibilityAliases = new ConcurrentHashMap<>(); /** * Hook to insert {@link Mapper}s after they are created. */ private MapperInjectionPoint mapperInjectionPoint; /** * Convenience method so we only have to change the driver in one place * if we switch to something new in the future * * @return a new instance of the HierarchicalStreamDriver we want to use */ public static HierarchicalStreamDriver getDefaultDriver() { return new StaxDriver(); } private static class StaxDriver extends StandardStaxDriver { /* * The below two methods are copied from com.thoughtworks.xstream.io.xml.AbstractXppDriver to preserve * compatibility. */ @Override public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out, PrettyPrintWriter.XML_1_1, getNameCoder()); } @Override public HierarchicalStreamWriter createWriter(OutputStream out) { /* * While it is tempting to use StandardCharsets.UTF_8 here, this would break * hudson.util.XStream2EncodingTest#toXMLUnspecifiedEncoding. */ return createWriter(new OutputStreamWriter(out, Charset.defaultCharset())); } /* * The below two methods are copied from com.thoughtworks.xstream.io.xml.StaxDriver for Java 17 compatibility. */ @Override protected XMLInputFactory createInputFactory() { final XMLInputFactory instance = XMLInputFactory.newInstance(); instance.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); instance.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); return instance; } @Override protected XMLOutputFactory createOutputFactory() { return XMLOutputFactory.newInstance(); } } public XStream2() { super(getDefaultDriver()); init(); classOwnership = null; } public XStream2(HierarchicalStreamDriver hierarchicalStreamDriver) { super(hierarchicalStreamDriver); init(); classOwnership = null; } /** * @since 2.318 */ public XStream2(ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { super(reflectionProvider, driver, classLoaderReference, mapper, converterLookup, converterRegistry); init(); classOwnership = null; } XStream2(ClassOwnership classOwnership) { super(getDefaultDriver()); init(); this.classOwnership = classOwnership; } @Override public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { return unmarshal(reader, root, dataHolder, false); } /** * Variant of {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)} that nulls out non-{@code transient} instance fields not defined in the source when unmarshaling into an existing object. * <p>Typically useful when loading user-supplied XML files in place (non-null {@code root}) * where some reference-valued fields of the root object may have legitimate reasons for being null. * Without this mode, it is impossible to clear such fields in an existing instance, * since XStream has no notation for a null field value. * Even for primitive-valued fields, it is useful to guarantee * that unmarshaling will produce the same result as creating a new instance. * <p>Do <em>not</em> use in cases where the root objects defines fields (typically {@code final}) * which it expects to be {@link NonNull} unless you are prepared to restore default values for those fields. * @param nullOut whether to perform this special behavior; * false to use the stock XStream behavior of leaving unmentioned {@code root} fields untouched * @see XmlFile#unmarshalNullingOut * @see <a href="https://issues.jenkins.io/browse/JENKINS-21017">JENKINS-21017</a> * @since 2.99 */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder, boolean nullOut) { // init() is too early to do this // defensive because some use of XStream happens before plugins are initialized. Jenkins h = Jenkins.getInstanceOrNull(); if (h != null && h.pluginManager != null && h.pluginManager.uberClassLoader != null) { setClassLoader(h.pluginManager.uberClassLoader); } Object o; if (root == null || !nullOut) { o = super.unmarshal(reader, root, dataHolder); } else { Set<String> topLevelFields = new HashSet<>(); o = super.unmarshal(new ReaderWrapper(reader) { int depth; @Override public void moveUp() { if (--depth == 0) { topLevelFields.add(getNodeName()); } super.moveUp(); } @Override public void moveDown() { try { super.moveDown(); } finally { depth++; } } }, root, dataHolder); if (o == root && getConverterLookup().lookupConverterForType(o.getClass()) instanceof RobustReflectionConverter) { getReflectionProvider().visitSerializableFields(o, (String name, Class type, Class definedIn, Object value) -> { if (topLevelFields.contains(name)) { return; } Field f = Fields.find(definedIn, name); Object v; if (type.isPrimitive()) { // oddly not in com.thoughtworks.xstream.core.util.Primitives v = ReflectionUtils.getVmDefaultValueForPrimitiveType(type); if (v.equals(value)) { return; } } else { if (value == null) { return; } v = null; } LOGGER.log(Level.FINE, "JENKINS-21017: nulling out {0} in {1}", new Object[] {f, o}); Fields.write(f, o, v); }); } } if (oldData.get() != null) { oldData.remove(); if (o instanceof Saveable) OldDataMonitor.report((Saveable) o, "1.106"); } return o; } @Override protected void setupConverters() { super.setupConverters(); // replace default reflection converter reflectionConverter = new RobustReflectionConverter(getMapper(), JVM.newReflectionProvider(), new PluginClassOwnership()); registerConverter(reflectionConverter, PRIORITY_VERY_LOW + 1); } /** * Specifies that a given field of a given class should not be treated with laxity by {@link RobustCollectionConverter}. * @param clazz a class which we expect to hold a non-{@code transient} field * @param field a field name in that class * @since 2.85 this method can be used from outside core, before then it was restricted since initially added in 1.551 / 1.532.2 */ public void addCriticalField(Class<?> clazz, String field) { reflectionConverter.addCriticalField(clazz, field); } static String trimVersion(String version) { // TODO seems like there should be some trick with VersionNumber to do this return version.replaceFirst(" .+$", ""); } private void init() { int updateLimit = SystemProperties.getInteger(COLLECTION_UPDATE_LIMIT_PROPERTY_NAME, COLLECTION_UPDATE_LIMIT_DEFAULT_VALUE); this.setCollectionUpdateLimit(updateLimit); // list up types that should be marshalled out like a value, without referential integrity tracking. addImmutableType(Result.class, false); // http://www.openwall.com/lists/oss-security/2017/04/03/4 denyTypes(new Class[] { void.class, Void.class }); registerConverter(new RobustCollectionConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new RobustMapConverter(getMapper()), 10); registerConverter(new ImmutableMapConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableSortedSetConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableSetConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new ImmutableListConverter(getMapper(), getReflectionProvider()), 10); registerConverter(new CopyOnWriteMap.Tree.ConverterImpl(getMapper()), 10); // needs to<SUF> registerConverter(new DescribableList.ConverterImpl(getMapper()), 10); // explicitly added to handle subtypes registerConverter(new Label.ConverterImpl(), 10); // SECURITY-637 against URL deserialization registerConverter(new SafeURLConverter(), 10); // this should come after all the XStream's default simpler converters, // but before reflection-based one kicks in. registerConverter(new AssociatedConverterImpl(this), -10); registerConverter(new BlacklistedTypesConverter(), PRIORITY_VERY_HIGH); // SECURITY-247 defense addPermission(AnyTypePermission.ANY); // covered by JEP-200, avoid securityWarningGiven registerConverter(new DynamicProxyConverter(getMapper(), new ClassLoaderReference(getClassLoader())) { // SECURITY-105 defense @Override public boolean canConvert(Class type) { return /* this precedes NullConverter */ type != null && super.canConvert(type); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new ConversionException("<dynamic-proxy> not supported"); } }, PRIORITY_VERY_HIGH); } @Override protected MapperWrapper wrapMapper(MapperWrapper next) { Mapper m = new CompatibilityMapper(new MapperWrapper(next) { @Override public String serializedClass(Class type) { if (type != null && ImmutableMap.class.isAssignableFrom(type)) return super.serializedClass(ImmutableMap.class); else if (type != null && ImmutableList.class.isAssignableFrom(type)) return super.serializedClass(ImmutableList.class); else return super.serializedClass(type); } }); mapperInjectionPoint = new MapperInjectionPoint(m); return mapperInjectionPoint; } public Mapper getMapperInjectionPoint() { return mapperInjectionPoint.getDelegate(); } /** * @deprecated Uses default encoding yet fails to write an encoding header. Prefer {@link #toXMLUTF8}. */ @Deprecated @Override public void toXML(Object obj, OutputStream out) { super.toXML(obj, out); } /** * Serializes to a byte stream. * Uses UTF-8 encoding and specifies that in the XML encoding declaration. * @since 1.504 */ public void toXMLUTF8(Object obj, OutputStream out) throws IOException { Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8); w.write("<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n"); toXML(obj, w); } /** * This method allows one to insert additional mappers after {@link XStream2} was created, * but because of the way XStream works internally, this needs to be done carefully. * Namely, * * <ol> * <li>You need to {@link #getMapperInjectionPoint()} wrap it, then put that back into {@link #setMapper(Mapper)}. * <li>The whole sequence needs to be synchronized against this object to avoid a concurrency issue. * </ol> */ public void setMapper(Mapper m) { mapperInjectionPoint.setDelegate(m); } static final class MapperInjectionPoint extends MapperDelegate { MapperInjectionPoint(Mapper wrapped) { super(wrapped); } public Mapper getDelegate() { return delegate; } public void setDelegate(Mapper m) { delegate = m; } } /** * Adds an alias in case class names change. * * Unlike {@link #alias(String, Class)}, which uses the registered alias name for writing XML, * this method registers an alias to be used only for the sake of reading from XML. This makes * this method usable for the situation when class names change. * * @param oldClassName * Fully qualified name of the old class name. * @param newClass * New class that's field-compatible with the given old class name. * @since 1.416 */ public void addCompatibilityAlias(String oldClassName, Class newClass) { compatibilityAliases.put(oldClassName, newClass); } /** * Prior to Hudson 1.106, XStream 1.1.x was used which encoded "$" in class names * as "-" instead of "_-" that is used now. Up through Hudson 1.348 compatibility * for old serialized data was maintained via {@link com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper}. * However, it was found (JENKINS-5768) that this caused fields with "__" to fail * deserialization due to double decoding. Now this class is used for compatibility. */ private class CompatibilityMapper extends MapperWrapper { private CompatibilityMapper(Mapper wrapped) { super(wrapped); } @Override public Class realClass(String elementName) { Class s = compatibilityAliases.get(elementName); if (s != null) return s; try { return super.realClass(elementName); } catch (CannotResolveClassException e) { // If a "-" is found, retry with mapping this to "$" if (elementName.indexOf('-') >= 0) try { Class c = super.realClass(elementName.replace('-', '$')); oldData.set(Boolean.TRUE); return c; } catch (CannotResolveClassException e2) { } // Throw original exception throw e; } } } /** * If a class defines a nested {@code ConverterImpl} subclass, use that as a {@link Converter}. * Its constructor may have XStream/XStream2 and/or Mapper parameters (or no params). */ private static final class AssociatedConverterImpl implements Converter { private final XStream xstream; private static final ClassValue<Class<? extends ConverterMatcher>> classCache = new ClassValue<Class<? extends ConverterMatcher>>() { @Override protected Class<? extends ConverterMatcher> computeValue(Class<?> type) { return computeConverterClass(type); } }; private final ConcurrentHashMap<Class<?>, Converter> cache = new ConcurrentHashMap<>(); private AssociatedConverterImpl(XStream xstream) { this.xstream = xstream; } @CheckForNull private Converter findConverter(@CheckForNull Class<?> t) { if (t == null) { return null; } Converter result = cache.computeIfAbsent(t, unused -> computeConverter(t)); // ConcurrentHashMap does not allow null, so use this object to represent null return result == this ? null : result; } @CheckForNull private static Class<? extends ConverterMatcher> computeConverterClass(@NonNull Class<?> t) { try { final ClassLoader classLoader = t.getClassLoader(); if (classLoader == null) { return null; } String name = t.getName() + "$ConverterImpl"; if (classLoader.getResource(name.replace('.', '/') + ".class") == null) { return null; } return classLoader.loadClass(name).asSubclass(ConverterMatcher.class); } catch (ClassNotFoundException e) { return null; } } @CheckForNull private Converter computeConverter(@NonNull Class<?> t) { Class<? extends ConverterMatcher> cl = classCache.get(t); if (cl == null) { // See above.. this object in cache represents null return this; } try { Constructor<?> c = cl.getConstructors()[0]; Class<?>[] p = c.getParameterTypes(); Object[] args = new Object[p.length]; for (int i = 0; i < p.length; i++) { if (p[i] == XStream.class || p[i] == XStream2.class) args[i] = xstream; else if (p[i] == Mapper.class) args[i] = xstream.getMapper(); else throw new InstantiationError("Unrecognized constructor parameter: " + p[i]); } ConverterMatcher cm = (ConverterMatcher) c.newInstance(args); return cm instanceof SingleValueConverter ? new SingleValueConverterWrapper((SingleValueConverter) cm) : (Converter) cm; } catch (IllegalAccessException e) { IllegalAccessError x = new IllegalAccessError(); x.initCause(e); throw x; } catch (InstantiationException | InvocationTargetException e) { InstantiationError x = new InstantiationError(); x.initCause(e); throw x; } } @Override public boolean canConvert(Class type) { return findConverter(type) != null; } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage") @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { findConverter(source.getClass()).marshal(source, writer, context); } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage") @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { return findConverter(context.getRequiredType()).unmarshal(reader, context); } } /** * Create a nested {@code ConverterImpl} subclass that extends this class to run some * callback code just after a type is unmarshalled by RobustReflectionConverter. * Example: <pre> public static class ConverterImpl extends XStream2.PassthruConverter&lt;MyType&gt; { * public ConverterImpl(XStream2 xstream) { super(xstream); } * {@literal @}Override protected void callback(MyType obj, UnmarshallingContext context) { * ... * </pre> */ public abstract static class PassthruConverter<T> implements Converter { private Converter converter; protected PassthruConverter(XStream2 xstream) { converter = xstream.reflectionConverter; } @Override public boolean canConvert(Class type) { // marshal/unmarshal called directly from AssociatedConverterImpl return false; } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { converter.marshal(source, writer, context); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Object obj = converter.unmarshal(reader, context); callback((T) obj, context); return obj; } protected abstract void callback(T obj, UnmarshallingContext context); } /** * Marks serialized classes as being owned by particular components. */ interface ClassOwnership { /** * Looks up the owner of a class, if any. * @param clazz a class which might be from a plugin * @return an identifier such as plugin name, or null */ @CheckForNull String ownerOf(Class<?> clazz); } class PluginClassOwnership implements ClassOwnership { private PluginManager pm; @Override public String ownerOf(Class<?> clazz) { if (classOwnership != null) { return classOwnership.ownerOf(clazz); } if (pm == null) { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null) { pm = j.getPluginManager(); } } if (pm == null) { return null; } // TODO: possibly recursively scan super class to discover dependencies PluginWrapper p = pm.whichPlugin(clazz); return p != null ? p.getShortName() + '@' + trimVersion(p.getVersion()) : null; } } private static class BlacklistedTypesConverter implements Converter { @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { throw new UnsupportedOperationException("Refusing to marshal " + source.getClass().getName() + " for security reasons; see https://www.jenkins.io/redirect/class-filter/"); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { throw new ConversionException("Refusing to unmarshal " + reader.getNodeName() + " for security reasons; see https://www.jenkins.io/redirect/class-filter/"); } @Override public boolean canConvert(Class type) { if (type == null) { return false; } String name = type.getName(); // claim we can convert all the scary stuff so we can throw exceptions when attempting to do so return ClassFilter.DEFAULT.isBlacklisted(name) || ClassFilter.DEFAULT.isBlacklisted(type); } } }
116008_1
/* * Copyright (c) 2016 Schibsted Products & Technology AS. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. */ package com.schibsted.security.strongbox.sdk.exceptions; /** * @author kvlees */ public class SerializationException extends RuntimeException { public SerializationException(String message) { super(message); } public SerializationException(String message, Throwable cause) { super(message, cause); } }
schibsted/strongbox
sdk/src/main/java/com/schibsted/security/strongbox/sdk/exceptions/SerializationException.java
125
/** * @author kvlees */
block_comment
nl
/* * Copyright (c) 2016 Schibsted Products & Technology AS. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. */ package com.schibsted.security.strongbox.sdk.exceptions; /** * @author kvlees <SUF>*/ public class SerializationException extends RuntimeException { public SerializationException(String message) { super(message); } public SerializationException(String message, Throwable cause) { super(message, cause); } }
101416_1
package hu.adsd.projects; import hu.adsd.ClimateApp; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ProductsConfigurationController implements Initializable { private ProductsConfiguration productsConfiguration; private int selectedConfiguration; @FXML private Label refEnergy; @FXML private Label totalEnergy; @FXML private Label differenceEnergy; @FXML private VBox buildingPartsBox; public ProductsConfigurationController( int selectedConfiguration ) { this.selectedConfiguration = selectedConfiguration; this.productsConfiguration = ClimateApp .getProject() .getConfigurations() .get( selectedConfiguration ); } @Override public void initialize( URL url, ResourceBundle resourceBundle ) { // Create BuildingParts with inner BuildingMaterials for ( BuildingPart buildingPart : productsConfiguration.getBuildingParts() ) { // Eerst nieuw vierkant maken // Create loader for loading productCardView VBOX FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "../../../projectBuildingPartView.fxml" ) ); // Use the ProductCardController Constructor with the current Product from the Loop fxmlLoader.setControllerFactory( controller -> new BuildingPartController( buildingPart ) ); // Load the VBox into the productsBox try { buildingPartsBox.getChildren().add( fxmlLoader.load() ); } catch ( IOException e ) { e.printStackTrace(); } } refEnergy.setText( "Lineair: " + productsConfiguration.getEmbodiedEnergy() ); totalEnergy.setText( "Huidig: " + productsConfiguration.getEmbodiedEnergy() ); differenceEnergy.setText( "Bespaard: " + productsConfiguration.getEmbodiedEnergy() ); } public void goToProject() throws IOException { ClimateApp.goToScreen( "projectView" ); } public void addProduct() throws IOException { ClimateApp.goToProductsScreen( selectedConfiguration ); } }
schonewillerf/ClimateApp
src/main/java/hu/adsd/projects/ProductsConfigurationController.java
624
// Eerst nieuw vierkant maken
line_comment
nl
package hu.adsd.projects; import hu.adsd.ClimateApp; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ProductsConfigurationController implements Initializable { private ProductsConfiguration productsConfiguration; private int selectedConfiguration; @FXML private Label refEnergy; @FXML private Label totalEnergy; @FXML private Label differenceEnergy; @FXML private VBox buildingPartsBox; public ProductsConfigurationController( int selectedConfiguration ) { this.selectedConfiguration = selectedConfiguration; this.productsConfiguration = ClimateApp .getProject() .getConfigurations() .get( selectedConfiguration ); } @Override public void initialize( URL url, ResourceBundle resourceBundle ) { // Create BuildingParts with inner BuildingMaterials for ( BuildingPart buildingPart : productsConfiguration.getBuildingParts() ) { // Eerst nieuw<SUF> // Create loader for loading productCardView VBOX FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "../../../projectBuildingPartView.fxml" ) ); // Use the ProductCardController Constructor with the current Product from the Loop fxmlLoader.setControllerFactory( controller -> new BuildingPartController( buildingPart ) ); // Load the VBox into the productsBox try { buildingPartsBox.getChildren().add( fxmlLoader.load() ); } catch ( IOException e ) { e.printStackTrace(); } } refEnergy.setText( "Lineair: " + productsConfiguration.getEmbodiedEnergy() ); totalEnergy.setText( "Huidig: " + productsConfiguration.getEmbodiedEnergy() ); differenceEnergy.setText( "Bespaard: " + productsConfiguration.getEmbodiedEnergy() ); } public void goToProject() throws IOException { ClimateApp.goToScreen( "projectView" ); } public void addProduct() throws IOException { ClimateApp.goToProductsScreen( selectedConfiguration ); } }
116208_55
package edu.southwestern.tasks.mario.level; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonStreamParser; import ch.idsia.ai.agents.Agent; import ch.idsia.ai.tasks.ProgressTask; import ch.idsia.mario.engine.LevelRenderer; import ch.idsia.mario.engine.level.Level; import ch.idsia.tools.CmdLineOptions; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.EvaluationOptions; import ch.idsia.tools.Evaluator; import ch.idsia.tools.ToolsConfigurator; import edu.southwestern.networks.Network; import edu.southwestern.parameters.Parameters; import edu.southwestern.util.datastructures.ArrayUtil; import edu.southwestern.util.stats.StatisticsUtilities; public class MarioLevelUtil { public static final int BLOCK_SIZE = 16; public static final int LEVEL_HEIGHT = 12; public static final double MAX_HEIGHT_INDEX = LEVEL_HEIGHT - 1; public static final int PRESENT_INDEX = 0; public static final double PRESENT_THRESHOLD = 0.0; public static final int SOLID_INDEX = 1; public static final char SOLID_CHAR = 'X'; public static final int BLOCK_INDEX = 2; public static final char BLOCK_CHAR = 'S'; public static final int QUESTION_INDEX = 3; public static final char QUESTION_CHAR = '?'; public static final int COIN_INDEX = 4; public static final char COIN_CHAR = 'o'; public static final int PIPE_INDEX = 5; public static final int CANNON_INDEX = 6; public static final int GOOMBA_INDEX = 7; public static final char GOOMBA_CHAR = 'E'; public static final char WINGED_GOOMBA_CHAR = 'W'; public static final int GREEN_KOOPA_INDEX = 8; public static final char GREEN_KOOPA_CHAR = 'g'; public static final char WINGED_GREEN_KOOPA_CHAR = 'G'; public static final int RED_KOOPA_INDEX = 9; public static final char RED_KOOPA_CHAR = 'r'; public static final char WINGED_RED_KOOPA_CHAR = 'R'; public static final int SPIKY_INDEX = 10; public static final char SPIKY_CHAR = '^'; public static final char WINGED_SPIKY_CHAR = '&'; public static final int WINGED_INDEX = 11; // If enemy, is it winged? public static final double WINGED_THRESHOLD = 0.75; public static final char EMPTY_CHAR = '-'; /** * Whether the character is any of the pipe characters * @param p A character * @return Whether it represents part of a pipe */ public static boolean isPipe(char p) { return p == '<' || p == '>' || p == '[' || p == ']'; } /** * Whether the character is part of a Bullet Bill cannon * @param c * @return */ public static boolean isCannon(char c) { return c == 'B' || c == 'b'; } /** * Whether the char is any of the koopas. Significant, since they take up two block cells * in height. * @param c * @return */ public static boolean isKoopa(char c) { return c == GREEN_KOOPA_CHAR || c == RED_KOOPA_CHAR || c == WINGED_GREEN_KOOPA_CHAR || c == WINGED_RED_KOOPA_CHAR; } /** * Generate Mario level layout in form of String array using CPPN. * @param net CPPN * @param width Width in Mario blocks * @return String array where each String is a row of the level */ public static String[] generateLevelLayoutFromCPPN(Network net, double[] inputMultiples, int width) { String[] level = new String[LEVEL_HEIGHT]; // Initially there are no enemies. Only allow one per column boolean[] enemyInColumn = new boolean[width]; double halfWidth = width/2.0; // Top row has problems if it contains objects char[] top = new char[width]; Arrays.fill(top, EMPTY_CHAR); level[0] = new String(top); for(int i = LEVEL_HEIGHT - 1; i > 0; i--) { // From bottom up: for enemy ground check level[i] = ""; for(int j = 0; j < width; j++) { double x = (j - halfWidth) / halfWidth; // Horizontal symmetry double y = (MAX_HEIGHT_INDEX - i) / MAX_HEIGHT_INDEX; // Increasing from ground up double[] inputs = new double[] {x,y,1.0}; // Turn certain inputs off for(int k = 0; k < inputMultiples.length; k++) { inputs[k] = inputs[k] * inputMultiples[k]; } double[] outputs = net.process(inputs); // for(int k = 0; k < level.length; k++) { // System.out.println(level[k]); // } //System.out.println("["+i+"]["+j+"]"+Arrays.toString(inputs)+Arrays.toString(outputs)); if(outputs[PRESENT_INDEX] > PRESENT_THRESHOLD) { outputs[PRESENT_INDEX] = Double.NEGATIVE_INFINITY; // Assure this index is not the biggest double wingedValue = outputs[WINGED_INDEX]; // Save winged value before making it negative infinity outputs[WINGED_INDEX] = Double.NEGATIVE_INFINITY; // Assure this index is not the biggest int highest = StatisticsUtilities.argmax(outputs); if(highest == SOLID_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : SOLID_CHAR; } else if(highest == BLOCK_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : BLOCK_CHAR; } else if(highest == QUESTION_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : QUESTION_CHAR; } else if(highest == COIN_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : COIN_CHAR; } else if (highest == PIPE_INDEX) { int leftEdge = level[i].length() - 1; if(level[i].length() % 2 == 1 && // Only every other spot can have pipes !isPipe(level[i].charAt(leftEdge))) { // Have to construct the pipe all the way down level[i] = level[i].substring(0, leftEdge) + "<>"; // Top int current = i+1; //System.out.println("before " + current + " leftEdge " + leftEdge); // Replace empty spaces with pipes while(current < LEVEL_HEIGHT && (isPipe(level[current].charAt(leftEdge)) || isPipe(level[current].charAt(leftEdge+1)) || isCannon(level[current].charAt(leftEdge)) || isCannon(level[current].charAt(leftEdge+1)) || level[current].charAt(leftEdge) == EMPTY_CHAR || level[current].charAt(leftEdge+1) == EMPTY_CHAR || level[current].charAt(leftEdge) == COIN_CHAR || level[current].charAt(leftEdge+1) == COIN_CHAR || OldLevelParser.isEnemy(level[current].charAt(leftEdge)) || OldLevelParser.isEnemy(level[current].charAt(leftEdge+1)))) { level[current] = level[current].substring(0, leftEdge) + "[]" + level[current].substring(leftEdge+2); // body //System.out.println(level[current]); current++; //System.out.println("loop " + current + " leftEdge " + leftEdge); } } else { // No room for pipe level[i] += EMPTY_CHAR; } } else if (highest == CANNON_INDEX) { int edge = level[i].length(); // Have to construct the cannon all the way down level[i] += "B"; // Top int current = i+1; // Replace empty spaces with cannon support while(current < LEVEL_HEIGHT && (isCannon(level[current].charAt(edge)) || level[current].charAt(edge) == EMPTY_CHAR || level[current].charAt(edge) == COIN_CHAR || OldLevelParser.isEnemy(level[current].charAt(edge)))) { level[current] = level[current].substring(0, edge) + "b" + level[current].substring(edge+1); // support current++; } } else { // Must be an enemy if(enemyInColumn[j]) { // Only allow one enemy per column: Too restrictive? level[i] += EMPTY_CHAR; } else { if(highest == GOOMBA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_GOOMBA_CHAR : GOOMBA_CHAR; } else if(highest == GREEN_KOOPA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_GREEN_KOOPA_CHAR : GREEN_KOOPA_CHAR; } else if(highest == RED_KOOPA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_RED_KOOPA_CHAR : RED_KOOPA_CHAR; } else { assert highest == SPIKY_INDEX : "Only option left is spiky: " + highest; level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_SPIKY_CHAR : SPIKY_CHAR; } // Indicate that there is now an enemy in the column enemyInColumn[j] = true; } } } else { level[i] += EMPTY_CHAR; } } } return level; } /** * Generates a level assuming all CPPN inputs are turned on. * Default behavior. * @param net CPPN that generates level * @param width Width of level in tiles * @return A Mario level */ public static Level generateLevelFromCPPN(Network net, int width) { return generateLevelFromCPPN(net, ArrayUtil.doubleOnes(net.numInputs()), width); } /** * Take a cppn and a width and completely generate the level * @param net CPPN * @param width In Mario blocks * @return Level instance */ public static Level generateLevelFromCPPN(Network net, double[] inputMultiples, int width) { String[] stringBlock = generateLevelLayoutFromCPPN(net, inputMultiples, width); ArrayList<String> lines = new ArrayList<String>(); for(int i = 0; i < stringBlock.length; i++) { //System.out.println(stringBlock[i]); lines.add(stringBlock[i]); } OldLevelParser parse = new OldLevelParser(); Level level = parse.createLevelASCII(lines); return level; } /** * Convert a VGLC Mario level to list of lists of numbers representing the GAN encoding. * @param filename Mario level file * @return List of lists */ public static ArrayList<List<Integer>> listLevelFromVGLCFile(String filename) { try { Scanner file = new Scanner(new File(filename)); ArrayList<String> lines = new ArrayList<>(); // Read all lines from file while(file.hasNextLine()) { lines.add(file.nextLine()); } file.close(); // Convert to array String[] lineArray = lines.toArray(new String[lines.size()]); // Convert to list ArrayList<List<Integer>> list = listLevelFromStringLevel(lineArray); return list; } catch (FileNotFoundException e) { e.printStackTrace(); } throw new IllegalStateException("Problem reading Mario level file: "+filename); } /** * takes in a level and separates it into its smaller subsections allowing * for comparison of chunks * @param oneLevel the level * @param segmentWidth the width of the segments/chunk * @return levelWithParsedSegments the level containing every segment */ public static List<List<List<Integer>>> getSegmentsFromLevel(List<List<Integer>> oneLevel, int segmentWidth){ if (oneLevel.get(0).size()%segmentWidth!=0){ System.out.println("getLevelStats: Level not multiple of segment width!"); return null; } int height = oneLevel.size(); List<List<List<Integer>>> levelWithParsedSegments = new ArrayList<List<List<Integer>>>(); // Loop through each segment int numSegments = oneLevel.get(0).size()/segmentWidth; for(int l=0; l<numSegments; l++){ ArrayList<List<Integer>> compareSegments = new ArrayList<List<Integer>>(); for(int i=0; i<height-1;i++){ // Loop from top to bottom ArrayList<Integer> a = new ArrayList<Integer>(); // Loop from left to right through the tiles in this particular segment for(int j=l*segmentWidth;j<(l+1)*segmentWidth;j++){ Integer tile = oneLevel.get(i).get(j); if(tile == MarioLevelUtil.SPIKY_INDEX|| tile == MarioLevelUtil.GOOMBA_INDEX|| tile==MarioLevelUtil.GREEN_KOOPA_INDEX|| tile==MarioLevelUtil.RED_KOOPA_INDEX|| tile==MarioLevelUtil.WINGED_INDEX) { a.add(MarioLevelUtil.PRESENT_INDEX); }else { a.add(tile); } } compareSegments.add(a); } levelWithParsedSegments.add(compareSegments); } return levelWithParsedSegments; } public static List<List<List<Integer>>> getSegmentsFromLevel(List<List<Integer>> oneLevel){ return getSegmentsFromLevel(oneLevel, 28); } /** * Convert from String representation to list of lists * @param stringLevel * @return */ public static ArrayList<List<Integer>> listLevelFromStringLevel(String[] stringLevel) { ArrayList<List<Integer>> result = new ArrayList<List<Integer>>(); for(String row : stringLevel) { List<Integer> listRow = new ArrayList<Integer>(row.length()); for(int i = 0; i < row.length(); i++) { //System.out.println(i + ":" + row.charAt(i)); Integer tile = Parameters.parameters.booleanParameter("marioGANUsesOriginalEncoding") ? OldLevelParser.indexOfBlock(row.charAt(i)) : LevelParser.tiles.get(row.charAt(i)); listRow.add(tile); } result.add(listRow); } return result; } // Evaluated levels have buffers added to the start and end that later need to be removed public static boolean removeMarioLevelBuffer = true; /** * Return an image of the level, excluding the buffer zones at the * beginning and end of every CPPN generated level. Also excludes * the background, Mario, and enemy sprites. * @param level A Mario Level * @return Image of Mario level */ public static BufferedImage getLevelImage(Level level) { EvaluationOptions options = new CmdLineOptions(new String[0]); ProgressTask task = new ProgressTask(options); // Added to change level options.setLevel(level); task.setOptions(options); int relevantWidth = (level.width - (removeMarioLevelBuffer ? (2*OldLevelParser.BUFFER_WIDTH) : 0)) * MarioLevelUtil.BLOCK_SIZE; BufferedImage image = new BufferedImage(relevantWidth, (1+level.height)*MarioLevelUtil.BLOCK_SIZE, BufferedImage.TYPE_INT_ARGB); // Skips buffer zones at start and end of level LevelRenderer.renderArea((Graphics2D) image.getGraphics(), level, 0, 0, OldLevelParser.BUFFER_WIDTH*BLOCK_SIZE, 0, relevantWidth, (1+level.height)*BLOCK_SIZE); return image; } /** * Specified agent plays the specified level with visual display * @param level * @param agent * @return */ public static List<EvaluationInfo> agentPlaysLevel(Level level, Agent agent) { EvaluationOptions options = new CmdLineOptions(new String[]{}); return agentPlaysLevel(level, agent, options); } /** * Same as above, but allows custom eval options that change many settings. * @param level Level to evaluate in * @param agent Agent to evaluate * @param options Mario configuration options (but not the level or agent) * @return list of information about the evaluations */ public static List<EvaluationInfo> agentPlaysLevel(Level level, Agent agent, EvaluationOptions options) { options.setAgent(agent); options.setLevel(level); return agentPlaysLevel(options); } /** * Now, the evaluation options must also specify the level and the agent. * @param options Mario options, including level and agent * @return evaluation results */ public static List<EvaluationInfo> agentPlaysLevel(EvaluationOptions options) { Evaluator evaluator = new Evaluator(options); List<EvaluationInfo> results = evaluator.evaluate(); ToolsConfigurator.DestroyMarioComponentFrame(); return results; } // /** // * For testing and debugging // * @param args // */ // public static void main(String[] args) { // Parameters.initializeParameterCollections(new String[] // {"runNumber:0","randomSeed:"+((int)(Math.random()*100)),"trials:1","mu:16","maxGens:500","io:false","netio:false","mating:true","allowMultipleFunctions:true","ftype:0","netChangeActivationRate:0.3","includeFullSigmoidFunction:true","includeFullGaussFunction:true","includeCosineFunction:true","includeGaussFunction:false","includeIdFunction:true","includeTriangleWaveFunction:true","includeSquareWaveFunction:true","includeFullSawtoothFunction:true","includeSigmoidFunction:false","includeAbsValFunction:true","includeSawtoothFunction:true"}); // MMNEAT.loadClasses(); // // //////////////////////////////////////////////////////// //// String[] stringBlock = new String[] { //// "--------------------------------------------------------", //// "--------------------------------------------------------", //// "--------------------------------------------------------", //// "---------ooooo------------------------------------------", //// "--------------------------------------------------------", //// "----?---S?S---------------------------------------------", //// "------------------X-------------------------------------", //// "-----------------XX---------------------E-----<>--------", //// "---SSSS--<>-----XXX---------------------X-----[]--------", //// "---------[]---XXXXX-------------------XXXXX---[]--------", //// "---------[]-XXXXXXX----------EE-----XXXXXXXXXX[]--------", //// "XXXXXXXXXXXXXXXXXXX-----XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", //// }; // // // Instead of specifying the level, create it with a TWEANN // TWEANNGenotype cppn = new TWEANNGenotype(3, 12, 0); // Archetype // // Randomize activation functions // new ActivationFunctionRandomReplacement().mutate(cppn); // // // Random mutations //// for(int i = 0; i < 50; i++) { //// cppn.mutate(); //// } // // TWEANN net = cppn.getPhenotype(); // DrawingPanel panel = new DrawingPanel(200,200, "Network"); // net.draw(panel, true, false); // // Level level = generateLevelFromCPPN(net, new double[] {1,1,1}, 60); // // Agent controller = new HumanKeyboardAgent(); //new SergeyKarakovskiy_JumpingAgent(); // EvaluationOptions options = new CmdLineOptions(new String[]{}); // options.setAgent(controller); // ProgressTask task = new ProgressTask(options); // // // Added to change level // options.setLevel(level); // // task.setOptions(options); // // int relevantWidth = (level.width - (2*OldLevelParser.BUFFER_WIDTH)) * BLOCK_SIZE; // //System.out.println("level.width:"+level.width); // //System.out.println("relevantWidth:"+relevantWidth); // DrawingPanel levelPanel = new DrawingPanel(relevantWidth,LEVEL_HEIGHT*BLOCK_SIZE, "Level"); // LevelRenderer.renderArea(levelPanel.getGraphics(), level, 0, 0, OldLevelParser.BUFFER_WIDTH*BLOCK_SIZE, 0, relevantWidth, LEVEL_HEIGHT*BLOCK_SIZE); // // System.out.println ("Score: " + task.evaluate(options.getAgent())[0]); // // // } // public static void main(String[] args) throws FileNotFoundException, InterruptedException { // String inputFile1 = "src/main/python/GAN/Mario-all.json"; // String inputFile2 = "src/main/python/GAN/Mario-all.json"; // FileReader file1 = new FileReader(inputFile1); // FileReader file2 = new FileReader(inputFile2); // ArrayList<ArrayList<ArrayList<Integer>>> parsedFile1 = parseLevelJson(file1); // ArrayList<ArrayList<ArrayList<Integer>>> parsedFile2 = parseLevelJson(file2); // // for (int i = 0; i < parsedFile1.size(); i++) { // printLevelsSideBySide(parsedFile1.get(i), parsedFile2.get(i)); // Thread.sleep(50); // System.out.println("\n\n"); // } // //// System.out.println("Overall size:"+parsedFile1.size()+" | "+parsedFile2.size()+"\n"); //// for (int i = 0; i < parsedFile1.size(); i++) { //// System.out.println(parsedFile1.get(i).size()+" | "+parsedFile2.get(i).size()+"\n"); //// } //// System.out.println(parsedFile1.equals(parsedFile2)); // // } public static ArrayList<ArrayList<ArrayList<Integer>>> parseLevelJson(FileReader file) { ArrayList<ArrayList<ArrayList<Integer>>> parsedFile = new ArrayList<ArrayList<ArrayList<Integer>>>(); JsonStreamParser jsonParser = new JsonStreamParser(file); JsonArray parsed = (JsonArray) jsonParser.next(); for (JsonElement element : parsed) { ArrayList<ArrayList<Integer>> inner1 = new ArrayList<ArrayList<Integer>>(); for (JsonElement element2 : (JsonArray) element) { ArrayList<Integer> inner2 = new ArrayList<Integer>(); for (JsonElement element3 : (JsonArray) element2) { inner2.add(element3.getAsBigInteger().intValue()); } inner1.add(inner2); } parsedFile.add(inner1); } return parsedFile; } public static void printLevelsSideBySide(ArrayList<ArrayList<Integer>> level, ArrayList<ArrayList<Integer>> level2) { String visualLine; Set<Entry<Character, Integer>> tileset = LevelParser.tiles.entrySet(); for (int i = 0; i < level.size(); i++) { visualLine = ""; for (Integer integ : level.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } visualLine += " | "; for (Integer integ : level2.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } System.out.println(visualLine); } } public static void printSingleLevel(List<List<Integer>> level) { String visualLine; Set<Entry<Character, Integer>> tileset = LevelParser.tiles.entrySet(); for (int i = 0; i < level.size(); i++) { visualLine = ""; for (Integer integ : level.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } System.out.println(visualLine); } } }
schrum2/MM-NEAT
src/main/java/edu/southwestern/tasks/mario/level/MarioLevelUtil.java
7,336
// Level level = generateLevelFromCPPN(net, new double[] {1,1,1}, 60);
line_comment
nl
package edu.southwestern.tasks.mario.level; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonStreamParser; import ch.idsia.ai.agents.Agent; import ch.idsia.ai.tasks.ProgressTask; import ch.idsia.mario.engine.LevelRenderer; import ch.idsia.mario.engine.level.Level; import ch.idsia.tools.CmdLineOptions; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.EvaluationOptions; import ch.idsia.tools.Evaluator; import ch.idsia.tools.ToolsConfigurator; import edu.southwestern.networks.Network; import edu.southwestern.parameters.Parameters; import edu.southwestern.util.datastructures.ArrayUtil; import edu.southwestern.util.stats.StatisticsUtilities; public class MarioLevelUtil { public static final int BLOCK_SIZE = 16; public static final int LEVEL_HEIGHT = 12; public static final double MAX_HEIGHT_INDEX = LEVEL_HEIGHT - 1; public static final int PRESENT_INDEX = 0; public static final double PRESENT_THRESHOLD = 0.0; public static final int SOLID_INDEX = 1; public static final char SOLID_CHAR = 'X'; public static final int BLOCK_INDEX = 2; public static final char BLOCK_CHAR = 'S'; public static final int QUESTION_INDEX = 3; public static final char QUESTION_CHAR = '?'; public static final int COIN_INDEX = 4; public static final char COIN_CHAR = 'o'; public static final int PIPE_INDEX = 5; public static final int CANNON_INDEX = 6; public static final int GOOMBA_INDEX = 7; public static final char GOOMBA_CHAR = 'E'; public static final char WINGED_GOOMBA_CHAR = 'W'; public static final int GREEN_KOOPA_INDEX = 8; public static final char GREEN_KOOPA_CHAR = 'g'; public static final char WINGED_GREEN_KOOPA_CHAR = 'G'; public static final int RED_KOOPA_INDEX = 9; public static final char RED_KOOPA_CHAR = 'r'; public static final char WINGED_RED_KOOPA_CHAR = 'R'; public static final int SPIKY_INDEX = 10; public static final char SPIKY_CHAR = '^'; public static final char WINGED_SPIKY_CHAR = '&'; public static final int WINGED_INDEX = 11; // If enemy, is it winged? public static final double WINGED_THRESHOLD = 0.75; public static final char EMPTY_CHAR = '-'; /** * Whether the character is any of the pipe characters * @param p A character * @return Whether it represents part of a pipe */ public static boolean isPipe(char p) { return p == '<' || p == '>' || p == '[' || p == ']'; } /** * Whether the character is part of a Bullet Bill cannon * @param c * @return */ public static boolean isCannon(char c) { return c == 'B' || c == 'b'; } /** * Whether the char is any of the koopas. Significant, since they take up two block cells * in height. * @param c * @return */ public static boolean isKoopa(char c) { return c == GREEN_KOOPA_CHAR || c == RED_KOOPA_CHAR || c == WINGED_GREEN_KOOPA_CHAR || c == WINGED_RED_KOOPA_CHAR; } /** * Generate Mario level layout in form of String array using CPPN. * @param net CPPN * @param width Width in Mario blocks * @return String array where each String is a row of the level */ public static String[] generateLevelLayoutFromCPPN(Network net, double[] inputMultiples, int width) { String[] level = new String[LEVEL_HEIGHT]; // Initially there are no enemies. Only allow one per column boolean[] enemyInColumn = new boolean[width]; double halfWidth = width/2.0; // Top row has problems if it contains objects char[] top = new char[width]; Arrays.fill(top, EMPTY_CHAR); level[0] = new String(top); for(int i = LEVEL_HEIGHT - 1; i > 0; i--) { // From bottom up: for enemy ground check level[i] = ""; for(int j = 0; j < width; j++) { double x = (j - halfWidth) / halfWidth; // Horizontal symmetry double y = (MAX_HEIGHT_INDEX - i) / MAX_HEIGHT_INDEX; // Increasing from ground up double[] inputs = new double[] {x,y,1.0}; // Turn certain inputs off for(int k = 0; k < inputMultiples.length; k++) { inputs[k] = inputs[k] * inputMultiples[k]; } double[] outputs = net.process(inputs); // for(int k = 0; k < level.length; k++) { // System.out.println(level[k]); // } //System.out.println("["+i+"]["+j+"]"+Arrays.toString(inputs)+Arrays.toString(outputs)); if(outputs[PRESENT_INDEX] > PRESENT_THRESHOLD) { outputs[PRESENT_INDEX] = Double.NEGATIVE_INFINITY; // Assure this index is not the biggest double wingedValue = outputs[WINGED_INDEX]; // Save winged value before making it negative infinity outputs[WINGED_INDEX] = Double.NEGATIVE_INFINITY; // Assure this index is not the biggest int highest = StatisticsUtilities.argmax(outputs); if(highest == SOLID_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : SOLID_CHAR; } else if(highest == BLOCK_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : BLOCK_CHAR; } else if(highest == QUESTION_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : QUESTION_CHAR; } else if(highest == COIN_INDEX) { level[i] += i < LEVEL_HEIGHT - 1 && isKoopa(level[i+1].charAt(j)) ? EMPTY_CHAR : COIN_CHAR; } else if (highest == PIPE_INDEX) { int leftEdge = level[i].length() - 1; if(level[i].length() % 2 == 1 && // Only every other spot can have pipes !isPipe(level[i].charAt(leftEdge))) { // Have to construct the pipe all the way down level[i] = level[i].substring(0, leftEdge) + "<>"; // Top int current = i+1; //System.out.println("before " + current + " leftEdge " + leftEdge); // Replace empty spaces with pipes while(current < LEVEL_HEIGHT && (isPipe(level[current].charAt(leftEdge)) || isPipe(level[current].charAt(leftEdge+1)) || isCannon(level[current].charAt(leftEdge)) || isCannon(level[current].charAt(leftEdge+1)) || level[current].charAt(leftEdge) == EMPTY_CHAR || level[current].charAt(leftEdge+1) == EMPTY_CHAR || level[current].charAt(leftEdge) == COIN_CHAR || level[current].charAt(leftEdge+1) == COIN_CHAR || OldLevelParser.isEnemy(level[current].charAt(leftEdge)) || OldLevelParser.isEnemy(level[current].charAt(leftEdge+1)))) { level[current] = level[current].substring(0, leftEdge) + "[]" + level[current].substring(leftEdge+2); // body //System.out.println(level[current]); current++; //System.out.println("loop " + current + " leftEdge " + leftEdge); } } else { // No room for pipe level[i] += EMPTY_CHAR; } } else if (highest == CANNON_INDEX) { int edge = level[i].length(); // Have to construct the cannon all the way down level[i] += "B"; // Top int current = i+1; // Replace empty spaces with cannon support while(current < LEVEL_HEIGHT && (isCannon(level[current].charAt(edge)) || level[current].charAt(edge) == EMPTY_CHAR || level[current].charAt(edge) == COIN_CHAR || OldLevelParser.isEnemy(level[current].charAt(edge)))) { level[current] = level[current].substring(0, edge) + "b" + level[current].substring(edge+1); // support current++; } } else { // Must be an enemy if(enemyInColumn[j]) { // Only allow one enemy per column: Too restrictive? level[i] += EMPTY_CHAR; } else { if(highest == GOOMBA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_GOOMBA_CHAR : GOOMBA_CHAR; } else if(highest == GREEN_KOOPA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_GREEN_KOOPA_CHAR : GREEN_KOOPA_CHAR; } else if(highest == RED_KOOPA_INDEX) { level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_RED_KOOPA_CHAR : RED_KOOPA_CHAR; } else { assert highest == SPIKY_INDEX : "Only option left is spiky: " + highest; level[i] += wingedValue > WINGED_THRESHOLD ? WINGED_SPIKY_CHAR : SPIKY_CHAR; } // Indicate that there is now an enemy in the column enemyInColumn[j] = true; } } } else { level[i] += EMPTY_CHAR; } } } return level; } /** * Generates a level assuming all CPPN inputs are turned on. * Default behavior. * @param net CPPN that generates level * @param width Width of level in tiles * @return A Mario level */ public static Level generateLevelFromCPPN(Network net, int width) { return generateLevelFromCPPN(net, ArrayUtil.doubleOnes(net.numInputs()), width); } /** * Take a cppn and a width and completely generate the level * @param net CPPN * @param width In Mario blocks * @return Level instance */ public static Level generateLevelFromCPPN(Network net, double[] inputMultiples, int width) { String[] stringBlock = generateLevelLayoutFromCPPN(net, inputMultiples, width); ArrayList<String> lines = new ArrayList<String>(); for(int i = 0; i < stringBlock.length; i++) { //System.out.println(stringBlock[i]); lines.add(stringBlock[i]); } OldLevelParser parse = new OldLevelParser(); Level level = parse.createLevelASCII(lines); return level; } /** * Convert a VGLC Mario level to list of lists of numbers representing the GAN encoding. * @param filename Mario level file * @return List of lists */ public static ArrayList<List<Integer>> listLevelFromVGLCFile(String filename) { try { Scanner file = new Scanner(new File(filename)); ArrayList<String> lines = new ArrayList<>(); // Read all lines from file while(file.hasNextLine()) { lines.add(file.nextLine()); } file.close(); // Convert to array String[] lineArray = lines.toArray(new String[lines.size()]); // Convert to list ArrayList<List<Integer>> list = listLevelFromStringLevel(lineArray); return list; } catch (FileNotFoundException e) { e.printStackTrace(); } throw new IllegalStateException("Problem reading Mario level file: "+filename); } /** * takes in a level and separates it into its smaller subsections allowing * for comparison of chunks * @param oneLevel the level * @param segmentWidth the width of the segments/chunk * @return levelWithParsedSegments the level containing every segment */ public static List<List<List<Integer>>> getSegmentsFromLevel(List<List<Integer>> oneLevel, int segmentWidth){ if (oneLevel.get(0).size()%segmentWidth!=0){ System.out.println("getLevelStats: Level not multiple of segment width!"); return null; } int height = oneLevel.size(); List<List<List<Integer>>> levelWithParsedSegments = new ArrayList<List<List<Integer>>>(); // Loop through each segment int numSegments = oneLevel.get(0).size()/segmentWidth; for(int l=0; l<numSegments; l++){ ArrayList<List<Integer>> compareSegments = new ArrayList<List<Integer>>(); for(int i=0; i<height-1;i++){ // Loop from top to bottom ArrayList<Integer> a = new ArrayList<Integer>(); // Loop from left to right through the tiles in this particular segment for(int j=l*segmentWidth;j<(l+1)*segmentWidth;j++){ Integer tile = oneLevel.get(i).get(j); if(tile == MarioLevelUtil.SPIKY_INDEX|| tile == MarioLevelUtil.GOOMBA_INDEX|| tile==MarioLevelUtil.GREEN_KOOPA_INDEX|| tile==MarioLevelUtil.RED_KOOPA_INDEX|| tile==MarioLevelUtil.WINGED_INDEX) { a.add(MarioLevelUtil.PRESENT_INDEX); }else { a.add(tile); } } compareSegments.add(a); } levelWithParsedSegments.add(compareSegments); } return levelWithParsedSegments; } public static List<List<List<Integer>>> getSegmentsFromLevel(List<List<Integer>> oneLevel){ return getSegmentsFromLevel(oneLevel, 28); } /** * Convert from String representation to list of lists * @param stringLevel * @return */ public static ArrayList<List<Integer>> listLevelFromStringLevel(String[] stringLevel) { ArrayList<List<Integer>> result = new ArrayList<List<Integer>>(); for(String row : stringLevel) { List<Integer> listRow = new ArrayList<Integer>(row.length()); for(int i = 0; i < row.length(); i++) { //System.out.println(i + ":" + row.charAt(i)); Integer tile = Parameters.parameters.booleanParameter("marioGANUsesOriginalEncoding") ? OldLevelParser.indexOfBlock(row.charAt(i)) : LevelParser.tiles.get(row.charAt(i)); listRow.add(tile); } result.add(listRow); } return result; } // Evaluated levels have buffers added to the start and end that later need to be removed public static boolean removeMarioLevelBuffer = true; /** * Return an image of the level, excluding the buffer zones at the * beginning and end of every CPPN generated level. Also excludes * the background, Mario, and enemy sprites. * @param level A Mario Level * @return Image of Mario level */ public static BufferedImage getLevelImage(Level level) { EvaluationOptions options = new CmdLineOptions(new String[0]); ProgressTask task = new ProgressTask(options); // Added to change level options.setLevel(level); task.setOptions(options); int relevantWidth = (level.width - (removeMarioLevelBuffer ? (2*OldLevelParser.BUFFER_WIDTH) : 0)) * MarioLevelUtil.BLOCK_SIZE; BufferedImage image = new BufferedImage(relevantWidth, (1+level.height)*MarioLevelUtil.BLOCK_SIZE, BufferedImage.TYPE_INT_ARGB); // Skips buffer zones at start and end of level LevelRenderer.renderArea((Graphics2D) image.getGraphics(), level, 0, 0, OldLevelParser.BUFFER_WIDTH*BLOCK_SIZE, 0, relevantWidth, (1+level.height)*BLOCK_SIZE); return image; } /** * Specified agent plays the specified level with visual display * @param level * @param agent * @return */ public static List<EvaluationInfo> agentPlaysLevel(Level level, Agent agent) { EvaluationOptions options = new CmdLineOptions(new String[]{}); return agentPlaysLevel(level, agent, options); } /** * Same as above, but allows custom eval options that change many settings. * @param level Level to evaluate in * @param agent Agent to evaluate * @param options Mario configuration options (but not the level or agent) * @return list of information about the evaluations */ public static List<EvaluationInfo> agentPlaysLevel(Level level, Agent agent, EvaluationOptions options) { options.setAgent(agent); options.setLevel(level); return agentPlaysLevel(options); } /** * Now, the evaluation options must also specify the level and the agent. * @param options Mario options, including level and agent * @return evaluation results */ public static List<EvaluationInfo> agentPlaysLevel(EvaluationOptions options) { Evaluator evaluator = new Evaluator(options); List<EvaluationInfo> results = evaluator.evaluate(); ToolsConfigurator.DestroyMarioComponentFrame(); return results; } // /** // * For testing and debugging // * @param args // */ // public static void main(String[] args) { // Parameters.initializeParameterCollections(new String[] // {"runNumber:0","randomSeed:"+((int)(Math.random()*100)),"trials:1","mu:16","maxGens:500","io:false","netio:false","mating:true","allowMultipleFunctions:true","ftype:0","netChangeActivationRate:0.3","includeFullSigmoidFunction:true","includeFullGaussFunction:true","includeCosineFunction:true","includeGaussFunction:false","includeIdFunction:true","includeTriangleWaveFunction:true","includeSquareWaveFunction:true","includeFullSawtoothFunction:true","includeSigmoidFunction:false","includeAbsValFunction:true","includeSawtoothFunction:true"}); // MMNEAT.loadClasses(); // // //////////////////////////////////////////////////////// //// String[] stringBlock = new String[] { //// "--------------------------------------------------------", //// "--------------------------------------------------------", //// "--------------------------------------------------------", //// "---------ooooo------------------------------------------", //// "--------------------------------------------------------", //// "----?---S?S---------------------------------------------", //// "------------------X-------------------------------------", //// "-----------------XX---------------------E-----<>--------", //// "---SSSS--<>-----XXX---------------------X-----[]--------", //// "---------[]---XXXXX-------------------XXXXX---[]--------", //// "---------[]-XXXXXXX----------EE-----XXXXXXXXXX[]--------", //// "XXXXXXXXXXXXXXXXXXX-----XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", //// }; // // // Instead of specifying the level, create it with a TWEANN // TWEANNGenotype cppn = new TWEANNGenotype(3, 12, 0); // Archetype // // Randomize activation functions // new ActivationFunctionRandomReplacement().mutate(cppn); // // // Random mutations //// for(int i = 0; i < 50; i++) { //// cppn.mutate(); //// } // // TWEANN net = cppn.getPhenotype(); // DrawingPanel panel = new DrawingPanel(200,200, "Network"); // net.draw(panel, true, false); // // Level level<SUF> // // Agent controller = new HumanKeyboardAgent(); //new SergeyKarakovskiy_JumpingAgent(); // EvaluationOptions options = new CmdLineOptions(new String[]{}); // options.setAgent(controller); // ProgressTask task = new ProgressTask(options); // // // Added to change level // options.setLevel(level); // // task.setOptions(options); // // int relevantWidth = (level.width - (2*OldLevelParser.BUFFER_WIDTH)) * BLOCK_SIZE; // //System.out.println("level.width:"+level.width); // //System.out.println("relevantWidth:"+relevantWidth); // DrawingPanel levelPanel = new DrawingPanel(relevantWidth,LEVEL_HEIGHT*BLOCK_SIZE, "Level"); // LevelRenderer.renderArea(levelPanel.getGraphics(), level, 0, 0, OldLevelParser.BUFFER_WIDTH*BLOCK_SIZE, 0, relevantWidth, LEVEL_HEIGHT*BLOCK_SIZE); // // System.out.println ("Score: " + task.evaluate(options.getAgent())[0]); // // // } // public static void main(String[] args) throws FileNotFoundException, InterruptedException { // String inputFile1 = "src/main/python/GAN/Mario-all.json"; // String inputFile2 = "src/main/python/GAN/Mario-all.json"; // FileReader file1 = new FileReader(inputFile1); // FileReader file2 = new FileReader(inputFile2); // ArrayList<ArrayList<ArrayList<Integer>>> parsedFile1 = parseLevelJson(file1); // ArrayList<ArrayList<ArrayList<Integer>>> parsedFile2 = parseLevelJson(file2); // // for (int i = 0; i < parsedFile1.size(); i++) { // printLevelsSideBySide(parsedFile1.get(i), parsedFile2.get(i)); // Thread.sleep(50); // System.out.println("\n\n"); // } // //// System.out.println("Overall size:"+parsedFile1.size()+" | "+parsedFile2.size()+"\n"); //// for (int i = 0; i < parsedFile1.size(); i++) { //// System.out.println(parsedFile1.get(i).size()+" | "+parsedFile2.get(i).size()+"\n"); //// } //// System.out.println(parsedFile1.equals(parsedFile2)); // // } public static ArrayList<ArrayList<ArrayList<Integer>>> parseLevelJson(FileReader file) { ArrayList<ArrayList<ArrayList<Integer>>> parsedFile = new ArrayList<ArrayList<ArrayList<Integer>>>(); JsonStreamParser jsonParser = new JsonStreamParser(file); JsonArray parsed = (JsonArray) jsonParser.next(); for (JsonElement element : parsed) { ArrayList<ArrayList<Integer>> inner1 = new ArrayList<ArrayList<Integer>>(); for (JsonElement element2 : (JsonArray) element) { ArrayList<Integer> inner2 = new ArrayList<Integer>(); for (JsonElement element3 : (JsonArray) element2) { inner2.add(element3.getAsBigInteger().intValue()); } inner1.add(inner2); } parsedFile.add(inner1); } return parsedFile; } public static void printLevelsSideBySide(ArrayList<ArrayList<Integer>> level, ArrayList<ArrayList<Integer>> level2) { String visualLine; Set<Entry<Character, Integer>> tileset = LevelParser.tiles.entrySet(); for (int i = 0; i < level.size(); i++) { visualLine = ""; for (Integer integ : level.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } visualLine += " | "; for (Integer integ : level2.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } System.out.println(visualLine); } } public static void printSingleLevel(List<List<Integer>> level) { String visualLine; Set<Entry<Character, Integer>> tileset = LevelParser.tiles.entrySet(); for (int i = 0; i < level.size(); i++) { visualLine = ""; for (Integer integ : level.get(i)) { for (Entry<Character, Integer> e : tileset) { if (e.getValue() == integ) { visualLine += e.getKey(); } } } System.out.println(visualLine); } } }
40069_2
package cic.cs.unb.ca.jnetpcap; import org.jnetpcap.Pcap; import org.jnetpcap.PcapClosedException; import org.jnetpcap.PcapHeader; import org.jnetpcap.nio.JBuffer; import org.jnetpcap.nio.JMemory; import org.jnetpcap.packet.JHeader; import org.jnetpcap.packet.JHeaderPool; import org.jnetpcap.packet.PcapPacket; import org.jnetpcap.packet.JRegistry; import org.jnetpcap.protocol.lan.Ethernet; import org.jnetpcap.protocol.network.Ip4; import org.jnetpcap.protocol.network.Ip6; import org.jnetpcap.protocol.tcpip.Tcp; import org.jnetpcap.protocol.tcpip.Udp; import org.jnetpcap.protocol.vpn.L2TP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PacketReader { private static final Logger logger = LoggerFactory.getLogger(PacketReader.class); private IdGenerator generator = new IdGenerator(); private Pcap pcapReader; private long firstPacket; private long lastPacket; private Ethernet eth; private Tcp tcp; private Udp udp; private Ip4 ipv4; private Ip6 ipv6; private L2TP l2tp; private PcapHeader hdr; private JBuffer buf; private int scanID; private boolean readIP6; private boolean readIP4; private String file; public PacketReader(String filename) { super(); this.readIP4 = true; this.readIP6 = false; this.config(filename); } public PacketReader(String filename, boolean readip4, boolean readip6) { super(); this.readIP4 = true; this.readIP6 = false; this.config(filename); } private void config(String filename){ file = filename; StringBuilder errbuf = new StringBuilder(); // For any error msgs if(!Pcap.isPcap080Loaded()){ System.out.println("Warning Jnetpcap:Pcap080 is not loaded!"); } if(!Pcap.isPcap100Loaded()){ System.out.println("Warning Jnetpcap:Pcap100 is not loaded!"); } pcapReader = Pcap.openOffline(filename, errbuf); this.firstPacket = 0L; this.lastPacket = 0L; if (pcapReader == null) { logger.error("Error while opening file for capture: "+errbuf.toString()); System.exit(-1); }else{ this.hdr = new PcapHeader(JMemory.POINTER); this.buf = new JBuffer(JMemory.POINTER); this.eth = new Ethernet(); this.ipv4 = new Ip4(); this.ipv6 = new Ip6(); this.tcp = new Tcp(); this.udp = new Udp(); this.l2tp = new L2TP(); this.scanID = JRegistry.mapDLTToId(pcapReader.datalink()); if (this.scanID!=Ethernet.ID) System.out.println("Warning!?"); } } public BasicPacketInfo nextPacket(){ PcapPacket packet; BasicPacketInfo packetInfo = null; try{ if(pcapReader.nextEx(hdr,buf) == Pcap.NEXT_EX_OK){ packet = new PcapPacket(hdr, buf); packet.scan(this.scanID); if (packet.hasHeader(eth)) { if (this.readIP4) { packetInfo = getIpv4Info(packet); if (packetInfo == null && this.readIP6) { packetInfo = getIpv6Info(packet); } } else if (this.readIP6) { packetInfo = getIpv6Info(packet); if (packetInfo == null && this.readIP4) { packetInfo = getIpv4Info(packet); } } if (packetInfo == null) { packetInfo = getVPNInfo(packet); } } else{ System.out.println("without Eth : " + this.ipv4.type()); } }else{ throw new PcapClosedException(); } }catch(PcapClosedException e){ System.out.println("PcapClosedException:" + e); logger.debug("Read All packets on {}",file); throw e; }catch(Exception ex){ System.out.println("Exception:" + ex); logger.debug(ex.getMessage()); } return packetInfo; } private BasicPacketInfo getIpv4Info(PcapPacket packet){ BasicPacketInfo packetInfo = null; try { if (eth.getNextHeaderId()==this.ipv4.ID) { this.ipv4 = packet.getHeader(this.ipv4); //this.ipv4 = packet.getHeader(this.ipv4); packetInfo = new BasicPacketInfo(this.generator); packetInfo.setSrc(this.ipv4.source()); packetInfo.setDst(this.ipv4.destination()); //packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMicros()); if (this.firstPacket == 0L) this.firstPacket = packet.getCaptureHeader().timestampInMillis(); this.lastPacket = packet.getCaptureHeader().timestampInMillis(); if(this.ipv4.getNextHeaderId()==this.tcp.ID){ // deze klopt niet! this.tcp = packet.getHeader(this.tcp); packetInfo.setTCPWindow(tcp.window()); packetInfo.setSrcPort(tcp.source()); packetInfo.setDstPort(tcp.destination()); packetInfo.setProtocol(6); packetInfo.setFlagFIN(tcp.flags_FIN()); packetInfo.setFlagPSH(tcp.flags_PSH()); packetInfo.setFlagURG(tcp.flags_URG()); packetInfo.setFlagSYN(tcp.flags_SYN()); packetInfo.setFlagACK(tcp.flags_ACK()); packetInfo.setFlagECE(tcp.flags_ECE()); packetInfo.setFlagCWR(tcp.flags_CWR()); packetInfo.setFlagRST(tcp.flags_RST()); packetInfo.setPayloadBytes(tcp.getPayloadLength()); packetInfo.setPayloadData(tcp.getPayload()); packetInfo.setHeaderBytes(tcp.getHeaderLength()); }else if(this.ipv4.getNextHeaderId()==this.udp.ID){ this.udp = packet.getHeader(this.udp); packetInfo.setSrcPort(udp.source()); packetInfo.setDstPort(udp.destination()); packetInfo.setPayloadBytes(udp.getPayloadLength()); packetInfo.setPayloadData(udp.getPayload()); packetInfo.setHeaderBytes(udp.getHeaderLength()); packetInfo.setProtocol(17); }else { return null; //logger.debug("other packet Ethernet -> {}"+ packet.hasHeader(new Ethernet())); //logger.debug("other packet Html -> {}"+ packet.hasHeader(new Html())); //logger.debug("other packet Http -> {}"+ packet.hasHeader(new Http())); //logger.debug("other packet SLL -> {}"+ packet.hasHeader(new SLL())); //logger.debug("other packet L2TP -> {}"+ packet.hasHeader(new L2TP())); //logger.debug("other packet Sctp -> {}"+ packet.hasHeader(new Sctp())); //logger.debug("other packet PPP -> {}"+ packet.hasHeader(new PPP())); //int headerCount = packet.getHeaderCount(); //for(int i=0;i<headerCount;i++) { // JHeader header = JHeaderPool.getDefault().getHeader(i); // //JHeader hh = packet.getHeaderByIndex(i, header); // //logger.debug("getIpv4Info: {} --description: {} ",header.getName(),header.getDescription()); //} } } } catch (Exception e) { e.printStackTrace(); packet.scan(ipv4.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip4())+"\n"; errormsg+="ip4********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } private BasicPacketInfo getIpv6Info(PcapPacket packet){ BasicPacketInfo packetInfo = null; try{ if(packet.hasHeader(ipv6)){ packet.scan(this.ipv6.ID); packetInfo = new BasicPacketInfo(this.generator); packetInfo.setSrc(this.ipv6.source()); packetInfo.setDst(this.ipv6.destination()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); if(packet.hasHeader(this.tcp)){ System.out.println("Warning recept for failure? packet.hasHeader(this.tcp)"); packetInfo.setSrcPort(tcp.source()); packetInfo.setDstPort(tcp.destination()); packetInfo.setPayloadBytes(tcp.getPayloadLength()); packetInfo.setPayloadData(tcp.getPayload()); packetInfo.setHeaderBytes(tcp.getHeaderLength()); packetInfo.setProtocol(6); }else if(packet.hasHeader(this.udp)){ System.out.println("Warning recept for failure? packet.hasHeader(this.udp)"); packetInfo.setSrcPort(udp.source()); packetInfo.setDstPort(udp.destination()); packetInfo.setPayloadBytes(udp.getPayloadLength()); packetInfo.setPayloadData(udp.getPayload()); packetInfo.setHeaderBytes(udp.getHeaderLength()); packetInfo.setProtocol(17); } } }catch(Exception e){ logger.debug(e.getMessage()); packet.scan(ipv6.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip6())+"\n"; errormsg+="ipv6********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; //System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } private BasicPacketInfo getVPNInfo(PcapPacket packet){ BasicPacketInfo packetInfo = null; try { if (packet.hasHeader(l2tp)){ if(this.readIP4){ packet.scan(ipv4.getId()); packetInfo = getIpv4Info(packet); if (packetInfo == null && this.readIP6){ packet.scan(ipv6.getId()); packetInfo = getIpv6Info(packet); } }else if(this.readIP6){ packet.scan(ipv6.getId()); packetInfo = getIpv6Info(packet); if (packetInfo == null && this.readIP4){ packet.scan(ipv4.getId()); packetInfo = getIpv4Info(packet); } } } } catch (Exception e) { logger.debug(e.getMessage()); packet.scan(l2tp.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new L2TP())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; //System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } public long getFirstPacket() { return firstPacket; } public void setFirstPacket(long firstPacket) { this.firstPacket = firstPacket; } public long getLastPacket() { return lastPacket; } public void setLastPacket(long lastPacket) { this.lastPacket = lastPacket; } /* * So far,The value of the field BasicPacketInfo.id is not used * It doesn't matter just using a static IdGenerator for realtime PcapPacket reading */ private static IdGenerator idGen = new IdGenerator(); public static BasicPacketInfo getBasicPacketInfo(PcapPacket packet,boolean readIP4, boolean readIP6) { BasicPacketInfo packetInfo = null; Protocol protocol = new Protocol(); if(readIP4){ packetInfo = getIpv4Info(packet,protocol); if (packetInfo == null && readIP6){ packetInfo = getIpv6Info(packet,protocol); } }else if(readIP6){ packetInfo = getIpv6Info(packet,protocol); if (packetInfo == null && readIP4){ packetInfo = getIpv4Info(packet,protocol); } } if (packetInfo == null){ packetInfo = getVPNInfo(packet,protocol,readIP4,readIP6); } return packetInfo; } private static BasicPacketInfo getVPNInfo(PcapPacket packet,Protocol protocol,boolean readIP4, boolean readIP6) { BasicPacketInfo packetInfo = null; try { packet.scan(L2TP.ID); if (packet.hasHeader(protocol.getL2tp())){ if(readIP4){ packet.scan(protocol.getIpv4().getId()); packetInfo = getIpv4Info(packet,protocol); if (packetInfo == null && readIP6){ packet.scan(protocol.getIpv6().getId()); packetInfo = getIpv6Info(packet,protocol); } }else if(readIP6){ packet.scan(protocol.getIpv6().getId()); packetInfo = getIpv6Info(packet,protocol); if (packetInfo == null && readIP4){ packet.scan(protocol.getIpv4().getId()); packetInfo = getIpv4Info(packet,protocol); } } } } catch (Exception e) { /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.l2tp.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new L2TP())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg);*/ return null; } return packetInfo; } private static BasicPacketInfo getIpv6Info(PcapPacket packet,Protocol protocol) { BasicPacketInfo packetInfo = null; try{ if(packet.hasHeader(protocol.getIpv6())){ packet.scan(protocol.getIpv6().ID); packetInfo = new BasicPacketInfo(idGen); packetInfo.setSrc(protocol.getIpv6().source()); packetInfo.setDst(protocol.getIpv6().destination()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); if(packet.hasHeader(protocol.getTcp())){ packet.scan(protocol.getTcp().ID); packetInfo.setSrcPort(protocol.getTcp().source()); packetInfo.setDstPort(protocol.getTcp().destination()); packetInfo.setPayloadBytes(protocol.getTcp().getPayloadLength()); packetInfo.setPayloadData(protocol.getTcp().getPayload()); packetInfo.setHeaderBytes(protocol.getTcp().getHeaderLength()); packetInfo.setProtocol(6); }else if(packet.hasHeader(protocol.getUdp())){ packet.scan(protocol.getUdp().ID); packetInfo.setSrcPort(protocol.getUdp().source()); packetInfo.setDstPort(protocol.getUdp().destination()); packetInfo.setPayloadBytes(protocol.getUdp().getPayloadLength()); packetInfo.setPayloadData(protocol.getUdp().getPayload()); packetInfo.setHeaderBytes(protocol.getUdp().getHeaderLength()); packetInfo.setProtocol(17); } } }catch(Exception e){ /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.ipv6.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip6())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg); //System.exit(-1);*/ return null; } return packetInfo; } private static BasicPacketInfo getIpv4Info(PcapPacket packet,Protocol protocol) { BasicPacketInfo packetInfo = null; try { if (packet.hasHeader(protocol.getIpv4())){ packetInfo = new BasicPacketInfo(idGen); packetInfo.setSrc(protocol.getIpv4().source()); packetInfo.setDst(protocol.getIpv4().destination()); //packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMicros()); /*if(this.firstPacket == 0L) this.firstPacket = packet.getCaptureHeader().timestampInMillis(); this.lastPacket = packet.getCaptureHeader().timestampInMillis();*/ if(packet.hasHeader(protocol.getTcp())){ packetInfo.setTCPWindow(protocol.getTcp().window()); packetInfo.setSrcPort(protocol.getTcp().source()); packetInfo.setDstPort(protocol.getTcp().destination()); packetInfo.setProtocol(6); packetInfo.setFlagFIN(protocol.getTcp().flags_FIN()); packetInfo.setFlagPSH(protocol.getTcp().flags_PSH()); packetInfo.setFlagURG(protocol.getTcp().flags_URG()); packetInfo.setFlagSYN(protocol.getTcp().flags_SYN()); packetInfo.setFlagACK(protocol.getTcp().flags_ACK()); packetInfo.setFlagECE(protocol.getTcp().flags_ECE()); packetInfo.setFlagCWR(protocol.getTcp().flags_CWR()); packetInfo.setFlagRST(protocol.getTcp().flags_RST()); packetInfo.setPayloadBytes(protocol.getTcp().getPayloadLength()); packetInfo.setPayloadData(protocol.getTcp().getPayload()); packetInfo.setHeaderBytes(protocol.getTcp().getHeaderLength()); }else if(packet.hasHeader(protocol.getUdp())){ packetInfo.setSrcPort(protocol.getUdp().source()); packetInfo.setDstPort(protocol.getUdp().destination()); packetInfo.setPayloadBytes(protocol.getUdp().getPayloadLength()); packetInfo.setPayloadData(protocol.getUdp().getPayload()); packetInfo.setHeaderBytes(protocol.getUdp().getHeaderLength()); packetInfo.setProtocol(17); } else { int headerCount = packet.getHeaderCount(); for(int i=0;i<headerCount;i++) { JHeader header = JHeaderPool.getDefault().getHeader(i); //JHeader hh = packet.getHeaderByIndex(i, header); //logger.debug("getIpv4Info: {} --description: {} ",header.getName(),header.getDescription()); } } } } catch (Exception e) { /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.ipv4.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip4())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg); return null;*/ } return packetInfo; } }
scilicet64/CICFlowMeter
src/main/java/cic/cs/unb/ca/jnetpcap/PacketReader.java
6,184
// deze klopt niet!
line_comment
nl
package cic.cs.unb.ca.jnetpcap; import org.jnetpcap.Pcap; import org.jnetpcap.PcapClosedException; import org.jnetpcap.PcapHeader; import org.jnetpcap.nio.JBuffer; import org.jnetpcap.nio.JMemory; import org.jnetpcap.packet.JHeader; import org.jnetpcap.packet.JHeaderPool; import org.jnetpcap.packet.PcapPacket; import org.jnetpcap.packet.JRegistry; import org.jnetpcap.protocol.lan.Ethernet; import org.jnetpcap.protocol.network.Ip4; import org.jnetpcap.protocol.network.Ip6; import org.jnetpcap.protocol.tcpip.Tcp; import org.jnetpcap.protocol.tcpip.Udp; import org.jnetpcap.protocol.vpn.L2TP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PacketReader { private static final Logger logger = LoggerFactory.getLogger(PacketReader.class); private IdGenerator generator = new IdGenerator(); private Pcap pcapReader; private long firstPacket; private long lastPacket; private Ethernet eth; private Tcp tcp; private Udp udp; private Ip4 ipv4; private Ip6 ipv6; private L2TP l2tp; private PcapHeader hdr; private JBuffer buf; private int scanID; private boolean readIP6; private boolean readIP4; private String file; public PacketReader(String filename) { super(); this.readIP4 = true; this.readIP6 = false; this.config(filename); } public PacketReader(String filename, boolean readip4, boolean readip6) { super(); this.readIP4 = true; this.readIP6 = false; this.config(filename); } private void config(String filename){ file = filename; StringBuilder errbuf = new StringBuilder(); // For any error msgs if(!Pcap.isPcap080Loaded()){ System.out.println("Warning Jnetpcap:Pcap080 is not loaded!"); } if(!Pcap.isPcap100Loaded()){ System.out.println("Warning Jnetpcap:Pcap100 is not loaded!"); } pcapReader = Pcap.openOffline(filename, errbuf); this.firstPacket = 0L; this.lastPacket = 0L; if (pcapReader == null) { logger.error("Error while opening file for capture: "+errbuf.toString()); System.exit(-1); }else{ this.hdr = new PcapHeader(JMemory.POINTER); this.buf = new JBuffer(JMemory.POINTER); this.eth = new Ethernet(); this.ipv4 = new Ip4(); this.ipv6 = new Ip6(); this.tcp = new Tcp(); this.udp = new Udp(); this.l2tp = new L2TP(); this.scanID = JRegistry.mapDLTToId(pcapReader.datalink()); if (this.scanID!=Ethernet.ID) System.out.println("Warning!?"); } } public BasicPacketInfo nextPacket(){ PcapPacket packet; BasicPacketInfo packetInfo = null; try{ if(pcapReader.nextEx(hdr,buf) == Pcap.NEXT_EX_OK){ packet = new PcapPacket(hdr, buf); packet.scan(this.scanID); if (packet.hasHeader(eth)) { if (this.readIP4) { packetInfo = getIpv4Info(packet); if (packetInfo == null && this.readIP6) { packetInfo = getIpv6Info(packet); } } else if (this.readIP6) { packetInfo = getIpv6Info(packet); if (packetInfo == null && this.readIP4) { packetInfo = getIpv4Info(packet); } } if (packetInfo == null) { packetInfo = getVPNInfo(packet); } } else{ System.out.println("without Eth : " + this.ipv4.type()); } }else{ throw new PcapClosedException(); } }catch(PcapClosedException e){ System.out.println("PcapClosedException:" + e); logger.debug("Read All packets on {}",file); throw e; }catch(Exception ex){ System.out.println("Exception:" + ex); logger.debug(ex.getMessage()); } return packetInfo; } private BasicPacketInfo getIpv4Info(PcapPacket packet){ BasicPacketInfo packetInfo = null; try { if (eth.getNextHeaderId()==this.ipv4.ID) { this.ipv4 = packet.getHeader(this.ipv4); //this.ipv4 = packet.getHeader(this.ipv4); packetInfo = new BasicPacketInfo(this.generator); packetInfo.setSrc(this.ipv4.source()); packetInfo.setDst(this.ipv4.destination()); //packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMicros()); if (this.firstPacket == 0L) this.firstPacket = packet.getCaptureHeader().timestampInMillis(); this.lastPacket = packet.getCaptureHeader().timestampInMillis(); if(this.ipv4.getNextHeaderId()==this.tcp.ID){ // deze klopt<SUF> this.tcp = packet.getHeader(this.tcp); packetInfo.setTCPWindow(tcp.window()); packetInfo.setSrcPort(tcp.source()); packetInfo.setDstPort(tcp.destination()); packetInfo.setProtocol(6); packetInfo.setFlagFIN(tcp.flags_FIN()); packetInfo.setFlagPSH(tcp.flags_PSH()); packetInfo.setFlagURG(tcp.flags_URG()); packetInfo.setFlagSYN(tcp.flags_SYN()); packetInfo.setFlagACK(tcp.flags_ACK()); packetInfo.setFlagECE(tcp.flags_ECE()); packetInfo.setFlagCWR(tcp.flags_CWR()); packetInfo.setFlagRST(tcp.flags_RST()); packetInfo.setPayloadBytes(tcp.getPayloadLength()); packetInfo.setPayloadData(tcp.getPayload()); packetInfo.setHeaderBytes(tcp.getHeaderLength()); }else if(this.ipv4.getNextHeaderId()==this.udp.ID){ this.udp = packet.getHeader(this.udp); packetInfo.setSrcPort(udp.source()); packetInfo.setDstPort(udp.destination()); packetInfo.setPayloadBytes(udp.getPayloadLength()); packetInfo.setPayloadData(udp.getPayload()); packetInfo.setHeaderBytes(udp.getHeaderLength()); packetInfo.setProtocol(17); }else { return null; //logger.debug("other packet Ethernet -> {}"+ packet.hasHeader(new Ethernet())); //logger.debug("other packet Html -> {}"+ packet.hasHeader(new Html())); //logger.debug("other packet Http -> {}"+ packet.hasHeader(new Http())); //logger.debug("other packet SLL -> {}"+ packet.hasHeader(new SLL())); //logger.debug("other packet L2TP -> {}"+ packet.hasHeader(new L2TP())); //logger.debug("other packet Sctp -> {}"+ packet.hasHeader(new Sctp())); //logger.debug("other packet PPP -> {}"+ packet.hasHeader(new PPP())); //int headerCount = packet.getHeaderCount(); //for(int i=0;i<headerCount;i++) { // JHeader header = JHeaderPool.getDefault().getHeader(i); // //JHeader hh = packet.getHeaderByIndex(i, header); // //logger.debug("getIpv4Info: {} --description: {} ",header.getName(),header.getDescription()); //} } } } catch (Exception e) { e.printStackTrace(); packet.scan(ipv4.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip4())+"\n"; errormsg+="ip4********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } private BasicPacketInfo getIpv6Info(PcapPacket packet){ BasicPacketInfo packetInfo = null; try{ if(packet.hasHeader(ipv6)){ packet.scan(this.ipv6.ID); packetInfo = new BasicPacketInfo(this.generator); packetInfo.setSrc(this.ipv6.source()); packetInfo.setDst(this.ipv6.destination()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); if(packet.hasHeader(this.tcp)){ System.out.println("Warning recept for failure? packet.hasHeader(this.tcp)"); packetInfo.setSrcPort(tcp.source()); packetInfo.setDstPort(tcp.destination()); packetInfo.setPayloadBytes(tcp.getPayloadLength()); packetInfo.setPayloadData(tcp.getPayload()); packetInfo.setHeaderBytes(tcp.getHeaderLength()); packetInfo.setProtocol(6); }else if(packet.hasHeader(this.udp)){ System.out.println("Warning recept for failure? packet.hasHeader(this.udp)"); packetInfo.setSrcPort(udp.source()); packetInfo.setDstPort(udp.destination()); packetInfo.setPayloadBytes(udp.getPayloadLength()); packetInfo.setPayloadData(udp.getPayload()); packetInfo.setHeaderBytes(udp.getHeaderLength()); packetInfo.setProtocol(17); } } }catch(Exception e){ logger.debug(e.getMessage()); packet.scan(ipv6.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip6())+"\n"; errormsg+="ipv6********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; //System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } private BasicPacketInfo getVPNInfo(PcapPacket packet){ BasicPacketInfo packetInfo = null; try { if (packet.hasHeader(l2tp)){ if(this.readIP4){ packet.scan(ipv4.getId()); packetInfo = getIpv4Info(packet); if (packetInfo == null && this.readIP6){ packet.scan(ipv6.getId()); packetInfo = getIpv6Info(packet); } }else if(this.readIP6){ packet.scan(ipv6.getId()); packetInfo = getIpv6Info(packet); if (packetInfo == null && this.readIP4){ packet.scan(ipv4.getId()); packetInfo = getIpv4Info(packet); } } } } catch (Exception e) { logger.debug(e.getMessage()); packet.scan(l2tp.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new L2TP())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; //System.out.println(errormsg); logger.debug(errormsg); //System.exit(-1); return null; } return packetInfo; } public long getFirstPacket() { return firstPacket; } public void setFirstPacket(long firstPacket) { this.firstPacket = firstPacket; } public long getLastPacket() { return lastPacket; } public void setLastPacket(long lastPacket) { this.lastPacket = lastPacket; } /* * So far,The value of the field BasicPacketInfo.id is not used * It doesn't matter just using a static IdGenerator for realtime PcapPacket reading */ private static IdGenerator idGen = new IdGenerator(); public static BasicPacketInfo getBasicPacketInfo(PcapPacket packet,boolean readIP4, boolean readIP6) { BasicPacketInfo packetInfo = null; Protocol protocol = new Protocol(); if(readIP4){ packetInfo = getIpv4Info(packet,protocol); if (packetInfo == null && readIP6){ packetInfo = getIpv6Info(packet,protocol); } }else if(readIP6){ packetInfo = getIpv6Info(packet,protocol); if (packetInfo == null && readIP4){ packetInfo = getIpv4Info(packet,protocol); } } if (packetInfo == null){ packetInfo = getVPNInfo(packet,protocol,readIP4,readIP6); } return packetInfo; } private static BasicPacketInfo getVPNInfo(PcapPacket packet,Protocol protocol,boolean readIP4, boolean readIP6) { BasicPacketInfo packetInfo = null; try { packet.scan(L2TP.ID); if (packet.hasHeader(protocol.getL2tp())){ if(readIP4){ packet.scan(protocol.getIpv4().getId()); packetInfo = getIpv4Info(packet,protocol); if (packetInfo == null && readIP6){ packet.scan(protocol.getIpv6().getId()); packetInfo = getIpv6Info(packet,protocol); } }else if(readIP6){ packet.scan(protocol.getIpv6().getId()); packetInfo = getIpv6Info(packet,protocol); if (packetInfo == null && readIP4){ packet.scan(protocol.getIpv4().getId()); packetInfo = getIpv4Info(packet,protocol); } } } } catch (Exception e) { /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.l2tp.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new L2TP())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg);*/ return null; } return packetInfo; } private static BasicPacketInfo getIpv6Info(PcapPacket packet,Protocol protocol) { BasicPacketInfo packetInfo = null; try{ if(packet.hasHeader(protocol.getIpv6())){ packet.scan(protocol.getIpv6().ID); packetInfo = new BasicPacketInfo(idGen); packetInfo.setSrc(protocol.getIpv6().source()); packetInfo.setDst(protocol.getIpv6().destination()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); if(packet.hasHeader(protocol.getTcp())){ packet.scan(protocol.getTcp().ID); packetInfo.setSrcPort(protocol.getTcp().source()); packetInfo.setDstPort(protocol.getTcp().destination()); packetInfo.setPayloadBytes(protocol.getTcp().getPayloadLength()); packetInfo.setPayloadData(protocol.getTcp().getPayload()); packetInfo.setHeaderBytes(protocol.getTcp().getHeaderLength()); packetInfo.setProtocol(6); }else if(packet.hasHeader(protocol.getUdp())){ packet.scan(protocol.getUdp().ID); packetInfo.setSrcPort(protocol.getUdp().source()); packetInfo.setDstPort(protocol.getUdp().destination()); packetInfo.setPayloadBytes(protocol.getUdp().getPayloadLength()); packetInfo.setPayloadData(protocol.getUdp().getPayload()); packetInfo.setHeaderBytes(protocol.getUdp().getHeaderLength()); packetInfo.setProtocol(17); } } }catch(Exception e){ /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.ipv6.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip6())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg); //System.exit(-1);*/ return null; } return packetInfo; } private static BasicPacketInfo getIpv4Info(PcapPacket packet,Protocol protocol) { BasicPacketInfo packetInfo = null; try { if (packet.hasHeader(protocol.getIpv4())){ packetInfo = new BasicPacketInfo(idGen); packetInfo.setSrc(protocol.getIpv4().source()); packetInfo.setDst(protocol.getIpv4().destination()); //packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMillis()); packetInfo.setTimeStamp(packet.getCaptureHeader().timestampInMicros()); /*if(this.firstPacket == 0L) this.firstPacket = packet.getCaptureHeader().timestampInMillis(); this.lastPacket = packet.getCaptureHeader().timestampInMillis();*/ if(packet.hasHeader(protocol.getTcp())){ packetInfo.setTCPWindow(protocol.getTcp().window()); packetInfo.setSrcPort(protocol.getTcp().source()); packetInfo.setDstPort(protocol.getTcp().destination()); packetInfo.setProtocol(6); packetInfo.setFlagFIN(protocol.getTcp().flags_FIN()); packetInfo.setFlagPSH(protocol.getTcp().flags_PSH()); packetInfo.setFlagURG(protocol.getTcp().flags_URG()); packetInfo.setFlagSYN(protocol.getTcp().flags_SYN()); packetInfo.setFlagACK(protocol.getTcp().flags_ACK()); packetInfo.setFlagECE(protocol.getTcp().flags_ECE()); packetInfo.setFlagCWR(protocol.getTcp().flags_CWR()); packetInfo.setFlagRST(protocol.getTcp().flags_RST()); packetInfo.setPayloadBytes(protocol.getTcp().getPayloadLength()); packetInfo.setPayloadData(protocol.getTcp().getPayload()); packetInfo.setHeaderBytes(protocol.getTcp().getHeaderLength()); }else if(packet.hasHeader(protocol.getUdp())){ packetInfo.setSrcPort(protocol.getUdp().source()); packetInfo.setDstPort(protocol.getUdp().destination()); packetInfo.setPayloadBytes(protocol.getUdp().getPayloadLength()); packetInfo.setPayloadData(protocol.getUdp().getPayload()); packetInfo.setHeaderBytes(protocol.getUdp().getHeaderLength()); packetInfo.setProtocol(17); } else { int headerCount = packet.getHeaderCount(); for(int i=0;i<headerCount;i++) { JHeader header = JHeaderPool.getDefault().getHeader(i); //JHeader hh = packet.getHeaderByIndex(i, header); //logger.debug("getIpv4Info: {} --description: {} ",header.getName(),header.getDescription()); } } } } catch (Exception e) { /* * BufferUnderflowException while decoding header * havn't fixed, so do not e.printStackTrace() */ //e.printStackTrace(); /*packet.scan(protocol.ipv4.getId()); String errormsg = ""; errormsg+=e.getMessage()+"\n"; //errormsg+=packet.getHeader(new Ip4())+"\n"; errormsg+="********************************************************************************"+"\n"; errormsg+=packet.toHexdump()+"\n"; logger.error(errormsg); return null;*/ } return packetInfo; } }
53786_10
package net.neonlotus.lolandroidapp; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; /** * Created by IntelliJ IDEA. * User: Ryan * Date: 10/26/11 * Time: 7:03 PM * To change this template use File | Settings | File Templates. */ public class Info extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //=========================== //==== GRID VIEW TESTING ==== setContentView(R.layout.champ_grid); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new CustomAdapter(this)); //bundle test stuff final Intent intent = new Intent(Info.this, Champion.class); final Bundle b = new Bundle(); final String[] champ_list_array = getResources().getStringArray(R.array.champ_list); final String[] champ_lore_array = getResources().getStringArray(R.array.champ_lore); final String[] champ_stats_array = getResources().getStringArray(R.array.champ_stats); final String[] champ_tag_lines = getResources().getStringArray(R.array.champ_taglines); //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, champ_list_array)); THIS //ListView lv = getListView(); THIS //lv.setTextFilterEnabled(true); THIS gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { //Copying stuff from list adapter click thing ChampObj obj = new ChampObj(); obj.setChampName(champ_list_array[position]); obj.setChampStory(champ_lore_array[position]); obj.setChampStats(champ_stats_array[position]); obj.setChampTags(champ_tag_lines[position]); intent.putExtra("net.neonlotus.lolandroidapp.ChampObj", obj); startActivity(intent); } }); //registerForContextMenu(); /*AdapterView.OnItemLongClickListener listener = new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //Log.d(TAG, "OnItemLongClickListener"); //Toast.makeText(getApplicationContext(),"LONG",Toast.LENGTH_SHORT).show(); //showOptionsMenu(position); return true; } }; gridview.setOnItemLongClickListener(listener);*/ /*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { THIS public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) { //Trying Scott parcel thing ChampObj obj = new ChampObj(); //Set values etc. obj.setChampName(champ_list_array[position]); obj.setChampStory(champ_lore_array[position]); obj.setChampStats(champ_stats_array[position]); obj.setChampTags(champ_tag_lines[position]); //Intent stuff :D intent.putExtra("net.neonlotus.lolandroidapp.ChampObj", obj); startActivity(intent); } //end on click });*/ } public class CustomAdapter extends BaseAdapter { private Context mContext; public CustomAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } final String[] champ_list_array = getResources().getStringArray(R.array.champ_list); // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { // if it's not recycled, initialize some attributes v = new View(getApplicationContext()); } else { v = (View) convertView; } //Set content here... LayoutInflater li = getLayoutInflater(); v = li.inflate(R.layout.icon, null); TextView tv = (TextView) v.findViewById(R.id.icon_text); tv.setText(champ_list_array[position]); ImageView iv = (ImageView) v.findViewById(R.id.icon_image); iv.setImageResource(mThumbIds[position]); iv.setPadding(5,5,5,5); return v; } // references to our images private Integer[] mThumbIds = { R.drawable.ahri, R.drawable.akal, R.drawable.ali, R.drawable.amumu, R.drawable.anivia, R.drawable.annie, R.drawable.ashe, R.drawable.blitz, R.drawable.brand, R.drawable.cait, R.drawable.cassi, R.drawable.cho, R.drawable.cork, R.drawable.drmu, R.drawable.evel, R.drawable.ezr, R.drawable.fiddle, R.drawable.fizz, R.drawable.galio, R.drawable.gang, R.drawable.garen, R.drawable.gragas, R.drawable.graves, R.drawable.heim, R.drawable.irel, R.drawable.janna, R.drawable.jarv, R.drawable.jax, R.drawable.karma, R.drawable.karth, R.drawable.kass, R.drawable.kata, R.drawable.kayle, R.drawable.kennen, R.drawable.kog, R.drawable.leblanc, R.drawable.leesin, R.drawable.leona, R.drawable.lux, R.drawable.malph, R.drawable.malz, R.drawable.mao, R.drawable.master, R.drawable.missfort, R.drawable.mord, R.drawable.morg, R.drawable.nasus, R.drawable.nidalee, R.drawable.noct, R.drawable.nunu, R.drawable.olaf, R.drawable.orian, R.drawable.panth, R.drawable.poppy, R.drawable.rammus, R.drawable.rene, R.drawable.riven, R.drawable.rumb, R.drawable.ryze, R.drawable.shaco, R.drawable.shen, R.drawable.shyv, R.drawable.singed, R.drawable.sion, R.drawable.sivir, R.drawable.skarn, R.drawable.sona, R.drawable.soraka, R.drawable.swain, R.drawable.talon, R.drawable.taric, R.drawable.teemo, R.drawable.trist, R.drawable.trundle, R.drawable.trynd, R.drawable.twifa, R.drawable.twitch, R.drawable.udyr, R.drawable.urgot, R.drawable.vayne, R.drawable.veig, R.drawable.viktor, R.drawable.vlad, R.drawable.volibear, R.drawable.warw, R.drawable.wukong, R.drawable.xera, R.drawable.xinz, R.drawable.yorik, R.drawable.zil }; } }
scottagarman/LeagueLore
src/net/neonlotus/lolandroidapp/Info.java
2,304
//Set content here...
line_comment
nl
package net.neonlotus.lolandroidapp; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; /** * Created by IntelliJ IDEA. * User: Ryan * Date: 10/26/11 * Time: 7:03 PM * To change this template use File | Settings | File Templates. */ public class Info extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //=========================== //==== GRID VIEW TESTING ==== setContentView(R.layout.champ_grid); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new CustomAdapter(this)); //bundle test stuff final Intent intent = new Intent(Info.this, Champion.class); final Bundle b = new Bundle(); final String[] champ_list_array = getResources().getStringArray(R.array.champ_list); final String[] champ_lore_array = getResources().getStringArray(R.array.champ_lore); final String[] champ_stats_array = getResources().getStringArray(R.array.champ_stats); final String[] champ_tag_lines = getResources().getStringArray(R.array.champ_taglines); //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, champ_list_array)); THIS //ListView lv = getListView(); THIS //lv.setTextFilterEnabled(true); THIS gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { //Copying stuff from list adapter click thing ChampObj obj = new ChampObj(); obj.setChampName(champ_list_array[position]); obj.setChampStory(champ_lore_array[position]); obj.setChampStats(champ_stats_array[position]); obj.setChampTags(champ_tag_lines[position]); intent.putExtra("net.neonlotus.lolandroidapp.ChampObj", obj); startActivity(intent); } }); //registerForContextMenu(); /*AdapterView.OnItemLongClickListener listener = new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //Log.d(TAG, "OnItemLongClickListener"); //Toast.makeText(getApplicationContext(),"LONG",Toast.LENGTH_SHORT).show(); //showOptionsMenu(position); return true; } }; gridview.setOnItemLongClickListener(listener);*/ /*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { THIS public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) { //Trying Scott parcel thing ChampObj obj = new ChampObj(); //Set values etc. obj.setChampName(champ_list_array[position]); obj.setChampStory(champ_lore_array[position]); obj.setChampStats(champ_stats_array[position]); obj.setChampTags(champ_tag_lines[position]); //Intent stuff :D intent.putExtra("net.neonlotus.lolandroidapp.ChampObj", obj); startActivity(intent); } //end on click });*/ } public class CustomAdapter extends BaseAdapter { private Context mContext; public CustomAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } final String[] champ_list_array = getResources().getStringArray(R.array.champ_list); // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { // if it's not recycled, initialize some attributes v = new View(getApplicationContext()); } else { v = (View) convertView; } //Set content<SUF> LayoutInflater li = getLayoutInflater(); v = li.inflate(R.layout.icon, null); TextView tv = (TextView) v.findViewById(R.id.icon_text); tv.setText(champ_list_array[position]); ImageView iv = (ImageView) v.findViewById(R.id.icon_image); iv.setImageResource(mThumbIds[position]); iv.setPadding(5,5,5,5); return v; } // references to our images private Integer[] mThumbIds = { R.drawable.ahri, R.drawable.akal, R.drawable.ali, R.drawable.amumu, R.drawable.anivia, R.drawable.annie, R.drawable.ashe, R.drawable.blitz, R.drawable.brand, R.drawable.cait, R.drawable.cassi, R.drawable.cho, R.drawable.cork, R.drawable.drmu, R.drawable.evel, R.drawable.ezr, R.drawable.fiddle, R.drawable.fizz, R.drawable.galio, R.drawable.gang, R.drawable.garen, R.drawable.gragas, R.drawable.graves, R.drawable.heim, R.drawable.irel, R.drawable.janna, R.drawable.jarv, R.drawable.jax, R.drawable.karma, R.drawable.karth, R.drawable.kass, R.drawable.kata, R.drawable.kayle, R.drawable.kennen, R.drawable.kog, R.drawable.leblanc, R.drawable.leesin, R.drawable.leona, R.drawable.lux, R.drawable.malph, R.drawable.malz, R.drawable.mao, R.drawable.master, R.drawable.missfort, R.drawable.mord, R.drawable.morg, R.drawable.nasus, R.drawable.nidalee, R.drawable.noct, R.drawable.nunu, R.drawable.olaf, R.drawable.orian, R.drawable.panth, R.drawable.poppy, R.drawable.rammus, R.drawable.rene, R.drawable.riven, R.drawable.rumb, R.drawable.ryze, R.drawable.shaco, R.drawable.shen, R.drawable.shyv, R.drawable.singed, R.drawable.sion, R.drawable.sivir, R.drawable.skarn, R.drawable.sona, R.drawable.soraka, R.drawable.swain, R.drawable.talon, R.drawable.taric, R.drawable.teemo, R.drawable.trist, R.drawable.trundle, R.drawable.trynd, R.drawable.twifa, R.drawable.twitch, R.drawable.udyr, R.drawable.urgot, R.drawable.vayne, R.drawable.veig, R.drawable.viktor, R.drawable.vlad, R.drawable.volibear, R.drawable.warw, R.drawable.wukong, R.drawable.xera, R.drawable.xinz, R.drawable.yorik, R.drawable.zil }; } }
23541_4
package org.firstinspires.ftc.teamcode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.classes.Drivetrain; import org.firstinspires.ftc.teamcode.classes.Hardware; import org.firstinspires.ftc.teamcode.classes.Lift; import org.firstinspires.ftc.teamcode.classes.Camera; import org.firstinspires.ftc.teamcode.classes.extra.GethPath; import org.firstinspires.ftc.teamcode.classes.extra.Position; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.TouchSensor; import static org.firstinspires.ftc.teamcode.classes.Hardware.*; import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*; @Autonomous(name = "Autonomous :)", group = "Centerstage") public class AutonomousCenterstage extends LinearOpMode { //Robot parts Hardware RobotHardware = new Hardware(); TouchSensor None; public Drivetrain CenterstageDriveTrain; public Lift Slides; public Lift Arm; public Lift Slider; public Camera Cam1; //Auton data StartPos sPos = StartPos.UNKNOWN; public String StartPosString; public void runOpMode() { RobotHardware.StartHardware(hardwareMap); CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit); Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit); Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor); telemetry.addData("Status: ", "Calibrating..."); CenterstageDriveTrain.Init(); Arm.Init(); Cam1.initVSProcesor(); telemetry.update(); try { File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt"); BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile)); StartPosString = fileReader.readLine(); } catch (IOException e) { telemetry.addData("Error: ", e); } telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", StartPosString); telemetry.update(); //Autonomous selecting pos while(!gamepad1.back && !isStopRequested()) { if (gamepad1.a) sPos = StartPos.BLUE1; if (gamepad1.b) sPos = StartPos.BLUE2; if (gamepad1.x) sPos = StartPos.RED1; if (gamepad1.y) sPos = StartPos.RED2; telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", sPos); telemetry.update(); } telemetry.addData("Status: ", "Waiting for start..."); telemetry.update(); // hier blijven herkennen tot start waitForStart(); // Code after start is pressed------------------------------------------------------------------------------------ while(!isStopRequested()) { Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon()); telemetry.addData("pos X: ", TeamEllementPos.x); telemetry.addData("pos Y: ", TeamEllementPos.y); telemetry.update(); //if( positie, 1, 2 of 3; rijd naar de juiste plek } } }
screwlooosescientists/FtcRobotController-master_ScrewLoooseScientists
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutonomousCenterstage.java
1,201
//if( positie, 1, 2 of 3; rijd naar de juiste plek
line_comment
nl
package org.firstinspires.ftc.teamcode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.classes.Drivetrain; import org.firstinspires.ftc.teamcode.classes.Hardware; import org.firstinspires.ftc.teamcode.classes.Lift; import org.firstinspires.ftc.teamcode.classes.Camera; import org.firstinspires.ftc.teamcode.classes.extra.GethPath; import org.firstinspires.ftc.teamcode.classes.extra.Position; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.TouchSensor; import static org.firstinspires.ftc.teamcode.classes.Hardware.*; import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*; @Autonomous(name = "Autonomous :)", group = "Centerstage") public class AutonomousCenterstage extends LinearOpMode { //Robot parts Hardware RobotHardware = new Hardware(); TouchSensor None; public Drivetrain CenterstageDriveTrain; public Lift Slides; public Lift Arm; public Lift Slider; public Camera Cam1; //Auton data StartPos sPos = StartPos.UNKNOWN; public String StartPosString; public void runOpMode() { RobotHardware.StartHardware(hardwareMap); CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit); Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit); Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor); telemetry.addData("Status: ", "Calibrating..."); CenterstageDriveTrain.Init(); Arm.Init(); Cam1.initVSProcesor(); telemetry.update(); try { File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt"); BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile)); StartPosString = fileReader.readLine(); } catch (IOException e) { telemetry.addData("Error: ", e); } telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", StartPosString); telemetry.update(); //Autonomous selecting pos while(!gamepad1.back && !isStopRequested()) { if (gamepad1.a) sPos = StartPos.BLUE1; if (gamepad1.b) sPos = StartPos.BLUE2; if (gamepad1.x) sPos = StartPos.RED1; if (gamepad1.y) sPos = StartPos.RED2; telemetry.addData("Status: ", "Selecting start pos..."); telemetry.addData("StartPos: ", sPos); telemetry.update(); } telemetry.addData("Status: ", "Waiting for start..."); telemetry.update(); // hier blijven herkennen tot start waitForStart(); // Code after start is pressed------------------------------------------------------------------------------------ while(!isStopRequested()) { Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon()); telemetry.addData("pos X: ", TeamEllementPos.x); telemetry.addData("pos Y: ", TeamEllementPos.y); telemetry.update(); //if( positie,<SUF> } } }
82561_16
package com.github.scribejava.core.oauth; import com.github.scribejava.core.builder.api.DefaultApi20; import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor; import com.github.scribejava.core.httpclient.HttpClient; import com.github.scribejava.core.httpclient.HttpClientConfig; import com.github.scribejava.core.model.DeviceAuthorization; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuth2AccessTokenErrorResponse; import com.github.scribejava.core.model.OAuth2Authorization; import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.OAuthConstants; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth2.OAuth2Error; import com.github.scribejava.core.pkce.PKCE; import com.github.scribejava.core.revoke.TokenTypeHint; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class OAuth20Service extends OAuthService { private static final String VERSION = "2.0"; private final DefaultApi20 api; private final String responseType; private final String defaultScope; public OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) { super(apiKey, apiSecret, callback, debugStream, userAgent, httpClientConfig, httpClient); this.responseType = responseType; this.api = api; this.defaultScope = defaultScope; } // ===== common OAuth methods ===== /** * {@inheritDoc} */ @Override public String getVersion() { return VERSION; } public void signRequest(String accessToken, OAuthRequest request) { api.getBearerSignature().signRequest(accessToken, request); } public void signRequest(OAuth2AccessToken accessToken, OAuthRequest request) { signRequest(accessToken == null ? null : accessToken.getAccessToken(), request); } /** * Returns the URL where you should redirect your users to authenticate your application. * * @return the URL where you should redirect your users */ public String getAuthorizationUrl() { return createAuthorizationUrlBuilder().build(); } public String getAuthorizationUrl(String state) { return createAuthorizationUrlBuilder() .state(state) .build(); } /** * Returns the URL where you should redirect your users to authenticate your application. * * @param additionalParams any additional GET params to add to the URL * @return the URL where you should redirect your users */ public String getAuthorizationUrl(Map<String, String> additionalParams) { return createAuthorizationUrlBuilder() .additionalParams(additionalParams) .build(); } public String getAuthorizationUrl(PKCE pkce) { return createAuthorizationUrlBuilder() .pkce(pkce) .build(); } public AuthorizationUrlBuilder createAuthorizationUrlBuilder() { return new AuthorizationUrlBuilder(this); } public DefaultApi20 getApi() { return api; } public OAuth2Authorization extractAuthorization(String redirectLocation) { final OAuth2Authorization authorization = new OAuth2Authorization(); int end = redirectLocation.indexOf('#'); if (end == -1) { end = redirectLocation.length(); } for (String param : redirectLocation.substring(redirectLocation.indexOf('?') + 1, end).split("&")) { final String[] keyValue = param.split("="); if (keyValue.length == 2) { try { switch (keyValue[0]) { case "code": authorization.setCode(URLDecoder.decode(keyValue[1], "UTF-8")); break; case "state": authorization.setState(URLDecoder.decode(keyValue[1], "UTF-8")); break; default: //just ignore any other param; } } catch (UnsupportedEncodingException ueE) { throw new IllegalStateException("jvm without UTF-8, really?", ueE); } } } return authorization; } public String getResponseType() { return responseType; } public String getDefaultScope() { return defaultScope; } protected void logRequestWithParams(String requestDescription, OAuthRequest request) { if (isDebug()) { log("created " + requestDescription + " request with body params [%s], query string params [%s]", request.getBodyParams().asFormUrlEncodedString(), request.getQueryStringParams().asFormUrlEncodedString()); } } // ===== common AccessToken request methods ===== //protected to facilitate mocking protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException, InterruptedException, ExecutionException { if (isDebug()) { log("send request for access token synchronously to %s", request.getCompleteUrl()); } try (Response response = execute(request)) { if (isDebug()) { log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getAccessTokenExtractor().extract(response); } } //protected to facilitate mocking protected Future<OAuth2AccessToken> sendAccessTokenRequestAsync(OAuthRequest request) { return sendAccessTokenRequestAsync(request, null); } //protected to facilitate mocking protected Future<OAuth2AccessToken> sendAccessTokenRequestAsync(OAuthRequest request, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { if (isDebug()) { log("send request for access token asynchronously to %s", request.getCompleteUrl()); } return execute(request, callback, new OAuthRequest.ResponseConverter<OAuth2AccessToken>() { @Override public OAuth2AccessToken convert(Response response) throws IOException { log("received response for access token"); if (isDebug()) { log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } final OAuth2AccessToken token = api.getAccessTokenExtractor().extract(response); response.close(); return token; } }); } // ===== get AccessToken authorisation code flow methods ===== protected OAuthRequest createAccessTokenRequest(AccessTokenRequestParams params) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); request.addParameter(OAuthConstants.CODE, params.getCode()); final String callback = getCallback(); if (callback != null) { request.addParameter(OAuthConstants.REDIRECT_URI, callback); } final String scope = params.getScope(); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); final String pkceCodeVerifier = params.getPkceCodeVerifier(); if (pkceCodeVerifier != null) { request.addParameter(PKCE.PKCE_CODE_VERIFIER_PARAM, pkceCodeVerifier); } final Map<String, String> extraParameters = params.getExtraParameters(); if (extraParameters != null && !extraParameters.isEmpty()) { for (Map.Entry<String, String> extraParameter : extraParameters.entrySet()) { request.addParameter(extraParameter.getKey(), extraParameter.getValue()); } } logRequestWithParams("access token", request); return request; } public Future<OAuth2AccessToken> getAccessTokenAsync(String code) { return getAccessToken(AccessTokenRequestParams.create(code), null); } public Future<OAuth2AccessToken> getAccessTokenAsync(AccessTokenRequestParams params) { return getAccessToken(params, null); } public OAuth2AccessToken getAccessToken(String code) throws IOException, InterruptedException, ExecutionException { return getAccessToken(AccessTokenRequestParams.create(code)); } public OAuth2AccessToken getAccessToken(AccessTokenRequestParams params) throws IOException, InterruptedException, ExecutionException { return sendAccessTokenRequestSync(createAccessTokenRequest(params)); } /** * Start the request to retrieve the access token. The optionally provided callback will be called with the Token * when it is available. * * @param params params * @param callback optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { return sendAccessTokenRequestAsync(createAccessTokenRequest(params), callback); } public Future<OAuth2AccessToken> getAccessToken(String code, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { return getAccessToken(AccessTokenRequestParams.create(code), callback); } // ===== refresh AccessToken methods ===== protected OAuthRequest createRefreshTokenRequest(String refreshToken, String scope) { if (refreshToken == null || refreshToken.isEmpty()) { throw new IllegalArgumentException("The refreshToken cannot be null or empty"); } final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getRefreshTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.REFRESH_TOKEN, refreshToken); request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.REFRESH_TOKEN); logRequestWithParams("refresh token", request); return request; } public Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken) { return refreshAccessToken(refreshToken, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken, String scope) { return refreshAccessToken(refreshToken, scope, null); } public OAuth2AccessToken refreshAccessToken(String refreshToken) throws IOException, InterruptedException, ExecutionException { return refreshAccessToken(refreshToken, (String) null); } public OAuth2AccessToken refreshAccessToken(String refreshToken, String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createRefreshTokenRequest(refreshToken, scope); return sendAccessTokenRequestSync(request); } public Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createRefreshTokenRequest(refreshToken, null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createRefreshTokenRequest(refreshToken, scope); return sendAccessTokenRequestAsync(request, callback); } // ===== get AccessToken password grant flow methods ===== protected OAuthRequest createAccessTokenPasswordGrantRequest(String username, String password, String scope) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addParameter(OAuthConstants.USERNAME, username); request.addParameter(OAuthConstants.PASSWORD, password); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.PASSWORD); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); logRequestWithParams("access token password grant", request); return request; } public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestSync(request); } public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password, String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, scope); return sendAccessTokenRequestSync(request); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password) { return getAccessTokenPasswordGrantAsync(username, password, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope) { return getAccessTokenPasswordGrantAsync(username, password, scope, null); } /** * Request Access Token Password Grant async version * * @param username User name * @param password User password * @param callback Optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, scope); return sendAccessTokenRequestAsync(request, callback); } // ===== get AccessToken client credentials flow methods ===== protected OAuthRequest createAccessTokenClientCredentialsGrantRequest(String scope) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.CLIENT_CREDENTIALS); logRequestWithParams("access token client credentials grant", request); return request; } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync() { return getAccessTokenClientCredentialsGrant((OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(String scope) { return getAccessTokenClientCredentialsGrant(scope, null); } public OAuth2AccessToken getAccessTokenClientCredentialsGrant() throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(null); return sendAccessTokenRequestSync(request); } public OAuth2AccessToken getAccessTokenClientCredentialsGrant(String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(scope); return sendAccessTokenRequestSync(request); } /** * Start the request to retrieve the access token using client-credentials grant. The optionally provided callback * will be called with the Token when it is available. * * @param callback optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant( OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(scope); return sendAccessTokenRequestAsync(request, callback); } // ===== revoke AccessToken methods ===== protected OAuthRequest createRevokeTokenRequest(String tokenToRevoke, TokenTypeHint tokenTypeHint) { final OAuthRequest request = new OAuthRequest(Verb.POST, api.getRevokeTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); request.addParameter("token", tokenToRevoke); if (tokenTypeHint != null) { request.addParameter("token_type_hint", tokenTypeHint.getValue()); } logRequestWithParams("revoke token", request); return request; } public Future<Void> revokeTokenAsync(String tokenToRevoke) { return revokeTokenAsync(tokenToRevoke, null); } public Future<Void> revokeTokenAsync(String tokenToRevoke, TokenTypeHint tokenTypeHint) { return revokeToken(tokenToRevoke, null, tokenTypeHint); } public void revokeToken(String tokenToRevoke) throws IOException, InterruptedException, ExecutionException { revokeToken(tokenToRevoke, (TokenTypeHint) null); } public void revokeToken(String tokenToRevoke, TokenTypeHint tokenTypeHint) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createRevokeTokenRequest(tokenToRevoke, tokenTypeHint); try (Response response = execute(request)) { checkForErrorRevokeToken(response); } } public Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback) { return revokeToken(tokenToRevoke, callback, null); } public Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback, TokenTypeHint tokenTypeHint) { final OAuthRequest request = createRevokeTokenRequest(tokenToRevoke, tokenTypeHint); return execute(request, callback, new OAuthRequest.ResponseConverter<Void>() { @Override public Void convert(Response response) throws IOException { checkForErrorRevokeToken(response); response.close(); return null; } }); } private void checkForErrorRevokeToken(Response response) throws IOException { if (response.getCode() != 200) { OAuth2AccessTokenJsonExtractor.instance().generateError(response); } } // ===== device Authorisation codes methods ===== protected OAuthRequest createDeviceAuthorizationCodesRequest(String scope) { final OAuthRequest request = new OAuthRequest(Verb.POST, api.getDeviceAuthorizationEndpoint()); request.addParameter(OAuthConstants.CLIENT_ID, getApiKey()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } logRequestWithParams("Device Authorization Codes", request); return request; } /** * Requests a set of verification codes from the authorization server with the default scope * * @see <a href="https://tools.ietf.org/html/rfc8628#section-3.1">RFC 8628</a> * * @return DeviceAuthorization * @throws InterruptedException InterruptedException * @throws ExecutionException ExecutionException * @throws IOException IOException */ public DeviceAuthorization getDeviceAuthorizationCodes() throws InterruptedException, ExecutionException, IOException { return getDeviceAuthorizationCodes((String) null); } /** * Requests a set of verification codes from the authorization server * * @see <a href="https://tools.ietf.org/html/rfc8628#section-3.1">RFC 8628</a> * * @param scope scope * @return DeviceAuthorization * @throws InterruptedException InterruptedException * @throws ExecutionException ExecutionException * @throws IOException IOException */ public DeviceAuthorization getDeviceAuthorizationCodes(String scope) throws InterruptedException, ExecutionException, IOException { final OAuthRequest request = createDeviceAuthorizationCodesRequest(scope); try (Response response = execute(request)) { if (isDebug()) { log("got DeviceAuthorizationCodes response"); log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getDeviceAuthorizationExtractor().extract(response); } } public Future<DeviceAuthorization> getDeviceAuthorizationCodes( OAuthAsyncRequestCallback<DeviceAuthorization> callback) { return getDeviceAuthorizationCodes(null, callback); } public Future<DeviceAuthorization> getDeviceAuthorizationCodes(String scope, OAuthAsyncRequestCallback<DeviceAuthorization> callback) { final OAuthRequest request = createDeviceAuthorizationCodesRequest(scope); return execute(request, callback, new OAuthRequest.ResponseConverter<DeviceAuthorization>() { @Override public DeviceAuthorization convert(Response response) throws IOException { final DeviceAuthorization deviceAuthorization = api.getDeviceAuthorizationExtractor().extract(response); response.close(); return deviceAuthorization; } }); } public Future<DeviceAuthorization> getDeviceAuthorizationCodesAsync() { return getDeviceAuthorizationCodesAsync(null); } public Future<DeviceAuthorization> getDeviceAuthorizationCodesAsync(String scope) { return getDeviceAuthorizationCodes(scope, null); } // ===== get AccessToken Device Authorisation grant flow methods ===== protected OAuthRequest createAccessTokenDeviceAuthorizationGrantRequest(DeviceAuthorization deviceAuthorization) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addParameter(OAuthConstants.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:device_code"); request.addParameter("device_code", deviceAuthorization.getDeviceCode()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); return request; } /** * Attempts to get a token from a server. * * Function {@link #pollAccessTokenDeviceAuthorizationGrant(com.github.scribejava.core.model.DeviceAuthorization)} * is usually used instead of this. * * @param deviceAuthorization deviceAuthorization * @return token * * @throws java.lang.InterruptedException InterruptedException * @throws java.util.concurrent.ExecutionException ExecutionException * @throws java.io.IOException IOException * @throws OAuth2AccessTokenErrorResponse If {@link OAuth2AccessTokenErrorResponse#getError()} is * {@link com.github.scribejava.core.oauth2.OAuth2Error#AUTHORIZATION_PENDING} or * {@link com.github.scribejava.core.oauth2.OAuth2Error#SLOW_DOWN}, another attempt should be made after a while. * * @see #getDeviceAuthorizationCodes() */ public OAuth2AccessToken getAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization) throws InterruptedException, ExecutionException, IOException { final OAuthRequest request = createAccessTokenDeviceAuthorizationGrantRequest(deviceAuthorization); try (Response response = execute(request)) { if (isDebug()) { log("got AccessTokenDeviceAuthorizationGrant response"); log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getAccessTokenExtractor().extract(response); } } public Future<OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenDeviceAuthorizationGrantRequest(deviceAuthorization); return execute(request, callback, new OAuthRequest.ResponseConverter<OAuth2AccessToken>() { @Override public OAuth2AccessToken convert(Response response) throws IOException { final OAuth2AccessToken accessToken = api.getAccessTokenExtractor().extract(response); response.close(); return accessToken; } }); } public Future<OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrantAsync( DeviceAuthorization deviceAuthorization) { return getAccessTokenDeviceAuthorizationGrant(deviceAuthorization, null); } /** * Periodically tries to get a token from a server (waiting for the user to give consent). Sync only version. No * Async variants yet, one should implement async scenarios themselves. * * @param deviceAuthorization deviceAuthorization * @return token * @throws java.lang.InterruptedException InterruptedException * @throws java.util.concurrent.ExecutionException ExecutionException * @throws java.io.IOException IOException * @throws OAuth2AccessTokenErrorResponse Indicates OAuth error. * * @see #getDeviceAuthorizationCodes() */ public OAuth2AccessToken pollAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization) throws InterruptedException, ExecutionException, IOException { long intervalMillis = deviceAuthorization.getIntervalSeconds() * 1000; while (true) { try { return getAccessTokenDeviceAuthorizationGrant(deviceAuthorization); } catch (OAuth2AccessTokenErrorResponse e) { if (e.getError() != OAuth2Error.AUTHORIZATION_PENDING) { if (e.getError() == OAuth2Error.SLOW_DOWN) { intervalMillis += 5000; } else { throw e; } } } Thread.sleep(intervalMillis); } } }
scribejava/scribejava
scribejava-core/src/main/java/com/github/scribejava/core/oauth/OAuth20Service.java
7,062
// ===== revoke AccessToken methods =====
line_comment
nl
package com.github.scribejava.core.oauth; import com.github.scribejava.core.builder.api.DefaultApi20; import com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor; import com.github.scribejava.core.httpclient.HttpClient; import com.github.scribejava.core.httpclient.HttpClientConfig; import com.github.scribejava.core.model.DeviceAuthorization; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuth2AccessTokenErrorResponse; import com.github.scribejava.core.model.OAuth2Authorization; import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.OAuthConstants; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth2.OAuth2Error; import com.github.scribejava.core.pkce.PKCE; import com.github.scribejava.core.revoke.TokenTypeHint; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class OAuth20Service extends OAuthService { private static final String VERSION = "2.0"; private final DefaultApi20 api; private final String responseType; private final String defaultScope; public OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) { super(apiKey, apiSecret, callback, debugStream, userAgent, httpClientConfig, httpClient); this.responseType = responseType; this.api = api; this.defaultScope = defaultScope; } // ===== common OAuth methods ===== /** * {@inheritDoc} */ @Override public String getVersion() { return VERSION; } public void signRequest(String accessToken, OAuthRequest request) { api.getBearerSignature().signRequest(accessToken, request); } public void signRequest(OAuth2AccessToken accessToken, OAuthRequest request) { signRequest(accessToken == null ? null : accessToken.getAccessToken(), request); } /** * Returns the URL where you should redirect your users to authenticate your application. * * @return the URL where you should redirect your users */ public String getAuthorizationUrl() { return createAuthorizationUrlBuilder().build(); } public String getAuthorizationUrl(String state) { return createAuthorizationUrlBuilder() .state(state) .build(); } /** * Returns the URL where you should redirect your users to authenticate your application. * * @param additionalParams any additional GET params to add to the URL * @return the URL where you should redirect your users */ public String getAuthorizationUrl(Map<String, String> additionalParams) { return createAuthorizationUrlBuilder() .additionalParams(additionalParams) .build(); } public String getAuthorizationUrl(PKCE pkce) { return createAuthorizationUrlBuilder() .pkce(pkce) .build(); } public AuthorizationUrlBuilder createAuthorizationUrlBuilder() { return new AuthorizationUrlBuilder(this); } public DefaultApi20 getApi() { return api; } public OAuth2Authorization extractAuthorization(String redirectLocation) { final OAuth2Authorization authorization = new OAuth2Authorization(); int end = redirectLocation.indexOf('#'); if (end == -1) { end = redirectLocation.length(); } for (String param : redirectLocation.substring(redirectLocation.indexOf('?') + 1, end).split("&")) { final String[] keyValue = param.split("="); if (keyValue.length == 2) { try { switch (keyValue[0]) { case "code": authorization.setCode(URLDecoder.decode(keyValue[1], "UTF-8")); break; case "state": authorization.setState(URLDecoder.decode(keyValue[1], "UTF-8")); break; default: //just ignore any other param; } } catch (UnsupportedEncodingException ueE) { throw new IllegalStateException("jvm without UTF-8, really?", ueE); } } } return authorization; } public String getResponseType() { return responseType; } public String getDefaultScope() { return defaultScope; } protected void logRequestWithParams(String requestDescription, OAuthRequest request) { if (isDebug()) { log("created " + requestDescription + " request with body params [%s], query string params [%s]", request.getBodyParams().asFormUrlEncodedString(), request.getQueryStringParams().asFormUrlEncodedString()); } } // ===== common AccessToken request methods ===== //protected to facilitate mocking protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException, InterruptedException, ExecutionException { if (isDebug()) { log("send request for access token synchronously to %s", request.getCompleteUrl()); } try (Response response = execute(request)) { if (isDebug()) { log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getAccessTokenExtractor().extract(response); } } //protected to facilitate mocking protected Future<OAuth2AccessToken> sendAccessTokenRequestAsync(OAuthRequest request) { return sendAccessTokenRequestAsync(request, null); } //protected to facilitate mocking protected Future<OAuth2AccessToken> sendAccessTokenRequestAsync(OAuthRequest request, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { if (isDebug()) { log("send request for access token asynchronously to %s", request.getCompleteUrl()); } return execute(request, callback, new OAuthRequest.ResponseConverter<OAuth2AccessToken>() { @Override public OAuth2AccessToken convert(Response response) throws IOException { log("received response for access token"); if (isDebug()) { log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } final OAuth2AccessToken token = api.getAccessTokenExtractor().extract(response); response.close(); return token; } }); } // ===== get AccessToken authorisation code flow methods ===== protected OAuthRequest createAccessTokenRequest(AccessTokenRequestParams params) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); request.addParameter(OAuthConstants.CODE, params.getCode()); final String callback = getCallback(); if (callback != null) { request.addParameter(OAuthConstants.REDIRECT_URI, callback); } final String scope = params.getScope(); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); final String pkceCodeVerifier = params.getPkceCodeVerifier(); if (pkceCodeVerifier != null) { request.addParameter(PKCE.PKCE_CODE_VERIFIER_PARAM, pkceCodeVerifier); } final Map<String, String> extraParameters = params.getExtraParameters(); if (extraParameters != null && !extraParameters.isEmpty()) { for (Map.Entry<String, String> extraParameter : extraParameters.entrySet()) { request.addParameter(extraParameter.getKey(), extraParameter.getValue()); } } logRequestWithParams("access token", request); return request; } public Future<OAuth2AccessToken> getAccessTokenAsync(String code) { return getAccessToken(AccessTokenRequestParams.create(code), null); } public Future<OAuth2AccessToken> getAccessTokenAsync(AccessTokenRequestParams params) { return getAccessToken(params, null); } public OAuth2AccessToken getAccessToken(String code) throws IOException, InterruptedException, ExecutionException { return getAccessToken(AccessTokenRequestParams.create(code)); } public OAuth2AccessToken getAccessToken(AccessTokenRequestParams params) throws IOException, InterruptedException, ExecutionException { return sendAccessTokenRequestSync(createAccessTokenRequest(params)); } /** * Start the request to retrieve the access token. The optionally provided callback will be called with the Token * when it is available. * * @param params params * @param callback optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { return sendAccessTokenRequestAsync(createAccessTokenRequest(params), callback); } public Future<OAuth2AccessToken> getAccessToken(String code, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { return getAccessToken(AccessTokenRequestParams.create(code), callback); } // ===== refresh AccessToken methods ===== protected OAuthRequest createRefreshTokenRequest(String refreshToken, String scope) { if (refreshToken == null || refreshToken.isEmpty()) { throw new IllegalArgumentException("The refreshToken cannot be null or empty"); } final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getRefreshTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.REFRESH_TOKEN, refreshToken); request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.REFRESH_TOKEN); logRequestWithParams("refresh token", request); return request; } public Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken) { return refreshAccessToken(refreshToken, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken, String scope) { return refreshAccessToken(refreshToken, scope, null); } public OAuth2AccessToken refreshAccessToken(String refreshToken) throws IOException, InterruptedException, ExecutionException { return refreshAccessToken(refreshToken, (String) null); } public OAuth2AccessToken refreshAccessToken(String refreshToken, String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createRefreshTokenRequest(refreshToken, scope); return sendAccessTokenRequestSync(request); } public Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createRefreshTokenRequest(refreshToken, null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createRefreshTokenRequest(refreshToken, scope); return sendAccessTokenRequestAsync(request, callback); } // ===== get AccessToken password grant flow methods ===== protected OAuthRequest createAccessTokenPasswordGrantRequest(String username, String password, String scope) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addParameter(OAuthConstants.USERNAME, username); request.addParameter(OAuthConstants.PASSWORD, password); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.PASSWORD); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); logRequestWithParams("access token password grant", request); return request; } public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestSync(request); } public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password, String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, scope); return sendAccessTokenRequestSync(request); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password) { return getAccessTokenPasswordGrantAsync(username, password, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope) { return getAccessTokenPasswordGrantAsync(username, password, scope, null); } /** * Request Access Token Password Grant async version * * @param username User name * @param password User password * @param callback Optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, scope); return sendAccessTokenRequestAsync(request, callback); } // ===== get AccessToken client credentials flow methods ===== protected OAuthRequest createAccessTokenClientCredentialsGrantRequest(String scope) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.CLIENT_CREDENTIALS); logRequestWithParams("access token client credentials grant", request); return request; } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync() { return getAccessTokenClientCredentialsGrant((OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(String scope) { return getAccessTokenClientCredentialsGrant(scope, null); } public OAuth2AccessToken getAccessTokenClientCredentialsGrant() throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(null); return sendAccessTokenRequestSync(request); } public OAuth2AccessToken getAccessTokenClientCredentialsGrant(String scope) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(scope); return sendAccessTokenRequestSync(request); } /** * Start the request to retrieve the access token using client-credentials grant. The optionally provided callback * will be called with the Token when it is available. * * @param callback optional callback * @return Future */ public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant( OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(null); return sendAccessTokenRequestAsync(request, callback); } public Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(String scope, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenClientCredentialsGrantRequest(scope); return sendAccessTokenRequestAsync(request, callback); } // ===== revoke<SUF> protected OAuthRequest createRevokeTokenRequest(String tokenToRevoke, TokenTypeHint tokenTypeHint) { final OAuthRequest request = new OAuthRequest(Verb.POST, api.getRevokeTokenEndpoint()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); request.addParameter("token", tokenToRevoke); if (tokenTypeHint != null) { request.addParameter("token_type_hint", tokenTypeHint.getValue()); } logRequestWithParams("revoke token", request); return request; } public Future<Void> revokeTokenAsync(String tokenToRevoke) { return revokeTokenAsync(tokenToRevoke, null); } public Future<Void> revokeTokenAsync(String tokenToRevoke, TokenTypeHint tokenTypeHint) { return revokeToken(tokenToRevoke, null, tokenTypeHint); } public void revokeToken(String tokenToRevoke) throws IOException, InterruptedException, ExecutionException { revokeToken(tokenToRevoke, (TokenTypeHint) null); } public void revokeToken(String tokenToRevoke, TokenTypeHint tokenTypeHint) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createRevokeTokenRequest(tokenToRevoke, tokenTypeHint); try (Response response = execute(request)) { checkForErrorRevokeToken(response); } } public Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback) { return revokeToken(tokenToRevoke, callback, null); } public Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback, TokenTypeHint tokenTypeHint) { final OAuthRequest request = createRevokeTokenRequest(tokenToRevoke, tokenTypeHint); return execute(request, callback, new OAuthRequest.ResponseConverter<Void>() { @Override public Void convert(Response response) throws IOException { checkForErrorRevokeToken(response); response.close(); return null; } }); } private void checkForErrorRevokeToken(Response response) throws IOException { if (response.getCode() != 200) { OAuth2AccessTokenJsonExtractor.instance().generateError(response); } } // ===== device Authorisation codes methods ===== protected OAuthRequest createDeviceAuthorizationCodesRequest(String scope) { final OAuthRequest request = new OAuthRequest(Verb.POST, api.getDeviceAuthorizationEndpoint()); request.addParameter(OAuthConstants.CLIENT_ID, getApiKey()); if (scope != null) { request.addParameter(OAuthConstants.SCOPE, scope); } else if (defaultScope != null) { request.addParameter(OAuthConstants.SCOPE, defaultScope); } logRequestWithParams("Device Authorization Codes", request); return request; } /** * Requests a set of verification codes from the authorization server with the default scope * * @see <a href="https://tools.ietf.org/html/rfc8628#section-3.1">RFC 8628</a> * * @return DeviceAuthorization * @throws InterruptedException InterruptedException * @throws ExecutionException ExecutionException * @throws IOException IOException */ public DeviceAuthorization getDeviceAuthorizationCodes() throws InterruptedException, ExecutionException, IOException { return getDeviceAuthorizationCodes((String) null); } /** * Requests a set of verification codes from the authorization server * * @see <a href="https://tools.ietf.org/html/rfc8628#section-3.1">RFC 8628</a> * * @param scope scope * @return DeviceAuthorization * @throws InterruptedException InterruptedException * @throws ExecutionException ExecutionException * @throws IOException IOException */ public DeviceAuthorization getDeviceAuthorizationCodes(String scope) throws InterruptedException, ExecutionException, IOException { final OAuthRequest request = createDeviceAuthorizationCodesRequest(scope); try (Response response = execute(request)) { if (isDebug()) { log("got DeviceAuthorizationCodes response"); log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getDeviceAuthorizationExtractor().extract(response); } } public Future<DeviceAuthorization> getDeviceAuthorizationCodes( OAuthAsyncRequestCallback<DeviceAuthorization> callback) { return getDeviceAuthorizationCodes(null, callback); } public Future<DeviceAuthorization> getDeviceAuthorizationCodes(String scope, OAuthAsyncRequestCallback<DeviceAuthorization> callback) { final OAuthRequest request = createDeviceAuthorizationCodesRequest(scope); return execute(request, callback, new OAuthRequest.ResponseConverter<DeviceAuthorization>() { @Override public DeviceAuthorization convert(Response response) throws IOException { final DeviceAuthorization deviceAuthorization = api.getDeviceAuthorizationExtractor().extract(response); response.close(); return deviceAuthorization; } }); } public Future<DeviceAuthorization> getDeviceAuthorizationCodesAsync() { return getDeviceAuthorizationCodesAsync(null); } public Future<DeviceAuthorization> getDeviceAuthorizationCodesAsync(String scope) { return getDeviceAuthorizationCodes(scope, null); } // ===== get AccessToken Device Authorisation grant flow methods ===== protected OAuthRequest createAccessTokenDeviceAuthorizationGrantRequest(DeviceAuthorization deviceAuthorization) { final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addParameter(OAuthConstants.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:device_code"); request.addParameter("device_code", deviceAuthorization.getDeviceCode()); api.getClientAuthentication().addClientAuthentication(request, getApiKey(), getApiSecret()); return request; } /** * Attempts to get a token from a server. * * Function {@link #pollAccessTokenDeviceAuthorizationGrant(com.github.scribejava.core.model.DeviceAuthorization)} * is usually used instead of this. * * @param deviceAuthorization deviceAuthorization * @return token * * @throws java.lang.InterruptedException InterruptedException * @throws java.util.concurrent.ExecutionException ExecutionException * @throws java.io.IOException IOException * @throws OAuth2AccessTokenErrorResponse If {@link OAuth2AccessTokenErrorResponse#getError()} is * {@link com.github.scribejava.core.oauth2.OAuth2Error#AUTHORIZATION_PENDING} or * {@link com.github.scribejava.core.oauth2.OAuth2Error#SLOW_DOWN}, another attempt should be made after a while. * * @see #getDeviceAuthorizationCodes() */ public OAuth2AccessToken getAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization) throws InterruptedException, ExecutionException, IOException { final OAuthRequest request = createAccessTokenDeviceAuthorizationGrantRequest(deviceAuthorization); try (Response response = execute(request)) { if (isDebug()) { log("got AccessTokenDeviceAuthorizationGrant response"); log("response status code: %s", response.getCode()); log("response body: %s", response.getBody()); } return api.getAccessTokenExtractor().extract(response); } } public Future<OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization, OAuthAsyncRequestCallback<OAuth2AccessToken> callback) { final OAuthRequest request = createAccessTokenDeviceAuthorizationGrantRequest(deviceAuthorization); return execute(request, callback, new OAuthRequest.ResponseConverter<OAuth2AccessToken>() { @Override public OAuth2AccessToken convert(Response response) throws IOException { final OAuth2AccessToken accessToken = api.getAccessTokenExtractor().extract(response); response.close(); return accessToken; } }); } public Future<OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrantAsync( DeviceAuthorization deviceAuthorization) { return getAccessTokenDeviceAuthorizationGrant(deviceAuthorization, null); } /** * Periodically tries to get a token from a server (waiting for the user to give consent). Sync only version. No * Async variants yet, one should implement async scenarios themselves. * * @param deviceAuthorization deviceAuthorization * @return token * @throws java.lang.InterruptedException InterruptedException * @throws java.util.concurrent.ExecutionException ExecutionException * @throws java.io.IOException IOException * @throws OAuth2AccessTokenErrorResponse Indicates OAuth error. * * @see #getDeviceAuthorizationCodes() */ public OAuth2AccessToken pollAccessTokenDeviceAuthorizationGrant(DeviceAuthorization deviceAuthorization) throws InterruptedException, ExecutionException, IOException { long intervalMillis = deviceAuthorization.getIntervalSeconds() * 1000; while (true) { try { return getAccessTokenDeviceAuthorizationGrant(deviceAuthorization); } catch (OAuth2AccessTokenErrorResponse e) { if (e.getError() != OAuth2Error.AUTHORIZATION_PENDING) { if (e.getError() == OAuth2Error.SLOW_DOWN) { intervalMillis += 5000; } else { throw e; } } } Thread.sleep(intervalMillis); } } }
185912_12
/* * Copyright (c) 2012, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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.github.sdbg.debug.core.internal.webkit.protocol; import com.github.sdbg.debug.core.internal.webkit.protocol.WebkitConnection.NotificationHandler; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; // TODO(devoncarew): review and add new css methods to this file /** * A WIP css domain object. * <p> * This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles) * have an associated <code>id</code> used in subsequent operations on the related object. Each * object type has a specific <code>id</code> structure, and those are not interchangeable between * objects of different kinds. CSS objects can be loaded using the <code>get*ForNode()</code> calls * (which accept a DOM node id). A client can also discover all the existing stylesheets with the * <code>getAllStyleSheets()</code> method (or keeping track of the <code>styleSheetAdded</code>/ * <code>styleSheetRemoved</code> events) and subsequently load the required stylesheet contents * using the <code>getStyleSheet[Text]()</code> methods. */ @WebkitUnsupported public class WebkitCSS extends WebkitDomain { public static interface CSSListener { /** * Fires whenever a MediaQuery result changes (for example, after a browser window has been * resized.) The current implementation considers only viewport-dependent media features. */ public void mediaQueryResultChanged(); /** * Called when the given style sheet changes. * * @param styleSheet */ public void styleSheetAdded(WebkitStyleSheetRef styleSheet); /** * Called when the given style sheet changes. * * @param styleSheetId */ public void styleSheetChanged(String styleSheetId); /** * Called when the given style sheet is removed. * * @param styleSheetId */ public void styleSheetRemoved(String styleSheetId); } private static final String STYLE_SHEET_ADDED = "CSS.styleSheetAdded"; private static final String STYLE_SHEET_CHANGED = "CSS.styleSheetChanged"; private static final String STYLE_SHEET_REMOVED = "CSS.styleSheetRemoved"; private static final String MEDIA_QUERY_RESULT_CHANGED = "CSS.mediaQueryResultChanged"; private List<CSSListener> listeners = new ArrayList<WebkitCSS.CSSListener>(); private List<WebkitStyleSheetRef> styleSheets = Collections.synchronizedList(new ArrayList<WebkitStyleSheetRef>()); /** * @param connection */ public WebkitCSS(WebkitConnection connection) { super(connection); connection.registerNotificationHandler("CSS.", new NotificationHandler() { @Override public void handleNotification(String method, JSONObject params) throws JSONException { handleCssNotification(method, params); } }); } public void addCSSListener(CSSListener listener) { listeners.add(listener); } public void disable() throws IOException { sendSimpleCommand("CSS.disable"); } public void enable() throws IOException { sendSimpleCommand("CSS.enable"); } public void getStyleSheet(String styleSheetId, final WebkitCallback<WebkitStyleSheet> callback) throws IOException { // "result":{ // "styleSheet":{ // "text":"h1 { font-size: 10pt }", // "styleSheetId":"1", // "rules":[ // { // "sourceLine":3, // "style":{ ... }, // "sourceURL":"http://0.0.0.0:3030/Users/dcarew/projects/dart/dart/samples/clock/Clock.html", // "selectorText":"h1", // "ruleId":{ // "ordinal":0, // "styleSheetId":"1" // }, // "origin":"regular", // "selectorRange":{ // "start":0, // "end":2 // } // } // ] // } // } // "result":{"styleSheet":{"text":"h2 {\n font-size: 8pt;\n}\n","styleSheetId":"2","rules" : // [{"sourceLine":0,"style":{"styleId":{"ordinal":0,"styleSheetId":"2"},"height":"","range":{"start" : // 4,"end":23},"width":"","cssText":"\n font-size: 8pt;\n","shorthandEntries":[],"cssProperties" : // [{"text":"font-size: 8pt;","range":{"start":3,"end":18},"status":"active","name":"font-size", // "implicit":false,"value":"8pt"}]},"sourceURL": // "http://0.0.0.0:3030/Users/foo/projects/dart/dart/samples/clock/clockstyle.css" // ,"selectorText":"h2","ruleId":{"ordinal":0,"styleSheetId":"2"},"origin":"regular","selectorRange" // :{"start":0,"end":2}}]}} try { JSONObject request = new JSONObject(); request.put("method", "CSS.getStyleSheet"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId)); connection.sendRequest(request, new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetStyleSheetResult(result)); } }); } catch (JSONException exception) { throw new IOException(exception); } } public List<WebkitStyleSheetRef> getStyleSheets() { return styleSheets; } public void getStyleSheetText(String styleSheetId, final WebkitCallback<String> callback) throws IOException { try { JSONObject request = new JSONObject(); request.put("method", "CSS.getStyleSheetText"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId)); connection.sendRequest(request, new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetStyleSheetTextResult(result)); } }); } catch (JSONException exception) { throw new IOException(exception); } } public void getSupportedCSSProperties(final WebkitCallback<String[]> callback) throws IOException { sendSimpleCommand("CSS.getSupportedCSSProperties", new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetSupportedPropertiesResult(result)); } }); } public void removeCSSListener(CSSListener listener) { listeners.remove(listener); } public void setStyleSheetText(String styleSheetId, String text) throws IOException { try { JSONObject request = new JSONObject(); request.put("method", "CSS.setStyleSheetText"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId).put("text", text)); connection.sendRequest(request); } catch (JSONException exception) { throw new IOException(exception); } } protected void handleCssNotification(String method, JSONObject params) throws JSONException { if (method.equals(STYLE_SHEET_ADDED)) { // {"method":"CSS.styleSheetAdded","params":{"header":{"title":"","frameId":"69818.1", // "sourceURL":"http://127.0.0.1:3030/Users/devoncarew/dart/todomvc-47/web/out/index.html", // "origin":"regular","styleSheetId":"7","disabled":false}}} WebkitStyleSheetRef styleSheet = WebkitStyleSheetRef.createFrom(params.getJSONObject("header")); styleSheets.add(styleSheet); //String styleSheetId = params.getJSONObject("header").getString("styleSheetId"); for (CSSListener listener : listeners) { listener.styleSheetAdded(styleSheet); } } else if (method.equals(STYLE_SHEET_CHANGED)) { String styleSheetId = params.getString("styleSheetId"); for (CSSListener listener : listeners) { listener.styleSheetChanged(styleSheetId); } } else if (method.equals(STYLE_SHEET_REMOVED)) { String styleSheetId = params.getString("styleSheetId"); for (CSSListener listener : listeners) { listener.styleSheetRemoved(styleSheetId); } } else if (method.equals(MEDIA_QUERY_RESULT_CHANGED)) { for (CSSListener listener : listeners) { listener.mediaQueryResultChanged(); } } else { WIPTrace.trace("unhandled notification: " + method); } } void frameStartedLoading() { // Clear out our cached style sheet information. styleSheets.clear(); } private WebkitResult<WebkitStyleSheet> convertGetStyleSheetResult(JSONObject object) throws JSONException { WebkitResult<WebkitStyleSheet> result = WebkitResult.createFrom(object); if (object.has("result")) { result.setResult(WebkitStyleSheet.createFrom(object.getJSONObject("result").getJSONObject( "styleSheet"))); } return result; } private WebkitResult<String> convertGetStyleSheetTextResult(JSONObject object) throws JSONException { WebkitResult<String> result = WebkitResult.createFrom(object); // "result":{"text":"h1 { font-size: 10pt }"} if (object.has("result")) { JSONObject obj = object.getJSONObject("result"); result.setResult(obj.getString("text")); } return result; } private WebkitResult<String[]> convertGetSupportedPropertiesResult(JSONObject object) throws JSONException { WebkitResult<String[]> result = WebkitResult.createFrom(object); // "result": { // "cssProperties": [ "color","direction","display","font","font-family", // "font-size","font-style","font-variant","font-weight","text-rendering","-webkit-font-feature-settings" ... // ] // } if (object.has("result")) { JSONObject obj = object.getJSONObject("result"); JSONArray arr = obj.getJSONArray("cssProperties"); String[] properties = new String[arr.length()]; for (int i = 0; i < properties.length; i++) { properties[i] = arr.getString(i); } result.setResult(properties); } return result; } }
sdbg/sdbg
com.github.sdbg.debug.core/src/com/github/sdbg/debug/core/internal/webkit/protocol/WebkitCSS.java
3,135
//String styleSheetId = params.getJSONObject("header").getString("styleSheetId");
line_comment
nl
/* * Copyright (c) 2012, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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.github.sdbg.debug.core.internal.webkit.protocol; import com.github.sdbg.debug.core.internal.webkit.protocol.WebkitConnection.NotificationHandler; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; // TODO(devoncarew): review and add new css methods to this file /** * A WIP css domain object. * <p> * This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles) * have an associated <code>id</code> used in subsequent operations on the related object. Each * object type has a specific <code>id</code> structure, and those are not interchangeable between * objects of different kinds. CSS objects can be loaded using the <code>get*ForNode()</code> calls * (which accept a DOM node id). A client can also discover all the existing stylesheets with the * <code>getAllStyleSheets()</code> method (or keeping track of the <code>styleSheetAdded</code>/ * <code>styleSheetRemoved</code> events) and subsequently load the required stylesheet contents * using the <code>getStyleSheet[Text]()</code> methods. */ @WebkitUnsupported public class WebkitCSS extends WebkitDomain { public static interface CSSListener { /** * Fires whenever a MediaQuery result changes (for example, after a browser window has been * resized.) The current implementation considers only viewport-dependent media features. */ public void mediaQueryResultChanged(); /** * Called when the given style sheet changes. * * @param styleSheet */ public void styleSheetAdded(WebkitStyleSheetRef styleSheet); /** * Called when the given style sheet changes. * * @param styleSheetId */ public void styleSheetChanged(String styleSheetId); /** * Called when the given style sheet is removed. * * @param styleSheetId */ public void styleSheetRemoved(String styleSheetId); } private static final String STYLE_SHEET_ADDED = "CSS.styleSheetAdded"; private static final String STYLE_SHEET_CHANGED = "CSS.styleSheetChanged"; private static final String STYLE_SHEET_REMOVED = "CSS.styleSheetRemoved"; private static final String MEDIA_QUERY_RESULT_CHANGED = "CSS.mediaQueryResultChanged"; private List<CSSListener> listeners = new ArrayList<WebkitCSS.CSSListener>(); private List<WebkitStyleSheetRef> styleSheets = Collections.synchronizedList(new ArrayList<WebkitStyleSheetRef>()); /** * @param connection */ public WebkitCSS(WebkitConnection connection) { super(connection); connection.registerNotificationHandler("CSS.", new NotificationHandler() { @Override public void handleNotification(String method, JSONObject params) throws JSONException { handleCssNotification(method, params); } }); } public void addCSSListener(CSSListener listener) { listeners.add(listener); } public void disable() throws IOException { sendSimpleCommand("CSS.disable"); } public void enable() throws IOException { sendSimpleCommand("CSS.enable"); } public void getStyleSheet(String styleSheetId, final WebkitCallback<WebkitStyleSheet> callback) throws IOException { // "result":{ // "styleSheet":{ // "text":"h1 { font-size: 10pt }", // "styleSheetId":"1", // "rules":[ // { // "sourceLine":3, // "style":{ ... }, // "sourceURL":"http://0.0.0.0:3030/Users/dcarew/projects/dart/dart/samples/clock/Clock.html", // "selectorText":"h1", // "ruleId":{ // "ordinal":0, // "styleSheetId":"1" // }, // "origin":"regular", // "selectorRange":{ // "start":0, // "end":2 // } // } // ] // } // } // "result":{"styleSheet":{"text":"h2 {\n font-size: 8pt;\n}\n","styleSheetId":"2","rules" : // [{"sourceLine":0,"style":{"styleId":{"ordinal":0,"styleSheetId":"2"},"height":"","range":{"start" : // 4,"end":23},"width":"","cssText":"\n font-size: 8pt;\n","shorthandEntries":[],"cssProperties" : // [{"text":"font-size: 8pt;","range":{"start":3,"end":18},"status":"active","name":"font-size", // "implicit":false,"value":"8pt"}]},"sourceURL": // "http://0.0.0.0:3030/Users/foo/projects/dart/dart/samples/clock/clockstyle.css" // ,"selectorText":"h2","ruleId":{"ordinal":0,"styleSheetId":"2"},"origin":"regular","selectorRange" // :{"start":0,"end":2}}]}} try { JSONObject request = new JSONObject(); request.put("method", "CSS.getStyleSheet"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId)); connection.sendRequest(request, new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetStyleSheetResult(result)); } }); } catch (JSONException exception) { throw new IOException(exception); } } public List<WebkitStyleSheetRef> getStyleSheets() { return styleSheets; } public void getStyleSheetText(String styleSheetId, final WebkitCallback<String> callback) throws IOException { try { JSONObject request = new JSONObject(); request.put("method", "CSS.getStyleSheetText"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId)); connection.sendRequest(request, new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetStyleSheetTextResult(result)); } }); } catch (JSONException exception) { throw new IOException(exception); } } public void getSupportedCSSProperties(final WebkitCallback<String[]> callback) throws IOException { sendSimpleCommand("CSS.getSupportedCSSProperties", new WebkitConnection.Callback() { @Override public void handleResult(JSONObject result) throws JSONException { callback.handleResult(convertGetSupportedPropertiesResult(result)); } }); } public void removeCSSListener(CSSListener listener) { listeners.remove(listener); } public void setStyleSheetText(String styleSheetId, String text) throws IOException { try { JSONObject request = new JSONObject(); request.put("method", "CSS.setStyleSheetText"); request.put("params", new JSONObject().put("styleSheetId", styleSheetId).put("text", text)); connection.sendRequest(request); } catch (JSONException exception) { throw new IOException(exception); } } protected void handleCssNotification(String method, JSONObject params) throws JSONException { if (method.equals(STYLE_SHEET_ADDED)) { // {"method":"CSS.styleSheetAdded","params":{"header":{"title":"","frameId":"69818.1", // "sourceURL":"http://127.0.0.1:3030/Users/devoncarew/dart/todomvc-47/web/out/index.html", // "origin":"regular","styleSheetId":"7","disabled":false}}} WebkitStyleSheetRef styleSheet = WebkitStyleSheetRef.createFrom(params.getJSONObject("header")); styleSheets.add(styleSheet); //String styleSheetId<SUF> for (CSSListener listener : listeners) { listener.styleSheetAdded(styleSheet); } } else if (method.equals(STYLE_SHEET_CHANGED)) { String styleSheetId = params.getString("styleSheetId"); for (CSSListener listener : listeners) { listener.styleSheetChanged(styleSheetId); } } else if (method.equals(STYLE_SHEET_REMOVED)) { String styleSheetId = params.getString("styleSheetId"); for (CSSListener listener : listeners) { listener.styleSheetRemoved(styleSheetId); } } else if (method.equals(MEDIA_QUERY_RESULT_CHANGED)) { for (CSSListener listener : listeners) { listener.mediaQueryResultChanged(); } } else { WIPTrace.trace("unhandled notification: " + method); } } void frameStartedLoading() { // Clear out our cached style sheet information. styleSheets.clear(); } private WebkitResult<WebkitStyleSheet> convertGetStyleSheetResult(JSONObject object) throws JSONException { WebkitResult<WebkitStyleSheet> result = WebkitResult.createFrom(object); if (object.has("result")) { result.setResult(WebkitStyleSheet.createFrom(object.getJSONObject("result").getJSONObject( "styleSheet"))); } return result; } private WebkitResult<String> convertGetStyleSheetTextResult(JSONObject object) throws JSONException { WebkitResult<String> result = WebkitResult.createFrom(object); // "result":{"text":"h1 { font-size: 10pt }"} if (object.has("result")) { JSONObject obj = object.getJSONObject("result"); result.setResult(obj.getString("text")); } return result; } private WebkitResult<String[]> convertGetSupportedPropertiesResult(JSONObject object) throws JSONException { WebkitResult<String[]> result = WebkitResult.createFrom(object); // "result": { // "cssProperties": [ "color","direction","display","font","font-family", // "font-size","font-style","font-variant","font-weight","text-rendering","-webkit-font-feature-settings" ... // ] // } if (object.has("result")) { JSONObject obj = object.getJSONObject("result"); JSONArray arr = obj.getJSONArray("cssProperties"); String[] properties = new String[arr.length()]; for (int i = 0; i < properties.length; i++) { properties[i] = arr.getString(i); } result.setResult(properties); } return result; } }
115352_80
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package argus.model; import java.util.Arrays; import java.util.Objects; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; public class Variable implements Cloneable { private static final Logger logger = Logger.getLogger(Variable.class.getName()); //private TauArgus tauArgus = Application.getTauArgusDll(); // Determines lengths of fixed sized arrays being used public static final int MAX_NUMBER_OF_MISSINGS = 2; public static final int MAX_NUMBER_OF_REQUESTS = 2; public static final int MAX_NUMBER_OF_DIST = 5; public static final int MAX_NUMBER_OF_HIER_LEVELS = 10; // Possible values for variable hierarchical; public static final int HIER_NONE = 0; public static final int HIER_LEVELS = 1; public static final int HIER_FILE = 2; public int index; // index for interfacing with TauArgus dll public Metadata metadata = null; public Variable originalVariable; public String name = ""; public Type type; public int bPos = 1; // Only used if data file type is fixed format public int varLen; public int nDecimals; // Only used if hasDecimals() returns true // Only used by variables of type 'Categorical' public String[] missing; public String totCode = ""; public boolean hasDistanceFunction; public int[] distanceFunction; public String codeListFile = ""; public int hierarchical; public int hierLevelsSum; public int[] hierLevels; public String hierFileName = ""; public String leadingString = "."; // Only used by variables of type 'Request' public String[] requestCode; // Only used in case of a recoded variable of type 'Categorical' public boolean recoded; public String currentRecodeFile = ""; public String currentRecodeCodeListFile = ""; public boolean inTable; public boolean truncatable; public int truncLevels; public Variable(Metadata metadata) { this.metadata = metadata; this.originalVariable = this; } public boolean isNumeric() { return type.isNumeric(); } public boolean hasDecimals() { return type.hasDecimals(); } public boolean isCategorical() { return type.isCategorical(); } public boolean isResponse() { return type.isResponse(); } public boolean isTotalCode(String code) { return code.equalsIgnoreCase(totCode); } public boolean isTotalCode2(String code) { return code.trim().equals(totCode) || code.trim().equals(""); } public boolean isMissing(String code) { for (int m = 0; m < Variable.MAX_NUMBER_OF_MISSINGS; m++) { if (StringUtils.isNotEmpty(missing[m]) && code.equals(missing[m])) { return true; } } return false; } public String getTotalCode() { if (totCode.equals("")) { return "Total"; } else { return totCode; } } public int numberOfMissings() { int nMissings = 0; if (isCategorical()) { while (nMissings < MAX_NUMBER_OF_MISSINGS && StringUtils.isNotEmpty(missing[nMissings])) { nMissings++; } } return nMissings; } public String normaliseMissing(String missing) { if (StringUtils.isBlank(missing)) { missing = ""; } else { missing = padCode(missing); } return missing; } public String normaliseCode(String code) { if (StringUtils.isNotEmpty(code) && hierarchical == HIER_NONE) { code = padCode(code); } return code; } public String padCode(String code) { return StringUtils.leftPad(code, varLen); } // public RecodeInfo readRecodeFile(String fileName) throws ArgusException, FileNotFoundException, IOException { // String recodeData = ""; // String missing1 = ""; // String missing2 = ""; // String codeList = ""; //// Anco 1.6 try with recources //// try (BufferedReader reader = new BufferedReader(new FileReader(fileName));) { // BufferedReader reader = null; // try {reader = new BufferedReader(new FileReader(fileName)); // Tokenizer tokenizer = new Tokenizer(reader); // while ((tokenizer.nextLine()) != null) { // String hs; // String token = tokenizer.nextToken(); // hs = tokenizer.getLine(); // if (token.equals("<MISSING>")) { // missing1 = tokenizer.nextToken(); // if (missing1.equals("")) { // throw new ArgusException("No Missing Values found after <MISSING>"); // } // token = tokenizer.nextToken(); // if (token.equals(",")) { // token = tokenizer.nextToken(); // } // missing2 = token; // } else if (token.equals("<CODELIST>")) { // codeList = tokenizer.nextToken(); // } else if (!token.equals("")) { // recodeData = recodeData + hs + "\n"; //// recodeData = recodeData + token + "\n"; // } // } // return new RecodeInfo(recodeData, missing1, missing2, codeList); // } // finally {reader.close();} // } // // public void writeRecodeFile(String fileName, RecodeInfo recodeInfo) throws IOException { //// anco 1.6 try with resources //// try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));) { // BufferedWriter writer = null; // try {writer = new BufferedWriter(new FileWriter(fileName)); // if (!recodeInfo.getMissing1().equals("") || !recodeInfo.getMissing2().equals("")) { // writer.write("<MISSING> " + recodeInfo.getMissing1() + " " + recodeInfo.getMissing2() + "\n"); // } // if (!recodeInfo.getCodeList().equals("")) { // writer.write("<CODELIST> " + recodeInfo.getCodeList() + "\n"); // } // writer.write(recodeInfo.getRecodeData() + "\n"); // } // finally {writer.close();} // } // // public void recode(RecodeInfo recodeInfo) throws ArgusException { // int nMissing = 0; String hs; // if (StringUtils.isNotBlank(recodeInfo.getMissing1())) { // nMissing = 1; // } // if (StringUtils.isNotBlank(recodeInfo.getMissing2())) { // nMissing = 2; // } // // int[] errorType = new int[1]; // int[] errorLine = new int[1]; // int[] errorPos = new int[1]; // String[] warning = new String[1]; ////The end of lines in the recode string cause a problem // hs = recodeInfo.getRecodeData(); //// hs = hs.replace("\n\r", "\n"); //// hs = hs.replace("\n", "\n\r"); //// hs = hs + "\n\r"; // if (tauArgus.DoRecode(index, hs, nMissing, recodeInfo.getMissing1(), recodeInfo.getMissing2(), errorType, errorLine, errorPos, warning)) { // currentRecodeCodeListFile = recodeInfo.getCodeList(); // recoded = true; // truncLevels = 0; // logger.info("Recode: variable (" + name + ") has been recoded"); // } else { // throw new ArgusException(tauArgus.GetErrorString(errorType[0]) + " " + warning[0] + " in recoding; line " + errorLine[0] + " pos " + errorPos[0]); // } // } // // public void applyRecodeTree(String fileName) throws ArgusException { ////Anco 1.6 try with resources ////overigens wordt de reader niet gesloten ??????? //// try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { // BufferedReader reader = null; // try {reader = new BufferedReader(new FileReader(new File(fileName))); // tauArgus.UndoRecode(index); // String regel = reader.readLine(); // if (!StringUtils.equals(regel, "<TREERECODE>")) { // throw new ArgusException("First line does not start with \"<TREERECODE>\""); // } // while ((regel = reader.readLine()) != null) { // if (StringUtils.isNotBlank(regel)) { // int codeIndex = TauArgusUtils.getCodeIndex(index, regel); // if (codeIndex == -1) { // throw new ArgusException("Code (" + regel + ") not found"); // } // tauArgus.SetVarCodeActive(index, codeIndex, false); // } // } // tauArgus.DoActiveRecode(index); // } // catch (Exception ex) { // // tauArgus.UndoRecode(index); // throw new ArgusException("Error in reading tree status in recode file " + fileName + ": " + ex.getMessage()); // } // } // // public void recode(String fileName) throws ArgusException, FileNotFoundException, IOException { // if (hierarchical != HIER_NONE) { // applyRecodeTree(fileName); // logger.info("Variable (" + name + ") recoded.\nRecode file used:" + fileName); // } else { // RecodeInfo recodeInfo = readRecodeFile(fileName); // recode(recodeInfo); // currentRecodeFile = fileName; // } // } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } final Variable variable = (Variable) obj; boolean equal = name.equals(variable.name) && type == variable.type && bPos == variable.bPos && varLen == variable.varLen; // && truncatable == variable.truncatable // only needed fot MuArgus if (variable.isCategorical()) { equal = equal && totCode.equals(variable.totCode) && Arrays.equals(missing, variable.missing) && hasDistanceFunction == variable.hasDistanceFunction && (!hasDistanceFunction || Arrays.equals(distanceFunction, variable.distanceFunction)) && codeListFile.equals(variable.codeListFile) && hierarchical == variable.hierarchical && (hierarchical != Variable.HIER_LEVELS || (hierLevelsSum == variable.hierLevelsSum && Arrays.equals(hierLevels, variable.hierLevels))) && (hierarchical != Variable.HIER_FILE || (leadingString.equals(variable.leadingString) && hierFileName.equals(variable.hierFileName))); } if (variable.hasDecimals()) { equal = equal && nDecimals == variable.nDecimals; } if (variable.type == Type.REQUEST) { equal = equal && Arrays.equals(requestCode, variable.requestCode); } return equal; } @Override public int hashCode() { int hash = 5; hash = 89 * hash + Objects.hashCode(this.name); hash = 89 * hash + Objects.hashCode(this.type); hash = 89 * hash + this.bPos; hash = 89 * hash + this.varLen; hash = 89 * hash + this.nDecimals; hash = 89 * hash + Arrays.deepHashCode(this.requestCode); hash = 89 * hash + (this.hasDistanceFunction ? 1 : 0); hash = 89 * hash + Arrays.hashCode(this.distanceFunction); hash = 89 * hash + this.hierarchical; hash = 89 * hash + Objects.hashCode(this.hierFileName); hash = 89 * hash + this.hierLevelsSum; hash = 89 * hash + Arrays.hashCode(this.hierLevels); hash = 89 * hash + Objects.hashCode(this.codeListFile); hash = 89 * hash + Objects.hashCode(this.leadingString); hash = 89 * hash + Arrays.deepHashCode(this.missing); hash = 89 * hash + Objects.hashCode(this.totCode); return hash; } @Override public Object clone() throws CloneNotSupportedException { Variable variable = (Variable)super.clone(); if (requestCode != null) { variable.requestCode = (String[])requestCode.clone(); } if (distanceFunction != null) { variable.distanceFunction = (int[])distanceFunction.clone(); } if (hierLevels != null) { variable.hierLevels = (int[])hierLevels.clone(); } if (missing != null) { variable.missing = (String[])missing.clone(); } variable.originalVariable = this; return variable; } }
sdcTools/arguslibrary
src/argus/model/Variable.java
3,865
// int codeIndex = TauArgusUtils.getCodeIndex(index, regel);
line_comment
nl
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package argus.model; import java.util.Arrays; import java.util.Objects; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; public class Variable implements Cloneable { private static final Logger logger = Logger.getLogger(Variable.class.getName()); //private TauArgus tauArgus = Application.getTauArgusDll(); // Determines lengths of fixed sized arrays being used public static final int MAX_NUMBER_OF_MISSINGS = 2; public static final int MAX_NUMBER_OF_REQUESTS = 2; public static final int MAX_NUMBER_OF_DIST = 5; public static final int MAX_NUMBER_OF_HIER_LEVELS = 10; // Possible values for variable hierarchical; public static final int HIER_NONE = 0; public static final int HIER_LEVELS = 1; public static final int HIER_FILE = 2; public int index; // index for interfacing with TauArgus dll public Metadata metadata = null; public Variable originalVariable; public String name = ""; public Type type; public int bPos = 1; // Only used if data file type is fixed format public int varLen; public int nDecimals; // Only used if hasDecimals() returns true // Only used by variables of type 'Categorical' public String[] missing; public String totCode = ""; public boolean hasDistanceFunction; public int[] distanceFunction; public String codeListFile = ""; public int hierarchical; public int hierLevelsSum; public int[] hierLevels; public String hierFileName = ""; public String leadingString = "."; // Only used by variables of type 'Request' public String[] requestCode; // Only used in case of a recoded variable of type 'Categorical' public boolean recoded; public String currentRecodeFile = ""; public String currentRecodeCodeListFile = ""; public boolean inTable; public boolean truncatable; public int truncLevels; public Variable(Metadata metadata) { this.metadata = metadata; this.originalVariable = this; } public boolean isNumeric() { return type.isNumeric(); } public boolean hasDecimals() { return type.hasDecimals(); } public boolean isCategorical() { return type.isCategorical(); } public boolean isResponse() { return type.isResponse(); } public boolean isTotalCode(String code) { return code.equalsIgnoreCase(totCode); } public boolean isTotalCode2(String code) { return code.trim().equals(totCode) || code.trim().equals(""); } public boolean isMissing(String code) { for (int m = 0; m < Variable.MAX_NUMBER_OF_MISSINGS; m++) { if (StringUtils.isNotEmpty(missing[m]) && code.equals(missing[m])) { return true; } } return false; } public String getTotalCode() { if (totCode.equals("")) { return "Total"; } else { return totCode; } } public int numberOfMissings() { int nMissings = 0; if (isCategorical()) { while (nMissings < MAX_NUMBER_OF_MISSINGS && StringUtils.isNotEmpty(missing[nMissings])) { nMissings++; } } return nMissings; } public String normaliseMissing(String missing) { if (StringUtils.isBlank(missing)) { missing = ""; } else { missing = padCode(missing); } return missing; } public String normaliseCode(String code) { if (StringUtils.isNotEmpty(code) && hierarchical == HIER_NONE) { code = padCode(code); } return code; } public String padCode(String code) { return StringUtils.leftPad(code, varLen); } // public RecodeInfo readRecodeFile(String fileName) throws ArgusException, FileNotFoundException, IOException { // String recodeData = ""; // String missing1 = ""; // String missing2 = ""; // String codeList = ""; //// Anco 1.6 try with recources //// try (BufferedReader reader = new BufferedReader(new FileReader(fileName));) { // BufferedReader reader = null; // try {reader = new BufferedReader(new FileReader(fileName)); // Tokenizer tokenizer = new Tokenizer(reader); // while ((tokenizer.nextLine()) != null) { // String hs; // String token = tokenizer.nextToken(); // hs = tokenizer.getLine(); // if (token.equals("<MISSING>")) { // missing1 = tokenizer.nextToken(); // if (missing1.equals("")) { // throw new ArgusException("No Missing Values found after <MISSING>"); // } // token = tokenizer.nextToken(); // if (token.equals(",")) { // token = tokenizer.nextToken(); // } // missing2 = token; // } else if (token.equals("<CODELIST>")) { // codeList = tokenizer.nextToken(); // } else if (!token.equals("")) { // recodeData = recodeData + hs + "\n"; //// recodeData = recodeData + token + "\n"; // } // } // return new RecodeInfo(recodeData, missing1, missing2, codeList); // } // finally {reader.close();} // } // // public void writeRecodeFile(String fileName, RecodeInfo recodeInfo) throws IOException { //// anco 1.6 try with resources //// try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));) { // BufferedWriter writer = null; // try {writer = new BufferedWriter(new FileWriter(fileName)); // if (!recodeInfo.getMissing1().equals("") || !recodeInfo.getMissing2().equals("")) { // writer.write("<MISSING> " + recodeInfo.getMissing1() + " " + recodeInfo.getMissing2() + "\n"); // } // if (!recodeInfo.getCodeList().equals("")) { // writer.write("<CODELIST> " + recodeInfo.getCodeList() + "\n"); // } // writer.write(recodeInfo.getRecodeData() + "\n"); // } // finally {writer.close();} // } // // public void recode(RecodeInfo recodeInfo) throws ArgusException { // int nMissing = 0; String hs; // if (StringUtils.isNotBlank(recodeInfo.getMissing1())) { // nMissing = 1; // } // if (StringUtils.isNotBlank(recodeInfo.getMissing2())) { // nMissing = 2; // } // // int[] errorType = new int[1]; // int[] errorLine = new int[1]; // int[] errorPos = new int[1]; // String[] warning = new String[1]; ////The end of lines in the recode string cause a problem // hs = recodeInfo.getRecodeData(); //// hs = hs.replace("\n\r", "\n"); //// hs = hs.replace("\n", "\n\r"); //// hs = hs + "\n\r"; // if (tauArgus.DoRecode(index, hs, nMissing, recodeInfo.getMissing1(), recodeInfo.getMissing2(), errorType, errorLine, errorPos, warning)) { // currentRecodeCodeListFile = recodeInfo.getCodeList(); // recoded = true; // truncLevels = 0; // logger.info("Recode: variable (" + name + ") has been recoded"); // } else { // throw new ArgusException(tauArgus.GetErrorString(errorType[0]) + " " + warning[0] + " in recoding; line " + errorLine[0] + " pos " + errorPos[0]); // } // } // // public void applyRecodeTree(String fileName) throws ArgusException { ////Anco 1.6 try with resources ////overigens wordt de reader niet gesloten ??????? //// try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { // BufferedReader reader = null; // try {reader = new BufferedReader(new FileReader(new File(fileName))); // tauArgus.UndoRecode(index); // String regel = reader.readLine(); // if (!StringUtils.equals(regel, "<TREERECODE>")) { // throw new ArgusException("First line does not start with \"<TREERECODE>\""); // } // while ((regel = reader.readLine()) != null) { // if (StringUtils.isNotBlank(regel)) { // int codeIndex<SUF> // if (codeIndex == -1) { // throw new ArgusException("Code (" + regel + ") not found"); // } // tauArgus.SetVarCodeActive(index, codeIndex, false); // } // } // tauArgus.DoActiveRecode(index); // } // catch (Exception ex) { // // tauArgus.UndoRecode(index); // throw new ArgusException("Error in reading tree status in recode file " + fileName + ": " + ex.getMessage()); // } // } // // public void recode(String fileName) throws ArgusException, FileNotFoundException, IOException { // if (hierarchical != HIER_NONE) { // applyRecodeTree(fileName); // logger.info("Variable (" + name + ") recoded.\nRecode file used:" + fileName); // } else { // RecodeInfo recodeInfo = readRecodeFile(fileName); // recode(recodeInfo); // currentRecodeFile = fileName; // } // } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } final Variable variable = (Variable) obj; boolean equal = name.equals(variable.name) && type == variable.type && bPos == variable.bPos && varLen == variable.varLen; // && truncatable == variable.truncatable // only needed fot MuArgus if (variable.isCategorical()) { equal = equal && totCode.equals(variable.totCode) && Arrays.equals(missing, variable.missing) && hasDistanceFunction == variable.hasDistanceFunction && (!hasDistanceFunction || Arrays.equals(distanceFunction, variable.distanceFunction)) && codeListFile.equals(variable.codeListFile) && hierarchical == variable.hierarchical && (hierarchical != Variable.HIER_LEVELS || (hierLevelsSum == variable.hierLevelsSum && Arrays.equals(hierLevels, variable.hierLevels))) && (hierarchical != Variable.HIER_FILE || (leadingString.equals(variable.leadingString) && hierFileName.equals(variable.hierFileName))); } if (variable.hasDecimals()) { equal = equal && nDecimals == variable.nDecimals; } if (variable.type == Type.REQUEST) { equal = equal && Arrays.equals(requestCode, variable.requestCode); } return equal; } @Override public int hashCode() { int hash = 5; hash = 89 * hash + Objects.hashCode(this.name); hash = 89 * hash + Objects.hashCode(this.type); hash = 89 * hash + this.bPos; hash = 89 * hash + this.varLen; hash = 89 * hash + this.nDecimals; hash = 89 * hash + Arrays.deepHashCode(this.requestCode); hash = 89 * hash + (this.hasDistanceFunction ? 1 : 0); hash = 89 * hash + Arrays.hashCode(this.distanceFunction); hash = 89 * hash + this.hierarchical; hash = 89 * hash + Objects.hashCode(this.hierFileName); hash = 89 * hash + this.hierLevelsSum; hash = 89 * hash + Arrays.hashCode(this.hierLevels); hash = 89 * hash + Objects.hashCode(this.codeListFile); hash = 89 * hash + Objects.hashCode(this.leadingString); hash = 89 * hash + Arrays.deepHashCode(this.missing); hash = 89 * hash + Objects.hashCode(this.totCode); return hash; } @Override public Object clone() throws CloneNotSupportedException { Variable variable = (Variable)super.clone(); if (requestCode != null) { variable.requestCode = (String[])requestCode.clone(); } if (distanceFunction != null) { variable.distanceFunction = (int[])distanceFunction.clone(); } if (hierLevels != null) { variable.hierLevels = (int[])hierLevels.clone(); } if (missing != null) { variable.missing = (String[])missing.clone(); } variable.originalVariable = this; return variable; } }
44595_14
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package muargus.controller; import argus.model.ArgusException; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.util.ArrayList; import java.io.File; import java.io.FileReader; import muargus.CalculationService; import muargus.MuARGUS; import muargus.extern.dataengine.Numerical; import muargus.model.MetadataMu; import muargus.model.TargetSwappingSpec; import muargus.model.ReplacementFile; import muargus.model.ReplacementSpec; import muargus.model.TargetedRecordSwapping; import muargus.model.VariableMu; import muargus.view.TargetedRecordSwappingView; /** * * @author pwof */ public class TargetedRecordSwappingController extends ControllerBase<TargetedRecordSwapping>{ private final MetadataMu metadata; /** * Constructor for the TargetedRecordSwappingController. * * @param parentView the Frame of the mainFrame. * @param metadata the original metadata. */ public TargetedRecordSwappingController(java.awt.Frame parentView, MetadataMu metadata) { super.setView(new TargetedRecordSwappingView(parentView, true, this)); this.metadata = metadata; fillModel(); getView().setMetadata(metadata); } /** * Gets the model and fills the model with the categorical variables if the * model is empty. */ private void fillModel() { TargetedRecordSwapping model = metadata.getCombinations().getTargetedRecordSwapping(); //TargetedRecordSwapping model = metadata.getTargetedRecordSwapping(); if (model.getVariables().isEmpty()) { for (VariableMu variable : this.metadata.getVariables()) { if (!variable.isNumeric()) { model.getVariables().add(variable); } } } setModel(model); } /** * Closes the view by setting its visibility to false. */ public void close() { getView().setVisible(false); } /** * Does the next step if the previous step was successful. * * @param success Boolean indicating whether the previous step was * successful. */ @Override protected void doNextStep(boolean success) { TargetSwappingSpec swapping = getModel().getTargetSwappings().get(getModel().getTargetSwappings().size() - 1); Numerical num = new Numerical(); // instance of the library-class int[] errorCode = new int[1]; int[] count_HID = new int[1]; int[] count_record = new int[1]; // Remove logfile from previous run File f1 = new File(MuARGUS.getTempDir()+"\\NonSwappedHID.txt"); f1.delete(); num.DoTargetedRecordSwap(swapping.getReplacementFile().getInputFilePath(), swapping.getReplacementFile().getOutputFilePath(), muargus.MuARGUS.getDefaultSeparator(), swapping.getOutputVariables().size(), swapping.getSwaprate(), swapping.getNProfiles(), swapping.getSimilarIndexes(), swapping.getNSim(), swapping.getHierarchyIndexes(), swapping.getNHier(), swapping.getRiskIndexes(), swapping.getNRisk(), swapping.getCarryIndexes(), swapping.getNCarry(), swapping.getHHID(), swapping.getkThreshold(), count_record, count_HID, swapping.getSeed(), errorCode, MuARGUS.getTempDir() + "\\NonSwappedHID.txt" ); if (errorCode[0] != 0) { getView().showErrorMessage(new ArgusException("Error during targeted record swapping")); this.metadata.getReplacementSpecs().remove(swapping); getModel().getTargetSwappings().remove(swapping); } else { if (f1.exists()){ try{ BufferedReader br = new BufferedReader(new FileReader(f1)); String[] Words = br.readLine().split(" "); br.close(); swapping.setCountNoDonor(Integer.parseInt(Words[0])); String Message = "WARNING: "; // First word in the file is number of non-swapped households Message += Words[0] + " households could not be swapped because no donor could be found (" + count_HID[0] + " households did get swapped).\n"; Message += "\nSee \"" + MuARGUS.getTempDir()+"\\NonSwappedHID.txt\" for the HID of households without donor.\n"; getView().showMessage(Message); SystemUtils.writeLogbook(Message); } catch (Exception ex) {getView().showMessage(ex.getMessage());} } else{ getView().showMessage("TargetedRecordSwapping successfully completed.\n" + count_HID[0] + " households are swapped."); } SystemUtils.writeLogbook("Tageted record swapping has been done.\n" + count_HID[0] + " households are swapped."); swapping.setCountSwappedHID(count_HID[0]); swapping.setCountSwappedRecords(count_record[0]); } getView().setProgress(0); getView().showStepName(""); getTargetedRecordSwappingView().updateVariableRows(swapping); swapping.setIsCalculated(true); getTargetedRecordSwappingView().enableMoveButtons(false); } /** * Gets the NumericalRankSwapping view. * * @return TargetedRecordSwappingView */ private TargetedRecordSwappingView getTargetedRecordSwappingView() { return (TargetedRecordSwappingView) getView(); } /** * Checks whether the value for the percentage is valid. * * @return Boolean indicating whether the value for the percentage is valid. */ private boolean checkFields() { double percentage = getTargetedRecordSwappingView().getSwaprate(); if (Double.isNaN(percentage) || percentage < 0 || percentage > 1) { getView().showErrorMessage(new ArgusException("Illegal value for the swaprate (should be > 0 and < 1)")); return false; } return true; } /** * Undo the applied Targeted Record Swapping */ public void undo() { ArrayList<VariableMu> selected = new ArrayList<>(); for (VariableMu variable : getTargetedRecordSwappingView().getSelectedSimilarVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedHierarchyVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedRiskVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedCarryVariables()){ if (!selected.contains(variable)) selected.add(variable); } if (selected.isEmpty()) { getView().showMessage(String.format("Nothing to Undo: Targeted Record Swapping was not applied yet.\n")); return; } selected.add(getTargetedRecordSwappingView().getHHIDVar()); if (!getView().showConfirmDialog(String.format("The Targeted Record Swapping involving %s will be removed. Continue?", VariableMu.printVariableNames(selected)))) { return; } String TargetSwappings = (getModel().getTargetSwappings().size()>1) ? "s are:" : " is:"; for (TargetSwappingSpec swapping : getModel().getTargetSwappings()) { if (swapping.getOutputVariables().size() == selected.size()) { boolean difference = false; for (VariableMu variable : swapping.getOutputVariables()) { if (!selected.contains(variable)) { difference = true; break; } } if (!difference) { getModel().getTargetSwappings().remove(swapping); this.metadata.getReplacementSpecs().remove(swapping); SystemUtils.writeLogbook("Targeted Record Swapping has been undone."); getTargetedRecordSwappingView().updateVariableRows(swapping); swapping.setIsCalculated(false); getTargetedRecordSwappingView().enableMoveButtons(true); return; } } TargetSwappings += "\n- " + VariableMu.printVariableNames(swapping.getOutputVariables()); } getView().showMessage(String.format("Targeted Record Swapping involving %s not found.\n" + "The available swapping" + TargetSwappings, VariableMu.printVariableNames(selected))); } /** * Calculates the numerical rank swapping. */ public void calculate() { if (!checkFields()) { return; } int nProfiles = getTargetedRecordSwappingView().getNumberofProfiles(); ArrayList<VariableMu> selectedSimilarVariables = getTargetedRecordSwappingView().getSelectedSimilarVariables(); ArrayList<VariableMu> selectedHierarchyVariables = getTargetedRecordSwappingView().getSelectedHierarchyVariables(); ArrayList<VariableMu> selectedRiskVariables = getTargetedRecordSwappingView().getSelectedRiskVariables(); ArrayList<VariableMu> selectedCarryVariables = getTargetedRecordSwappingView().getSelectedCarryVariables(); if (variablesAreUsed(selectedSimilarVariables)||variablesAreUsed(selectedHierarchyVariables)||variablesAreUsed(selectedRiskVariables)) { if (!getView().showConfirmDialog("One or more of the selected variables are already modified. Continue?")) { return; } } ArrayList<VariableMu> selectedVariables = new ArrayList<>(); for (VariableMu variable : selectedSimilarVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedHierarchyVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedRiskVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedCarryVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } selectedVariables.add(getTargetedRecordSwappingView().getHHIDVar()); TargetSwappingSpec targetSwapping = new TargetSwappingSpec(nProfiles, getTargetedRecordSwappingView().getNSim(), selectedHierarchyVariables.size(), selectedRiskVariables.size(), selectedCarryVariables.size(), getTargetedRecordSwappingView().getSwaprate(), getTargetedRecordSwappingView().getkanonThreshold(), getTargetedRecordSwappingView().getSeed()); try { CalculationService service = MuARGUS.getCalculationService(); targetSwapping.getOutputVariables().addAll(selectedVariables); targetSwapping.setReplacementFile(new ReplacementFile("TargetSwapping")); targetSwapping.calculateSimilarIndexes(selectedSimilarVariables); targetSwapping.calculateHierarchyIndexes(selectedHierarchyVariables); targetSwapping.calculateRiskIndexes(selectedRiskVariables); targetSwapping.calculateCarryIndexes(selectedCarryVariables); targetSwapping.calculateHHIdIndex(getTargetedRecordSwappingView().getHHIDVar()); this.metadata.getReplacementSpecs().add(targetSwapping); // Begin Calculation Service heeft mogelijk nog niet voldoende metadata, als TRS wordt aangeroepen vóór combinations gezet zijn //service.setMetadata(this.metadata); //service.exploreFile(this); // End Calculation Service heeft mogelijk nog niet voldoende metadata, als TRS wordt aangeroepen vóór combinations gezet zijn service.makeReplacementFile(this); getModel().getTargetSwappings().add(targetSwapping); } catch (ArgusException ex) { this.metadata.getReplacementSpecs().remove(targetSwapping); getView().showErrorMessage(ex); } } /** * Returns whether at least one variable is used. * * @param variables Arraylist of VariableMu's. * @return Boolean indicating whether at least one variable is used. */ private boolean variablesAreUsed(ArrayList<VariableMu> variables) { for (VariableMu variable : variables) { for (ReplacementSpec replacement : this.metadata.getReplacementSpecs()) { if (replacement.getOutputVariables().contains(variable)) { return true; } } } return false; } }
sdcTools/muargus
src/muargus/controller/TargetedRecordSwappingController.java
3,558
// Begin Calculation Service heeft mogelijk nog niet voldoende metadata, als TRS wordt aangeroepen vóór combinations gezet zijn
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package muargus.controller; import argus.model.ArgusException; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.util.ArrayList; import java.io.File; import java.io.FileReader; import muargus.CalculationService; import muargus.MuARGUS; import muargus.extern.dataengine.Numerical; import muargus.model.MetadataMu; import muargus.model.TargetSwappingSpec; import muargus.model.ReplacementFile; import muargus.model.ReplacementSpec; import muargus.model.TargetedRecordSwapping; import muargus.model.VariableMu; import muargus.view.TargetedRecordSwappingView; /** * * @author pwof */ public class TargetedRecordSwappingController extends ControllerBase<TargetedRecordSwapping>{ private final MetadataMu metadata; /** * Constructor for the TargetedRecordSwappingController. * * @param parentView the Frame of the mainFrame. * @param metadata the original metadata. */ public TargetedRecordSwappingController(java.awt.Frame parentView, MetadataMu metadata) { super.setView(new TargetedRecordSwappingView(parentView, true, this)); this.metadata = metadata; fillModel(); getView().setMetadata(metadata); } /** * Gets the model and fills the model with the categorical variables if the * model is empty. */ private void fillModel() { TargetedRecordSwapping model = metadata.getCombinations().getTargetedRecordSwapping(); //TargetedRecordSwapping model = metadata.getTargetedRecordSwapping(); if (model.getVariables().isEmpty()) { for (VariableMu variable : this.metadata.getVariables()) { if (!variable.isNumeric()) { model.getVariables().add(variable); } } } setModel(model); } /** * Closes the view by setting its visibility to false. */ public void close() { getView().setVisible(false); } /** * Does the next step if the previous step was successful. * * @param success Boolean indicating whether the previous step was * successful. */ @Override protected void doNextStep(boolean success) { TargetSwappingSpec swapping = getModel().getTargetSwappings().get(getModel().getTargetSwappings().size() - 1); Numerical num = new Numerical(); // instance of the library-class int[] errorCode = new int[1]; int[] count_HID = new int[1]; int[] count_record = new int[1]; // Remove logfile from previous run File f1 = new File(MuARGUS.getTempDir()+"\\NonSwappedHID.txt"); f1.delete(); num.DoTargetedRecordSwap(swapping.getReplacementFile().getInputFilePath(), swapping.getReplacementFile().getOutputFilePath(), muargus.MuARGUS.getDefaultSeparator(), swapping.getOutputVariables().size(), swapping.getSwaprate(), swapping.getNProfiles(), swapping.getSimilarIndexes(), swapping.getNSim(), swapping.getHierarchyIndexes(), swapping.getNHier(), swapping.getRiskIndexes(), swapping.getNRisk(), swapping.getCarryIndexes(), swapping.getNCarry(), swapping.getHHID(), swapping.getkThreshold(), count_record, count_HID, swapping.getSeed(), errorCode, MuARGUS.getTempDir() + "\\NonSwappedHID.txt" ); if (errorCode[0] != 0) { getView().showErrorMessage(new ArgusException("Error during targeted record swapping")); this.metadata.getReplacementSpecs().remove(swapping); getModel().getTargetSwappings().remove(swapping); } else { if (f1.exists()){ try{ BufferedReader br = new BufferedReader(new FileReader(f1)); String[] Words = br.readLine().split(" "); br.close(); swapping.setCountNoDonor(Integer.parseInt(Words[0])); String Message = "WARNING: "; // First word in the file is number of non-swapped households Message += Words[0] + " households could not be swapped because no donor could be found (" + count_HID[0] + " households did get swapped).\n"; Message += "\nSee \"" + MuARGUS.getTempDir()+"\\NonSwappedHID.txt\" for the HID of households without donor.\n"; getView().showMessage(Message); SystemUtils.writeLogbook(Message); } catch (Exception ex) {getView().showMessage(ex.getMessage());} } else{ getView().showMessage("TargetedRecordSwapping successfully completed.\n" + count_HID[0] + " households are swapped."); } SystemUtils.writeLogbook("Tageted record swapping has been done.\n" + count_HID[0] + " households are swapped."); swapping.setCountSwappedHID(count_HID[0]); swapping.setCountSwappedRecords(count_record[0]); } getView().setProgress(0); getView().showStepName(""); getTargetedRecordSwappingView().updateVariableRows(swapping); swapping.setIsCalculated(true); getTargetedRecordSwappingView().enableMoveButtons(false); } /** * Gets the NumericalRankSwapping view. * * @return TargetedRecordSwappingView */ private TargetedRecordSwappingView getTargetedRecordSwappingView() { return (TargetedRecordSwappingView) getView(); } /** * Checks whether the value for the percentage is valid. * * @return Boolean indicating whether the value for the percentage is valid. */ private boolean checkFields() { double percentage = getTargetedRecordSwappingView().getSwaprate(); if (Double.isNaN(percentage) || percentage < 0 || percentage > 1) { getView().showErrorMessage(new ArgusException("Illegal value for the swaprate (should be > 0 and < 1)")); return false; } return true; } /** * Undo the applied Targeted Record Swapping */ public void undo() { ArrayList<VariableMu> selected = new ArrayList<>(); for (VariableMu variable : getTargetedRecordSwappingView().getSelectedSimilarVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedHierarchyVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedRiskVariables()){ if (!selected.contains(variable)) selected.add(variable); } for (VariableMu variable : getTargetedRecordSwappingView().getSelectedCarryVariables()){ if (!selected.contains(variable)) selected.add(variable); } if (selected.isEmpty()) { getView().showMessage(String.format("Nothing to Undo: Targeted Record Swapping was not applied yet.\n")); return; } selected.add(getTargetedRecordSwappingView().getHHIDVar()); if (!getView().showConfirmDialog(String.format("The Targeted Record Swapping involving %s will be removed. Continue?", VariableMu.printVariableNames(selected)))) { return; } String TargetSwappings = (getModel().getTargetSwappings().size()>1) ? "s are:" : " is:"; for (TargetSwappingSpec swapping : getModel().getTargetSwappings()) { if (swapping.getOutputVariables().size() == selected.size()) { boolean difference = false; for (VariableMu variable : swapping.getOutputVariables()) { if (!selected.contains(variable)) { difference = true; break; } } if (!difference) { getModel().getTargetSwappings().remove(swapping); this.metadata.getReplacementSpecs().remove(swapping); SystemUtils.writeLogbook("Targeted Record Swapping has been undone."); getTargetedRecordSwappingView().updateVariableRows(swapping); swapping.setIsCalculated(false); getTargetedRecordSwappingView().enableMoveButtons(true); return; } } TargetSwappings += "\n- " + VariableMu.printVariableNames(swapping.getOutputVariables()); } getView().showMessage(String.format("Targeted Record Swapping involving %s not found.\n" + "The available swapping" + TargetSwappings, VariableMu.printVariableNames(selected))); } /** * Calculates the numerical rank swapping. */ public void calculate() { if (!checkFields()) { return; } int nProfiles = getTargetedRecordSwappingView().getNumberofProfiles(); ArrayList<VariableMu> selectedSimilarVariables = getTargetedRecordSwappingView().getSelectedSimilarVariables(); ArrayList<VariableMu> selectedHierarchyVariables = getTargetedRecordSwappingView().getSelectedHierarchyVariables(); ArrayList<VariableMu> selectedRiskVariables = getTargetedRecordSwappingView().getSelectedRiskVariables(); ArrayList<VariableMu> selectedCarryVariables = getTargetedRecordSwappingView().getSelectedCarryVariables(); if (variablesAreUsed(selectedSimilarVariables)||variablesAreUsed(selectedHierarchyVariables)||variablesAreUsed(selectedRiskVariables)) { if (!getView().showConfirmDialog("One or more of the selected variables are already modified. Continue?")) { return; } } ArrayList<VariableMu> selectedVariables = new ArrayList<>(); for (VariableMu variable : selectedSimilarVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedHierarchyVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedRiskVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } for (VariableMu variable : selectedCarryVariables){ if (!selectedVariables.contains(variable)) selectedVariables.add(variable); } selectedVariables.add(getTargetedRecordSwappingView().getHHIDVar()); TargetSwappingSpec targetSwapping = new TargetSwappingSpec(nProfiles, getTargetedRecordSwappingView().getNSim(), selectedHierarchyVariables.size(), selectedRiskVariables.size(), selectedCarryVariables.size(), getTargetedRecordSwappingView().getSwaprate(), getTargetedRecordSwappingView().getkanonThreshold(), getTargetedRecordSwappingView().getSeed()); try { CalculationService service = MuARGUS.getCalculationService(); targetSwapping.getOutputVariables().addAll(selectedVariables); targetSwapping.setReplacementFile(new ReplacementFile("TargetSwapping")); targetSwapping.calculateSimilarIndexes(selectedSimilarVariables); targetSwapping.calculateHierarchyIndexes(selectedHierarchyVariables); targetSwapping.calculateRiskIndexes(selectedRiskVariables); targetSwapping.calculateCarryIndexes(selectedCarryVariables); targetSwapping.calculateHHIdIndex(getTargetedRecordSwappingView().getHHIDVar()); this.metadata.getReplacementSpecs().add(targetSwapping); // Begin Calculation<SUF> //service.setMetadata(this.metadata); //service.exploreFile(this); // End Calculation Service heeft mogelijk nog niet voldoende metadata, als TRS wordt aangeroepen vóór combinations gezet zijn service.makeReplacementFile(this); getModel().getTargetSwappings().add(targetSwapping); } catch (ArgusException ex) { this.metadata.getReplacementSpecs().remove(targetSwapping); getView().showErrorMessage(ex); } } /** * Returns whether at least one variable is used. * * @param variables Arraylist of VariableMu's. * @return Boolean indicating whether at least one variable is used. */ private boolean variablesAreUsed(ArrayList<VariableMu> variables) { for (VariableMu variable : variables) { for (ReplacementSpec replacement : this.metadata.getReplacementSpecs()) { if (replacement.getOutputVariables().contains(variable)) { return true; } } } return false; } }
2224_5
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import tauargus.extern.dataengine.TauArgus; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author ahnl * This package contains all routines needed to run the hypercube/GHMiter method * Routines are available for creating the input files for GHMiter * checking and adapting the input files * Retrieving the solution and storing the suppression * * */ public class GHMiter { // private TauArgus TAUARGUS; private static final Logger LOGGER = Logger.getLogger(GHMiter.class.getName()); private static String Token; //private TableSet tableSet; Not used????? private static final TauArgus TAUARGUS = Application.getTauArgusDll(); private static DecimalFormat ghMiterDecimalFormat; public static boolean ShowProto002; public static void RunGHMiter(TableSet tableSet) throws ArgusException{ Date startDate = new Date(); ShowProto002 = false; SystemUtils.writeLogbook("Start of the hypercube protection for table " + TableService.getTableDescription(tableSet)); ghMiterDecimalFormat = SystemUtils.getInternalDecimalFormat(tableSet.respVar.nDecimals); //WriteEingabe ; Integer ReturnVal = TAUARGUS.WriteGHMITERDataCell(Application.getTempFile("EINGABE.TMP"), tableSet.index, false); if (!(ReturnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the Hypercube"); } SchrijfSTEUER(tableSet.index, ""); CleanGHMiterFiles(); //SchijfTABELLE Nog toevoegen parameters voor linked tables; SchrijfTABELLE(Application.getTempFile("TABELLE"), tableSet.index, false, 0); //OpschonenEingabe Apriory percentage?? OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABE")); //Run GHMiter RunGHMiterEXE(); //ReadSecondariesBack ReadSecondariesGHMiter(tableSet, "AUSGABE"); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} tableSet.processingTime = (int) diff; tableSet.suppressed = TableSet.SUP_GHMITER; SystemUtils.writeLogbook("End of hypercube protection. Time used "+ diff+ " seconds\n" + "Number of suppressions: " +tableSet.nSecond); } static boolean ReadSecondariesGHMiter(TableSet tableSet, String ausgabe) throws ArgusException { int[] NSec; String hs; boolean oke; NSec = new int[1]; File f = new File(Application.getTempFile(ausgabe)); oke = f.exists(); if (!oke) { hs = "The file "+ausgabe+" could not be found"; if (TauArgusUtils.ExistFile(Application.getTempFile("PROTO002"))){ hs = "See file PROTO002"; ShowProto002 = true; } hs = "The hypercube could not be applied\n" + hs; throw new ArgusException(hs); } testProto003(tableSet); int OkeCode = TAUARGUS.SetSecondaryGHMITER(Application.getTempFile(ausgabe), tableSet.index, NSec, false); //OkeCode = 4007; if (OkeCode == 4007){ if (Application.isAnco()) tableSet.ghMiterMessage = "Some frozen/protected cells needed to be suppressed\n"; writeFrozen(tableSet.expVar.size()); OkeCode = 1; } if (OkeCode != 1) { //GHMiter failed TableService.undoSuppress(tableSet.index); } else { tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_GHMITER; } return (OkeCode == 1); } static void writeFrozen(int nDim ){ String regel, EINGABEst = "", AUSGABEst; int i; double x; try{ BufferedReader eingabe = new BufferedReader(new FileReader(Application.getTempFile("EINGABE"))); BufferedReader ausgabe = new BufferedReader(new FileReader(Application.getTempFile("AUSGABE"))); BufferedWriter frozen = new BufferedWriter(new FileWriter(Application.getTempFile("frozen.txt"))); frozen.write("Overview of frozen cells");frozen.newLine(); frozen.write("Cell value and codes");frozen.newLine(); while((EINGABEst = eingabe.readLine()) != null) { AUSGABEst = ausgabe.readLine(); EINGABEst = EINGABEst.trim(); AUSGABEst = AUSGABEst.trim(); AUSGABEst = GetToken(AUSGABEst); if (Token.equals("1129")){ // a frozen cell found for(i=0;i<=2;i++){EINGABEst = GetToken(EINGABEst);} regel = Token; //The cell value for(i=0;i<=3;i++){EINGABEst = GetToken(EINGABEst);} // Tehremainder are the spanning codes x = Double.parseDouble(Token); if (x == 0){ for (i=0;i<nDim;i++){ EINGABEst = GetToken(EINGABEst);} regel = regel + " : " + EINGABEst; frozen.write(regel); frozen.newLine(); } } } frozen.close(); eingabe.close(); ausgabe.close(); } catch(Exception ex){} } static void testProto003(TableSet tableSet)throws ArgusException { int i, nt; String[] regel = new String[1]; String hs; for (i=0;i<TableSet.MAX_GH_MITER_RATIO;i++) {tableSet.ghMiterRatio[i] = 0;} if (!TauArgusUtils.ExistFile(Application.getTempFile("proto003"))){ return;} try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("proto003"))); regel[0] = in.readLine().trim(); nt = 0; for (i=0;i<TableSet.MAX_GH_MITER_RATIO;i++){ hs = TauArgusUtils.GetSimpleToken(regel); if (!hs.equals("")) tableSet.ghMiterRatio[i] = Integer.parseInt((hs)); nt = nt + tableSet.ghMiterRatio[i]; } if (nt !=0 ) {tableSet.ghMiterMessage = tableSet.ghMiterMessage + "Some (" + nt + ") cells could not be fully protected\nSave table and see report file for more info.";} } catch(Exception ex){} } public static void RunGHMiterEXE() throws ArgusException{ ArrayList<String> commandline = new ArrayList<>(); String GHMiter = ""; try { GHMiter = SystemUtils.getApplicationDirectory(GHMiter.class).getCanonicalPath(); } catch (Exception ex) {} //GHMiter = "\"" + GHMiter + "/Ghmiter4.exe\""; //Results in double quotes (""GHMiter4.exe""), some systems cannot deal with that correctly GHMiter += "\\Ghmiter4.exe"; commandline.add(GHMiter); TauArgusUtils.writeBatchFileForExec( "RunGH", commandline); int result = ExecUtils.execCommand(commandline, Application.getTempDir(),false, "Run Hypercube"); if (result != 0){ throw new ArgusException("A problem was encountered running the hypercube");} } static void OpschonenEINGABE(double aprioryPerc, TableSet tableSet, String fileName)throws ArgusException { int D, p, Flen, RespLen; String Hs, Regel; String Stat, Freq, ValueSt, minResp, maxResp; double Value, X; Variable variable = tableSet.respVar; D = variable.nDecimals; try{ BufferedReader in = new BufferedReader(new FileReader(fileName+".TMP")); Hs = in.readLine(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); Flen = Hs.length(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); Flen = Flen-Hs.length(); RespLen = Hs.length(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); RespLen = RespLen-Hs.length(); in.close(); in = new BufferedReader(new FileReader(fileName+".TMP")); BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); while((Hs = in.readLine()) != null) { Hs = Hs.trim(); Hs = GetToken(Hs); Stat = Token; Hs = GetToken(Hs); Freq = Token; Hs = GetToken(Hs); ValueSt = Token; Value = Double.parseDouble(ValueSt); if( (Freq.equals("2") ) & (Value == 0) & (Stat.equals("1"))) {Freq = "0";} if ( Freq.equals("1") & Stat.equals("1") ) { Freq = "2";} if ( Freq.equals("1") & Stat.equals("129") & !tableSet.ghMiterApplySingleton) {Freq = "2";} Regel = AddLeadingSpaces(Stat,5) + AddLeadingSpaces(Freq,Flen) + AddLeadingSpaces(ValueSt,RespLen); if ( aprioryPerc == 100 && tableSet.minTabVal == 0) { //basically do nothing Regel = Regel + " " + Hs; } else { // first 2 lousy one's Hs = GetToken(Hs); Regel = Regel + " "+ Token; Hs = GetToken(Hs); Regel = Regel + " "+ Token; Hs = GetToken(Hs); maxResp = Token; Hs = GetToken(Hs); minResp = Token; if ( Double.parseDouble(minResp) == 0 && Double.parseDouble(maxResp) == 0) {X = 0;} else { X = Math.abs(aprioryPerc / 100.0) * Value;} Regel = Regel + " "+ String.format(Locale.US, "%."+D+"f", X); //ghMiterDecimalFormat.format(X); if (Double.parseDouble(minResp) > 0){ if ((Value - X) < tableSet.minTabVal) { X = Value - tableSet.minTabVal;} } Regel = Regel + " "+ String.format(Locale.US, "%."+D+"f", X); //ghMiterDecimalFormat.format(X); Regel = Regel + " "+ Hs; } out.write (Regel); out.newLine(); } out.close(); } catch (Exception ex) { LOGGER.log(Level.SEVERE, null, ex); throw new ArgusException("A problem was encountered when preparing the file EINGABE"); } } static boolean SchrijfTABELLE (String FileTABELLE, int tIndex, boolean Linked, Integer CoverDim) throws ArgusException { Integer t1, t2, P1, P4, P5, NExpVar, D; int j, NA; String Hs; double CellResp, MinTVal; TableSet tableSet; if (!Linked) { t1 = tIndex; t2=tIndex;} else { t1 = 0; t2= TableService.numberOfTables()-1; } P4 = 0; P5 = 0; // ANCO nog een loopje over de tabellen voor linked for (int t=t1;t<=t2;t++){ tableSet = TableService.getTable(t); NExpVar = tableSet.expVar.size(); for ( int i=1; i<=NExpVar; i++){ Variable variable = tableSet.expVar.get(i-1); j=variable.index; NA = TauArgusUtils.getNumberOfActiveCodes(j); if (P4 < NA) {P4=NA;} //if (P5 < NExpVar) {P5 = NExpVar;} // ? Why for each i: NExpVar is fixed per table? } if (P5 < NExpVar) {P5 = NExpVar;} } if (Linked) { P5=CoverDim; tableSet = TableService.getTable(0); } else { tableSet = TableService.getTable(tIndex);} Hs = ""; switch (tableSet.ghMiterSize){ case 0: Hs = "50960000 200 6000"; // Normal break; case 1: P1 = 62500000 + 250 + 225000; // Large //P1 = (P1 + 63 + P4 + 100000) * 4; // Why "P1 + 63 + P4" as compared to case 2: "P1 + 63 * P4" ? P1 = (P1 + 63 * P4 + 100000) * 4; Hs = Integer.toString(P1) + " 250 25000"; break; case 2: P1 = 9 * tableSet.ghMiterSubtable; // Manual P1 = (62500000 + tableSet.ghMiterSubcode + P1 + 63 * P4 + 100000) * 4; // Why "P1 + 63 * P4" as compared to case 1: "P1 + 63 + P4" ? Hs = Integer.toString(P1) + " " + Integer.toString(tableSet.ghMiterSubcode)+" "+ Integer.toString(tableSet.ghMiterSubtable); break; } Hs = Hs + " " + Integer.toString(P4) + " " + Integer.toString(P5); try { BufferedWriter out = new BufferedWriter(new FileWriter(FileTABELLE)); out.write (Hs ); out.newLine(); Hs = "0 0 1"; out.write (Hs ); out.newLine(); CellResp = 0; MinTVal = 0; D = 0; for (int t=t1;t<=t2;t++){ tableSet = TableService.getTable(t); CellResp = Math.max(CellResp, tableSet.maxTabVal); MinTVal = Math.min(MinTVal, tableSet.minTabVal); D = Math.max(D, tableSet.respVar.nDecimals); } Hs = String.format(Locale.US, "%."+D+"f", CellResp); if (MinTVal >=0) {Hs = "0.000005 "+ Hs;} else {Hs = String.format(Locale.US, "%."+D+"f", 1.5 * MinTVal) + " " + String.format(Locale.US, "%."+D+"f", 1, CellResp - MinTVal);} out.write (Hs ); out.newLine(); out.write("0.00"); out.newLine(); if (MinTVal >= 0) {out.write("0");} else {out.write("1");} out.newLine(); j = 0; for (int t=t1;t<=t2;t++) { tableSet = TableService.getTable(t); j = Math.max(j, tableSet.expVar.size()); } out.write (" " +j+" 1 "); out.newLine();//MaxDim out.write (t2-t1+1+" "); out.newLine(); out.close(); return true; } catch (Exception ex) { throw new ArgusException("Unable to write the file TABELLE for the Hypercube"); } } public static void SchrijfSTEUER(Integer TableNumber, String number) throws ArgusException { String HS, HS1; TableSet tableSet = TableService.getTable(TableNumber); double X, Y; X = 0; Y = 0; if (tableSet.domRule){ if (tableSet.domK[0] != 0){ X = 100.0 / tableSet.domK[0]; X = 2 * (X-1);} else{ X = 100.0 / tableSet.domK[2]; X = 2 * (X-1);} } if (tableSet.pqRule){ if (tableSet.pqP[0] != 0) {Y = 2 * tableSet.pqP[0] / 100.0; } else {Y = 2 * tableSet.pqP[2] / 100.0; } } if (Y > X) { X = Y;} if (X == 0) { if (tableSet.frequencyRule){ if (tableSet.frequencyMarge[0] != 0) { X= tableSet.frequencyMarge[0] * 2 /100.0;} else { X= tableSet.frequencyMarge[1] * 2 /100.0;} } else if (tableSet.piepRule[0]){ X = tableSet.piepMarge[0] * 2 / 100.0;} else if (tableSet.piepRule[1]){ X = tableSet.piepMarge[1] * 2 / 100.0;} else if (tableSet.manualMarge != 0) {X = tableSet.manualMarge * 2 / 100.0;} } if (tableSet.ghMiterApriory){ HS1 = "0 1 0";} else {X = 0; HS1 = " 0 0 0";} tableSet.ratio = X; // getting info on table-parameters HS = String.format(Locale.US,"%10.8f", X); // Using Locale.US to ensure the use decimalseparator = "." HS = HS + " 0.00"; Integer OkeCode = TAUARGUS.WriteGHMITERSteuer(Application.getTempFile("STEUER"+number), HS, HS1, TableNumber); if (OkeCode != 1) {throw new ArgusException("Unable to write the file STEUER for the Hypercube");} } static void CleanGHMiterFiles() { TauArgusUtils.DeleteFileWild("PROTO*.*", Application.getTempDir()); TauArgusUtils.DeleteFile(Application.getTempFile("proto001")); TauArgusUtils.DeleteFile(Application.getTempFile("proto002")); TauArgusUtils.DeleteFile(Application.getTempFile("proto003")); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft17f001")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft14f001")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft09file")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft10file")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft12file")); TauArgusUtils.DeleteFileWild("Ft*fi*.*", Application.getTempDir()); TauArgusUtils.DeleteFileWild("Ft*f0*.*", Application.getTempDir()); TauArgusUtils.DeleteFile(Application.getTempFile("SCHNEID")); TauArgusUtils.DeleteFile(Application.getTempFile("MAMPTABI")); TauArgusUtils.DeleteFile(Application.getTempFile("VARIABLE")); TauArgusUtils.DeleteFile(Application.getTempFile("AGGPOSRC")); TauArgusUtils.DeleteFile(Application.getTempFile("ENDE")); TauArgusUtils.DeleteFile(Application.getTempFile("frozen.txt")); } static String GetToken(String St) { Integer p; String Hs; p = St.indexOf(" "); if (p == 0) { Token = St; Hs = ""; } else { Token = St.substring(0, p); Hs = St.substring(p + 1).trim(); } return Hs; } static String AddLeadingSpaces(String St, Integer Len) { Integer L; String Hs; L = St.length(); L = Len - L; Hs = String.format(Locale.US,"%" + Len + "s", St); //??? Shouldn't this be L instead of Len ???? return Hs; } }
sdcTools/tauargus
src/tauargus/model/GHMiter.java
6,141
//SchijfTABELLE Nog toevoegen parameters voor linked tables;
line_comment
nl
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import tauargus.extern.dataengine.TauArgus; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author ahnl * This package contains all routines needed to run the hypercube/GHMiter method * Routines are available for creating the input files for GHMiter * checking and adapting the input files * Retrieving the solution and storing the suppression * * */ public class GHMiter { // private TauArgus TAUARGUS; private static final Logger LOGGER = Logger.getLogger(GHMiter.class.getName()); private static String Token; //private TableSet tableSet; Not used????? private static final TauArgus TAUARGUS = Application.getTauArgusDll(); private static DecimalFormat ghMiterDecimalFormat; public static boolean ShowProto002; public static void RunGHMiter(TableSet tableSet) throws ArgusException{ Date startDate = new Date(); ShowProto002 = false; SystemUtils.writeLogbook("Start of the hypercube protection for table " + TableService.getTableDescription(tableSet)); ghMiterDecimalFormat = SystemUtils.getInternalDecimalFormat(tableSet.respVar.nDecimals); //WriteEingabe ; Integer ReturnVal = TAUARGUS.WriteGHMITERDataCell(Application.getTempFile("EINGABE.TMP"), tableSet.index, false); if (!(ReturnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the Hypercube"); } SchrijfSTEUER(tableSet.index, ""); CleanGHMiterFiles(); //SchijfTABELLE Nog<SUF> SchrijfTABELLE(Application.getTempFile("TABELLE"), tableSet.index, false, 0); //OpschonenEingabe Apriory percentage?? OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABE")); //Run GHMiter RunGHMiterEXE(); //ReadSecondariesBack ReadSecondariesGHMiter(tableSet, "AUSGABE"); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} tableSet.processingTime = (int) diff; tableSet.suppressed = TableSet.SUP_GHMITER; SystemUtils.writeLogbook("End of hypercube protection. Time used "+ diff+ " seconds\n" + "Number of suppressions: " +tableSet.nSecond); } static boolean ReadSecondariesGHMiter(TableSet tableSet, String ausgabe) throws ArgusException { int[] NSec; String hs; boolean oke; NSec = new int[1]; File f = new File(Application.getTempFile(ausgabe)); oke = f.exists(); if (!oke) { hs = "The file "+ausgabe+" could not be found"; if (TauArgusUtils.ExistFile(Application.getTempFile("PROTO002"))){ hs = "See file PROTO002"; ShowProto002 = true; } hs = "The hypercube could not be applied\n" + hs; throw new ArgusException(hs); } testProto003(tableSet); int OkeCode = TAUARGUS.SetSecondaryGHMITER(Application.getTempFile(ausgabe), tableSet.index, NSec, false); //OkeCode = 4007; if (OkeCode == 4007){ if (Application.isAnco()) tableSet.ghMiterMessage = "Some frozen/protected cells needed to be suppressed\n"; writeFrozen(tableSet.expVar.size()); OkeCode = 1; } if (OkeCode != 1) { //GHMiter failed TableService.undoSuppress(tableSet.index); } else { tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_GHMITER; } return (OkeCode == 1); } static void writeFrozen(int nDim ){ String regel, EINGABEst = "", AUSGABEst; int i; double x; try{ BufferedReader eingabe = new BufferedReader(new FileReader(Application.getTempFile("EINGABE"))); BufferedReader ausgabe = new BufferedReader(new FileReader(Application.getTempFile("AUSGABE"))); BufferedWriter frozen = new BufferedWriter(new FileWriter(Application.getTempFile("frozen.txt"))); frozen.write("Overview of frozen cells");frozen.newLine(); frozen.write("Cell value and codes");frozen.newLine(); while((EINGABEst = eingabe.readLine()) != null) { AUSGABEst = ausgabe.readLine(); EINGABEst = EINGABEst.trim(); AUSGABEst = AUSGABEst.trim(); AUSGABEst = GetToken(AUSGABEst); if (Token.equals("1129")){ // a frozen cell found for(i=0;i<=2;i++){EINGABEst = GetToken(EINGABEst);} regel = Token; //The cell value for(i=0;i<=3;i++){EINGABEst = GetToken(EINGABEst);} // Tehremainder are the spanning codes x = Double.parseDouble(Token); if (x == 0){ for (i=0;i<nDim;i++){ EINGABEst = GetToken(EINGABEst);} regel = regel + " : " + EINGABEst; frozen.write(regel); frozen.newLine(); } } } frozen.close(); eingabe.close(); ausgabe.close(); } catch(Exception ex){} } static void testProto003(TableSet tableSet)throws ArgusException { int i, nt; String[] regel = new String[1]; String hs; for (i=0;i<TableSet.MAX_GH_MITER_RATIO;i++) {tableSet.ghMiterRatio[i] = 0;} if (!TauArgusUtils.ExistFile(Application.getTempFile("proto003"))){ return;} try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("proto003"))); regel[0] = in.readLine().trim(); nt = 0; for (i=0;i<TableSet.MAX_GH_MITER_RATIO;i++){ hs = TauArgusUtils.GetSimpleToken(regel); if (!hs.equals("")) tableSet.ghMiterRatio[i] = Integer.parseInt((hs)); nt = nt + tableSet.ghMiterRatio[i]; } if (nt !=0 ) {tableSet.ghMiterMessage = tableSet.ghMiterMessage + "Some (" + nt + ") cells could not be fully protected\nSave table and see report file for more info.";} } catch(Exception ex){} } public static void RunGHMiterEXE() throws ArgusException{ ArrayList<String> commandline = new ArrayList<>(); String GHMiter = ""; try { GHMiter = SystemUtils.getApplicationDirectory(GHMiter.class).getCanonicalPath(); } catch (Exception ex) {} //GHMiter = "\"" + GHMiter + "/Ghmiter4.exe\""; //Results in double quotes (""GHMiter4.exe""), some systems cannot deal with that correctly GHMiter += "\\Ghmiter4.exe"; commandline.add(GHMiter); TauArgusUtils.writeBatchFileForExec( "RunGH", commandline); int result = ExecUtils.execCommand(commandline, Application.getTempDir(),false, "Run Hypercube"); if (result != 0){ throw new ArgusException("A problem was encountered running the hypercube");} } static void OpschonenEINGABE(double aprioryPerc, TableSet tableSet, String fileName)throws ArgusException { int D, p, Flen, RespLen; String Hs, Regel; String Stat, Freq, ValueSt, minResp, maxResp; double Value, X; Variable variable = tableSet.respVar; D = variable.nDecimals; try{ BufferedReader in = new BufferedReader(new FileReader(fileName+".TMP")); Hs = in.readLine(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); Flen = Hs.length(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); Flen = Flen-Hs.length(); RespLen = Hs.length(); Hs = Hs.trim(); p = Hs.indexOf(" "); Hs = Hs.substring(p); RespLen = RespLen-Hs.length(); in.close(); in = new BufferedReader(new FileReader(fileName+".TMP")); BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); while((Hs = in.readLine()) != null) { Hs = Hs.trim(); Hs = GetToken(Hs); Stat = Token; Hs = GetToken(Hs); Freq = Token; Hs = GetToken(Hs); ValueSt = Token; Value = Double.parseDouble(ValueSt); if( (Freq.equals("2") ) & (Value == 0) & (Stat.equals("1"))) {Freq = "0";} if ( Freq.equals("1") & Stat.equals("1") ) { Freq = "2";} if ( Freq.equals("1") & Stat.equals("129") & !tableSet.ghMiterApplySingleton) {Freq = "2";} Regel = AddLeadingSpaces(Stat,5) + AddLeadingSpaces(Freq,Flen) + AddLeadingSpaces(ValueSt,RespLen); if ( aprioryPerc == 100 && tableSet.minTabVal == 0) { //basically do nothing Regel = Regel + " " + Hs; } else { // first 2 lousy one's Hs = GetToken(Hs); Regel = Regel + " "+ Token; Hs = GetToken(Hs); Regel = Regel + " "+ Token; Hs = GetToken(Hs); maxResp = Token; Hs = GetToken(Hs); minResp = Token; if ( Double.parseDouble(minResp) == 0 && Double.parseDouble(maxResp) == 0) {X = 0;} else { X = Math.abs(aprioryPerc / 100.0) * Value;} Regel = Regel + " "+ String.format(Locale.US, "%."+D+"f", X); //ghMiterDecimalFormat.format(X); if (Double.parseDouble(minResp) > 0){ if ((Value - X) < tableSet.minTabVal) { X = Value - tableSet.minTabVal;} } Regel = Regel + " "+ String.format(Locale.US, "%."+D+"f", X); //ghMiterDecimalFormat.format(X); Regel = Regel + " "+ Hs; } out.write (Regel); out.newLine(); } out.close(); } catch (Exception ex) { LOGGER.log(Level.SEVERE, null, ex); throw new ArgusException("A problem was encountered when preparing the file EINGABE"); } } static boolean SchrijfTABELLE (String FileTABELLE, int tIndex, boolean Linked, Integer CoverDim) throws ArgusException { Integer t1, t2, P1, P4, P5, NExpVar, D; int j, NA; String Hs; double CellResp, MinTVal; TableSet tableSet; if (!Linked) { t1 = tIndex; t2=tIndex;} else { t1 = 0; t2= TableService.numberOfTables()-1; } P4 = 0; P5 = 0; // ANCO nog een loopje over de tabellen voor linked for (int t=t1;t<=t2;t++){ tableSet = TableService.getTable(t); NExpVar = tableSet.expVar.size(); for ( int i=1; i<=NExpVar; i++){ Variable variable = tableSet.expVar.get(i-1); j=variable.index; NA = TauArgusUtils.getNumberOfActiveCodes(j); if (P4 < NA) {P4=NA;} //if (P5 < NExpVar) {P5 = NExpVar;} // ? Why for each i: NExpVar is fixed per table? } if (P5 < NExpVar) {P5 = NExpVar;} } if (Linked) { P5=CoverDim; tableSet = TableService.getTable(0); } else { tableSet = TableService.getTable(tIndex);} Hs = ""; switch (tableSet.ghMiterSize){ case 0: Hs = "50960000 200 6000"; // Normal break; case 1: P1 = 62500000 + 250 + 225000; // Large //P1 = (P1 + 63 + P4 + 100000) * 4; // Why "P1 + 63 + P4" as compared to case 2: "P1 + 63 * P4" ? P1 = (P1 + 63 * P4 + 100000) * 4; Hs = Integer.toString(P1) + " 250 25000"; break; case 2: P1 = 9 * tableSet.ghMiterSubtable; // Manual P1 = (62500000 + tableSet.ghMiterSubcode + P1 + 63 * P4 + 100000) * 4; // Why "P1 + 63 * P4" as compared to case 1: "P1 + 63 + P4" ? Hs = Integer.toString(P1) + " " + Integer.toString(tableSet.ghMiterSubcode)+" "+ Integer.toString(tableSet.ghMiterSubtable); break; } Hs = Hs + " " + Integer.toString(P4) + " " + Integer.toString(P5); try { BufferedWriter out = new BufferedWriter(new FileWriter(FileTABELLE)); out.write (Hs ); out.newLine(); Hs = "0 0 1"; out.write (Hs ); out.newLine(); CellResp = 0; MinTVal = 0; D = 0; for (int t=t1;t<=t2;t++){ tableSet = TableService.getTable(t); CellResp = Math.max(CellResp, tableSet.maxTabVal); MinTVal = Math.min(MinTVal, tableSet.minTabVal); D = Math.max(D, tableSet.respVar.nDecimals); } Hs = String.format(Locale.US, "%."+D+"f", CellResp); if (MinTVal >=0) {Hs = "0.000005 "+ Hs;} else {Hs = String.format(Locale.US, "%."+D+"f", 1.5 * MinTVal) + " " + String.format(Locale.US, "%."+D+"f", 1, CellResp - MinTVal);} out.write (Hs ); out.newLine(); out.write("0.00"); out.newLine(); if (MinTVal >= 0) {out.write("0");} else {out.write("1");} out.newLine(); j = 0; for (int t=t1;t<=t2;t++) { tableSet = TableService.getTable(t); j = Math.max(j, tableSet.expVar.size()); } out.write (" " +j+" 1 "); out.newLine();//MaxDim out.write (t2-t1+1+" "); out.newLine(); out.close(); return true; } catch (Exception ex) { throw new ArgusException("Unable to write the file TABELLE for the Hypercube"); } } public static void SchrijfSTEUER(Integer TableNumber, String number) throws ArgusException { String HS, HS1; TableSet tableSet = TableService.getTable(TableNumber); double X, Y; X = 0; Y = 0; if (tableSet.domRule){ if (tableSet.domK[0] != 0){ X = 100.0 / tableSet.domK[0]; X = 2 * (X-1);} else{ X = 100.0 / tableSet.domK[2]; X = 2 * (X-1);} } if (tableSet.pqRule){ if (tableSet.pqP[0] != 0) {Y = 2 * tableSet.pqP[0] / 100.0; } else {Y = 2 * tableSet.pqP[2] / 100.0; } } if (Y > X) { X = Y;} if (X == 0) { if (tableSet.frequencyRule){ if (tableSet.frequencyMarge[0] != 0) { X= tableSet.frequencyMarge[0] * 2 /100.0;} else { X= tableSet.frequencyMarge[1] * 2 /100.0;} } else if (tableSet.piepRule[0]){ X = tableSet.piepMarge[0] * 2 / 100.0;} else if (tableSet.piepRule[1]){ X = tableSet.piepMarge[1] * 2 / 100.0;} else if (tableSet.manualMarge != 0) {X = tableSet.manualMarge * 2 / 100.0;} } if (tableSet.ghMiterApriory){ HS1 = "0 1 0";} else {X = 0; HS1 = " 0 0 0";} tableSet.ratio = X; // getting info on table-parameters HS = String.format(Locale.US,"%10.8f", X); // Using Locale.US to ensure the use decimalseparator = "." HS = HS + " 0.00"; Integer OkeCode = TAUARGUS.WriteGHMITERSteuer(Application.getTempFile("STEUER"+number), HS, HS1, TableNumber); if (OkeCode != 1) {throw new ArgusException("Unable to write the file STEUER for the Hypercube");} } static void CleanGHMiterFiles() { TauArgusUtils.DeleteFileWild("PROTO*.*", Application.getTempDir()); TauArgusUtils.DeleteFile(Application.getTempFile("proto001")); TauArgusUtils.DeleteFile(Application.getTempFile("proto002")); TauArgusUtils.DeleteFile(Application.getTempFile("proto003")); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft17f001")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft14f001")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft09file")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft10file")); TauArgusUtils.DeleteFile(Application.getTempFile("Ft12file")); TauArgusUtils.DeleteFileWild("Ft*fi*.*", Application.getTempDir()); TauArgusUtils.DeleteFileWild("Ft*f0*.*", Application.getTempDir()); TauArgusUtils.DeleteFile(Application.getTempFile("SCHNEID")); TauArgusUtils.DeleteFile(Application.getTempFile("MAMPTABI")); TauArgusUtils.DeleteFile(Application.getTempFile("VARIABLE")); TauArgusUtils.DeleteFile(Application.getTempFile("AGGPOSRC")); TauArgusUtils.DeleteFile(Application.getTempFile("ENDE")); TauArgusUtils.DeleteFile(Application.getTempFile("frozen.txt")); } static String GetToken(String St) { Integer p; String Hs; p = St.indexOf(" "); if (p == 0) { Token = St; Hs = ""; } else { Token = St.substring(0, p); Hs = St.substring(p + 1).trim(); } return Hs; } static String AddLeadingSpaces(String St, Integer Len) { Integer L; String Hs; L = St.length(); L = Len - L; Hs = String.format(Locale.US,"%" + Len + "s", St); //??? Shouldn't this be L instead of Len ???? return Hs; } }
160414_6
package roborally.model; import be.kuleuven.cs.som.annotate.Basic; import roborally.property.Energy; import roborally.property.Weight; /** * Deze klasse houdt een batterij bij. Deze heeft een positie, een gewicht en een hoeveelheid energie. Deze kan door een robot gedragen worden. * * @invar De hoeveelheid energie van een batterij moet altijd geldig zijn. * |isValidBatteryEnergyAmount(getEnergy()) * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @version 2.1 */ public class Battery extends Item{ /** * Maakt een nieuwe batterij aan. * * @param energy * Energie van de nieuwe batterij. * * @param weight * Massa van de batterij. * * @post De energie van de nieuwe batterij is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) * * @post Het gewicht van de nieuwe batterij is gelijk aan het gegeven gewicht. * |new.getWeight().equals(weight) */ public Battery(Energy energy, Weight weight){ super(weight); setEnergy(energy); } /** * Deze methode wijzigt de energie van de batterij. * * @param energy * De nieuwe energie van het item. * * @pre Energie moet geldige hoeveelheid zijn. * |isValidBatteryEnergy(energy) * * @post De energie van het item is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) */ public void setEnergy(Energy energy) { this.energy = energy; } /** * Geeft de energie van de batterij. * * @return Energie van de batterij. * |energy */ @Basic public Energy getEnergy() { return energy; } /** * Energie in de batterij. */ private Energy energy; /** * Deze methode kijkt na of de gegeven energie geldig is voor een batterij. * * @param energy * De energie die nagekeken moet worden. * * @return Een boolean die true is als de energie geldig is. * |if(!Energy.isValidEnergyAmount(energy.getEnergy())) * | false * |(energy.getEnergy() <= MAX_ENERGY.getEnergy()) */ public static boolean isValidBatteryEnergy(Energy energy){ if(!Energy.isValidEnergyAmount(energy.getEnergy())) return false; return (energy.getEnergy() <= MAX_ENERGY.getEnergy()); } /** * De maximale energie van een batterij. */ public final static Energy MAX_ENERGY = new Energy(5000); /** * Deze methode wordt opgeroepen wanneer de batterij geraakt wordt door een laser of een surprise box. * * @post De nieuwe energie van de batterij is gelijk aan het maximum of aan 500 meer dan wat hij ervoor had. * |new.getEnergy().equals(MAX_ENERGY) || new.getEnergy().equals(Energy.energySum(getEnergy(), HIT_ENERGY)) */ @Override protected void damage(){ Energy newEnergy = Energy.energySum(getEnergy(), HIT_ENERGY); if (newEnergy.getEnergy() > MAX_ENERGY.getEnergy()) setEnergy(MAX_ENERGY); setEnergy(newEnergy); } /** * De hoeveelheid energie die een battery bij krijgt wanneer hij geraakt wordt. */ private final static Energy HIT_ENERGY = new Energy(500); /* * Deze methode zet het object om naar een String. * * @return Een textuele representatie van dit object waarbij duidelijk wordt wat de eigenschappen van dit object zijn. * |super.toString() + ", energie: " + getEnergy().toString() * * @see roborally.model.Item#toString() */ @Override public String toString() { return super.toString() + ", energie: " + getEnergy().toString(); } }
sdebruyn/student-Java-game-Roborally
src/roborally/model/Battery.java
1,279
/** * De maximale energie van een batterij. */
block_comment
nl
package roborally.model; import be.kuleuven.cs.som.annotate.Basic; import roborally.property.Energy; import roborally.property.Weight; /** * Deze klasse houdt een batterij bij. Deze heeft een positie, een gewicht en een hoeveelheid energie. Deze kan door een robot gedragen worden. * * @invar De hoeveelheid energie van een batterij moet altijd geldig zijn. * |isValidBatteryEnergyAmount(getEnergy()) * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @version 2.1 */ public class Battery extends Item{ /** * Maakt een nieuwe batterij aan. * * @param energy * Energie van de nieuwe batterij. * * @param weight * Massa van de batterij. * * @post De energie van de nieuwe batterij is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) * * @post Het gewicht van de nieuwe batterij is gelijk aan het gegeven gewicht. * |new.getWeight().equals(weight) */ public Battery(Energy energy, Weight weight){ super(weight); setEnergy(energy); } /** * Deze methode wijzigt de energie van de batterij. * * @param energy * De nieuwe energie van het item. * * @pre Energie moet geldige hoeveelheid zijn. * |isValidBatteryEnergy(energy) * * @post De energie van het item is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) */ public void setEnergy(Energy energy) { this.energy = energy; } /** * Geeft de energie van de batterij. * * @return Energie van de batterij. * |energy */ @Basic public Energy getEnergy() { return energy; } /** * Energie in de batterij. */ private Energy energy; /** * Deze methode kijkt na of de gegeven energie geldig is voor een batterij. * * @param energy * De energie die nagekeken moet worden. * * @return Een boolean die true is als de energie geldig is. * |if(!Energy.isValidEnergyAmount(energy.getEnergy())) * | false * |(energy.getEnergy() <= MAX_ENERGY.getEnergy()) */ public static boolean isValidBatteryEnergy(Energy energy){ if(!Energy.isValidEnergyAmount(energy.getEnergy())) return false; return (energy.getEnergy() <= MAX_ENERGY.getEnergy()); } /** * De maximale energie<SUF>*/ public final static Energy MAX_ENERGY = new Energy(5000); /** * Deze methode wordt opgeroepen wanneer de batterij geraakt wordt door een laser of een surprise box. * * @post De nieuwe energie van de batterij is gelijk aan het maximum of aan 500 meer dan wat hij ervoor had. * |new.getEnergy().equals(MAX_ENERGY) || new.getEnergy().equals(Energy.energySum(getEnergy(), HIT_ENERGY)) */ @Override protected void damage(){ Energy newEnergy = Energy.energySum(getEnergy(), HIT_ENERGY); if (newEnergy.getEnergy() > MAX_ENERGY.getEnergy()) setEnergy(MAX_ENERGY); setEnergy(newEnergy); } /** * De hoeveelheid energie die een battery bij krijgt wanneer hij geraakt wordt. */ private final static Energy HIT_ENERGY = new Energy(500); /* * Deze methode zet het object om naar een String. * * @return Een textuele representatie van dit object waarbij duidelijk wordt wat de eigenschappen van dit object zijn. * |super.toString() + ", energie: " + getEnergy().toString() * * @see roborally.model.Item#toString() */ @Override public String toString() { return super.toString() + ", energie: " + getEnergy().toString(); } }
87570_1
package servlets; import com.ghostchat.facade.ChatFacade; import com.ghostchat.model.Chat; import com.ghostchat.model.ChatComparator; import com.ghostchat.model.Message; import com.ghostchat.model.MessageBox; import com.ghostchat.model.User; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; @WebServlet(name = "GhostChatServlet", urlPatterns = {"/GhostChatServlet"}) public class GhostChatServlet extends HttpServlet { private ChatFacade facade; @Override public void init() { facade = new ChatFacade(); } @Override public void destroy() { facade = null; } /** * Ghost Chat Servlet * Deze servlet gebruikt requests om in het model data op te vragen. * Data wordt terug gestuurd IN JSON FORMAAT (geconverteerd van XML). * * URL van de Servlet op Jelastic: * http://env-0432771.jelastic.dogado.eu/GhostChat/GhostChatServlet * * Functie oproepen gebreurt door de naam mee te geven als actie * (zie mogelijke acties hieronder) * * Voorbeeld: * http://env-0432771.jelastic.dogado.eu/GhostChat/GhostChatServlet?action=getStats * (= geeft stats terug van online gebruikers en chats) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String action = request.getParameter("action"); String output = ""; if (action != null) { if (action.equals("getStats")) { output += "<stats>"; output += "<users>" + facade.countTotalUsers() + "</users>"; output += "<chats>" + facade.countTotalChats() + "</chats>"; output += "</stats>"; } else if (action.equals("checkAvailibility")) { String chatname = request.getParameter("chatname"); output += "<chat>"; output += "<exists>" + facade.chatExists(chatname) + "</exists>"; output += "</chat>"; } else if (action.equals("createGroupChat")) { String chatname = request.getParameter("chatname"); String ownername = request.getParameter("ownername"); String country = request.getParameter("country"); boolean showLocation = Boolean.parseBoolean(request.getParameter("showlocation")); boolean listed = Boolean.parseBoolean(request.getParameter("listed")); facade.createGroupChat(chatname, listed, ownername, "", country, showLocation); facade.addUserToGroupChat(chatname, ownername, "", country, showLocation); } else if (action.equals("usernameExists")) { String chatname = request.getParameter("chatname"); String username = request.getParameter("username"); output += "<usernameexists>" + facade.isUserInChat(chatname, username) + "</usernameexists>"; } else if (action.equals("joinGroupChat")) { String chatname = request.getParameter("chatname"); String ownername = request.getParameter("ownername"); String country = request.getParameter("country"); boolean showLocation = Boolean.parseBoolean(request.getParameter("showlocation")); facade.addUserToGroupChat(chatname, ownername, "", country, showLocation); } else if (action.equals("leaveChat")) { String username = request.getParameter("username"); facade.removeUserFromChat(username); } else if (action.equals("getChatData")) { String chatname = request.getParameter("chatname"); output += "<chat>"; output += "<onlineusers>" + facade.countChatUsers(chatname) + "</onlineusers>"; output += "<messagecount>" + facade.countChatMessages(chatname) + "</messagecount>"; output += "<messageboxes>"; for (MessageBox box : facade.getMessageBoxes(chatname)) { Date time = new Date(box.sendtime); DateFormat timef = new SimpleDateFormat("HH:mm:ss"); String timeString = timef.format(time); output += "<messagebox>"; output += "<username>" + box.user.getUsername() + "</username>"; output += "<timestamp>" + timeString + "</timestamp>"; for (Message message : box.messages) { output += "<messages>" + message.getMessage() + "</messages>"; } output += "<haslocation>" + box.user.hasLocation() + "</haslocation>"; if(box.user.hasLocation()) { output += "<location>" + box.user.getLocation().getCountry() + "</location>"; } output += "</messagebox>"; } output += "</messageboxes>"; output += "</chat>"; } else if(action.equals("sendMessage")) { String chatname = request.getParameter("chatname"); String username = request.getParameter("username"); String message = request.getParameter("message"); facade.sendMessage(chatname, username, message); } else if(action.equals("getChatUsers")) { String chatname = request.getParameter("chatname"); List<User> users = facade.getUsers(chatname); User owner = facade.getChatOwner(chatname); for(User user : users) { output += "<user>"; Date now = new Date(); Date time = new Date(now.getTime() - user.getJoined()); DateFormat timef = new SimpleDateFormat("HH:mm:ss"); String timeString = timef.format(time); output += "<username>" + user.getUsername() + "</username>"; output += "<chattime>" + timeString + "</chattime>"; output += "<isowner>" + owner.equals(user) + "</isowner>"; output += "<haslocation>" + user.hasLocation() + "</haslocation>"; if(user.hasLocation()) { output += "<location>" + user.getLocation().getCountry() + "</location>"; } output += "</user>"; } } else if(action.equals("getRandomListedChat")) { List<Chat> chats = facade.getChats(); boolean found = false; for(Chat chat : chats) { if(chat.isListed() && chat.countUsers() == 1) { output += "<chatname>" + chat.getName() + "</chatname>"; found = true; break; } } if(found == false) { output += "<chatname>" + facade.generateChatName() + "</chatname>"; } output += "<found>" + found + "</found>"; } else if(action.equals("getListedChats")) { List<Chat> chats = facade.getChats(); List<Chat> listedChats = new ArrayList<Chat>(); for(Chat chat : chats) { if(chat.isListed()) { listedChats.add(chat); } } // Sorteer de lijst op users online in de chat, zie compareTo van chats Collections.sort(listedChats, new ChatComparator()); output += "<chats>"; for(Chat c : listedChats) { output += "<chat>"; output += "<chatname>" + c.getName() + "</chatname>"; output += "<usercount>" + c.getUsers().size() + "</usercount>"; output += "</chat>"; } output += "</chats>"; } } try { JSONObject xmlJSONObj = XML.toJSONObject(output); PrintWriter writer = response.getWriter(); writer.write(xmlJSONObj.toString()); } catch (JSONException je) {} } }
sdec/GhostChat_Web
src/java/servlets/GhostChatServlet.java
2,337
// Sorteer de lijst op users online in de chat, zie compareTo van chats
line_comment
nl
package servlets; import com.ghostchat.facade.ChatFacade; import com.ghostchat.model.Chat; import com.ghostchat.model.ChatComparator; import com.ghostchat.model.Message; import com.ghostchat.model.MessageBox; import com.ghostchat.model.User; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; @WebServlet(name = "GhostChatServlet", urlPatterns = {"/GhostChatServlet"}) public class GhostChatServlet extends HttpServlet { private ChatFacade facade; @Override public void init() { facade = new ChatFacade(); } @Override public void destroy() { facade = null; } /** * Ghost Chat Servlet * Deze servlet gebruikt requests om in het model data op te vragen. * Data wordt terug gestuurd IN JSON FORMAAT (geconverteerd van XML). * * URL van de Servlet op Jelastic: * http://env-0432771.jelastic.dogado.eu/GhostChat/GhostChatServlet * * Functie oproepen gebreurt door de naam mee te geven als actie * (zie mogelijke acties hieronder) * * Voorbeeld: * http://env-0432771.jelastic.dogado.eu/GhostChat/GhostChatServlet?action=getStats * (= geeft stats terug van online gebruikers en chats) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String action = request.getParameter("action"); String output = ""; if (action != null) { if (action.equals("getStats")) { output += "<stats>"; output += "<users>" + facade.countTotalUsers() + "</users>"; output += "<chats>" + facade.countTotalChats() + "</chats>"; output += "</stats>"; } else if (action.equals("checkAvailibility")) { String chatname = request.getParameter("chatname"); output += "<chat>"; output += "<exists>" + facade.chatExists(chatname) + "</exists>"; output += "</chat>"; } else if (action.equals("createGroupChat")) { String chatname = request.getParameter("chatname"); String ownername = request.getParameter("ownername"); String country = request.getParameter("country"); boolean showLocation = Boolean.parseBoolean(request.getParameter("showlocation")); boolean listed = Boolean.parseBoolean(request.getParameter("listed")); facade.createGroupChat(chatname, listed, ownername, "", country, showLocation); facade.addUserToGroupChat(chatname, ownername, "", country, showLocation); } else if (action.equals("usernameExists")) { String chatname = request.getParameter("chatname"); String username = request.getParameter("username"); output += "<usernameexists>" + facade.isUserInChat(chatname, username) + "</usernameexists>"; } else if (action.equals("joinGroupChat")) { String chatname = request.getParameter("chatname"); String ownername = request.getParameter("ownername"); String country = request.getParameter("country"); boolean showLocation = Boolean.parseBoolean(request.getParameter("showlocation")); facade.addUserToGroupChat(chatname, ownername, "", country, showLocation); } else if (action.equals("leaveChat")) { String username = request.getParameter("username"); facade.removeUserFromChat(username); } else if (action.equals("getChatData")) { String chatname = request.getParameter("chatname"); output += "<chat>"; output += "<onlineusers>" + facade.countChatUsers(chatname) + "</onlineusers>"; output += "<messagecount>" + facade.countChatMessages(chatname) + "</messagecount>"; output += "<messageboxes>"; for (MessageBox box : facade.getMessageBoxes(chatname)) { Date time = new Date(box.sendtime); DateFormat timef = new SimpleDateFormat("HH:mm:ss"); String timeString = timef.format(time); output += "<messagebox>"; output += "<username>" + box.user.getUsername() + "</username>"; output += "<timestamp>" + timeString + "</timestamp>"; for (Message message : box.messages) { output += "<messages>" + message.getMessage() + "</messages>"; } output += "<haslocation>" + box.user.hasLocation() + "</haslocation>"; if(box.user.hasLocation()) { output += "<location>" + box.user.getLocation().getCountry() + "</location>"; } output += "</messagebox>"; } output += "</messageboxes>"; output += "</chat>"; } else if(action.equals("sendMessage")) { String chatname = request.getParameter("chatname"); String username = request.getParameter("username"); String message = request.getParameter("message"); facade.sendMessage(chatname, username, message); } else if(action.equals("getChatUsers")) { String chatname = request.getParameter("chatname"); List<User> users = facade.getUsers(chatname); User owner = facade.getChatOwner(chatname); for(User user : users) { output += "<user>"; Date now = new Date(); Date time = new Date(now.getTime() - user.getJoined()); DateFormat timef = new SimpleDateFormat("HH:mm:ss"); String timeString = timef.format(time); output += "<username>" + user.getUsername() + "</username>"; output += "<chattime>" + timeString + "</chattime>"; output += "<isowner>" + owner.equals(user) + "</isowner>"; output += "<haslocation>" + user.hasLocation() + "</haslocation>"; if(user.hasLocation()) { output += "<location>" + user.getLocation().getCountry() + "</location>"; } output += "</user>"; } } else if(action.equals("getRandomListedChat")) { List<Chat> chats = facade.getChats(); boolean found = false; for(Chat chat : chats) { if(chat.isListed() && chat.countUsers() == 1) { output += "<chatname>" + chat.getName() + "</chatname>"; found = true; break; } } if(found == false) { output += "<chatname>" + facade.generateChatName() + "</chatname>"; } output += "<found>" + found + "</found>"; } else if(action.equals("getListedChats")) { List<Chat> chats = facade.getChats(); List<Chat> listedChats = new ArrayList<Chat>(); for(Chat chat : chats) { if(chat.isListed()) { listedChats.add(chat); } } // Sorteer de<SUF> Collections.sort(listedChats, new ChatComparator()); output += "<chats>"; for(Chat c : listedChats) { output += "<chat>"; output += "<chatname>" + c.getName() + "</chatname>"; output += "<usercount>" + c.getUsers().size() + "</usercount>"; output += "</chat>"; } output += "</chats>"; } } try { JSONObject xmlJSONObj = XML.toJSONObject(output); PrintWriter writer = response.getWriter(); writer.write(xmlJSONObj.toString()); } catch (JSONException je) {} } }
35783_7
package nl.thuis.sdm.java8; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; public class StreamTest { public static void main(String[] args) { // Tweede commit // Derde commit // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(new FileFilter() { // // @Override // public boolean accept(File f) { // return f.isDirectory(); // } // }); // for (File file : files) { // System.out.println(file.getName()); // } // FileFilter ff = (File f) -> f.isDirectory(); // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(ff); // for (File file : files) { // System.out.println(file.getName()); // } // Commit van GitHub List<String> strings = new ArrayList<>(); strings.add("Een"); strings.add("Twee"); strings.add("Drie"); strings.add("Vier"); strings.add("Vijf"); new StringPrinter().print2(strings, s -> s.length()<4); } }
sdemul/Speeltuin
src/main/java/nl/thuis/sdm/java8/StreamTest.java
347
// Commit van GitHub
line_comment
nl
package nl.thuis.sdm.java8; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; public class StreamTest { public static void main(String[] args) { // Tweede commit // Derde commit // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(new FileFilter() { // // @Override // public boolean accept(File f) { // return f.isDirectory(); // } // }); // for (File file : files) { // System.out.println(file.getName()); // } // FileFilter ff = (File f) -> f.isDirectory(); // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(ff); // for (File file : files) { // System.out.println(file.getName()); // } // Commit van<SUF> List<String> strings = new ArrayList<>(); strings.add("Een"); strings.add("Twee"); strings.add("Drie"); strings.add("Vier"); strings.add("Vijf"); new StringPrinter().print2(strings, s -> s.length()<4); } }
206983_63
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * 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 the University of Konstanz 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 <COPYRIGHT HOLDER> 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. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed start element. // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns) { // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/shredder/XMLImport.java
2,537
// RevNode... mTsns) {
line_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * 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 the University of Konstanz 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 <COPYRIGHT HOLDER> 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. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed start element. // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns)<SUF> // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
179122_1
package com.secbro2.drools.demo; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * @author zzs */ public class CepDemo { public static void main(String[] args) throws InterruptedException { KieServices kieServices = KieServices.Factory.get(); KieBaseConfiguration config = kieServices.newKieBaseConfiguration(); config.setOption(EventProcessingOption.STREAM); KieContainer container = kieServices.getKieClasspathContainer(); // KieBase kieBase = container.getKieBase("test-cep"); KieBase kieBase = container.newKieBase("test-cep",config); KieSession kieSession = kieBase.newKieSession(); Person p1 = new Person(1,"Tom"); Person p2 = new Person(2,"Lucy"); kieSession.insert(p1); Thread.sleep(3000); kieSession.insert(p2); int count = kieSession.fireAllRules(); System.out.println("Fire " + count + " rules!"); } }
secbr/drools
drools-lesson2/src/main/java/com/secbro2/drools/demo/CepDemo.java
359
// KieBase kieBase = container.getKieBase("test-cep");
line_comment
nl
package com.secbro2.drools.demo; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * @author zzs */ public class CepDemo { public static void main(String[] args) throws InterruptedException { KieServices kieServices = KieServices.Factory.get(); KieBaseConfiguration config = kieServices.newKieBaseConfiguration(); config.setOption(EventProcessingOption.STREAM); KieContainer container = kieServices.getKieClasspathContainer(); // KieBase kieBase<SUF> KieBase kieBase = container.newKieBase("test-cep",config); KieSession kieSession = kieBase.newKieSession(); Person p1 = new Person(1,"Tom"); Person p2 = new Person(2,"Lucy"); kieSession.insert(p1); Thread.sleep(3000); kieSession.insert(p2); int count = kieSession.fireAllRules(); System.out.println("Fire " + count + " rules!"); } }
208673_4
/* * Copyright (c) 2004-2012 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.engine; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.yawlfoundation.yawl.authentication.YSession; import org.yawlfoundation.yawl.elements.YAWLServiceGateway; import org.yawlfoundation.yawl.elements.YAWLServiceReference; import org.yawlfoundation.yawl.elements.YTask; import org.yawlfoundation.yawl.elements.state.YIdentifier; import org.yawlfoundation.yawl.engine.announcement.AnnouncementContext; import org.yawlfoundation.yawl.engine.announcement.YAnnouncement; import org.yawlfoundation.yawl.engine.announcement.YEngineEvent; import org.yawlfoundation.yawl.engine.interfce.interfaceB.InterfaceB_EngineBasedClient; import org.yawlfoundation.yawl.engine.interfce.interfaceB.InterfaceB_HttpsEngineBasedClient; import org.yawlfoundation.yawl.engine.interfce.interfaceX.InterfaceX_EngineSideClient; import org.yawlfoundation.yawl.exceptions.YAWLException; import org.yawlfoundation.yawl.exceptions.YStateException; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.yawlfoundation.yawl.engine.announcement.YEngineEvent.*; /** * Handles the announcement of engine-generated events to the environment. * * @author Michael Adams * @date 10/04/2010 */ public class YAnnouncer { private final ObserverGatewayController _controller; private final YEngine _engine; private final Logger _logger; private final Set<InterfaceX_EngineSideClient> _interfaceXListeners; private AnnouncementContext _announcementContext; protected YAnnouncer(YEngine engine) { _engine = engine; _logger = LogManager.getLogger(this.getClass()); _interfaceXListeners = new HashSet<InterfaceX_EngineSideClient>(); _announcementContext = AnnouncementContext.NORMAL; _controller = new ObserverGatewayController(); // Initialise the standard Observer Gateways. // Currently the two standard gateways are the HTTP and HTTPS driven // IB Servlet client. try { _controller.addGateway(new InterfaceB_EngineBasedClient()); _controller.addGateway(new InterfaceB_HttpsEngineBasedClient()); } catch (YAWLException ye) { _logger.warn("Failed to register default observer gateways. The Engine " + "may be unable to send notifications to services!", ye); } } public ObserverGatewayController getObserverGatewayController() { return _controller; } public synchronized void registerInterfaceBObserverGateway(ObserverGateway gateway) throws YAWLException { boolean firstGateway = _controller.isEmpty(); _controller.addGateway(gateway); if (firstGateway) rennounceRestoredItems(); } protected AnnouncementContext getAnnouncementContext() { return _announcementContext; } private void setAnnouncementContext(AnnouncementContext context) { _announcementContext = context; } /******************************************************************************/ // INTERFACE X LISTENER MGT // protected void addInterfaceXListener(InterfaceX_EngineSideClient listener) { _interfaceXListeners.add(listener); } protected void addInterfaceXListener(String uri) { addInterfaceXListener(new InterfaceX_EngineSideClient(uri)); } protected boolean removeInterfaceXListener(InterfaceX_EngineSideClient listener) { return _interfaceXListeners.remove(listener); } protected boolean removeInterfaceXListener(String uri) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { if (listener.getURI().equals(uri)) { return removeInterfaceXListener(listener); } } return false; } protected boolean hasInterfaceXListeners() { return ! _interfaceXListeners.isEmpty(); } protected void shutdownInterfaceXListeners() { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.shutdown(); } } /******************************************************************************/ // INTERFACE B (OBSERVER GATEWAY) ANNOUNCEMENTS // /** * Called by the engine when its initialisation is complete. Broadcast to all * registered services and gateways. * @param services the set of currently registered services * @param maxWaitSeconds timeout to announce to each service before giving up */ protected void announceEngineInitialisationCompletion( Set<YAWLServiceReference> services, int maxWaitSeconds) { _controller.notifyEngineInitialised(services, maxWaitSeconds); } /** * Called by the engine when a case is cancelled. Broadcast to all registered * services and gateways. * @param id the identifier of the cancelled case * @param services the set of currently registered services */ protected void announceCaseCancellation(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseCancellation(services, id); announceCaseCancellationToInterfaceXListeners(id); } /** * Called by YWorkItemTimer when a work item's timer expires. Announced only to * the designated service or gateway. * @param item the work item that has had its timer expire */ public void announceTimerExpiryEvent(YWorkItem item) { announceToGateways(createAnnouncement(item, TIMER_EXPIRED)); announceTimerExpiryToInterfaceXListeners(item); _engine.getInstanceCache().setTimerExpired(item); } /** * Called by the engine when a case is suspending. Broadcast to all registered * services and gateways. * @param id the identifier of the suspending case * @param services the set of currently registered services */ protected void announceCaseSuspending(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseSuspending(id, services); } /** * Called by the engine when a case has suspended. Broadcast to all registered * services and gateways. * @param id the identifier of the suspended case * @param services the set of currently registered services */ protected void announceCaseSuspended(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseSuspended(id, services); } /** * Called by the engine when a case has resumed from suspension. Broadcast to all * registered services and gateways. * @param id the identifier of the resumed case * @param services the set of currently registered services */ protected void announceCaseResumption(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseResumption(id, services); } protected void announceCaseStart(YSpecificationID specID, YIdentifier caseID, String launchingService, boolean delayed) { // if delayed, service string is uri, if not its a current sessionhandle if (! delayed) { YSession session = _engine.getSessionCache().getSession(launchingService); launchingService = (session != null) ? session.getURI() : null; } _controller.notifyCaseStarting(_engine.getYAWLServices(), specID, caseID, launchingService, delayed); } /** * Called by a case's net runner when it completes. Announced only to the designated * service or gateway when the 'service' parameter is not null, otherwise it is * broadcast to all registered services and gateways. * @param service the name of the service or gateway to announce the case completion * to. If null, the event will be announced to all registered services and gateways * @param caseID the identifier of the completed case * @param caseData the final output data for the case */ protected void announceCaseCompletion(YAWLServiceReference service, YIdentifier caseID, Document caseData) { if (service == null) { _controller.notifyCaseCompletion(_engine.getYAWLServices(), caseID, caseData); } else _controller.notifyCaseCompletion(service, caseID, caseData); } /** * Called by a workitem when it has a change of status. Broadcast to all * registered services and gateways. * @param item the work item that has had a change of status * @param oldStatus the previous status of the work item * @param newStatus the new status of the workitem */ protected void announceWorkItemStatusChange(YWorkItem item, YWorkItemStatus oldStatus, YWorkItemStatus newStatus) { _logger.debug("Announcing workitem status change from '{}' to new status '{}' " + "for workitem '{}'.", oldStatus, newStatus, item.getWorkItemID().toString()); _controller.notifyWorkItemStatusChange(_engine.getYAWLServices(), item, oldStatus, newStatus); } /** * Called by a workitem when it is cancelled. Announced only to the designated * service or gateway. * @param item the work item that has had a change of status */ public void announceCancelledWorkItem(YWorkItem item) { announceToGateways(createAnnouncement(item, ITEM_CANCEL)); } /** * Called by the engine when it begins to shutdown. Broadcast to all registered * services and gateways. */ protected void shutdownObserverGateways() { _controller.shutdownObserverGateways(); } /** * Called by the engine each time a net runner advances a case, resulting in the * enabling and/or cancelling of one or more work items. * @param announcements A set of work item enabling or cancellation events */ protected void announceToGateways(Set<YAnnouncement> announcements) { if (announcements != null) { _logger.debug("Announcing {} events.", announcements.size()); _controller.announce(announcements); } } private void announceToGateways(YAnnouncement announcement) { if (announcement != null) { _logger.debug("Announcing one event."); _controller.announce(announcement); } } protected YAnnouncement createAnnouncement(YAWLServiceReference ys, YWorkItem item, YEngineEvent event) { if (ys == null) ys = _engine.getDefaultWorklist(); return (ys != null) ? new YAnnouncement(ys, item, event, getAnnouncementContext()) : null; } protected YAnnouncement createAnnouncement(YWorkItem item, YEngineEvent event) { YTask task = item.getTask(); if ((task != null) && (task.getDecompositionPrototype() != null)) { YAWLServiceGateway wsgw = (YAWLServiceGateway) task.getDecompositionPrototype(); if (wsgw != null) { return createAnnouncement(wsgw.getYawlService(), item, event); } } return null; } // this method triggered by an IB service when it decides it is not going // to handle (i.e. checkout) a workitem announced to it. It passes the workitem to // the default worklist service for normal assignment. public void rejectAnnouncedEnabledTask(YWorkItem item) { YAWLServiceReference defaultWorklist = _engine.getDefaultWorklist(); if (defaultWorklist != null) { _logger.debug("Announcing enabled task {} on service {}", item.getIDString(), defaultWorklist.getServiceID()); announceToGateways(createAnnouncement(defaultWorklist, item, ITEM_ADD)); } // also raise an item abort exception for custom handling by services announceWorkItemAbortToInterfaceXListeners(item); } /******************************************************************************/ // INTERFACE X ANNOUNCEMENTS // protected void announceCheckWorkItemConstraints(YWorkItem item, Document data, boolean preCheck) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Check Constraints for task {} on client {}", item.getIDString(), listener.toString()); listener.announceCheckWorkItemConstraints(item, data, preCheck); } } protected void announceCheckCaseConstraints(YSpecificationID specID, String caseID, String data, boolean preCheck) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Check Constraints for case {} on client {}", caseID, listener.toString()); listener.announceCheckCaseConstraints(specID, caseID, data, preCheck); } } protected void announceTimeServiceExpiry(YWorkItem item, List timeOutTaskIds) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Time Out for item {} on client {}", item.getWorkItemID().toString(), listener.toString()); listener.announceTimeOut(item, timeOutTaskIds); } } private void announceWorkItemAbortToInterfaceXListeners(YWorkItem item) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.announceWorkitemAbort(item); } } private void announceCaseCancellationToInterfaceXListeners(YIdentifier caseID) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Cancel Case for case {} on client {}", caseID.toString(), listener.toString()); listener.announceCaseCancellation(caseID.get_idString()); } } private void announceTimerExpiryToInterfaceXListeners(YWorkItem item) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.announceTimeOut(item, null); } } /******************************************************************************/ // WORKITEM REANNOUNCEMENTS // private void rennounceRestoredItems() { //MLF: moved from restore logic. There is no point in reannouncing before the first gateway // is registered as the announcements will simply fall on deaf errors. Obviously we // also don't want to do it everytime either! int sum = 0; _logger.debug("Detected first gateway registration. Reannouncing all work items."); setAnnouncementContext(AnnouncementContext.RECOVERING); try { _logger.debug("Reannouncing all enabled workitems"); int itemsReannounced = reannounceEnabledWorkItems(); _logger.debug("{} enabled workitems reannounced", itemsReannounced); sum += itemsReannounced; _logger.debug("Reannouncing all executing workitems"); itemsReannounced = reannounceExecutingWorkItems(); _logger.debug("{} executing workitems reannounced", itemsReannounced); sum += itemsReannounced; _logger.debug("Reannouncing all fired workitems"); itemsReannounced = reannounceFiredWorkItems(); _logger.debug("{} fired workitems reannounced", itemsReannounced); sum += itemsReannounced; } catch (YStateException e) { _logger.error("Failure whilst reannouncing workitems. " + "Some workitems might not have been reannounced.", e); } setAnnouncementContext(AnnouncementContext.NORMAL); _logger.debug("Reannounced {} workitems in total.", sum); } /** * Causes the engine to re-announce all workitems which are in an "enabled" state.<P> * * @return The number of enabled workitems that were reannounced */ public int reannounceEnabledWorkItems() throws YStateException { _logger.debug("--> reannounceEnabledWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getEnabledWorkItems()); } /** * Causes the engine to re-announce all workitems which are in an "executing" state.<P> * * @return The number of executing workitems that were reannounced */ protected int reannounceExecutingWorkItems() throws YStateException { _logger.debug("--> reannounceExecutingWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getExecutingWorkItems()); } /** * Causes the engine to re-announce all workitems which are in an "fired" state.<P> * * @return The number of fired workitems that were reannounced */ protected int reannounceFiredWorkItems() throws YStateException { _logger.debug("--> reannounceFiredWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getFiredWorkItems()); } private int reannounceWorkItems(Set<YWorkItem> workItems) throws YStateException { Set<YAnnouncement> announcements = new HashSet<YAnnouncement>(); for (YWorkItem workitem : workItems) { YAnnouncement announcement = createAnnouncement(workitem, ITEM_ADD); if (announcement != null) announcements.add(announcement); } announceToGateways(announcements); return workItems.size(); } /** * Causes the engine to re-announce a specific workitem regardless of state.<P> */ protected void reannounceWorkItem(YWorkItem workItem) throws YStateException { _logger.debug("--> reannounceWorkItem: WorkitemID={}", workItem.getWorkItemID().toString()); announceToGateways(createAnnouncement(workItem, ITEM_ADD)); _logger.debug("<-- reannounceEnabledWorkItem"); } protected void announceDeadlock(YIdentifier caseID, Set<YTask> tasks) { _controller.notifyDeadlock(_engine.getYAWLServices(), caseID, tasks); } }
sedstef/yawl
src/org/yawlfoundation/yawl/engine/YAnnouncer.java
5,079
// IB Servlet client.
line_comment
nl
/* * Copyright (c) 2004-2012 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL 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. * * YAWL 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 YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.engine; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.yawlfoundation.yawl.authentication.YSession; import org.yawlfoundation.yawl.elements.YAWLServiceGateway; import org.yawlfoundation.yawl.elements.YAWLServiceReference; import org.yawlfoundation.yawl.elements.YTask; import org.yawlfoundation.yawl.elements.state.YIdentifier; import org.yawlfoundation.yawl.engine.announcement.AnnouncementContext; import org.yawlfoundation.yawl.engine.announcement.YAnnouncement; import org.yawlfoundation.yawl.engine.announcement.YEngineEvent; import org.yawlfoundation.yawl.engine.interfce.interfaceB.InterfaceB_EngineBasedClient; import org.yawlfoundation.yawl.engine.interfce.interfaceB.InterfaceB_HttpsEngineBasedClient; import org.yawlfoundation.yawl.engine.interfce.interfaceX.InterfaceX_EngineSideClient; import org.yawlfoundation.yawl.exceptions.YAWLException; import org.yawlfoundation.yawl.exceptions.YStateException; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.yawlfoundation.yawl.engine.announcement.YEngineEvent.*; /** * Handles the announcement of engine-generated events to the environment. * * @author Michael Adams * @date 10/04/2010 */ public class YAnnouncer { private final ObserverGatewayController _controller; private final YEngine _engine; private final Logger _logger; private final Set<InterfaceX_EngineSideClient> _interfaceXListeners; private AnnouncementContext _announcementContext; protected YAnnouncer(YEngine engine) { _engine = engine; _logger = LogManager.getLogger(this.getClass()); _interfaceXListeners = new HashSet<InterfaceX_EngineSideClient>(); _announcementContext = AnnouncementContext.NORMAL; _controller = new ObserverGatewayController(); // Initialise the standard Observer Gateways. // Currently the two standard gateways are the HTTP and HTTPS driven // IB Servlet<SUF> try { _controller.addGateway(new InterfaceB_EngineBasedClient()); _controller.addGateway(new InterfaceB_HttpsEngineBasedClient()); } catch (YAWLException ye) { _logger.warn("Failed to register default observer gateways. The Engine " + "may be unable to send notifications to services!", ye); } } public ObserverGatewayController getObserverGatewayController() { return _controller; } public synchronized void registerInterfaceBObserverGateway(ObserverGateway gateway) throws YAWLException { boolean firstGateway = _controller.isEmpty(); _controller.addGateway(gateway); if (firstGateway) rennounceRestoredItems(); } protected AnnouncementContext getAnnouncementContext() { return _announcementContext; } private void setAnnouncementContext(AnnouncementContext context) { _announcementContext = context; } /******************************************************************************/ // INTERFACE X LISTENER MGT // protected void addInterfaceXListener(InterfaceX_EngineSideClient listener) { _interfaceXListeners.add(listener); } protected void addInterfaceXListener(String uri) { addInterfaceXListener(new InterfaceX_EngineSideClient(uri)); } protected boolean removeInterfaceXListener(InterfaceX_EngineSideClient listener) { return _interfaceXListeners.remove(listener); } protected boolean removeInterfaceXListener(String uri) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { if (listener.getURI().equals(uri)) { return removeInterfaceXListener(listener); } } return false; } protected boolean hasInterfaceXListeners() { return ! _interfaceXListeners.isEmpty(); } protected void shutdownInterfaceXListeners() { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.shutdown(); } } /******************************************************************************/ // INTERFACE B (OBSERVER GATEWAY) ANNOUNCEMENTS // /** * Called by the engine when its initialisation is complete. Broadcast to all * registered services and gateways. * @param services the set of currently registered services * @param maxWaitSeconds timeout to announce to each service before giving up */ protected void announceEngineInitialisationCompletion( Set<YAWLServiceReference> services, int maxWaitSeconds) { _controller.notifyEngineInitialised(services, maxWaitSeconds); } /** * Called by the engine when a case is cancelled. Broadcast to all registered * services and gateways. * @param id the identifier of the cancelled case * @param services the set of currently registered services */ protected void announceCaseCancellation(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseCancellation(services, id); announceCaseCancellationToInterfaceXListeners(id); } /** * Called by YWorkItemTimer when a work item's timer expires. Announced only to * the designated service or gateway. * @param item the work item that has had its timer expire */ public void announceTimerExpiryEvent(YWorkItem item) { announceToGateways(createAnnouncement(item, TIMER_EXPIRED)); announceTimerExpiryToInterfaceXListeners(item); _engine.getInstanceCache().setTimerExpired(item); } /** * Called by the engine when a case is suspending. Broadcast to all registered * services and gateways. * @param id the identifier of the suspending case * @param services the set of currently registered services */ protected void announceCaseSuspending(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseSuspending(id, services); } /** * Called by the engine when a case has suspended. Broadcast to all registered * services and gateways. * @param id the identifier of the suspended case * @param services the set of currently registered services */ protected void announceCaseSuspended(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseSuspended(id, services); } /** * Called by the engine when a case has resumed from suspension. Broadcast to all * registered services and gateways. * @param id the identifier of the resumed case * @param services the set of currently registered services */ protected void announceCaseResumption(YIdentifier id, Set<YAWLServiceReference> services) { _controller.notifyCaseResumption(id, services); } protected void announceCaseStart(YSpecificationID specID, YIdentifier caseID, String launchingService, boolean delayed) { // if delayed, service string is uri, if not its a current sessionhandle if (! delayed) { YSession session = _engine.getSessionCache().getSession(launchingService); launchingService = (session != null) ? session.getURI() : null; } _controller.notifyCaseStarting(_engine.getYAWLServices(), specID, caseID, launchingService, delayed); } /** * Called by a case's net runner when it completes. Announced only to the designated * service or gateway when the 'service' parameter is not null, otherwise it is * broadcast to all registered services and gateways. * @param service the name of the service or gateway to announce the case completion * to. If null, the event will be announced to all registered services and gateways * @param caseID the identifier of the completed case * @param caseData the final output data for the case */ protected void announceCaseCompletion(YAWLServiceReference service, YIdentifier caseID, Document caseData) { if (service == null) { _controller.notifyCaseCompletion(_engine.getYAWLServices(), caseID, caseData); } else _controller.notifyCaseCompletion(service, caseID, caseData); } /** * Called by a workitem when it has a change of status. Broadcast to all * registered services and gateways. * @param item the work item that has had a change of status * @param oldStatus the previous status of the work item * @param newStatus the new status of the workitem */ protected void announceWorkItemStatusChange(YWorkItem item, YWorkItemStatus oldStatus, YWorkItemStatus newStatus) { _logger.debug("Announcing workitem status change from '{}' to new status '{}' " + "for workitem '{}'.", oldStatus, newStatus, item.getWorkItemID().toString()); _controller.notifyWorkItemStatusChange(_engine.getYAWLServices(), item, oldStatus, newStatus); } /** * Called by a workitem when it is cancelled. Announced only to the designated * service or gateway. * @param item the work item that has had a change of status */ public void announceCancelledWorkItem(YWorkItem item) { announceToGateways(createAnnouncement(item, ITEM_CANCEL)); } /** * Called by the engine when it begins to shutdown. Broadcast to all registered * services and gateways. */ protected void shutdownObserverGateways() { _controller.shutdownObserverGateways(); } /** * Called by the engine each time a net runner advances a case, resulting in the * enabling and/or cancelling of one or more work items. * @param announcements A set of work item enabling or cancellation events */ protected void announceToGateways(Set<YAnnouncement> announcements) { if (announcements != null) { _logger.debug("Announcing {} events.", announcements.size()); _controller.announce(announcements); } } private void announceToGateways(YAnnouncement announcement) { if (announcement != null) { _logger.debug("Announcing one event."); _controller.announce(announcement); } } protected YAnnouncement createAnnouncement(YAWLServiceReference ys, YWorkItem item, YEngineEvent event) { if (ys == null) ys = _engine.getDefaultWorklist(); return (ys != null) ? new YAnnouncement(ys, item, event, getAnnouncementContext()) : null; } protected YAnnouncement createAnnouncement(YWorkItem item, YEngineEvent event) { YTask task = item.getTask(); if ((task != null) && (task.getDecompositionPrototype() != null)) { YAWLServiceGateway wsgw = (YAWLServiceGateway) task.getDecompositionPrototype(); if (wsgw != null) { return createAnnouncement(wsgw.getYawlService(), item, event); } } return null; } // this method triggered by an IB service when it decides it is not going // to handle (i.e. checkout) a workitem announced to it. It passes the workitem to // the default worklist service for normal assignment. public void rejectAnnouncedEnabledTask(YWorkItem item) { YAWLServiceReference defaultWorklist = _engine.getDefaultWorklist(); if (defaultWorklist != null) { _logger.debug("Announcing enabled task {} on service {}", item.getIDString(), defaultWorklist.getServiceID()); announceToGateways(createAnnouncement(defaultWorklist, item, ITEM_ADD)); } // also raise an item abort exception for custom handling by services announceWorkItemAbortToInterfaceXListeners(item); } /******************************************************************************/ // INTERFACE X ANNOUNCEMENTS // protected void announceCheckWorkItemConstraints(YWorkItem item, Document data, boolean preCheck) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Check Constraints for task {} on client {}", item.getIDString(), listener.toString()); listener.announceCheckWorkItemConstraints(item, data, preCheck); } } protected void announceCheckCaseConstraints(YSpecificationID specID, String caseID, String data, boolean preCheck) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Check Constraints for case {} on client {}", caseID, listener.toString()); listener.announceCheckCaseConstraints(specID, caseID, data, preCheck); } } protected void announceTimeServiceExpiry(YWorkItem item, List timeOutTaskIds) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Time Out for item {} on client {}", item.getWorkItemID().toString(), listener.toString()); listener.announceTimeOut(item, timeOutTaskIds); } } private void announceWorkItemAbortToInterfaceXListeners(YWorkItem item) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.announceWorkitemAbort(item); } } private void announceCaseCancellationToInterfaceXListeners(YIdentifier caseID) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { _logger.debug("Announcing Cancel Case for case {} on client {}", caseID.toString(), listener.toString()); listener.announceCaseCancellation(caseID.get_idString()); } } private void announceTimerExpiryToInterfaceXListeners(YWorkItem item) { for (InterfaceX_EngineSideClient listener : _interfaceXListeners) { listener.announceTimeOut(item, null); } } /******************************************************************************/ // WORKITEM REANNOUNCEMENTS // private void rennounceRestoredItems() { //MLF: moved from restore logic. There is no point in reannouncing before the first gateway // is registered as the announcements will simply fall on deaf errors. Obviously we // also don't want to do it everytime either! int sum = 0; _logger.debug("Detected first gateway registration. Reannouncing all work items."); setAnnouncementContext(AnnouncementContext.RECOVERING); try { _logger.debug("Reannouncing all enabled workitems"); int itemsReannounced = reannounceEnabledWorkItems(); _logger.debug("{} enabled workitems reannounced", itemsReannounced); sum += itemsReannounced; _logger.debug("Reannouncing all executing workitems"); itemsReannounced = reannounceExecutingWorkItems(); _logger.debug("{} executing workitems reannounced", itemsReannounced); sum += itemsReannounced; _logger.debug("Reannouncing all fired workitems"); itemsReannounced = reannounceFiredWorkItems(); _logger.debug("{} fired workitems reannounced", itemsReannounced); sum += itemsReannounced; } catch (YStateException e) { _logger.error("Failure whilst reannouncing workitems. " + "Some workitems might not have been reannounced.", e); } setAnnouncementContext(AnnouncementContext.NORMAL); _logger.debug("Reannounced {} workitems in total.", sum); } /** * Causes the engine to re-announce all workitems which are in an "enabled" state.<P> * * @return The number of enabled workitems that were reannounced */ public int reannounceEnabledWorkItems() throws YStateException { _logger.debug("--> reannounceEnabledWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getEnabledWorkItems()); } /** * Causes the engine to re-announce all workitems which are in an "executing" state.<P> * * @return The number of executing workitems that were reannounced */ protected int reannounceExecutingWorkItems() throws YStateException { _logger.debug("--> reannounceExecutingWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getExecutingWorkItems()); } /** * Causes the engine to re-announce all workitems which are in an "fired" state.<P> * * @return The number of fired workitems that were reannounced */ protected int reannounceFiredWorkItems() throws YStateException { _logger.debug("--> reannounceFiredWorkItems"); return reannounceWorkItems(_engine.getWorkItemRepository().getFiredWorkItems()); } private int reannounceWorkItems(Set<YWorkItem> workItems) throws YStateException { Set<YAnnouncement> announcements = new HashSet<YAnnouncement>(); for (YWorkItem workitem : workItems) { YAnnouncement announcement = createAnnouncement(workitem, ITEM_ADD); if (announcement != null) announcements.add(announcement); } announceToGateways(announcements); return workItems.size(); } /** * Causes the engine to re-announce a specific workitem regardless of state.<P> */ protected void reannounceWorkItem(YWorkItem workItem) throws YStateException { _logger.debug("--> reannounceWorkItem: WorkitemID={}", workItem.getWorkItemID().toString()); announceToGateways(createAnnouncement(workItem, ITEM_ADD)); _logger.debug("<-- reannounceEnabledWorkItem"); } protected void announceDeadlock(YIdentifier caseID, Set<YTask> tasks) { _controller.notifyDeadlock(_engine.getYAWLServices(), caseID, tasks); } }
764_10
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
seek-for-android/pool
applications/EidForAndroid/src/be/cosic/android/eid/gui/Functions.java
5,291
//TODO : dit niet in een specifieke functie zetten?
line_comment
nl
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO :<SUF> } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
81555_23
package de.seemoo.nexmon.jammer.receiver; import android.app.Fragment; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import de.seemoo.nexmon.jammer.MainActivity; import de.seemoo.nexmon.jammer.R; import de.seemoo.nexmon.jammer.global.ColorsTuDarmstadt; import de.seemoo.nexmon.jammer.utils.Nexutil; import static com.github.mikephil.charting.utils.ColorTemplate.rgb; /** * Created by Stathis on 05-May-17. */ //MAC, IP Address, new graph button public class ReceiverFragment extends Fragment implements IAxisValueFormatter { public ConcurrentHashMap<String, float[]> data = new ConcurrentHashMap<>(); ViewGroup container; AlertDialog helpDialog; Menu menu; private UDPReceiver udpReceiver; private Plotter plotter; private HorizontalBarChart mChart; private ArrayList<String> hashes = new ArrayList<>(); private SortedSet<Packet> packetSet = new TreeSet<>(); private Semaphore semaphore; private TextView xAxisLabel; private TextView yAxisLabel; private TableLayout streamDescriptionTable; private View streamDescriptionScrollView; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * Inflate the layout for this fragment */ this.container = container; createAlertDialogs(); setHasOptionsMenu(true); return inflater.inflate(R.layout.receiver_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //installCustomWiFiFirmware(); xAxisLabel = (TextView) getView().findViewById(R.id.x_axis); yAxisLabel = (TextView) getView().findViewById(R.id.y_axis); streamDescriptionTable = (TableLayout) getView().findViewById(R.id.streamDescriptionTable); streamDescriptionScrollView = getView().findViewById(R.id.streamDescriptionScrollView); mChart = (HorizontalBarChart) getView().findViewById(R.id.chart1); initializePlot(); udpReceiver = new UDPReceiver(); plotter = new Plotter(); semaphore = new Semaphore(1, true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { this.menu = menu; super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.start: if (item.getTitle().toString().equals("Stop")) { try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 0); Nexutil.getInstance().setIoctl(512, 0); // deactivate filtering for MAC addresses udpReceiver.shutdown(); plotter.shutdown(); item.setTitle("Start"); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } } else { try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 96); Nexutil.getInstance().setIoctl(508); // set NEXMON MAC address Nexutil.getInstance().setIoctl(512, 1); // activate filtering for MAC addresses udpReceiver = new UDPReceiver(); udpReceiver.start(); plotter = new Plotter(); plotter.start(); item.setTitle("Stop"); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } } return true; case R.id.reset: try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 0); Nexutil.getInstance().setIoctl(512, 0); // deactivate filtering for MAC addresses udpReceiver.shutdown(); plotter.shutdown(); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } mChart.clear(); initializePlot(); data = new ConcurrentHashMap<>(); hashes = new ArrayList<>(); packetSet = new TreeSet<>(); menu.findItem(R.id.start).setTitle("Start"); xAxisLabel.setVisibility(View.GONE); yAxisLabel.setVisibility(View.GONE); streamDescriptionScrollView.setVisibility(View.GONE); return true; case R.id.help_receiver: try { String ret = Nexutil.getInstance().getIoctl(500); Log.d("Shell", ret); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } helpDialog.show(); return true; } return super.onOptionsItemSelected(item); } public void createAlertDialogs() { View list_layout = getActivity().getLayoutInflater().inflate(R.layout.help_receiver, null, true); WebView wvHelp = (WebView) list_layout.findViewById(R.id.wvHelp); wvHelp.loadUrl("file:///android_asset/html/help_receiver.html"); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(list_layout); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("CLOSE", null); // create alert dialog helpDialog = alertDialogBuilder.create(); } private void initializePlot() { mChart.getDescription().setEnabled(false); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(40); mChart.setNoDataText("No packets were received yet"); mChart.setAutoScaleMinMaxEnabled(false); mChart.setKeepPositionOnRotation(true); mChart.setPinchZoom(true); mChart.setDrawGridBackground(false); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(false); mChart.setHighlightFullBarEnabled(false); mChart.setHighlightPerTapEnabled(false); mChart.setHighlightPerDragEnabled(false); mChart.setHardwareAccelerationEnabled(true); // change the position of the y-labels YAxis leftAxis = mChart.getAxisRight(); leftAxis.setDrawGridLines(false); // this replaces setStartAtZero(true) //leftAxis.setValueFormatter(new com.github.mikephil.charting.formatter.LargeValueFormatter()); mChart.getAxisLeft().setEnabled(false); XAxis xAxis = mChart.getXAxis(); xAxis.setValueFormatter(this); xAxis.setGranularity(1); xAxis.setGranularityEnabled(true); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); Legend l = mChart.getLegend(); l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); l.setOrientation(Legend.LegendOrientation.HORIZONTAL); l.setDrawInside(false); l.setFormSize(8f); l.setFormToTextSpace(4f); l.setXEntrySpace(6f); } private void updatePlot() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ArrayList<BarEntry> yVals = new ArrayList<BarEntry>(); streamDescriptionTable.removeAllViews(); final TableRow tableHeader = (TableRow) getActivity().getLayoutInflater().inflate(R.layout.receiver_plot_table_header, null); //Add row to the table streamDescriptionTable.addView(tableHeader); int i = 0; for (HashMap.Entry<String, float[]> entry : data.entrySet()) { String key = entry.getKey(); String[] params = key.split("-"); final TableRow tableRow = (TableRow) getActivity().getLayoutInflater().inflate(R.layout.receiver_plot_table_row, null); TextView tv; //Filling in cells tv = (TextView) tableRow.findViewById(R.id.nameValue); tv.setText("Stream " + i); tv = (TextView) tableRow.findViewById(R.id.nodeValue); tv.setText(params[0]); tv = (TextView) tableRow.findViewById(R.id.portValue); tv.setText(params[1]); tv = (TextView) tableRow.findViewById(R.id.encodingValue); switch (params[2]) { case "1": tv.setText("11b"); break; case "2": tv.setText("11a/g"); break; case "3": tv.setText("11n"); break; case "4": tv.setText("11ac"); break; } tv = (TextView) tableRow.findViewById(R.id.bandwidthValue); switch (params[3]) { case "0": tv.setText("20 MHz"); break; case "1": tv.setText("80 MHz"); break; case "2": tv.setText("80 MHz"); break; } tv = (TextView) tableRow.findViewById(R.id.rateValue); switch (params[2]) { case "1": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; case "2": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; case "3": tv.setText("MCS " + params[4]); break; case "4": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; } tv = (TextView) tableRow.findViewById(R.id.ldpcValue); tv.setText(params[5]); tableRow.setBackgroundColor(i % 2 == 0 ? rgb("#DCDCDC") : rgb("#ffffff")); //Add row to the table streamDescriptionTable.addView(tableRow); float[] value = entry.getValue(); float val1 = value[1]; float val2 = value[0]; yVals.add(new BarEntry(i, new float[]{val1, val2})); i++; } BarDataSet set; if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { set = (BarDataSet) mChart.getData().getDataSetByIndex(0); set.setValues(yVals); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { set = new BarDataSet(yVals, ""); set.setDrawIcons(false); set.setColors(getColors()); set.setStackLabels(new String[]{"FCS incorrect", "FCS correct"}); ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); dataSets.add(set); BarData data = new BarData(dataSets); //data.setValueFormatter(new com.github.mikephil.charting.formatter.LargeValueFormatter()); mChart.setData(data); } mChart.setFitBars(true); xAxisLabel.setVisibility(View.VISIBLE); yAxisLabel.setVisibility(View.VISIBLE); streamDescriptionScrollView.setVisibility(View.VISIBLE); mChart.invalidate(); } }); } @Override public String getFormattedValue(float value, AxisBase axis) { // "value" represents the position of the label on the axis (x or y) return "Stream " + (int) value; } private int[] getColors() { int stacksize = 2; // have as many colors as stack-values per entry int[] colors = new int[stacksize]; colors[0] = ColorsTuDarmstadt.COLOR_1B; colors[1] = ColorsTuDarmstadt.COLOR_6B; return colors; } private final class UDPReceiver extends Thread { public static final int RECV_BUFFER_SIZE = 1000; private static final String TAG = "UDPReceiverThread"; private final char[] hexArray = "0123456789ABCDEF".toCharArray(); private boolean mContinueRunning = true; private DatagramSocket mSocket = null; public String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public void run() { Log.d(TAG, "Thread run"); mContinueRunning = true; try { mSocket = new DatagramSocket(5500); } catch (SocketException e) { // TODO: Handle address already in use. Log.d(TAG, "Error opening the UDP socket."); e.printStackTrace(); return; } byte[] buffer = new byte[RECV_BUFFER_SIZE]; DatagramPacket p = new DatagramPacket(buffer, buffer.length); while (mContinueRunning) { try { mSocket.receive(p); // TODO: Check source address of packet and/or validate it with other means } catch (IOException e) { e.printStackTrace(); } if (!mContinueRunning) { Log.d(TAG, "Stop thread activity..."); break; } Packet packet = new Packet(buffer); //Log.d(TAG, "timestamp: " + packet.timestamp_mac + " port: " + packet.port + " fcs_error error: " + packet.fcs_error + " length: " + packet.length); try { semaphore.acquire(); packetSet.add(packet); if (!data.containsKey(packet.hash)) { hashes.add(packet.hash); data.put(packet.hash, new float[2]); Log.d(TAG, "add " + packet.hash); } semaphore.release(); } catch (Exception e) { e.printStackTrace(); } } Log.d(TAG, "Thread afterrun"); } public void shutdown() { mContinueRunning = false; mSocket.close(); } } private final class Plotter extends Thread { private static final String TAG = "PlotterThread"; private boolean mContinueRunning = true; public void run() { Log.d(TAG, "Plotter Thread run"); mContinueRunning = true; while (mContinueRunning) { try { long windows_size = 1L; int count_removes = 0; long current_time = System.nanoTime(); long time = current_time - windows_size * 1000000000L; //Log.d(TAG, "acquiring Semaphore"); semaphore.acquire(); for (Iterator<Packet> i = packetSet.iterator(); i.hasNext(); ) { Packet pa = i.next(); if (pa.timestamp_android < time) { i.remove(); count_removes++; } } if (hashes.size() > 0) { for (String hash : hashes) { int sum_length_fcs_1 = 0; int sum_length_fcs_0 = 0; for (Iterator<Packet> i = packetSet.iterator(); i.hasNext(); ) { Packet pa = i.next(); if (hash.equals(pa.hash)) { if (pa.fcs_error) { sum_length_fcs_1 += pa.length; } else { sum_length_fcs_0 += pa.length; } } } float throughput_fcs_0 = sum_length_fcs_0 / windows_size * 8 / 1e6f; float throughput_fcs_1 = sum_length_fcs_1 / windows_size * 8 / 1e6f; data.get(hash)[0] = throughput_fcs_0; data.get(hash)[1] = throughput_fcs_1; if (data.size() > 0) updatePlot(); //Log.d(TAG, "Plotting!!!"); } } semaphore.release(); //Log.d(TAG, "releasing Semaphore"); sleep(1000); if (!mContinueRunning) { Log.d(TAG, "Stop thread activity..."); break; } } catch (Exception e) { e.printStackTrace(); } } Log.d(TAG, "Plotter afterrun"); } public void shutdown() { mContinueRunning = false; } } /* struct jamming_receiver_header { uint32 timestamp; uint16 node; uint16 port; bool fcs_error; uint16 length; uint8 encoding; uint8 bandwidth; uint16 rate; bool ldpc; } */ public class Packet implements Comparable<Packet> { long timestamp_mac; long timestamp_android; int port; boolean fcs_error; int length; byte encoding; byte bandwidth; int rate; boolean ldpc; String hash; String node; public Packet(byte buffer[]) { ByteBuffer buf = ByteBuffer.wrap(buffer); buf.order(ByteOrder.LITTLE_ENDIAN); this.timestamp_mac = (long) buf.getInt() & 0xffffffffL; this.timestamp_android = System.nanoTime(); this.node = String.format("%04x", (int) buf.getShort() & 0xffff); this.port = (int) buf.getShort() & 0xffff; this.fcs_error = ((int) buf.get() & 0xf) == 1; this.length = (int) buf.getShort() & 0xffff; this.encoding = buf.get(); this.bandwidth = buf.get(); this.rate = (int) buf.getShort() & 0xffff; this.ldpc = ((int) buf.get() & 0xf) == 1; this.hash = node + "-" + port + "-" + encoding + "-" + bandwidth + "-" + rate + "-" + ldpc; } public int compareTo(Packet other) { return Long.compare(this.timestamp_android, other.timestamp_android); } } }
seemoo-lab/wisec2017_nexmon_jammer_demo_app
WiFiJammer/app/src/main/java/de/seemoo/nexmon/jammer/receiver/ReceiverFragment.java
6,013
/* struct jamming_receiver_header { uint32 timestamp; uint16 node; uint16 port; bool fcs_error; uint16 length; uint8 encoding; uint8 bandwidth; uint16 rate; bool ldpc; } */
block_comment
nl
package de.seemoo.nexmon.jammer.receiver; import android.app.Fragment; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.github.mikephil.charting.charts.HorizontalBarChart; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import de.seemoo.nexmon.jammer.MainActivity; import de.seemoo.nexmon.jammer.R; import de.seemoo.nexmon.jammer.global.ColorsTuDarmstadt; import de.seemoo.nexmon.jammer.utils.Nexutil; import static com.github.mikephil.charting.utils.ColorTemplate.rgb; /** * Created by Stathis on 05-May-17. */ //MAC, IP Address, new graph button public class ReceiverFragment extends Fragment implements IAxisValueFormatter { public ConcurrentHashMap<String, float[]> data = new ConcurrentHashMap<>(); ViewGroup container; AlertDialog helpDialog; Menu menu; private UDPReceiver udpReceiver; private Plotter plotter; private HorizontalBarChart mChart; private ArrayList<String> hashes = new ArrayList<>(); private SortedSet<Packet> packetSet = new TreeSet<>(); private Semaphore semaphore; private TextView xAxisLabel; private TextView yAxisLabel; private TableLayout streamDescriptionTable; private View streamDescriptionScrollView; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * Inflate the layout for this fragment */ this.container = container; createAlertDialogs(); setHasOptionsMenu(true); return inflater.inflate(R.layout.receiver_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //installCustomWiFiFirmware(); xAxisLabel = (TextView) getView().findViewById(R.id.x_axis); yAxisLabel = (TextView) getView().findViewById(R.id.y_axis); streamDescriptionTable = (TableLayout) getView().findViewById(R.id.streamDescriptionTable); streamDescriptionScrollView = getView().findViewById(R.id.streamDescriptionScrollView); mChart = (HorizontalBarChart) getView().findViewById(R.id.chart1); initializePlot(); udpReceiver = new UDPReceiver(); plotter = new Plotter(); semaphore = new Semaphore(1, true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { this.menu = menu; super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.start: if (item.getTitle().toString().equals("Stop")) { try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 0); Nexutil.getInstance().setIoctl(512, 0); // deactivate filtering for MAC addresses udpReceiver.shutdown(); plotter.shutdown(); item.setTitle("Start"); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } } else { try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 96); Nexutil.getInstance().setIoctl(508); // set NEXMON MAC address Nexutil.getInstance().setIoctl(512, 1); // activate filtering for MAC addresses udpReceiver = new UDPReceiver(); udpReceiver.start(); plotter = new Plotter(); plotter.start(); item.setTitle("Stop"); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } } return true; case R.id.reset: try { Nexutil.getInstance().setIoctl(Nexutil.WLC_SET_MONITOR, 0); Nexutil.getInstance().setIoctl(512, 0); // deactivate filtering for MAC addresses udpReceiver.shutdown(); plotter.shutdown(); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } mChart.clear(); initializePlot(); data = new ConcurrentHashMap<>(); hashes = new ArrayList<>(); packetSet = new TreeSet<>(); menu.findItem(R.id.start).setTitle("Start"); xAxisLabel.setVisibility(View.GONE); yAxisLabel.setVisibility(View.GONE); streamDescriptionScrollView.setVisibility(View.GONE); return true; case R.id.help_receiver: try { String ret = Nexutil.getInstance().getIoctl(500); Log.d("Shell", ret); } catch (Nexutil.FirmwareNotFoundException e) { MainActivity.getInstance().getFirmwareDialog().show(); } helpDialog.show(); return true; } return super.onOptionsItemSelected(item); } public void createAlertDialogs() { View list_layout = getActivity().getLayoutInflater().inflate(R.layout.help_receiver, null, true); WebView wvHelp = (WebView) list_layout.findViewById(R.id.wvHelp); wvHelp.loadUrl("file:///android_asset/html/help_receiver.html"); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(list_layout); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton("CLOSE", null); // create alert dialog helpDialog = alertDialogBuilder.create(); } private void initializePlot() { mChart.getDescription().setEnabled(false); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(40); mChart.setNoDataText("No packets were received yet"); mChart.setAutoScaleMinMaxEnabled(false); mChart.setKeepPositionOnRotation(true); mChart.setPinchZoom(true); mChart.setDrawGridBackground(false); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(false); mChart.setHighlightFullBarEnabled(false); mChart.setHighlightPerTapEnabled(false); mChart.setHighlightPerDragEnabled(false); mChart.setHardwareAccelerationEnabled(true); // change the position of the y-labels YAxis leftAxis = mChart.getAxisRight(); leftAxis.setDrawGridLines(false); // this replaces setStartAtZero(true) //leftAxis.setValueFormatter(new com.github.mikephil.charting.formatter.LargeValueFormatter()); mChart.getAxisLeft().setEnabled(false); XAxis xAxis = mChart.getXAxis(); xAxis.setValueFormatter(this); xAxis.setGranularity(1); xAxis.setGranularityEnabled(true); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); Legend l = mChart.getLegend(); l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); l.setOrientation(Legend.LegendOrientation.HORIZONTAL); l.setDrawInside(false); l.setFormSize(8f); l.setFormToTextSpace(4f); l.setXEntrySpace(6f); } private void updatePlot() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { ArrayList<BarEntry> yVals = new ArrayList<BarEntry>(); streamDescriptionTable.removeAllViews(); final TableRow tableHeader = (TableRow) getActivity().getLayoutInflater().inflate(R.layout.receiver_plot_table_header, null); //Add row to the table streamDescriptionTable.addView(tableHeader); int i = 0; for (HashMap.Entry<String, float[]> entry : data.entrySet()) { String key = entry.getKey(); String[] params = key.split("-"); final TableRow tableRow = (TableRow) getActivity().getLayoutInflater().inflate(R.layout.receiver_plot_table_row, null); TextView tv; //Filling in cells tv = (TextView) tableRow.findViewById(R.id.nameValue); tv.setText("Stream " + i); tv = (TextView) tableRow.findViewById(R.id.nodeValue); tv.setText(params[0]); tv = (TextView) tableRow.findViewById(R.id.portValue); tv.setText(params[1]); tv = (TextView) tableRow.findViewById(R.id.encodingValue); switch (params[2]) { case "1": tv.setText("11b"); break; case "2": tv.setText("11a/g"); break; case "3": tv.setText("11n"); break; case "4": tv.setText("11ac"); break; } tv = (TextView) tableRow.findViewById(R.id.bandwidthValue); switch (params[3]) { case "0": tv.setText("20 MHz"); break; case "1": tv.setText("80 MHz"); break; case "2": tv.setText("80 MHz"); break; } tv = (TextView) tableRow.findViewById(R.id.rateValue); switch (params[2]) { case "1": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; case "2": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; case "3": tv.setText("MCS " + params[4]); break; case "4": tv.setText(((double) Integer.parseInt(params[4]) / 2) + " Mbps"); break; } tv = (TextView) tableRow.findViewById(R.id.ldpcValue); tv.setText(params[5]); tableRow.setBackgroundColor(i % 2 == 0 ? rgb("#DCDCDC") : rgb("#ffffff")); //Add row to the table streamDescriptionTable.addView(tableRow); float[] value = entry.getValue(); float val1 = value[1]; float val2 = value[0]; yVals.add(new BarEntry(i, new float[]{val1, val2})); i++; } BarDataSet set; if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) { set = (BarDataSet) mChart.getData().getDataSetByIndex(0); set.setValues(yVals); mChart.getData().notifyDataChanged(); mChart.notifyDataSetChanged(); } else { set = new BarDataSet(yVals, ""); set.setDrawIcons(false); set.setColors(getColors()); set.setStackLabels(new String[]{"FCS incorrect", "FCS correct"}); ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); dataSets.add(set); BarData data = new BarData(dataSets); //data.setValueFormatter(new com.github.mikephil.charting.formatter.LargeValueFormatter()); mChart.setData(data); } mChart.setFitBars(true); xAxisLabel.setVisibility(View.VISIBLE); yAxisLabel.setVisibility(View.VISIBLE); streamDescriptionScrollView.setVisibility(View.VISIBLE); mChart.invalidate(); } }); } @Override public String getFormattedValue(float value, AxisBase axis) { // "value" represents the position of the label on the axis (x or y) return "Stream " + (int) value; } private int[] getColors() { int stacksize = 2; // have as many colors as stack-values per entry int[] colors = new int[stacksize]; colors[0] = ColorsTuDarmstadt.COLOR_1B; colors[1] = ColorsTuDarmstadt.COLOR_6B; return colors; } private final class UDPReceiver extends Thread { public static final int RECV_BUFFER_SIZE = 1000; private static final String TAG = "UDPReceiverThread"; private final char[] hexArray = "0123456789ABCDEF".toCharArray(); private boolean mContinueRunning = true; private DatagramSocket mSocket = null; public String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public void run() { Log.d(TAG, "Thread run"); mContinueRunning = true; try { mSocket = new DatagramSocket(5500); } catch (SocketException e) { // TODO: Handle address already in use. Log.d(TAG, "Error opening the UDP socket."); e.printStackTrace(); return; } byte[] buffer = new byte[RECV_BUFFER_SIZE]; DatagramPacket p = new DatagramPacket(buffer, buffer.length); while (mContinueRunning) { try { mSocket.receive(p); // TODO: Check source address of packet and/or validate it with other means } catch (IOException e) { e.printStackTrace(); } if (!mContinueRunning) { Log.d(TAG, "Stop thread activity..."); break; } Packet packet = new Packet(buffer); //Log.d(TAG, "timestamp: " + packet.timestamp_mac + " port: " + packet.port + " fcs_error error: " + packet.fcs_error + " length: " + packet.length); try { semaphore.acquire(); packetSet.add(packet); if (!data.containsKey(packet.hash)) { hashes.add(packet.hash); data.put(packet.hash, new float[2]); Log.d(TAG, "add " + packet.hash); } semaphore.release(); } catch (Exception e) { e.printStackTrace(); } } Log.d(TAG, "Thread afterrun"); } public void shutdown() { mContinueRunning = false; mSocket.close(); } } private final class Plotter extends Thread { private static final String TAG = "PlotterThread"; private boolean mContinueRunning = true; public void run() { Log.d(TAG, "Plotter Thread run"); mContinueRunning = true; while (mContinueRunning) { try { long windows_size = 1L; int count_removes = 0; long current_time = System.nanoTime(); long time = current_time - windows_size * 1000000000L; //Log.d(TAG, "acquiring Semaphore"); semaphore.acquire(); for (Iterator<Packet> i = packetSet.iterator(); i.hasNext(); ) { Packet pa = i.next(); if (pa.timestamp_android < time) { i.remove(); count_removes++; } } if (hashes.size() > 0) { for (String hash : hashes) { int sum_length_fcs_1 = 0; int sum_length_fcs_0 = 0; for (Iterator<Packet> i = packetSet.iterator(); i.hasNext(); ) { Packet pa = i.next(); if (hash.equals(pa.hash)) { if (pa.fcs_error) { sum_length_fcs_1 += pa.length; } else { sum_length_fcs_0 += pa.length; } } } float throughput_fcs_0 = sum_length_fcs_0 / windows_size * 8 / 1e6f; float throughput_fcs_1 = sum_length_fcs_1 / windows_size * 8 / 1e6f; data.get(hash)[0] = throughput_fcs_0; data.get(hash)[1] = throughput_fcs_1; if (data.size() > 0) updatePlot(); //Log.d(TAG, "Plotting!!!"); } } semaphore.release(); //Log.d(TAG, "releasing Semaphore"); sleep(1000); if (!mContinueRunning) { Log.d(TAG, "Stop thread activity..."); break; } } catch (Exception e) { e.printStackTrace(); } } Log.d(TAG, "Plotter afterrun"); } public void shutdown() { mContinueRunning = false; } } /* struct jamming_receiver_header {<SUF>*/ public class Packet implements Comparable<Packet> { long timestamp_mac; long timestamp_android; int port; boolean fcs_error; int length; byte encoding; byte bandwidth; int rate; boolean ldpc; String hash; String node; public Packet(byte buffer[]) { ByteBuffer buf = ByteBuffer.wrap(buffer); buf.order(ByteOrder.LITTLE_ENDIAN); this.timestamp_mac = (long) buf.getInt() & 0xffffffffL; this.timestamp_android = System.nanoTime(); this.node = String.format("%04x", (int) buf.getShort() & 0xffff); this.port = (int) buf.getShort() & 0xffff; this.fcs_error = ((int) buf.get() & 0xf) == 1; this.length = (int) buf.getShort() & 0xffff; this.encoding = buf.get(); this.bandwidth = buf.get(); this.rate = (int) buf.getShort() & 0xffff; this.ldpc = ((int) buf.get() & 0xf) == 1; this.hash = node + "-" + port + "-" + encoding + "-" + bandwidth + "-" + rate + "-" + ldpc; } public int compareTo(Packet other) { return Long.compare(this.timestamp_android, other.timestamp_android); } } }
118739_2
/* * Copyright 2012-2014 eBay Software Foundation and selendroid committers. * * 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 io.selendroid.server.handler; import io.selendroid.server.common.Response; import io.selendroid.server.common.SelendroidResponse; import io.selendroid.server.common.http.HttpRequest; import io.selendroid.server.model.AndroidElement; import io.selendroid.server.model.Session; import io.selendroid.server.util.SelendroidLogger; import org.json.JSONException; import org.json.JSONObject; /** * Send keys to a given element. */ public class SendKeysToElement extends SafeRequestHandler { public SendKeysToElement(String mappedUri) { super(mappedUri); } @Override public Response safeHandle(HttpRequest request) throws JSONException { SelendroidLogger.info("send keys to element command"); String id = getElementId(request); AndroidElement element = getElementFromCache(request, id); String[] keysToSend = extractKeysToSendFromPayload(request); if (isNativeEvents(request)) { element.enterText(keysToSend); }else{ element.setText(keysToSend); } return new SelendroidResponse(getSessionId(request), ""); } boolean isNativeEvents(HttpRequest request) { JSONObject config = getSelendroidDriver(request).getSession().getCommandConfiguration( Session.SEND_KEYS_TO_ELEMENT); if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) { try { return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY); } catch (JSONException e) {} } // default is native events return true; } }
selendroid/selendroid
selendroid-server/src/main/java/io/selendroid/server/handler/SendKeysToElement.java
608
// default is native events
line_comment
nl
/* * Copyright 2012-2014 eBay Software Foundation and selendroid committers. * * 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 io.selendroid.server.handler; import io.selendroid.server.common.Response; import io.selendroid.server.common.SelendroidResponse; import io.selendroid.server.common.http.HttpRequest; import io.selendroid.server.model.AndroidElement; import io.selendroid.server.model.Session; import io.selendroid.server.util.SelendroidLogger; import org.json.JSONException; import org.json.JSONObject; /** * Send keys to a given element. */ public class SendKeysToElement extends SafeRequestHandler { public SendKeysToElement(String mappedUri) { super(mappedUri); } @Override public Response safeHandle(HttpRequest request) throws JSONException { SelendroidLogger.info("send keys to element command"); String id = getElementId(request); AndroidElement element = getElementFromCache(request, id); String[] keysToSend = extractKeysToSendFromPayload(request); if (isNativeEvents(request)) { element.enterText(keysToSend); }else{ element.setText(keysToSend); } return new SelendroidResponse(getSessionId(request), ""); } boolean isNativeEvents(HttpRequest request) { JSONObject config = getSelendroidDriver(request).getSession().getCommandConfiguration( Session.SEND_KEYS_TO_ELEMENT); if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) { try { return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY); } catch (JSONException e) {} } // default is<SUF> return true; } }
178081_0
package com.semdejong.week2; class Medewerker { String naam; static int kluiscode; } class TestMedewerker { public static void main(String[] args) { Medewerker med1 = new Medewerker(); Medewerker med2 = new Medewerker(); med1.kluiscode = 12345; med2.kluiscode = 54321; System.out.println(med1.kluiscode); // print 54321, want de code is aangepast door med2 System.out.println(med2.kluiscode); // print 54321 System.out.println(Medewerker.kluiscode); // print 54321 } }
semdejong/ItVitae-java-group-50
src/com/semdejong/week2/StaticExample.java
196
// print 54321, want de code is aangepast door med2
line_comment
nl
package com.semdejong.week2; class Medewerker { String naam; static int kluiscode; } class TestMedewerker { public static void main(String[] args) { Medewerker med1 = new Medewerker(); Medewerker med2 = new Medewerker(); med1.kluiscode = 12345; med2.kluiscode = 54321; System.out.println(med1.kluiscode); // print 54321,<SUF> System.out.println(med2.kluiscode); // print 54321 System.out.println(Medewerker.kluiscode); // print 54321 } }
172864_1
package hpi.rcstream; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by magnus on 19.04.16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RCFeedEntry { public String comment; // "[[:File:Nl-geheugenplaatsjes.ogg]] added to category" public String wiki; // "commonswiki" public String server_name; // "commons.wikimedia.org" public String title; // "Category:Male Dutch pronunciation" public long timestamp; // 1461069130 public String server_script_path; // "/w" public int namespace; // 14 public String server_url; // "https://commons.wikimedia.org" public String user; // "RileyBot" public Boolean bot; // true public String type; // "categorize" public long id; // 215733984 public Object length; @Override public String toString() { return type.toUpperCase() + " " + id + ": " + title + " " + user + (bot?"(bot) ":" "); } }
semmul2016group4/RCStream
src/main/java/hpi/rcstream/RCFeedEntry.java
301
// "[[:File:Nl-geheugenplaatsjes.ogg]] added to category"
line_comment
nl
package hpi.rcstream; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by magnus on 19.04.16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RCFeedEntry { public String comment; // "[[:File:Nl-geheugenplaatsjes.ogg]] added<SUF> public String wiki; // "commonswiki" public String server_name; // "commons.wikimedia.org" public String title; // "Category:Male Dutch pronunciation" public long timestamp; // 1461069130 public String server_script_path; // "/w" public int namespace; // 14 public String server_url; // "https://commons.wikimedia.org" public String user; // "RileyBot" public Boolean bot; // true public String type; // "categorize" public long id; // 215733984 public Object length; @Override public String toString() { return type.toUpperCase() + " " + id + ": " + title + " " + user + (bot?"(bot) ":" "); } }
34059_1
/** * LICENSE INFORMATION * * Copyright 2005-2008 by FZI (http://www.fzi.de). Licensed under a BSD license * (http://www.opensource.org/licenses/bsd-license.php) <OWNER> = Max Völkel * <ORGANIZATION> = FZI Forschungszentrum Informatik Karlsruhe, Karlsruhe, * Germany <YEAR> = 2010 * * Further project information at http://semanticweb.org/wiki/RDF2Go */ package org.ontoware.rdf2go.model; import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.exception.ModelRuntimeException; import org.ontoware.rdf2go.model.node.NodeOrVariable; import org.ontoware.rdf2go.model.node.ResourceOrVariable; import org.ontoware.rdf2go.model.node.UriOrVariable; /** * * @author voelkel */ public interface FindableModelSet { /** * Search across all existing models * * @param contextURI * @param subject * @param predicate * @param object * @return all matching statements in all models * @throws ModelRuntimeException */ ClosableIterator<Statement> findStatements(UriOrVariable contextURI, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException; /** * Search across all existing models * * @param pattern * @return all statements matching the quad pattern * @throws ModelRuntimeException */ ClosableIterator<Statement> findStatements(QuadPattern pattern) throws ModelRuntimeException; /** * @param contextURI * @param subject * @param predicate * @param object * @return true, if a Model named 'contextURI' contains the statement * (s,p,o) * @throws ModelRuntimeException */ boolean containsStatements(UriOrVariable contextURI, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException; /** * @param s a Statement * @return true if the modelset contains a model with context s.getContext() * which contains the statement s. If the context is null, the * default graph is checked. * @throws ModelRuntimeException */ boolean contains(Statement s) throws ModelRuntimeException; /** * @param pattern * @return the number of statements matchingthe pattern. This is for all * graphs matching the context of the pattern (this is none, one or * all graphs). In matching graphs the number of matching statements * is accumulated and returned. * @throws ModelRuntimeException */ long countStatements(QuadPattern pattern) throws ModelRuntimeException; /** * @param context * @param subject * @param predicate * @param object * @return a QuadPattern */ QuadPattern createQuadPattern(UriOrVariable context, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object); }
semweb4j/semweb4j
org.semweb4j.rdf2go.api/src/main/java/org/ontoware/rdf2go/model/FindableModelSet.java
895
/** * * @author voelkel */
block_comment
nl
/** * LICENSE INFORMATION * * Copyright 2005-2008 by FZI (http://www.fzi.de). Licensed under a BSD license * (http://www.opensource.org/licenses/bsd-license.php) <OWNER> = Max Völkel * <ORGANIZATION> = FZI Forschungszentrum Informatik Karlsruhe, Karlsruhe, * Germany <YEAR> = 2010 * * Further project information at http://semanticweb.org/wiki/RDF2Go */ package org.ontoware.rdf2go.model; import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.exception.ModelRuntimeException; import org.ontoware.rdf2go.model.node.NodeOrVariable; import org.ontoware.rdf2go.model.node.ResourceOrVariable; import org.ontoware.rdf2go.model.node.UriOrVariable; /** * * @author voelkel <SUF>*/ public interface FindableModelSet { /** * Search across all existing models * * @param contextURI * @param subject * @param predicate * @param object * @return all matching statements in all models * @throws ModelRuntimeException */ ClosableIterator<Statement> findStatements(UriOrVariable contextURI, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException; /** * Search across all existing models * * @param pattern * @return all statements matching the quad pattern * @throws ModelRuntimeException */ ClosableIterator<Statement> findStatements(QuadPattern pattern) throws ModelRuntimeException; /** * @param contextURI * @param subject * @param predicate * @param object * @return true, if a Model named 'contextURI' contains the statement * (s,p,o) * @throws ModelRuntimeException */ boolean containsStatements(UriOrVariable contextURI, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException; /** * @param s a Statement * @return true if the modelset contains a model with context s.getContext() * which contains the statement s. If the context is null, the * default graph is checked. * @throws ModelRuntimeException */ boolean contains(Statement s) throws ModelRuntimeException; /** * @param pattern * @return the number of statements matchingthe pattern. This is for all * graphs matching the context of the pattern (this is none, one or * all graphs). In matching graphs the number of matching statements * is accumulated and returned. * @throws ModelRuntimeException */ long countStatements(QuadPattern pattern) throws ModelRuntimeException; /** * @param context * @param subject * @param predicate * @param object * @return a QuadPattern */ QuadPattern createQuadPattern(UriOrVariable context, ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object); }
44571_0
public class DataController { private static DataController instance = null; ModelDiagram md; // mogelijk meerdere diagrammen? private DataController() { } public DataController getInstance() { if(instance == null) instance = new DataController(); return instance; } public ModelDiagram getModel() { } }
senkz/PaF-Relationship-helper-for-usecases-and-UML
src/DataController.java
99
// mogelijk meerdere diagrammen?
line_comment
nl
public class DataController { private static DataController instance = null; ModelDiagram md; // mogelijk meerdere<SUF> private DataController() { } public DataController getInstance() { if(instance == null) instance = new DataController(); return instance; } public ModelDiagram getModel() { } }
48363_35
package me.rigamortis.seppuku.impl.patch; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import me.rigamortis.seppuku.Seppuku; import me.rigamortis.seppuku.api.event.player.EventFovModifier; import me.rigamortis.seppuku.api.event.player.EventGetMouseOver; import me.rigamortis.seppuku.api.event.player.EventPlayerReach; import me.rigamortis.seppuku.api.event.render.*; import me.rigamortis.seppuku.api.patch.ClassPatch; import me.rigamortis.seppuku.api.patch.MethodPatch; import me.rigamortis.seppuku.api.util.ASMUtil; import me.rigamortis.seppuku.impl.management.PatchManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.util.EntitySelectors; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import team.stiff.pomelo.EventManager; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import static org.objectweb.asm.Opcodes.*; /** * Author Seth * 4/6/2019 @ 12:46 PM. */ public final class EntityRendererPatch extends ClassPatch { public EntityRendererPatch() { super("net.minecraft.client.renderer.EntityRenderer", "buq"); } /** * This is our 2d render context * Anything rendered here will be in screen space * It should be called after forge and have top priority * * @param partialTicks */ public static void updateCameraAndRenderHook(float partialTicks) { //dispatch our event so we can render stuff on our screen Seppuku.INSTANCE.getEventManager().dispatchEvent(new EventRender2D(partialTicks, new ScaledResolution(Minecraft.getMinecraft()))); } /** * This is our 3d render context * Anything rendered here will be rendered in world space * before your hand * * @param partialTicks */ public static void renderWorldPassHook(float partialTicks) { if (Seppuku.INSTANCE.getCameraManager().isCameraRecording()) { return; } //dispatch our event and pass partial ticks in Seppuku.INSTANCE.getEventManager().dispatchEvent(new EventRender3D(partialTicks)); } /** * Our hurtCameraEffect hook * Used to disable the screen shaking effect while taking damage * * @return */ public static boolean hurtCameraEffectHook() { //dispatch our event final EventHurtCamEffect event = new EventHurtCamEffect(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } public static boolean orientCameraHook() { final EventOrientCamera event = new EventOrientCamera(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } /** * getMouseOver (original game function with modified event handling) * * @param partialTicks */ public static void getMouseOverHook(float partialTicks) { final Minecraft mc = Minecraft.getMinecraft(); final Entity entity = mc.getRenderViewEntity(); if (entity != null && mc.world != null) { mc.profiler.startSection("pick"); mc.pointedEntity = null; double d0 = mc.playerController.getBlockReachDistance(); mc.objectMouseOver = entity.rayTrace(d0, partialTicks); Vec3d vec3d = entity.getPositionEyes(partialTicks); boolean flag = false; double d1 = d0; if (mc.playerController.extendedReach()) { final EventPlayerReach event = new EventPlayerReach(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); d1 = event.isCanceled() ? event.getReach() : 6.0d; d0 = d1; } else if (d0 > 3.0D) { flag = true; } if (mc.objectMouseOver != null) { d1 = mc.objectMouseOver.hitVec.distanceTo(vec3d); } Vec3d vec3d1 = entity.getLook(1.0F); Vec3d vec3d2 = vec3d.add(vec3d1.x * d0, vec3d1.y * d0, vec3d1.z * d0); mc.entityRenderer.pointedEntity = null; Vec3d vec3d3 = null; float f = 1.0F; List<Entity> list = mc.world.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().expand(vec3d1.x * d0, vec3d1.y * d0, vec3d1.z * d0).grow(1.0D, 1.0D, 1.0D), Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate<Entity>() { public boolean apply(@Nullable Entity p_apply_1_) { return p_apply_1_ != null && p_apply_1_.canBeCollidedWith(); } })); final EventGetMouseOver event = new EventGetMouseOver(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); if (event.isCanceled()) { list = new ArrayList<>(); } double d2 = d1; for (int j = 0; j < list.size(); ++j) { Entity entity1 = list.get(j); AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().grow(entity1.getCollisionBorderSize()); RayTraceResult raytraceresult = axisalignedbb.calculateIntercept(vec3d, vec3d2); if (axisalignedbb.contains(vec3d)) { if (d2 >= 0.0D) { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult == null ? vec3d : raytraceresult.hitVec; d2 = 0.0D; } } else if (raytraceresult != null) { double d3 = vec3d.distanceTo(raytraceresult.hitVec); if (d3 < d2 || d2 == 0.0D) { if (entity1.getLowestRidingEntity() == entity.getLowestRidingEntity() && !entity1.canRiderInteract()) { if (d2 == 0.0D) { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult.hitVec; } } else { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult.hitVec; d2 = d3; } } } } if (mc.entityRenderer.pointedEntity != null && flag && vec3d.distanceTo(vec3d3) > 3.0D) { mc.entityRenderer.pointedEntity = null; mc.objectMouseOver = new RayTraceResult(RayTraceResult.Type.MISS, vec3d3, null, new BlockPos(vec3d3)); } if (mc.entityRenderer.pointedEntity != null && (d2 < d1 || mc.objectMouseOver == null)) { mc.objectMouseOver = new RayTraceResult(mc.entityRenderer.pointedEntity, vec3d3); if (mc.entityRenderer.pointedEntity instanceof EntityLivingBase || mc.entityRenderer.pointedEntity instanceof EntityItemFrame) { mc.pointedEntity = mc.entityRenderer.pointedEntity; } } mc.profiler.endSection(); } } /** * This is our renderName hook * Used to disable rendering minecrafts default * name tags on certain entities * * @param fontRenderer * @param str * @param x * @param y * @param z * @param verticalShift * @param viewerYaw * @param viewerPitch * @param isThirdPersonFrontal * @param isSneaking * @return */ public static boolean drawNameplateHook(FontRenderer fontRenderer, String str, float x, float y, float z, int verticalShift, float viewerYaw, float viewerPitch, boolean isThirdPersonFrontal, boolean isSneaking) { //dispatch our event and pass the entity in final EventDrawNameplate event = new EventDrawNameplate(fontRenderer, str, x, y, z, verticalShift, viewerYaw, viewerPitch, isThirdPersonFrontal, isSneaking); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } /** * This is where we place our 2d rendering context * * @param methodNode * @param env */ @MethodPatch( mcpName = "updateCameraAndRender", notchName = "a", mcpDesc = "(FJ)V") public void updateCameraAndRender(MethodNode methodNode, PatchManager.Environment env) { //find the instruction that calls renderGameOverlay final AbstractInsnNode target = ASMUtil.findMethodInsn(methodNode, INVOKEVIRTUAL, env == PatchManager.Environment.IDE ? "net/minecraft/client/gui/GuiIngame" : "biq", env == PatchManager.Environment.IDE ? "renderGameOverlay" : "a", "(F)V"); if (target != null) { //create a list of instructions final InsnList insnList = new InsnList(); //add FLOAD to pass partialTicks param into our hook function insnList.add(new VarInsnNode(FLOAD, 1)); //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "updateCameraAndRenderHook", "(F)V", false)); //insert our instructions after the renderGameOverlay call methodNode.instructions.insert(target, insnList); } } /** * This is where we place our 3d rendering context * * @param methodNode * @param env */ @MethodPatch( mcpName = "renderWorldPass", notchName = "a", mcpDesc = "(IFJ)V") public void renderWorldPass(MethodNode methodNode, PatchManager.Environment env) { //find the LDC instruction with the value "hand" //there is only 1 in this function and its passed into the call //mc.mcProfiler.endStartSection("hand"); final AbstractInsnNode target = ASMUtil.findInsnLdc(methodNode, "hand"); if (target != null) { //make a list of instructions final InsnList list = new InsnList(); //add FLOAD to pass the partialTicks param into our hook function list.add(new VarInsnNode(FLOAD, 2)); //call our hook function list.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "renderWorldPassHook", "(F)V", false)); //insert the list of instructions 1 instruction after the LDC methodNode.instructions.insert(target.getNext(), list); } } /** * This is where minecraft rotates and shakes your screen * while taking damage * * @param methodNode * @param env */ @MethodPatch( mcpName = "hurtCameraEffect", notchName = "d", mcpDesc = "(F)V") public void hurtCameraEffect(MethodNode methodNode, PatchManager.Environment env) { //create a list of instructions and add the needed instructions to call our hook function final InsnList insnList = new InsnList(); //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "hurtCameraEffectHook", "()Z", false)); //add a label to jump to final LabelNode jmp = new LabelNode(); //add if equals and pass the label insnList.add(new JumpInsnNode(IFEQ, jmp)); //add return so the rest of the function doesn't get called insnList.add(new InsnNode(RETURN)); //add our label insnList.add(jmp); //insert the list of instructions at the top of the function methodNode.instructions.insert(insnList); } @MethodPatch( mcpName = "orientCamera", notchName = "f", mcpDesc = "(F)V") public void orientCamera(MethodNode methodNode, PatchManager.Environment env) { final AbstractInsnNode target = ASMUtil.findMethodInsn(methodNode, INVOKEVIRTUAL, env == PatchManager.Environment.IDE ? "net/minecraft/client/multiplayer/WorldClient" : "bsb", env == PatchManager.Environment.IDE ? "rayTraceBlocks" : "a", env == PatchManager.Environment.IDE ? "(Lnet/minecraft/util/math/Vec3d;Lnet/minecraft/util/math/Vec3d;)Lnet/minecraft/util/math/RayTraceResult;" : "(Lbhe;Lbhe;)Lbhc;"); if (target != null) { final InsnList insnList = new InsnList(); insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "orientCameraHook", "()Z", false)); final LabelNode jmp = new LabelNode(); insnList.add(new JumpInsnNode(IFEQ, jmp)); insnList.add(new InsnNode(ACONST_NULL)); insnList.add(new VarInsnNode(ASTORE, 24)); insnList.add(jmp); methodNode.instructions.insert(target.getNext(), insnList); } } //private void setupFog(int startCoords, float partialTicks) { // @MethodPatch( // mcpName = "setupFog", // notchName = "a", // mcpDesc = "(IF)V") // public void setupFog(MethodNode methodNode, PatchManager.Environment env) { // final InsnList insnList = new InsnList(); // insnList.add(new VarInsnNode(ILOAD, 1)); // insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "setupFogHook", "(I)V", false)); // //insnList.add(new InsnNode(RETURN)); // methodNode.instructions.insert(insnList); // } // // public static void setupFogHook(int startCoords) { // final EventSetupFog event = new EventSetupFog(startCoords); // Seppuku.INSTANCE.getEventManager().dispatchEvent(event); // } @MethodPatch( mcpName = "getFOVModifier", notchName = "a", mcpDesc = "(FZ)F") public void getFovModifier(MethodNode methodNode, PatchManager.Environment env) { final InsnList insnList = new InsnList(); insnList.add(new TypeInsnNode(NEW, Type.getInternalName(EventFovModifier.class))); insnList.add(new InsnNode(DUP)); insnList.add(new MethodInsnNode(INVOKESPECIAL, Type.getInternalName(EventFovModifier.class), "<init>", "()V", false)); insnList.add(new VarInsnNode(ASTORE, 5)); insnList.add(new FieldInsnNode(GETSTATIC, Type.getInternalName(Seppuku.class), "INSTANCE", "Lme/rigamortis/seppuku/Seppuku;")); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Seppuku.class), "getEventManager", "()Lteam/stiff/pomelo/EventManager;", false)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(EventManager.class), "dispatchEvent", "(Ljava/lang/Object;)Ljava/lang/Object;", true)); insnList.add(new InsnNode(POP)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(EventFovModifier.class), "isCanceled", "()Z", false)); final LabelNode label = new LabelNode(); insnList.add(new JumpInsnNode(IFEQ, label)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(EventFovModifier.class), "getFov", "()F", false)); insnList.add(new InsnNode(FRETURN)); insnList.add(label); methodNode.instructions.insert(insnList); } @MethodPatch( mcpName = "getMouseOver", notchName = "a", mcpDesc = "(F)V") public void getMouseOver(MethodNode methodNode, PatchManager.Environment env) { final InsnList insnList = new InsnList(); insnList.add(new VarInsnNode(FLOAD, 1)); insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "getMouseOverHook", "(F)V", false)); insnList.add(new InsnNode(RETURN)); methodNode.instructions.insert(insnList); } /** * This is where minecraft renders name plates * * @param methodNode * @param env */ @MethodPatch( mcpName = "drawNameplate", notchName = "a", mcpDesc = "(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;FFFIFFZZ)V", notchDesc = "(Lbip;Ljava/lang/String;FFFIFFZZ)V") public void drawNameplate(MethodNode methodNode, PatchManager.Environment env) { //create a list of instructions and add the needed instructions to call our hook function final InsnList insnList = new InsnList(); //add ALOAD instructions to pass all arguments into our hook function //drawNameplate is static so argument indices start from 0 since there is no `this` insnList.add(new VarInsnNode(ALOAD, 0)); // fontRenderer insnList.add(new VarInsnNode(ALOAD, 1)); // str insnList.add(new VarInsnNode(FLOAD, 2)); // x insnList.add(new VarInsnNode(FLOAD, 3)); // y insnList.add(new VarInsnNode(FLOAD, 4)); // z insnList.add(new VarInsnNode(ILOAD, 5)); // verticalShift insnList.add(new VarInsnNode(FLOAD, 6)); // viewerYaw insnList.add(new VarInsnNode(FLOAD, 7)); // viewerPitch insnList.add(new VarInsnNode(ILOAD, 8)); // isThirdPersonFrontal insnList.add(new VarInsnNode(ILOAD, 9)); // isSneaking //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "drawNameplateHook", env == PatchManager.Environment.IDE ? "(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;FFFIFFZZ)Z" : "(Lbip;Ljava/lang/String;FFFIFFZZ)Z", false)); //add a label to jump to final LabelNode jmp = new LabelNode(); //add if equals and pass the label insnList.add(new JumpInsnNode(IFEQ, jmp)); //add return so the rest of the function doesn't get called insnList.add(new InsnNode(RETURN)); //add our label insnList.add(jmp); //insert the list of instructions at the top of the function methodNode.instructions.insert(insnList); } }
seppukudevelopment/seppuku
src/main/java/me/rigamortis/seppuku/impl/patch/EntityRendererPatch.java
5,700
// public void setupFog(MethodNode methodNode, PatchManager.Environment env) {
line_comment
nl
package me.rigamortis.seppuku.impl.patch; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import me.rigamortis.seppuku.Seppuku; import me.rigamortis.seppuku.api.event.player.EventFovModifier; import me.rigamortis.seppuku.api.event.player.EventGetMouseOver; import me.rigamortis.seppuku.api.event.player.EventPlayerReach; import me.rigamortis.seppuku.api.event.render.*; import me.rigamortis.seppuku.api.patch.ClassPatch; import me.rigamortis.seppuku.api.patch.MethodPatch; import me.rigamortis.seppuku.api.util.ASMUtil; import me.rigamortis.seppuku.impl.management.PatchManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.util.EntitySelectors; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import team.stiff.pomelo.EventManager; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import static org.objectweb.asm.Opcodes.*; /** * Author Seth * 4/6/2019 @ 12:46 PM. */ public final class EntityRendererPatch extends ClassPatch { public EntityRendererPatch() { super("net.minecraft.client.renderer.EntityRenderer", "buq"); } /** * This is our 2d render context * Anything rendered here will be in screen space * It should be called after forge and have top priority * * @param partialTicks */ public static void updateCameraAndRenderHook(float partialTicks) { //dispatch our event so we can render stuff on our screen Seppuku.INSTANCE.getEventManager().dispatchEvent(new EventRender2D(partialTicks, new ScaledResolution(Minecraft.getMinecraft()))); } /** * This is our 3d render context * Anything rendered here will be rendered in world space * before your hand * * @param partialTicks */ public static void renderWorldPassHook(float partialTicks) { if (Seppuku.INSTANCE.getCameraManager().isCameraRecording()) { return; } //dispatch our event and pass partial ticks in Seppuku.INSTANCE.getEventManager().dispatchEvent(new EventRender3D(partialTicks)); } /** * Our hurtCameraEffect hook * Used to disable the screen shaking effect while taking damage * * @return */ public static boolean hurtCameraEffectHook() { //dispatch our event final EventHurtCamEffect event = new EventHurtCamEffect(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } public static boolean orientCameraHook() { final EventOrientCamera event = new EventOrientCamera(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } /** * getMouseOver (original game function with modified event handling) * * @param partialTicks */ public static void getMouseOverHook(float partialTicks) { final Minecraft mc = Minecraft.getMinecraft(); final Entity entity = mc.getRenderViewEntity(); if (entity != null && mc.world != null) { mc.profiler.startSection("pick"); mc.pointedEntity = null; double d0 = mc.playerController.getBlockReachDistance(); mc.objectMouseOver = entity.rayTrace(d0, partialTicks); Vec3d vec3d = entity.getPositionEyes(partialTicks); boolean flag = false; double d1 = d0; if (mc.playerController.extendedReach()) { final EventPlayerReach event = new EventPlayerReach(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); d1 = event.isCanceled() ? event.getReach() : 6.0d; d0 = d1; } else if (d0 > 3.0D) { flag = true; } if (mc.objectMouseOver != null) { d1 = mc.objectMouseOver.hitVec.distanceTo(vec3d); } Vec3d vec3d1 = entity.getLook(1.0F); Vec3d vec3d2 = vec3d.add(vec3d1.x * d0, vec3d1.y * d0, vec3d1.z * d0); mc.entityRenderer.pointedEntity = null; Vec3d vec3d3 = null; float f = 1.0F; List<Entity> list = mc.world.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().expand(vec3d1.x * d0, vec3d1.y * d0, vec3d1.z * d0).grow(1.0D, 1.0D, 1.0D), Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate<Entity>() { public boolean apply(@Nullable Entity p_apply_1_) { return p_apply_1_ != null && p_apply_1_.canBeCollidedWith(); } })); final EventGetMouseOver event = new EventGetMouseOver(); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); if (event.isCanceled()) { list = new ArrayList<>(); } double d2 = d1; for (int j = 0; j < list.size(); ++j) { Entity entity1 = list.get(j); AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().grow(entity1.getCollisionBorderSize()); RayTraceResult raytraceresult = axisalignedbb.calculateIntercept(vec3d, vec3d2); if (axisalignedbb.contains(vec3d)) { if (d2 >= 0.0D) { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult == null ? vec3d : raytraceresult.hitVec; d2 = 0.0D; } } else if (raytraceresult != null) { double d3 = vec3d.distanceTo(raytraceresult.hitVec); if (d3 < d2 || d2 == 0.0D) { if (entity1.getLowestRidingEntity() == entity.getLowestRidingEntity() && !entity1.canRiderInteract()) { if (d2 == 0.0D) { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult.hitVec; } } else { mc.entityRenderer.pointedEntity = entity1; vec3d3 = raytraceresult.hitVec; d2 = d3; } } } } if (mc.entityRenderer.pointedEntity != null && flag && vec3d.distanceTo(vec3d3) > 3.0D) { mc.entityRenderer.pointedEntity = null; mc.objectMouseOver = new RayTraceResult(RayTraceResult.Type.MISS, vec3d3, null, new BlockPos(vec3d3)); } if (mc.entityRenderer.pointedEntity != null && (d2 < d1 || mc.objectMouseOver == null)) { mc.objectMouseOver = new RayTraceResult(mc.entityRenderer.pointedEntity, vec3d3); if (mc.entityRenderer.pointedEntity instanceof EntityLivingBase || mc.entityRenderer.pointedEntity instanceof EntityItemFrame) { mc.pointedEntity = mc.entityRenderer.pointedEntity; } } mc.profiler.endSection(); } } /** * This is our renderName hook * Used to disable rendering minecrafts default * name tags on certain entities * * @param fontRenderer * @param str * @param x * @param y * @param z * @param verticalShift * @param viewerYaw * @param viewerPitch * @param isThirdPersonFrontal * @param isSneaking * @return */ public static boolean drawNameplateHook(FontRenderer fontRenderer, String str, float x, float y, float z, int verticalShift, float viewerYaw, float viewerPitch, boolean isThirdPersonFrontal, boolean isSneaking) { //dispatch our event and pass the entity in final EventDrawNameplate event = new EventDrawNameplate(fontRenderer, str, x, y, z, verticalShift, viewerYaw, viewerPitch, isThirdPersonFrontal, isSneaking); Seppuku.INSTANCE.getEventManager().dispatchEvent(event); return event.isCanceled(); } /** * This is where we place our 2d rendering context * * @param methodNode * @param env */ @MethodPatch( mcpName = "updateCameraAndRender", notchName = "a", mcpDesc = "(FJ)V") public void updateCameraAndRender(MethodNode methodNode, PatchManager.Environment env) { //find the instruction that calls renderGameOverlay final AbstractInsnNode target = ASMUtil.findMethodInsn(methodNode, INVOKEVIRTUAL, env == PatchManager.Environment.IDE ? "net/minecraft/client/gui/GuiIngame" : "biq", env == PatchManager.Environment.IDE ? "renderGameOverlay" : "a", "(F)V"); if (target != null) { //create a list of instructions final InsnList insnList = new InsnList(); //add FLOAD to pass partialTicks param into our hook function insnList.add(new VarInsnNode(FLOAD, 1)); //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "updateCameraAndRenderHook", "(F)V", false)); //insert our instructions after the renderGameOverlay call methodNode.instructions.insert(target, insnList); } } /** * This is where we place our 3d rendering context * * @param methodNode * @param env */ @MethodPatch( mcpName = "renderWorldPass", notchName = "a", mcpDesc = "(IFJ)V") public void renderWorldPass(MethodNode methodNode, PatchManager.Environment env) { //find the LDC instruction with the value "hand" //there is only 1 in this function and its passed into the call //mc.mcProfiler.endStartSection("hand"); final AbstractInsnNode target = ASMUtil.findInsnLdc(methodNode, "hand"); if (target != null) { //make a list of instructions final InsnList list = new InsnList(); //add FLOAD to pass the partialTicks param into our hook function list.add(new VarInsnNode(FLOAD, 2)); //call our hook function list.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "renderWorldPassHook", "(F)V", false)); //insert the list of instructions 1 instruction after the LDC methodNode.instructions.insert(target.getNext(), list); } } /** * This is where minecraft rotates and shakes your screen * while taking damage * * @param methodNode * @param env */ @MethodPatch( mcpName = "hurtCameraEffect", notchName = "d", mcpDesc = "(F)V") public void hurtCameraEffect(MethodNode methodNode, PatchManager.Environment env) { //create a list of instructions and add the needed instructions to call our hook function final InsnList insnList = new InsnList(); //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "hurtCameraEffectHook", "()Z", false)); //add a label to jump to final LabelNode jmp = new LabelNode(); //add if equals and pass the label insnList.add(new JumpInsnNode(IFEQ, jmp)); //add return so the rest of the function doesn't get called insnList.add(new InsnNode(RETURN)); //add our label insnList.add(jmp); //insert the list of instructions at the top of the function methodNode.instructions.insert(insnList); } @MethodPatch( mcpName = "orientCamera", notchName = "f", mcpDesc = "(F)V") public void orientCamera(MethodNode methodNode, PatchManager.Environment env) { final AbstractInsnNode target = ASMUtil.findMethodInsn(methodNode, INVOKEVIRTUAL, env == PatchManager.Environment.IDE ? "net/minecraft/client/multiplayer/WorldClient" : "bsb", env == PatchManager.Environment.IDE ? "rayTraceBlocks" : "a", env == PatchManager.Environment.IDE ? "(Lnet/minecraft/util/math/Vec3d;Lnet/minecraft/util/math/Vec3d;)Lnet/minecraft/util/math/RayTraceResult;" : "(Lbhe;Lbhe;)Lbhc;"); if (target != null) { final InsnList insnList = new InsnList(); insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "orientCameraHook", "()Z", false)); final LabelNode jmp = new LabelNode(); insnList.add(new JumpInsnNode(IFEQ, jmp)); insnList.add(new InsnNode(ACONST_NULL)); insnList.add(new VarInsnNode(ASTORE, 24)); insnList.add(jmp); methodNode.instructions.insert(target.getNext(), insnList); } } //private void setupFog(int startCoords, float partialTicks) { // @MethodPatch( // mcpName = "setupFog", // notchName = "a", // mcpDesc = "(IF)V") // public void<SUF> // final InsnList insnList = new InsnList(); // insnList.add(new VarInsnNode(ILOAD, 1)); // insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "setupFogHook", "(I)V", false)); // //insnList.add(new InsnNode(RETURN)); // methodNode.instructions.insert(insnList); // } // // public static void setupFogHook(int startCoords) { // final EventSetupFog event = new EventSetupFog(startCoords); // Seppuku.INSTANCE.getEventManager().dispatchEvent(event); // } @MethodPatch( mcpName = "getFOVModifier", notchName = "a", mcpDesc = "(FZ)F") public void getFovModifier(MethodNode methodNode, PatchManager.Environment env) { final InsnList insnList = new InsnList(); insnList.add(new TypeInsnNode(NEW, Type.getInternalName(EventFovModifier.class))); insnList.add(new InsnNode(DUP)); insnList.add(new MethodInsnNode(INVOKESPECIAL, Type.getInternalName(EventFovModifier.class), "<init>", "()V", false)); insnList.add(new VarInsnNode(ASTORE, 5)); insnList.add(new FieldInsnNode(GETSTATIC, Type.getInternalName(Seppuku.class), "INSTANCE", "Lme/rigamortis/seppuku/Seppuku;")); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Seppuku.class), "getEventManager", "()Lteam/stiff/pomelo/EventManager;", false)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(EventManager.class), "dispatchEvent", "(Ljava/lang/Object;)Ljava/lang/Object;", true)); insnList.add(new InsnNode(POP)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(EventFovModifier.class), "isCanceled", "()Z", false)); final LabelNode label = new LabelNode(); insnList.add(new JumpInsnNode(IFEQ, label)); insnList.add(new VarInsnNode(ALOAD, 5)); insnList.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(EventFovModifier.class), "getFov", "()F", false)); insnList.add(new InsnNode(FRETURN)); insnList.add(label); methodNode.instructions.insert(insnList); } @MethodPatch( mcpName = "getMouseOver", notchName = "a", mcpDesc = "(F)V") public void getMouseOver(MethodNode methodNode, PatchManager.Environment env) { final InsnList insnList = new InsnList(); insnList.add(new VarInsnNode(FLOAD, 1)); insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "getMouseOverHook", "(F)V", false)); insnList.add(new InsnNode(RETURN)); methodNode.instructions.insert(insnList); } /** * This is where minecraft renders name plates * * @param methodNode * @param env */ @MethodPatch( mcpName = "drawNameplate", notchName = "a", mcpDesc = "(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;FFFIFFZZ)V", notchDesc = "(Lbip;Ljava/lang/String;FFFIFFZZ)V") public void drawNameplate(MethodNode methodNode, PatchManager.Environment env) { //create a list of instructions and add the needed instructions to call our hook function final InsnList insnList = new InsnList(); //add ALOAD instructions to pass all arguments into our hook function //drawNameplate is static so argument indices start from 0 since there is no `this` insnList.add(new VarInsnNode(ALOAD, 0)); // fontRenderer insnList.add(new VarInsnNode(ALOAD, 1)); // str insnList.add(new VarInsnNode(FLOAD, 2)); // x insnList.add(new VarInsnNode(FLOAD, 3)); // y insnList.add(new VarInsnNode(FLOAD, 4)); // z insnList.add(new VarInsnNode(ILOAD, 5)); // verticalShift insnList.add(new VarInsnNode(FLOAD, 6)); // viewerYaw insnList.add(new VarInsnNode(FLOAD, 7)); // viewerPitch insnList.add(new VarInsnNode(ILOAD, 8)); // isThirdPersonFrontal insnList.add(new VarInsnNode(ILOAD, 9)); // isSneaking //call our hook function insnList.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(this.getClass()), "drawNameplateHook", env == PatchManager.Environment.IDE ? "(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;FFFIFFZZ)Z" : "(Lbip;Ljava/lang/String;FFFIFFZZ)Z", false)); //add a label to jump to final LabelNode jmp = new LabelNode(); //add if equals and pass the label insnList.add(new JumpInsnNode(IFEQ, jmp)); //add return so the rest of the function doesn't get called insnList.add(new InsnNode(RETURN)); //add our label insnList.add(jmp); //insert the list of instructions at the top of the function methodNode.instructions.insert(insnList); } }
146669_40
package org.seqcode.math.stats; /********************************************************** * * Class CubicSpline * * Class for performing an interpolation using a cubic spline * setTabulatedArrays and interpolate adapted, with modification to * an object-oriented approach, from Numerical Recipes in C (http://www.nr.com/) * * * WRITTEN BY: Dr Michael Thomas Flanagan * * DATE: May 2002 * UPDATE: 29 April 2005, 17 February 2006, 21 September 2006, 4 December 2007 * 24 March 2008 (Thanks to Peter Neuhaus, Florida Institute for Human and Machine Cognition) * 21 September 2008 * 14 January 2009 - point deletion and check for 3 points reordered (Thanks to Jan Sacha, Vrije Universiteit Amsterdam) * * DOCUMENTATION: * See Michael Thomas Flanagan's Java library on-line web page: * http://www.ee.ucl.ac.uk/~mflanaga/java/CubicSpline.html * http://www.ee.ucl.ac.uk/~mflanaga/java/ * * Copyright (c) 2002 - 2008 Michael Thomas Flanagan * * PERMISSION TO COPY: * * Permission to use, copy and modify this software and its documentation for NON-COMMERCIAL purposes is granted, without fee, * provided that an acknowledgement to the author, Dr Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies * and associated documentation or publications. * * Redistributions of the source code of this source code, or parts of the source codes, must retain the above copyright notice, * this list of conditions and the following disclaimer and requires written permission from the Michael Thomas Flanagan: * * Redistribution in binary form of all or parts of this class 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 and requires written permission * from the Michael Thomas Flanagan: * * Dr Michael Thomas Flanagan makes no representations about the suitability or fitness of the software for any or for a particular purpose. * Dr Michael Thomas Flanagan shall not be liable for any damages suffered as a result of using, modifying or distributing this software * or its derivatives. * ***************************************************************************************/ public class CubicSpline{ private int nPoints = 0; // no. of tabulated points private int nPointsOriginal = 0; // no. of tabulated points after any deletions of identical points private double[] y = null; // y=f(x) tabulated function private double[] x = null; // x in tabulated function f(x) private int[]newAndOldIndices; // record of indices on ordering x into ascending order private double xMin = Double.NaN; // minimum x value private double xMax = Double.NaN; // maximum x value private double range = Double.NaN; // xMax - xMin private double[] d2ydx2 = null; // second derivatives of y private double yp1 = Double.NaN; // first derivative at point one // default value = NaN (natural spline) private double ypn = Double.NaN; // first derivative at point n // default value = NaN (natural spline) private boolean derivCalculated = false; // = true when the derivatives have been calculated private String subMatrixIndices = " "; // String of indices of the submatrices that have called CubicSpline from higher order interpolation private boolean checkPoints = false; // = true when points checked for identical values private boolean averageIdenticalAbscissae = false; // if true: the the ordinate values for identical abscissae are averaged // if false: the abscissae values are separated by 0.001 of the total abscissae range; private static double potentialRoundingError = 5e-15; // potential rounding error used in checking wheter a value lies within the interpolation bounds private static boolean roundingCheck = true; // = true: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // Constructors // Constructor with data arrays initialised to arrays x and y public CubicSpline(double[] x, double[] y){ this.nPoints=x.length; this.nPointsOriginal = this.nPoints; if(this.nPoints!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length "+ this.nPoints + " " + y.length); if(this.nPoints<3)throw new IllegalArgumentException("A minimum of three data points is needed"); this.x = new double[nPoints]; this.y = new double[nPoints]; this.d2ydx2 = new double[nPoints]; for(int i=0; i<this.nPoints; i++){ this.x[i]=x[i]; this.y[i]=y[i]; } orderPoints(); } // Constructor with data arrays initialised to zero // Primarily for use by BiCubicSpline public CubicSpline(int nPoints){ this.nPoints=nPoints; this.nPointsOriginal = this.nPoints; if(this.nPoints<3)throw new IllegalArgumentException("A minimum of three data points is needed"); this.x = new double[nPoints]; this.y = new double[nPoints]; this.d2ydx2 = new double[nPoints]; } // METHODS // Reset rounding error check option // Default option: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // This method causes this check to be ignored and an exception to be thrown if any poit lies outside the interpolation bounds public static void noRoundingErrorCheck(){ CubicSpline.roundingCheck = false; } // Reset potential rounding error value // Default option: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // The default value for the potential rounding error is 5e-15*times the 10^exponent of the value outside the bounds // This method allows the 5e-15 to be reset public static void potentialRoundingError(double potentialRoundingError){ CubicSpline.potentialRoundingError = potentialRoundingError; } // Resets the x y data arrays - primarily for use in BiCubicSpline public void resetData(double[] x, double[] y){ this.nPoints = this.nPointsOriginal; if(x.length!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length"); if(this.nPoints!=x.length)throw new IllegalArgumentException("Original array length not matched by new array length"); for(int i=0; i<this.nPoints; i++){ this.x[i]=x[i]; this.y[i]=y[i]; } orderPoints(); } // Set sub-matrix indices - for use with higher order interpolations calling CubicSpline public void setSubMatrix(String subMatrixIndices){ this.subMatrixIndices = subMatrixIndices; } // Reset the default handing of identical abscissae with different ordinates // from the default option of separating the two relevant abscissae by 0.001 of the range // to avraging the relevant ordinates public void averageIdenticalAbscissae(){ this.averageIdenticalAbscissae = true; } // Sort points into an ascending abscissa order public void orderPoints(){ double[] dummy = new double[nPoints]; this.newAndOldIndices = new int[nPoints]; // Sort x into ascending order storing indices changes Fmath.selectionSort(this.x, dummy, this.newAndOldIndices); // Sort x into ascending order and make y match the new order storing both new x and new y Fmath.selectionSort(this.x, this.y, this.x, this.y); // Minimum and maximum values and range this.xMin = Fmath.minimum(this.x); this.xMax = Fmath.maximum(this.x); range = xMax - xMin; } // get the maximum value public double getXmax(){ return this.xMax; } // get the minimum value public double getXmin(){ return this.xMin; } // get the limits of x public double[] getLimits(){ double[] limits = {this.xMin, this.xMax}; return limits; } // print to screen the limis of x public void displayLimits(){ System.out.println("\nThe limits of the abscissae (x-values) are " + this.xMin + " and " + this.xMax +"\n"); } // Checks for and removes all but one of identical points // Checks and appropriately handles identical abscissae with differing ordinates public void checkForIdenticalPoints(){ int nP = this.nPoints; boolean test1 = true; int ii = 0; while(test1){ boolean test2 = true; int jj = ii+1; while(test2){ if(this.x[ii]==this.x[jj]){ if(this.y[ii]==this.y[jj]){ System.out.print(subMatrixIndices + "CubicSpline: Two identical points, " + this.x[ii] + ", " + this.y[ii]); System.out.println(", in data array at indices " + this.newAndOldIndices[ii] + " and " + this.newAndOldIndices[jj] + ", latter point removed"); for(int i=jj; i<nP-1; i++){ this.x[i] = this.x[i+1]; this.y[i] = this.y[i+1]; this.newAndOldIndices[i-1] = this.newAndOldIndices[i]; } nP--; for(int i=nP; i<this.nPoints; i++){ this.x[i] = Double.NaN; this.y[i] = Double.NaN; this.newAndOldIndices[i-1] = -1000; } } else{ if(this.averageIdenticalAbscissae==true){ System.out.print(subMatrixIndices + "CubicSpline: Two identical points on the absicca (x-axis) with different ordinate (y-axis) values, " + x[ii] + ": " + y[ii] + ", " + y[jj]); System.out.println(", average of the ordinates taken"); this.y[ii] = (this.y[ii] + this.y[jj])/2.0D; for(int i=jj; i<nP-1; i++){ this.x[i] = this.x[i+1]; this.y[i] = this.y[i+1]; this.newAndOldIndices[i-1] = this.newAndOldIndices[i]; } nP--; for(int i=nP; i<this.nPoints; i++){ this.x[i] = Double.NaN; this.y[i] = Double.NaN; this.newAndOldIndices[i-1] = -1000; } } else{ double sepn = range*0.0005D; System.out.print(subMatrixIndices + "CubicSpline: Two identical points on the absicca (x-axis) with different ordinate (y-axis) values, " + x[ii] + ": " + y[ii] + ", " + y[jj]); boolean check = false; if(ii==0){ if(x[2]-x[1]<=sepn)sepn = (x[2]-x[1])/2.0D; if(this.y[0]>this.y[1]){ if(this.y[1]>this.y[2]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ if(this.y[2]<=this.y[1]){ check = swap(ii, jj, sepn); } else{ check = stay(ii, jj, sepn); } } } if(jj==nP-1){ if(x[nP-2]-x[nP-3]<=sepn)sepn = (x[nP-2]-x[nP-3])/2.0D; if(this.y[ii]<=this.y[jj]){ if(this.y[ii-1]<=this.y[ii]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ if(this.y[ii-1]<=this.y[ii]){ check = swap(ii, jj, sepn); } else{ check = stay(ii, jj, sepn); } } } if(ii!=0 && jj!=nP-1){ if(x[ii]-x[ii-1]<=sepn)sepn = (x[ii]-x[ii-1])/2; if(x[jj+1]-x[jj]<=sepn)sepn = (x[jj+1]-x[jj])/2; if(this.y[ii]>this.y[ii-1]){ if(this.y[jj]>this.y[ii]){ if(this.y[jj]>this.y[jj+1]){ if(this.y[ii-1]<=this.y[jj+1]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ check = stay(ii, jj, sepn); } } else{ if(this.y[jj+1]>this.y[jj]){ if(this.y[jj+1]>this.y[ii-1] && this.y[jj+1]>this.y[ii-1]){ check = stay(ii, jj, sepn); } } else{ check = swap(ii, jj, sepn); } } } else{ if(this.y[jj]>this.y[ii]){ if(this.y[jj+1]>this.y[jj]){ check = stay(ii, jj, sepn); } } else{ if(this.y[jj+1]>this.y[ii-1]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } } } if(check==false){ check = stay(ii, jj, sepn); } System.out.println(", the two abscissae have been separated by a distance " + sepn); jj++; } } if((nP-1)==ii)test2 = false; } else{ jj++; } if(jj>=nP)test2 = false; } ii++; if(ii>=nP-1)test1 = false; } this.nPoints = nP; if(this.nPoints<3)throw new IllegalArgumentException("Removal of duplicate points has reduced the number of points to less than the required minimum of three data points"); this.checkPoints = true; } // Swap method for checkForIdenticalPoints procedure private boolean swap(int ii, int jj, double sepn){ this.x[ii] += sepn; this.x[jj] -= sepn; double hold = this.x[ii]; this.x[ii] = this.x[jj]; this.x[jj] = hold; hold = this.y[ii]; this.y[ii] = this.y[jj]; this.y[jj] = hold; return true; } // Stay method for checkForIdenticalPoints procedure private boolean stay(int ii, int jj, double sepn){ this.x[ii] -= sepn; this.x[jj] += sepn; return true; } // Returns a new CubicSpline setting array lengths to n and all array values to zero with natural spline default // Primarily for use in BiCubicSpline public static CubicSpline zero(int n){ if(n<3)throw new IllegalArgumentException("A minimum of three data points is needed"); CubicSpline aa = new CubicSpline(n); return aa; } // Create a one dimensional array of cubic spline objects of length n each of array length m // Primarily for use in BiCubicSpline public static CubicSpline[] oneDarray(int n, int m){ if(m<3)throw new IllegalArgumentException("A minimum of three data points is needed"); CubicSpline[] a =new CubicSpline[n]; for(int i=0; i<n; i++){ a[i]=CubicSpline.zero(m); } return a; } // Enters the first derivatives of the cubic spline at // the first and last point of the tabulated data // Overrides a natural spline public void setDerivLimits(double yp1, double ypn){ this.yp1=yp1; this.ypn=ypn; } // Resets a natural spline // Use above - this kept for backward compatibility public void setDerivLimits(){ this.yp1=Double.NaN; this.ypn=Double.NaN; } // Enters the first derivatives of the cubic spline at // the first and last point of the tabulated data // Overrides a natural spline // Use setDerivLimits(double yp1, double ypn) - this kept for backward compatibility public void setDeriv(double yp1, double ypn){ this.yp1=yp1; this.ypn=ypn; this.derivCalculated = false; } // Returns the internal array of second derivatives public double[] getDeriv(){ if(!this.derivCalculated)this.calcDeriv(); return this.d2ydx2; } // Sets the internal array of second derivatives // Used primarily with BiCubicSpline public void setDeriv(double[] deriv){ this.d2ydx2 = deriv; this.derivCalculated = true; } // Calculates the second derivatives of the tabulated function // for use by the cubic spline interpolation method (.interpolate) // This method follows the procedure in Numerical Methods C language procedure for calculating second derivatives public void calcDeriv(){ double p=0.0D,qn=0.0D,sig=0.0D,un=0.0D; double[] u = new double[nPoints]; if (Double.isNaN(this.yp1)){ d2ydx2[0]=u[0]=0.0; } else{ this.d2ydx2[0] = -0.5; u[0]=(3.0/(this.x[1]-this.x[0]))*((this.y[1]-this.y[0])/(this.x[1]-this.x[0])-this.yp1); } for(int i=1;i<=this.nPoints-2;i++){ sig=(this.x[i]-this.x[i-1])/(this.x[i+1]-this.x[i-1]); p=sig*this.d2ydx2[i-1]+2.0; this.d2ydx2[i]=(sig-1.0)/p; u[i]=(this.y[i+1]-this.y[i])/(this.x[i+1]-this.x[i]) - (this.y[i]-this.y[i-1])/(this.x[i]-this.x[i-1]); u[i]=(6.0*u[i]/(this.x[i+1]-this.x[i-1])-sig*u[i-1])/p; } if (Double.isNaN(this.ypn)){ qn=un=0.0; } else{ qn=0.5; un=(3.0/(this.x[nPoints-1]-this.x[this.nPoints-2]))*(this.ypn-(this.y[this.nPoints-1]-this.y[this.nPoints-2])/(this.x[this.nPoints-1]-x[this.nPoints-2])); } this.d2ydx2[this.nPoints-1]=(un-qn*u[this.nPoints-2])/(qn*this.d2ydx2[this.nPoints-2]+1.0); for(int k=this.nPoints-2;k>=0;k--){ this.d2ydx2[k]=this.d2ydx2[k]*this.d2ydx2[k+1]+u[k]; } this.derivCalculated = true; } // INTERPOLATE // Returns an interpolated value of y for a value of x from a tabulated function y=f(x) // after the data has been entered via a constructor. // The derivatives are calculated, bt calcDeriv(), on the first call to this method ands are // then stored for use on all subsequent calls public double interpolate(double xx){ if(!this.checkPoints)this.checkForIdenticalPoints(); // Check for violation of interpolation bounds if (xx<this.x[0]){ // if violation is less than potntial rounding error - amend to lie with bounds if(CubicSpline.roundingCheck && Math.abs(x[0]-xx)<=Math.pow(10, Math.floor(Math.log10(Math.abs(this.x[0]))))*CubicSpline.potentialRoundingError){ xx = x[0]; } else{ throw new IllegalArgumentException("x ("+xx+") is outside the range of data points ("+x[0]+" to "+x[this.nPoints-1] + ")"); } } if (xx>this.x[this.nPoints-1]){ if(CubicSpline.roundingCheck && Math.abs(xx-this.x[this.nPoints-1])<=Math.pow(10, Math.floor(Math.log10(Math.abs(this.x[this.nPoints-1]))))*CubicSpline.potentialRoundingError){ xx = this.x[this.nPoints-1]; } else{ throw new IllegalArgumentException("x ("+xx+") is outside the range of data points ("+x[0]+" to "+x[this.nPoints-1] + ")"); } } if(!this.derivCalculated)this.calcDeriv(); double h=0.0D,b=0.0D,a=0.0D, yy=0.0D; int k=0; int klo=0; int khi=this.nPoints-1; while (khi-klo > 1){ k=(khi+klo) >> 1; if(this.x[k] > xx){ khi=k; } else{ klo=k; } } h=this.x[khi]-this.x[klo]; if (h == 0.0){ throw new IllegalArgumentException("Two values of x are identical: point "+klo+ " ("+this.x[klo]+") and point "+khi+ " ("+this.x[khi]+")" ); } else{ a=(this.x[khi]-xx)/h; b=(xx-this.x[klo])/h; yy=a*this.y[klo]+b*this.y[khi]+((a*a*a-a)*this.d2ydx2[klo]+(b*b*b-b)*this.d2ydx2[khi])*(h*h)/6.0; } return yy; } // Returns an interpolated value of y for a value of x (xx) from a tabulated function y=f(x) // after the derivatives (deriv) have been calculated independently of calcDeriv(). public static double interpolate(double xx, double[] x, double[] y, double[] deriv){ if(((x.length != y.length) || (x.length != deriv.length)) || (y.length != deriv.length)){ throw new IllegalArgumentException("array lengths are not all equal"); } int n = x.length; double h=0.0D, b=0.0D, a=0.0D, yy = 0.0D; int k=0; int klo=0; int khi=n-1; while(khi-klo > 1){ k=(khi+klo) >> 1; if(x[k] > xx){ khi=k; } else{ klo=k; } } h=x[khi]-x[klo]; if (h == 0.0){ throw new IllegalArgumentException("Two values of x are identical"); } else{ a=(x[khi]-xx)/h; b=(xx-x[klo])/h; yy=a*y[klo]+b*y[khi]+((a*a*a-a)*deriv[klo]+(b*b*b-b)*deriv[khi])*(h*h)/6.0; } return yy; } }
seqcode/seqcode-core
src/org/seqcode/math/stats/CubicSpline.java
7,992
// get the maximum value
line_comment
nl
package org.seqcode.math.stats; /********************************************************** * * Class CubicSpline * * Class for performing an interpolation using a cubic spline * setTabulatedArrays and interpolate adapted, with modification to * an object-oriented approach, from Numerical Recipes in C (http://www.nr.com/) * * * WRITTEN BY: Dr Michael Thomas Flanagan * * DATE: May 2002 * UPDATE: 29 April 2005, 17 February 2006, 21 September 2006, 4 December 2007 * 24 March 2008 (Thanks to Peter Neuhaus, Florida Institute for Human and Machine Cognition) * 21 September 2008 * 14 January 2009 - point deletion and check for 3 points reordered (Thanks to Jan Sacha, Vrije Universiteit Amsterdam) * * DOCUMENTATION: * See Michael Thomas Flanagan's Java library on-line web page: * http://www.ee.ucl.ac.uk/~mflanaga/java/CubicSpline.html * http://www.ee.ucl.ac.uk/~mflanaga/java/ * * Copyright (c) 2002 - 2008 Michael Thomas Flanagan * * PERMISSION TO COPY: * * Permission to use, copy and modify this software and its documentation for NON-COMMERCIAL purposes is granted, without fee, * provided that an acknowledgement to the author, Dr Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies * and associated documentation or publications. * * Redistributions of the source code of this source code, or parts of the source codes, must retain the above copyright notice, * this list of conditions and the following disclaimer and requires written permission from the Michael Thomas Flanagan: * * Redistribution in binary form of all or parts of this class 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 and requires written permission * from the Michael Thomas Flanagan: * * Dr Michael Thomas Flanagan makes no representations about the suitability or fitness of the software for any or for a particular purpose. * Dr Michael Thomas Flanagan shall not be liable for any damages suffered as a result of using, modifying or distributing this software * or its derivatives. * ***************************************************************************************/ public class CubicSpline{ private int nPoints = 0; // no. of tabulated points private int nPointsOriginal = 0; // no. of tabulated points after any deletions of identical points private double[] y = null; // y=f(x) tabulated function private double[] x = null; // x in tabulated function f(x) private int[]newAndOldIndices; // record of indices on ordering x into ascending order private double xMin = Double.NaN; // minimum x value private double xMax = Double.NaN; // maximum x value private double range = Double.NaN; // xMax - xMin private double[] d2ydx2 = null; // second derivatives of y private double yp1 = Double.NaN; // first derivative at point one // default value = NaN (natural spline) private double ypn = Double.NaN; // first derivative at point n // default value = NaN (natural spline) private boolean derivCalculated = false; // = true when the derivatives have been calculated private String subMatrixIndices = " "; // String of indices of the submatrices that have called CubicSpline from higher order interpolation private boolean checkPoints = false; // = true when points checked for identical values private boolean averageIdenticalAbscissae = false; // if true: the the ordinate values for identical abscissae are averaged // if false: the abscissae values are separated by 0.001 of the total abscissae range; private static double potentialRoundingError = 5e-15; // potential rounding error used in checking wheter a value lies within the interpolation bounds private static boolean roundingCheck = true; // = true: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // Constructors // Constructor with data arrays initialised to arrays x and y public CubicSpline(double[] x, double[] y){ this.nPoints=x.length; this.nPointsOriginal = this.nPoints; if(this.nPoints!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length "+ this.nPoints + " " + y.length); if(this.nPoints<3)throw new IllegalArgumentException("A minimum of three data points is needed"); this.x = new double[nPoints]; this.y = new double[nPoints]; this.d2ydx2 = new double[nPoints]; for(int i=0; i<this.nPoints; i++){ this.x[i]=x[i]; this.y[i]=y[i]; } orderPoints(); } // Constructor with data arrays initialised to zero // Primarily for use by BiCubicSpline public CubicSpline(int nPoints){ this.nPoints=nPoints; this.nPointsOriginal = this.nPoints; if(this.nPoints<3)throw new IllegalArgumentException("A minimum of three data points is needed"); this.x = new double[nPoints]; this.y = new double[nPoints]; this.d2ydx2 = new double[nPoints]; } // METHODS // Reset rounding error check option // Default option: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // This method causes this check to be ignored and an exception to be thrown if any poit lies outside the interpolation bounds public static void noRoundingErrorCheck(){ CubicSpline.roundingCheck = false; } // Reset potential rounding error value // Default option: points outside the interpolation bounds by less than the potential rounding error rounded to the bounds limit // The default value for the potential rounding error is 5e-15*times the 10^exponent of the value outside the bounds // This method allows the 5e-15 to be reset public static void potentialRoundingError(double potentialRoundingError){ CubicSpline.potentialRoundingError = potentialRoundingError; } // Resets the x y data arrays - primarily for use in BiCubicSpline public void resetData(double[] x, double[] y){ this.nPoints = this.nPointsOriginal; if(x.length!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length"); if(this.nPoints!=x.length)throw new IllegalArgumentException("Original array length not matched by new array length"); for(int i=0; i<this.nPoints; i++){ this.x[i]=x[i]; this.y[i]=y[i]; } orderPoints(); } // Set sub-matrix indices - for use with higher order interpolations calling CubicSpline public void setSubMatrix(String subMatrixIndices){ this.subMatrixIndices = subMatrixIndices; } // Reset the default handing of identical abscissae with different ordinates // from the default option of separating the two relevant abscissae by 0.001 of the range // to avraging the relevant ordinates public void averageIdenticalAbscissae(){ this.averageIdenticalAbscissae = true; } // Sort points into an ascending abscissa order public void orderPoints(){ double[] dummy = new double[nPoints]; this.newAndOldIndices = new int[nPoints]; // Sort x into ascending order storing indices changes Fmath.selectionSort(this.x, dummy, this.newAndOldIndices); // Sort x into ascending order and make y match the new order storing both new x and new y Fmath.selectionSort(this.x, this.y, this.x, this.y); // Minimum and maximum values and range this.xMin = Fmath.minimum(this.x); this.xMax = Fmath.maximum(this.x); range = xMax - xMin; } // get the<SUF> public double getXmax(){ return this.xMax; } // get the minimum value public double getXmin(){ return this.xMin; } // get the limits of x public double[] getLimits(){ double[] limits = {this.xMin, this.xMax}; return limits; } // print to screen the limis of x public void displayLimits(){ System.out.println("\nThe limits of the abscissae (x-values) are " + this.xMin + " and " + this.xMax +"\n"); } // Checks for and removes all but one of identical points // Checks and appropriately handles identical abscissae with differing ordinates public void checkForIdenticalPoints(){ int nP = this.nPoints; boolean test1 = true; int ii = 0; while(test1){ boolean test2 = true; int jj = ii+1; while(test2){ if(this.x[ii]==this.x[jj]){ if(this.y[ii]==this.y[jj]){ System.out.print(subMatrixIndices + "CubicSpline: Two identical points, " + this.x[ii] + ", " + this.y[ii]); System.out.println(", in data array at indices " + this.newAndOldIndices[ii] + " and " + this.newAndOldIndices[jj] + ", latter point removed"); for(int i=jj; i<nP-1; i++){ this.x[i] = this.x[i+1]; this.y[i] = this.y[i+1]; this.newAndOldIndices[i-1] = this.newAndOldIndices[i]; } nP--; for(int i=nP; i<this.nPoints; i++){ this.x[i] = Double.NaN; this.y[i] = Double.NaN; this.newAndOldIndices[i-1] = -1000; } } else{ if(this.averageIdenticalAbscissae==true){ System.out.print(subMatrixIndices + "CubicSpline: Two identical points on the absicca (x-axis) with different ordinate (y-axis) values, " + x[ii] + ": " + y[ii] + ", " + y[jj]); System.out.println(", average of the ordinates taken"); this.y[ii] = (this.y[ii] + this.y[jj])/2.0D; for(int i=jj; i<nP-1; i++){ this.x[i] = this.x[i+1]; this.y[i] = this.y[i+1]; this.newAndOldIndices[i-1] = this.newAndOldIndices[i]; } nP--; for(int i=nP; i<this.nPoints; i++){ this.x[i] = Double.NaN; this.y[i] = Double.NaN; this.newAndOldIndices[i-1] = -1000; } } else{ double sepn = range*0.0005D; System.out.print(subMatrixIndices + "CubicSpline: Two identical points on the absicca (x-axis) with different ordinate (y-axis) values, " + x[ii] + ": " + y[ii] + ", " + y[jj]); boolean check = false; if(ii==0){ if(x[2]-x[1]<=sepn)sepn = (x[2]-x[1])/2.0D; if(this.y[0]>this.y[1]){ if(this.y[1]>this.y[2]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ if(this.y[2]<=this.y[1]){ check = swap(ii, jj, sepn); } else{ check = stay(ii, jj, sepn); } } } if(jj==nP-1){ if(x[nP-2]-x[nP-3]<=sepn)sepn = (x[nP-2]-x[nP-3])/2.0D; if(this.y[ii]<=this.y[jj]){ if(this.y[ii-1]<=this.y[ii]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ if(this.y[ii-1]<=this.y[ii]){ check = swap(ii, jj, sepn); } else{ check = stay(ii, jj, sepn); } } } if(ii!=0 && jj!=nP-1){ if(x[ii]-x[ii-1]<=sepn)sepn = (x[ii]-x[ii-1])/2; if(x[jj+1]-x[jj]<=sepn)sepn = (x[jj+1]-x[jj])/2; if(this.y[ii]>this.y[ii-1]){ if(this.y[jj]>this.y[ii]){ if(this.y[jj]>this.y[jj+1]){ if(this.y[ii-1]<=this.y[jj+1]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } else{ check = stay(ii, jj, sepn); } } else{ if(this.y[jj+1]>this.y[jj]){ if(this.y[jj+1]>this.y[ii-1] && this.y[jj+1]>this.y[ii-1]){ check = stay(ii, jj, sepn); } } else{ check = swap(ii, jj, sepn); } } } else{ if(this.y[jj]>this.y[ii]){ if(this.y[jj+1]>this.y[jj]){ check = stay(ii, jj, sepn); } } else{ if(this.y[jj+1]>this.y[ii-1]){ check = stay(ii, jj, sepn); } else{ check = swap(ii, jj, sepn); } } } } if(check==false){ check = stay(ii, jj, sepn); } System.out.println(", the two abscissae have been separated by a distance " + sepn); jj++; } } if((nP-1)==ii)test2 = false; } else{ jj++; } if(jj>=nP)test2 = false; } ii++; if(ii>=nP-1)test1 = false; } this.nPoints = nP; if(this.nPoints<3)throw new IllegalArgumentException("Removal of duplicate points has reduced the number of points to less than the required minimum of three data points"); this.checkPoints = true; } // Swap method for checkForIdenticalPoints procedure private boolean swap(int ii, int jj, double sepn){ this.x[ii] += sepn; this.x[jj] -= sepn; double hold = this.x[ii]; this.x[ii] = this.x[jj]; this.x[jj] = hold; hold = this.y[ii]; this.y[ii] = this.y[jj]; this.y[jj] = hold; return true; } // Stay method for checkForIdenticalPoints procedure private boolean stay(int ii, int jj, double sepn){ this.x[ii] -= sepn; this.x[jj] += sepn; return true; } // Returns a new CubicSpline setting array lengths to n and all array values to zero with natural spline default // Primarily for use in BiCubicSpline public static CubicSpline zero(int n){ if(n<3)throw new IllegalArgumentException("A minimum of three data points is needed"); CubicSpline aa = new CubicSpline(n); return aa; } // Create a one dimensional array of cubic spline objects of length n each of array length m // Primarily for use in BiCubicSpline public static CubicSpline[] oneDarray(int n, int m){ if(m<3)throw new IllegalArgumentException("A minimum of three data points is needed"); CubicSpline[] a =new CubicSpline[n]; for(int i=0; i<n; i++){ a[i]=CubicSpline.zero(m); } return a; } // Enters the first derivatives of the cubic spline at // the first and last point of the tabulated data // Overrides a natural spline public void setDerivLimits(double yp1, double ypn){ this.yp1=yp1; this.ypn=ypn; } // Resets a natural spline // Use above - this kept for backward compatibility public void setDerivLimits(){ this.yp1=Double.NaN; this.ypn=Double.NaN; } // Enters the first derivatives of the cubic spline at // the first and last point of the tabulated data // Overrides a natural spline // Use setDerivLimits(double yp1, double ypn) - this kept for backward compatibility public void setDeriv(double yp1, double ypn){ this.yp1=yp1; this.ypn=ypn; this.derivCalculated = false; } // Returns the internal array of second derivatives public double[] getDeriv(){ if(!this.derivCalculated)this.calcDeriv(); return this.d2ydx2; } // Sets the internal array of second derivatives // Used primarily with BiCubicSpline public void setDeriv(double[] deriv){ this.d2ydx2 = deriv; this.derivCalculated = true; } // Calculates the second derivatives of the tabulated function // for use by the cubic spline interpolation method (.interpolate) // This method follows the procedure in Numerical Methods C language procedure for calculating second derivatives public void calcDeriv(){ double p=0.0D,qn=0.0D,sig=0.0D,un=0.0D; double[] u = new double[nPoints]; if (Double.isNaN(this.yp1)){ d2ydx2[0]=u[0]=0.0; } else{ this.d2ydx2[0] = -0.5; u[0]=(3.0/(this.x[1]-this.x[0]))*((this.y[1]-this.y[0])/(this.x[1]-this.x[0])-this.yp1); } for(int i=1;i<=this.nPoints-2;i++){ sig=(this.x[i]-this.x[i-1])/(this.x[i+1]-this.x[i-1]); p=sig*this.d2ydx2[i-1]+2.0; this.d2ydx2[i]=(sig-1.0)/p; u[i]=(this.y[i+1]-this.y[i])/(this.x[i+1]-this.x[i]) - (this.y[i]-this.y[i-1])/(this.x[i]-this.x[i-1]); u[i]=(6.0*u[i]/(this.x[i+1]-this.x[i-1])-sig*u[i-1])/p; } if (Double.isNaN(this.ypn)){ qn=un=0.0; } else{ qn=0.5; un=(3.0/(this.x[nPoints-1]-this.x[this.nPoints-2]))*(this.ypn-(this.y[this.nPoints-1]-this.y[this.nPoints-2])/(this.x[this.nPoints-1]-x[this.nPoints-2])); } this.d2ydx2[this.nPoints-1]=(un-qn*u[this.nPoints-2])/(qn*this.d2ydx2[this.nPoints-2]+1.0); for(int k=this.nPoints-2;k>=0;k--){ this.d2ydx2[k]=this.d2ydx2[k]*this.d2ydx2[k+1]+u[k]; } this.derivCalculated = true; } // INTERPOLATE // Returns an interpolated value of y for a value of x from a tabulated function y=f(x) // after the data has been entered via a constructor. // The derivatives are calculated, bt calcDeriv(), on the first call to this method ands are // then stored for use on all subsequent calls public double interpolate(double xx){ if(!this.checkPoints)this.checkForIdenticalPoints(); // Check for violation of interpolation bounds if (xx<this.x[0]){ // if violation is less than potntial rounding error - amend to lie with bounds if(CubicSpline.roundingCheck && Math.abs(x[0]-xx)<=Math.pow(10, Math.floor(Math.log10(Math.abs(this.x[0]))))*CubicSpline.potentialRoundingError){ xx = x[0]; } else{ throw new IllegalArgumentException("x ("+xx+") is outside the range of data points ("+x[0]+" to "+x[this.nPoints-1] + ")"); } } if (xx>this.x[this.nPoints-1]){ if(CubicSpline.roundingCheck && Math.abs(xx-this.x[this.nPoints-1])<=Math.pow(10, Math.floor(Math.log10(Math.abs(this.x[this.nPoints-1]))))*CubicSpline.potentialRoundingError){ xx = this.x[this.nPoints-1]; } else{ throw new IllegalArgumentException("x ("+xx+") is outside the range of data points ("+x[0]+" to "+x[this.nPoints-1] + ")"); } } if(!this.derivCalculated)this.calcDeriv(); double h=0.0D,b=0.0D,a=0.0D, yy=0.0D; int k=0; int klo=0; int khi=this.nPoints-1; while (khi-klo > 1){ k=(khi+klo) >> 1; if(this.x[k] > xx){ khi=k; } else{ klo=k; } } h=this.x[khi]-this.x[klo]; if (h == 0.0){ throw new IllegalArgumentException("Two values of x are identical: point "+klo+ " ("+this.x[klo]+") and point "+khi+ " ("+this.x[khi]+")" ); } else{ a=(this.x[khi]-xx)/h; b=(xx-this.x[klo])/h; yy=a*this.y[klo]+b*this.y[khi]+((a*a*a-a)*this.d2ydx2[klo]+(b*b*b-b)*this.d2ydx2[khi])*(h*h)/6.0; } return yy; } // Returns an interpolated value of y for a value of x (xx) from a tabulated function y=f(x) // after the derivatives (deriv) have been calculated independently of calcDeriv(). public static double interpolate(double xx, double[] x, double[] y, double[] deriv){ if(((x.length != y.length) || (x.length != deriv.length)) || (y.length != deriv.length)){ throw new IllegalArgumentException("array lengths are not all equal"); } int n = x.length; double h=0.0D, b=0.0D, a=0.0D, yy = 0.0D; int k=0; int klo=0; int khi=n-1; while(khi-klo > 1){ k=(khi+klo) >> 1; if(x[k] > xx){ khi=k; } else{ klo=k; } } h=x[khi]-x[klo]; if (h == 0.0){ throw new IllegalArgumentException("Two values of x are identical"); } else{ a=(x[khi]-xx)/h; b=(xx-x[klo])/h; yy=a*y[klo]+b*y[khi]+((a*a*a-a)*deriv[klo]+(b*b*b-b)*deriv[khi])*(h*h)/6.0; } return yy; } }
72828_24
package apollo.gui.detailviewers.exonviewer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import apollo.datamodel.*; import apollo.editor.AnnotationChangeEvent; import apollo.editor.AnnotationChangeListener; import apollo.gui.event.*; import apollo.dataadapter.DataLoadEvent; import apollo.dataadapter.DataLoadListener; import apollo.gui.ControlledObjectI; import apollo.gui.Controller; import apollo.gui.Transformer; import apollo.gui.genomemap.StrandedZoomableApolloPanel; import apollo.gui.SelectionManager; import apollo.gui.synteny.CurationManager; import apollo.gui.synteny.GuiCurationState; public class BaseFineEditor extends JFrame implements FeatureSelectionListener, ControlledObjectI, AnnotationChangeListener { private static final Color [] colorList = { new Color(0,0,0), new Color(255,255,0), new Color(0,255,255), new Color(255,0,255), new Color(255,0,0), new Color(0,255,0), new Color(0,0,255)}; private static int colorIndex = 0; private static ArrayList baseEditorInstanceList = new ArrayList(5); protected BaseEditorPanel editorPanel = null; private TranslationViewer translationViewer; private JViewport viewport; protected JLabel lengthLabel; private JComboBox transcriptComboBox; StrandedZoomableApolloPanel szap; Transformer transformer; private FineEditorScrollListener scrollListener; Color indicatorColor; JPanel colorSwatch; SelectionManager selection_manager; protected JButton findButton; protected JButton clearFindsButton; protected JButton goToButton; protected JCheckBox showIntronBox; // Need? private JCheckBox followSelectionCheckBox; protected JButton upstream_button; protected JButton downstream_button; private AnnotatedFeatureI currentAnnot;//Transcript protected Transcript neighbor_up; protected Transcript neighbor_down; private GuiCurationState curationState; public static void showBaseEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { BaseFineEditor bfe = new BaseFineEditor(editMe,curationState,geneHolder); baseEditorInstanceList.add(bfe); } private BaseFineEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { super((editMe.isForwardStrand() ? "Forward" : "Reverse") + " Strand Exon Editor"); this.curationState = curationState; curationState.getController().addListener(this); curationState.getController().addListener(new BaseEditorDataListener()); szap = curationState.getSZAP(); transformer = szap.getScaleView().getTransform(); int seqStart = curationState.getCurationSet().getLow(); int seqEnd = curationState.getCurationSet().getHigh(); //FeatureSetI annFeatSet=((DrawableFeatureSet)view.getDrawableSet()).getFeatureSet(); editorPanel = new BaseEditorPanel(curationState, this, !editMe.isForwardStrand(), seqStart, seqEnd, geneHolder); initGui(editMe); // cant do til after editorPanel made // cant do this til after initGui (editorPanel needs to know size) editorPanel.displayAnnot(editMe); attachListeners(); showEditRegion(); displayAnnot(getTransOrOneLevelAnn(editMe)); translationViewer.repaint(); setVisible(true); // Might just be linux, but bofe gets iconified on close if (getState()==Frame.ICONIFIED) setState(Frame.NORMAL); } /** ControlledObjectI interface - but controller now comes from curationState */ public void setController(Controller controller) { //this.controller = controller; //controller.addListener (this); } public Controller getController() { return curationState.getController(); } public Object getControllerWindow() { return this; } // Although they are removed we need to remove from hash in controller public boolean needsAutoRemoval() { return true; } public void setSelectionManager (SelectionManager sm) { this.selection_manager = sm; } public SelectionManager getSelectionManager () { return curationState.getSelectionManager();//this.selection_manager; } private void removeComponents(Container cont) { Component[] components = cont.getComponents(); Component comp; for (int i = 0; i < components.length; i++) { comp = components[i]; if (comp != null) { cont.remove(comp); if (comp instanceof Container) removeComponents((Container) comp); } } } public boolean handleAnnotationChangeEvent(AnnotationChangeEvent evt) { if (this.isVisible() && evt.getSource() != this) { if (evt.isCompound()) { for (int i = 0; i < evt.getNumberOfChildren(); ++i) { handleAnnotationChangeEvent(evt.getChildChangeEvent(i)); } return true; } if (evt.isEndOfEditSession()) { // Dont want scrolling on ann change, also sf for redraw is the // gene, so it just goes to 1st trans which is problematic. displayAnnot(currentAnnot); repaint(); // this is the needed repaint after the changes return true; } /* AnnotatedFeatureI gene = evt.getChangedAnnot(); for (Object o : szap.getAnnotations().getFeatures()) { AnnotatedFeatureI feat = (AnnotatedFeatureI)o; if (feat.getId().equals(gene.getId())) { //gene = feat; break; } } */ if (evt.isAdd()) { AnnotatedFeatureI annotToDisplay = null; AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Attaching %s(%d)\n", t, t.hashCode()); editorPanel.attachAnnot(t); if (currentAnnot != null && t.getName().equals(currentAnnot.getName())) { annotToDisplay = t; } } } if (annotToDisplay == null) { annotToDisplay = (AnnotatedFeatureI)evt.getChangedAnnot().getFeatureAt(0); } displayAnnot(annotToDisplay); return true; } if (evt.isDelete()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Detaching %s(%d)\n", t, t.hashCode()); editorPanel.detachTranscript(t); } } return true; } /* // getAnnotation() can be null after a delete - return if null? SeqFeatureI sf = evt.getAnnotTop(); // If the annotation event is not for the editors strand then return boolean is_reverse = (sf.getStrand() == -1); if (editorPanel.getReverseStrand() != is_reverse) return false; if (evt.isDelete() && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } } else if (evt.isDelete() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } else if ((evt.isAdd() || evt.isSplit() || evt.isMerge()) && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); int tier = editorPanel.attachAnnot (t); } } else if (evt.isAdd() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); int tier = editorPanel.attachAnnot (t); } // Exon split or intron made - same thing isnt it? else if (evt.isAdd() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel // to pick up new exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); } else if (evt.isDelete() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel to remove exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); // or editorPanel.removeFeature((Exon)evt.getSecondFeature()); } // else if (evt.isReplace()) { //&&evt.isTopAnnotChange - always true of replace // AnnotatedFeatureI old_gene = evt.getReplacedFeature(); // AnnotatedFeatureI new_gene = (AnnotatedFeatureI)evt.getChangedFeature(); // int trans_count = old_gene.size(); // /* This does assume that there are no changes in the number // of transcripts between the old and the new. Might be safer // to separate the 2 loops */ // for (int i = 0; i < trans_count; i++) { // Transcript t; // t = (Transcript) old_gene.getFeatureAt (i); // editorPanel.detachTranscript (t); // t = (Transcript) new_gene.getFeatureAt (i); // int tier = editorPanel.attachTranscript (t); // } // // This is so that we don't select a different transcript // AnnotatedFeatureI current_gene = (current_transcript != null ? // current_transcript.getGene() : null); // if (current_gene != null && current_gene == old_gene) { // int index = current_gene.getFeatureIndex(current_transcript); // current_transcript = (Transcript) new_gene.getFeatureAt(index); // } // } // this isnt possible - all replaces are for top annots // else if (evt.isReplace() && evt.isTranscriptChange()) { // Transcript old_trans = (Transcript)evt.getReplacedFeature(); // Transcript new_trans = (Transcript)evt.getChangedFeature(); // editorPanel.detachTranscript (old_trans); // int tier = editorPanel.attachTranscript (new_trans); // // This is so that we don't select a different transcript // if (current_transcript != null && current_transcript == old_trans) { // current_transcript = new_trans; // } // } } return true; } /** Handle the selection event (feature was selected in another window--select it here) This is also where selections from BaseFineEditor come in which are really internal selections. Only handle external selection if followSelection is checked */ public boolean handleFeatureSelectionEvent (FeatureSelectionEvent evt) { if (!canHandleSelection(evt,this)) return false; // now we do something, canHanSel filters for GenAnnIs AnnotatedFeatureI gai = (AnnotatedFeatureI)evt.getFeatures().getFeature(0); displayAnnot(getTransOrOneLevelAnn(gai)); translationViewer.repaint(); return true; } /** Does all the handle selection checks for BaseFineEditor and BaseEditorPanel */ boolean canHandleSelection(FeatureSelectionEvent evt,Object self) { if ((noExternalSelection() && isExternalSelection(evt)) && !evt.forceSelection()) return false; if (evt.getSource() == self) return false; if (!this.isVisible()) return false; if (evt.getFeatures().size() == 0) return false; SeqFeatureI sf = evt.getFeatures().getFeature(0); // if strand of selection is not our strand return boolean is_reverse = (sf.getStrand() == -1); if (is_reverse != editorPanel.getReverseStrand()) return false; if ( ! (sf instanceof AnnotatedFeatureI)) return false;//repaint transVw? else return true; } /** True if the selection comes from outside world. false if from this OR editorPanel */ private boolean isExternalSelection(FeatureSelectionEvent e) { if (e.getSource() == this || e.getSource() == editorPanel) return false; return true; } private boolean noExternalSelection() { return !followSelectionCheckBox.isSelected(); } public Color getIndicatorColor() { return indicatorColor; } /** puts up vertical lines in szap(main window) indicating the region EDE is * displaying - make private? */ private void showEditRegion() { colorIndex = (colorIndex + 1) % colorList.length; indicatorColor = colorList[colorIndex]; colorSwatch.setBackground(indicatorColor); szap.addHighlightRegion(editorPanel, indicatorColor, editorPanel.getReverseStrand()); } public void attachListeners() { // changeListener = new AnnotationChangeDoodad(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { szap.removeHighlightRegion(editorPanel); szap.repaint(); BaseFineEditor.this.setVisible(false); } } ); clearFindsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.setShowHitZones(false); clearFindsButton.setEnabled(false); } } ); findButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showFindDialog(); } } ); goToButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showGoToDialog(); } } ); showIntronBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { translationViewer. setDrawIntrons(showIntronBox.isSelected()); } } ); upstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_up); } } ); downstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_down); } } ); } private class FineEditorScrollListener implements ChangeListener { int oldstart = -1; int oldwidth = -1; public void stateChanged(ChangeEvent e) { szap.repaint(); translationViewer.repaint(); } } /** Dispose all editors currently in existence. Keeps track of all instances for this purpose */ public static void disposeAllEditors() { for (Iterator it = baseEditorInstanceList.iterator(); it.hasNext(); ) ((BaseFineEditor)it.next()).dispose(); baseEditorInstanceList.clear(); } private class BaseEditorDataListener implements DataLoadListener { public boolean handleDataLoadEvent(DataLoadEvent e) { if (!e.dataRetrievalBeginning()) return false; disposeAllEditors(); curationState.getController().removeListener(this); return true; } } public void dispose() { removeComponents(this); editorPanel.cleanup(); // 1.3.1 popup mem leak & remove listener szap.removeHighlightRegion(editorPanel); editorPanel = null; translationViewer = null; viewport.removeChangeListener(scrollListener); viewport = null; lengthLabel = null; //featureNameLabel = null; transcriptComboBox = null; szap = null; transformer = null; scrollListener = null; indicatorColor = null; colorSwatch = null; // changeListener = null; // removeWindowListener(windowListener); // windowListener = null; getController().removeListener(this); //getController() = null; //view = null; findButton = null; clearFindsButton = null; goToButton = null; upstream_button = null; downstream_button = null; super.dispose(); } private void initGui(AnnotatedFeatureI annot) { translationViewer = new TranslationViewer(editorPanel); translationViewer.setBackground(Color.black); transcriptComboBox = new JComboBox(); lengthLabel = new JLabel("Translation length: <no feature selected>"); lengthLabel.setForeground(Color.black); findButton = new JButton("Find sequence..."); // clearFindsBox = new JCheckBox("Show search hits"); clearFindsButton = new JButton("Clear search hits"); // Disable until we actually get search results clearFindsButton.setEnabled(false); goToButton = new JButton("GoTo..."); showIntronBox = new JCheckBox("Show introns in translation viewer", true); showIntronBox.setBackground (Color.white); followSelectionCheckBox = new JCheckBox("Follow external selection",false); followSelectionCheckBox.setBackground(Color.white); upstream_button = new JButton (); downstream_button = new JButton (); colorSwatch = new JPanel(); setSize(824,500); JScrollPane pane = new JScrollPane(editorPanel); pane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pane.setRowHeaderView(new BaseFineEditorRowHeader(editorPanel)); viewport = pane.getViewport(); colorSwatch.setPreferredSize(new Dimension(10,10)); getContentPane().setBackground (Color.white); getContentPane().setLayout(new BorderLayout()); getContentPane().add(colorSwatch, "North"); getContentPane().add(pane, "Center"); Box transcriptListBox = new Box(BoxLayout.X_AXIS); JLabel tranLabel; // 1 LEVEL ANNOT if (annot.isAnnotTop()) tranLabel = new JLabel("Annotation: "); else // 3-level tranLabel = new JLabel("Transcript: "); tranLabel.setForeground(Color.black); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(tranLabel); transcriptListBox.setBackground(Color.white); transcriptComboBox.setMaximumSize(new Dimension(300,30)); transcriptListBox.add(transcriptComboBox); transcriptListBox.add(Box.createHorizontalGlue()); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(lengthLabel); transcriptListBox.add(Box.createHorizontalGlue()); Box checkboxesTop = new Box(BoxLayout.X_AXIS); checkboxesTop.setBackground (Color.white); checkboxesTop.add(Box.createHorizontalStrut(5)); checkboxesTop.add(findButton); checkboxesTop.add(Box.createHorizontalStrut(10)); checkboxesTop.add(clearFindsButton); checkboxesTop.add(Box.createHorizontalStrut(15)); checkboxesTop.add(goToButton); checkboxesTop.add(Box.createHorizontalGlue()); Box checkboxesBottom = new Box(BoxLayout.X_AXIS); checkboxesBottom.add(showIntronBox); checkboxesBottom.add(Box.createHorizontalGlue()); checkboxesBottom.add(Box.createHorizontalStrut(10)); checkboxesBottom.add(followSelectionCheckBox); Box checkboxes = new Box(BoxLayout.Y_AXIS); checkboxes.add(checkboxesTop); checkboxes.add(checkboxesBottom); Box labelPanel = new Box(BoxLayout.Y_AXIS); labelPanel.setBackground(Color.white); labelPanel.add(transcriptListBox); labelPanel.add(Box.createVerticalStrut(5)); labelPanel.add(checkboxes); Box navPanel = new Box(BoxLayout.Y_AXIS); navPanel.setBackground (Color.white); navPanel.add(upstream_button); navPanel.add(Box.createVerticalStrut(10)); navPanel.add(downstream_button); navPanel.add(Box.createVerticalGlue()); Box textBoxes = new Box(BoxLayout.X_AXIS); textBoxes.setBackground (Color.white); textBoxes.add(labelPanel); textBoxes.add(navPanel); Box detailPanel = new Box(BoxLayout.Y_AXIS); detailPanel.setBackground(Color.white); detailPanel.add(translationViewer); detailPanel.add(textBoxes); getContentPane().add(detailPanel, "South"); validateTree(); scrollListener = new FineEditorScrollListener(); viewport.addChangeListener(scrollListener); transcriptComboBox.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_U && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { CurationManager.getActiveCurationState().getTransactionManager().undo(this); } } }); } /** Both fires off selection event and displays annot */ private void selectAnnot(AnnotatedFeatureI annot) { displayAnnot(getTransOrOneLevelAnn(annot)); translationViewer.repaint(); BaseFocusEvent evt = new BaseFocusEvent(this, annot.getStart(), annot); getController().handleBaseFocusEvent(evt); getSelectionManager().select(annot,this); // sends off selection } /** Display AnnotatedFeatureI feature. * Exon, Transcript, and Gene are all GenericAnnotationI. * No selection event is fired. (selectAnnot fires and displays) */ private void displayAnnot(AnnotatedFeatureI annot) { currentAnnot = annot; if (currentAnnot == null) { transcriptComboBox.removeAllItems(); transcriptComboBox.addItem("<no feature selected>"); lengthLabel.setText("Translation length: <no feature selected>"); upstream_button.setLabel(""); downstream_button.setLabel(""); translationViewer.setTranscript(null,editorPanel.getSelectedTier()); // ?? return; } //else { setupTranscriptComboBox(currentAnnot); SeqFeatureI topAnnot = currentAnnot; if (topAnnot.isTranscript()) topAnnot = currentAnnot.getRefFeature(); if (topAnnot.isProteinCodingGene()) { String translation = currentAnnot.translate(); if (translation == null) { lengthLabel.setText("Translation length: <no start selected>"); } else { lengthLabel.setText("Translation length: " + currentAnnot.translate().length()); } } else { lengthLabel.setText(topAnnot.getFeatureType() + " annotation"); } FeatureSetI holder = (FeatureSetI) topAnnot.getRefFeature(); neighbor_up = null; neighbor_down = null; if (holder != null) { int index = holder.getFeatureIndex(topAnnot); // get next neighbor up that has whole sequence for (int i = index-1; i >= 0 && neighbor_up==null; i--) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_up = trans; } } // get next neighbor down that has whole sequence for (int i = index+1; i < holder.size() && neighbor_down==null; i++) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_down = trans; } } } upstream_button.setLabel (neighbor_up == null ? "" : "Go to next 5' annotation (" + neighbor_up.getParent().getName()+")"); upstream_button.setVisible (neighbor_up != null); downstream_button.setLabel (neighbor_down == null ? "" : "Go to next 3' annotation (" + neighbor_down.getParent().getName()+")"); downstream_button.setVisible (neighbor_down != null); //} // todo - translationViewer take in 1 level annot if (currentAnnot.isTranscript()) translationViewer.setTranscript((Transcript)currentAnnot, editorPanel.getSelectedTier()); } /** Sets up transcriptComboBox (pulldown list) with transcript and * its parent gene's other transcripts, with transcript selected */ private void setupTranscriptComboBox(AnnotatedFeatureI annot) { // could also check for gene change before doing a removeAll if (transcriptComboBox.getSelectedItem() == annot) return; // adding and removing items causes item events to fire so need to remove // listener here - is there any other way to supress firing? transcriptComboBox.removeItemListener(transItemListener); transcriptComboBox.removeAllItems(); if (annot==null) { transcriptComboBox.addItem("<no feature selected>"); return; } // 1 LEVEL ANNOT if (annot.isAnnotTop()) { transcriptComboBox.addItem(annot); return; } // TRANSCRIPT SeqFeatureI gene = annot.getRefFeature(); Vector transcripts = gene.getFeatures(); for (int i=0; i<transcripts.size(); i++) transcriptComboBox.addItem(transcripts.elementAt(i)); transcriptComboBox.setSelectedItem(annot); // transcript transcriptComboBox.addItemListener(transItemListener); } private TranscriptComboBoxItemListener transItemListener = new TranscriptComboBoxItemListener(); private class TranscriptComboBoxItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && e.getItem() instanceof Transcript) selectAnnot((Transcript)e.getItem()); } } /** AssemblyFeature is the only GAI at the moment that has no relation to // a transcript. Dont think they can end up in ede (??). // Would be nice to have an interface that was solely for the exon // trans gene heirarchy? Should we actively make sure AssemblyFeatures dont // get into ede? (filter in AnnotationMenu?) returns null if no transcript can be found. */ private AnnotatedFeatureI getTransOrOneLevelAnn(AnnotatedFeatureI af) { if (af != null) { if (af.isTranscript()) return af; if (af.isExon()) return af.getRefFeature().getAnnotatedFeature(); if (af.isAnnotTop()) { if (af.hasKids()) return af.getFeatureAt(0).getAnnotatedFeature(); // transcript else // 1 level annot return af; } } return null; } }
seqflow/BatchAmpTargetSeqSearch
src/main/java/apollo/gui/detailviewers/exonviewer/BaseFineEditor.java
8,006
// else if (evt.isReplace() && evt.isTranscriptChange()) {
line_comment
nl
package apollo.gui.detailviewers.exonviewer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import apollo.datamodel.*; import apollo.editor.AnnotationChangeEvent; import apollo.editor.AnnotationChangeListener; import apollo.gui.event.*; import apollo.dataadapter.DataLoadEvent; import apollo.dataadapter.DataLoadListener; import apollo.gui.ControlledObjectI; import apollo.gui.Controller; import apollo.gui.Transformer; import apollo.gui.genomemap.StrandedZoomableApolloPanel; import apollo.gui.SelectionManager; import apollo.gui.synteny.CurationManager; import apollo.gui.synteny.GuiCurationState; public class BaseFineEditor extends JFrame implements FeatureSelectionListener, ControlledObjectI, AnnotationChangeListener { private static final Color [] colorList = { new Color(0,0,0), new Color(255,255,0), new Color(0,255,255), new Color(255,0,255), new Color(255,0,0), new Color(0,255,0), new Color(0,0,255)}; private static int colorIndex = 0; private static ArrayList baseEditorInstanceList = new ArrayList(5); protected BaseEditorPanel editorPanel = null; private TranslationViewer translationViewer; private JViewport viewport; protected JLabel lengthLabel; private JComboBox transcriptComboBox; StrandedZoomableApolloPanel szap; Transformer transformer; private FineEditorScrollListener scrollListener; Color indicatorColor; JPanel colorSwatch; SelectionManager selection_manager; protected JButton findButton; protected JButton clearFindsButton; protected JButton goToButton; protected JCheckBox showIntronBox; // Need? private JCheckBox followSelectionCheckBox; protected JButton upstream_button; protected JButton downstream_button; private AnnotatedFeatureI currentAnnot;//Transcript protected Transcript neighbor_up; protected Transcript neighbor_down; private GuiCurationState curationState; public static void showBaseEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { BaseFineEditor bfe = new BaseFineEditor(editMe,curationState,geneHolder); baseEditorInstanceList.add(bfe); } private BaseFineEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { super((editMe.isForwardStrand() ? "Forward" : "Reverse") + " Strand Exon Editor"); this.curationState = curationState; curationState.getController().addListener(this); curationState.getController().addListener(new BaseEditorDataListener()); szap = curationState.getSZAP(); transformer = szap.getScaleView().getTransform(); int seqStart = curationState.getCurationSet().getLow(); int seqEnd = curationState.getCurationSet().getHigh(); //FeatureSetI annFeatSet=((DrawableFeatureSet)view.getDrawableSet()).getFeatureSet(); editorPanel = new BaseEditorPanel(curationState, this, !editMe.isForwardStrand(), seqStart, seqEnd, geneHolder); initGui(editMe); // cant do til after editorPanel made // cant do this til after initGui (editorPanel needs to know size) editorPanel.displayAnnot(editMe); attachListeners(); showEditRegion(); displayAnnot(getTransOrOneLevelAnn(editMe)); translationViewer.repaint(); setVisible(true); // Might just be linux, but bofe gets iconified on close if (getState()==Frame.ICONIFIED) setState(Frame.NORMAL); } /** ControlledObjectI interface - but controller now comes from curationState */ public void setController(Controller controller) { //this.controller = controller; //controller.addListener (this); } public Controller getController() { return curationState.getController(); } public Object getControllerWindow() { return this; } // Although they are removed we need to remove from hash in controller public boolean needsAutoRemoval() { return true; } public void setSelectionManager (SelectionManager sm) { this.selection_manager = sm; } public SelectionManager getSelectionManager () { return curationState.getSelectionManager();//this.selection_manager; } private void removeComponents(Container cont) { Component[] components = cont.getComponents(); Component comp; for (int i = 0; i < components.length; i++) { comp = components[i]; if (comp != null) { cont.remove(comp); if (comp instanceof Container) removeComponents((Container) comp); } } } public boolean handleAnnotationChangeEvent(AnnotationChangeEvent evt) { if (this.isVisible() && evt.getSource() != this) { if (evt.isCompound()) { for (int i = 0; i < evt.getNumberOfChildren(); ++i) { handleAnnotationChangeEvent(evt.getChildChangeEvent(i)); } return true; } if (evt.isEndOfEditSession()) { // Dont want scrolling on ann change, also sf for redraw is the // gene, so it just goes to 1st trans which is problematic. displayAnnot(currentAnnot); repaint(); // this is the needed repaint after the changes return true; } /* AnnotatedFeatureI gene = evt.getChangedAnnot(); for (Object o : szap.getAnnotations().getFeatures()) { AnnotatedFeatureI feat = (AnnotatedFeatureI)o; if (feat.getId().equals(gene.getId())) { //gene = feat; break; } } */ if (evt.isAdd()) { AnnotatedFeatureI annotToDisplay = null; AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Attaching %s(%d)\n", t, t.hashCode()); editorPanel.attachAnnot(t); if (currentAnnot != null && t.getName().equals(currentAnnot.getName())) { annotToDisplay = t; } } } if (annotToDisplay == null) { annotToDisplay = (AnnotatedFeatureI)evt.getChangedAnnot().getFeatureAt(0); } displayAnnot(annotToDisplay); return true; } if (evt.isDelete()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Detaching %s(%d)\n", t, t.hashCode()); editorPanel.detachTranscript(t); } } return true; } /* // getAnnotation() can be null after a delete - return if null? SeqFeatureI sf = evt.getAnnotTop(); // If the annotation event is not for the editors strand then return boolean is_reverse = (sf.getStrand() == -1); if (editorPanel.getReverseStrand() != is_reverse) return false; if (evt.isDelete() && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } } else if (evt.isDelete() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } else if ((evt.isAdd() || evt.isSplit() || evt.isMerge()) && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); int tier = editorPanel.attachAnnot (t); } } else if (evt.isAdd() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); int tier = editorPanel.attachAnnot (t); } // Exon split or intron made - same thing isnt it? else if (evt.isAdd() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel // to pick up new exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); } else if (evt.isDelete() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel to remove exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); // or editorPanel.removeFeature((Exon)evt.getSecondFeature()); } // else if (evt.isReplace()) { //&&evt.isTopAnnotChange - always true of replace // AnnotatedFeatureI old_gene = evt.getReplacedFeature(); // AnnotatedFeatureI new_gene = (AnnotatedFeatureI)evt.getChangedFeature(); // int trans_count = old_gene.size(); // /* This does assume that there are no changes in the number // of transcripts between the old and the new. Might be safer // to separate the 2 loops */ // for (int i = 0; i < trans_count; i++) { // Transcript t; // t = (Transcript) old_gene.getFeatureAt (i); // editorPanel.detachTranscript (t); // t = (Transcript) new_gene.getFeatureAt (i); // int tier = editorPanel.attachTranscript (t); // } // // This is so that we don't select a different transcript // AnnotatedFeatureI current_gene = (current_transcript != null ? // current_transcript.getGene() : null); // if (current_gene != null && current_gene == old_gene) { // int index = current_gene.getFeatureIndex(current_transcript); // current_transcript = (Transcript) new_gene.getFeatureAt(index); // } // } // this isnt possible - all replaces are for top annots // else if<SUF> // Transcript old_trans = (Transcript)evt.getReplacedFeature(); // Transcript new_trans = (Transcript)evt.getChangedFeature(); // editorPanel.detachTranscript (old_trans); // int tier = editorPanel.attachTranscript (new_trans); // // This is so that we don't select a different transcript // if (current_transcript != null && current_transcript == old_trans) { // current_transcript = new_trans; // } // } } return true; } /** Handle the selection event (feature was selected in another window--select it here) This is also where selections from BaseFineEditor come in which are really internal selections. Only handle external selection if followSelection is checked */ public boolean handleFeatureSelectionEvent (FeatureSelectionEvent evt) { if (!canHandleSelection(evt,this)) return false; // now we do something, canHanSel filters for GenAnnIs AnnotatedFeatureI gai = (AnnotatedFeatureI)evt.getFeatures().getFeature(0); displayAnnot(getTransOrOneLevelAnn(gai)); translationViewer.repaint(); return true; } /** Does all the handle selection checks for BaseFineEditor and BaseEditorPanel */ boolean canHandleSelection(FeatureSelectionEvent evt,Object self) { if ((noExternalSelection() && isExternalSelection(evt)) && !evt.forceSelection()) return false; if (evt.getSource() == self) return false; if (!this.isVisible()) return false; if (evt.getFeatures().size() == 0) return false; SeqFeatureI sf = evt.getFeatures().getFeature(0); // if strand of selection is not our strand return boolean is_reverse = (sf.getStrand() == -1); if (is_reverse != editorPanel.getReverseStrand()) return false; if ( ! (sf instanceof AnnotatedFeatureI)) return false;//repaint transVw? else return true; } /** True if the selection comes from outside world. false if from this OR editorPanel */ private boolean isExternalSelection(FeatureSelectionEvent e) { if (e.getSource() == this || e.getSource() == editorPanel) return false; return true; } private boolean noExternalSelection() { return !followSelectionCheckBox.isSelected(); } public Color getIndicatorColor() { return indicatorColor; } /** puts up vertical lines in szap(main window) indicating the region EDE is * displaying - make private? */ private void showEditRegion() { colorIndex = (colorIndex + 1) % colorList.length; indicatorColor = colorList[colorIndex]; colorSwatch.setBackground(indicatorColor); szap.addHighlightRegion(editorPanel, indicatorColor, editorPanel.getReverseStrand()); } public void attachListeners() { // changeListener = new AnnotationChangeDoodad(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { szap.removeHighlightRegion(editorPanel); szap.repaint(); BaseFineEditor.this.setVisible(false); } } ); clearFindsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.setShowHitZones(false); clearFindsButton.setEnabled(false); } } ); findButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showFindDialog(); } } ); goToButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showGoToDialog(); } } ); showIntronBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { translationViewer. setDrawIntrons(showIntronBox.isSelected()); } } ); upstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_up); } } ); downstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_down); } } ); } private class FineEditorScrollListener implements ChangeListener { int oldstart = -1; int oldwidth = -1; public void stateChanged(ChangeEvent e) { szap.repaint(); translationViewer.repaint(); } } /** Dispose all editors currently in existence. Keeps track of all instances for this purpose */ public static void disposeAllEditors() { for (Iterator it = baseEditorInstanceList.iterator(); it.hasNext(); ) ((BaseFineEditor)it.next()).dispose(); baseEditorInstanceList.clear(); } private class BaseEditorDataListener implements DataLoadListener { public boolean handleDataLoadEvent(DataLoadEvent e) { if (!e.dataRetrievalBeginning()) return false; disposeAllEditors(); curationState.getController().removeListener(this); return true; } } public void dispose() { removeComponents(this); editorPanel.cleanup(); // 1.3.1 popup mem leak & remove listener szap.removeHighlightRegion(editorPanel); editorPanel = null; translationViewer = null; viewport.removeChangeListener(scrollListener); viewport = null; lengthLabel = null; //featureNameLabel = null; transcriptComboBox = null; szap = null; transformer = null; scrollListener = null; indicatorColor = null; colorSwatch = null; // changeListener = null; // removeWindowListener(windowListener); // windowListener = null; getController().removeListener(this); //getController() = null; //view = null; findButton = null; clearFindsButton = null; goToButton = null; upstream_button = null; downstream_button = null; super.dispose(); } private void initGui(AnnotatedFeatureI annot) { translationViewer = new TranslationViewer(editorPanel); translationViewer.setBackground(Color.black); transcriptComboBox = new JComboBox(); lengthLabel = new JLabel("Translation length: <no feature selected>"); lengthLabel.setForeground(Color.black); findButton = new JButton("Find sequence..."); // clearFindsBox = new JCheckBox("Show search hits"); clearFindsButton = new JButton("Clear search hits"); // Disable until we actually get search results clearFindsButton.setEnabled(false); goToButton = new JButton("GoTo..."); showIntronBox = new JCheckBox("Show introns in translation viewer", true); showIntronBox.setBackground (Color.white); followSelectionCheckBox = new JCheckBox("Follow external selection",false); followSelectionCheckBox.setBackground(Color.white); upstream_button = new JButton (); downstream_button = new JButton (); colorSwatch = new JPanel(); setSize(824,500); JScrollPane pane = new JScrollPane(editorPanel); pane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pane.setRowHeaderView(new BaseFineEditorRowHeader(editorPanel)); viewport = pane.getViewport(); colorSwatch.setPreferredSize(new Dimension(10,10)); getContentPane().setBackground (Color.white); getContentPane().setLayout(new BorderLayout()); getContentPane().add(colorSwatch, "North"); getContentPane().add(pane, "Center"); Box transcriptListBox = new Box(BoxLayout.X_AXIS); JLabel tranLabel; // 1 LEVEL ANNOT if (annot.isAnnotTop()) tranLabel = new JLabel("Annotation: "); else // 3-level tranLabel = new JLabel("Transcript: "); tranLabel.setForeground(Color.black); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(tranLabel); transcriptListBox.setBackground(Color.white); transcriptComboBox.setMaximumSize(new Dimension(300,30)); transcriptListBox.add(transcriptComboBox); transcriptListBox.add(Box.createHorizontalGlue()); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(lengthLabel); transcriptListBox.add(Box.createHorizontalGlue()); Box checkboxesTop = new Box(BoxLayout.X_AXIS); checkboxesTop.setBackground (Color.white); checkboxesTop.add(Box.createHorizontalStrut(5)); checkboxesTop.add(findButton); checkboxesTop.add(Box.createHorizontalStrut(10)); checkboxesTop.add(clearFindsButton); checkboxesTop.add(Box.createHorizontalStrut(15)); checkboxesTop.add(goToButton); checkboxesTop.add(Box.createHorizontalGlue()); Box checkboxesBottom = new Box(BoxLayout.X_AXIS); checkboxesBottom.add(showIntronBox); checkboxesBottom.add(Box.createHorizontalGlue()); checkboxesBottom.add(Box.createHorizontalStrut(10)); checkboxesBottom.add(followSelectionCheckBox); Box checkboxes = new Box(BoxLayout.Y_AXIS); checkboxes.add(checkboxesTop); checkboxes.add(checkboxesBottom); Box labelPanel = new Box(BoxLayout.Y_AXIS); labelPanel.setBackground(Color.white); labelPanel.add(transcriptListBox); labelPanel.add(Box.createVerticalStrut(5)); labelPanel.add(checkboxes); Box navPanel = new Box(BoxLayout.Y_AXIS); navPanel.setBackground (Color.white); navPanel.add(upstream_button); navPanel.add(Box.createVerticalStrut(10)); navPanel.add(downstream_button); navPanel.add(Box.createVerticalGlue()); Box textBoxes = new Box(BoxLayout.X_AXIS); textBoxes.setBackground (Color.white); textBoxes.add(labelPanel); textBoxes.add(navPanel); Box detailPanel = new Box(BoxLayout.Y_AXIS); detailPanel.setBackground(Color.white); detailPanel.add(translationViewer); detailPanel.add(textBoxes); getContentPane().add(detailPanel, "South"); validateTree(); scrollListener = new FineEditorScrollListener(); viewport.addChangeListener(scrollListener); transcriptComboBox.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_U && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { CurationManager.getActiveCurationState().getTransactionManager().undo(this); } } }); } /** Both fires off selection event and displays annot */ private void selectAnnot(AnnotatedFeatureI annot) { displayAnnot(getTransOrOneLevelAnn(annot)); translationViewer.repaint(); BaseFocusEvent evt = new BaseFocusEvent(this, annot.getStart(), annot); getController().handleBaseFocusEvent(evt); getSelectionManager().select(annot,this); // sends off selection } /** Display AnnotatedFeatureI feature. * Exon, Transcript, and Gene are all GenericAnnotationI. * No selection event is fired. (selectAnnot fires and displays) */ private void displayAnnot(AnnotatedFeatureI annot) { currentAnnot = annot; if (currentAnnot == null) { transcriptComboBox.removeAllItems(); transcriptComboBox.addItem("<no feature selected>"); lengthLabel.setText("Translation length: <no feature selected>"); upstream_button.setLabel(""); downstream_button.setLabel(""); translationViewer.setTranscript(null,editorPanel.getSelectedTier()); // ?? return; } //else { setupTranscriptComboBox(currentAnnot); SeqFeatureI topAnnot = currentAnnot; if (topAnnot.isTranscript()) topAnnot = currentAnnot.getRefFeature(); if (topAnnot.isProteinCodingGene()) { String translation = currentAnnot.translate(); if (translation == null) { lengthLabel.setText("Translation length: <no start selected>"); } else { lengthLabel.setText("Translation length: " + currentAnnot.translate().length()); } } else { lengthLabel.setText(topAnnot.getFeatureType() + " annotation"); } FeatureSetI holder = (FeatureSetI) topAnnot.getRefFeature(); neighbor_up = null; neighbor_down = null; if (holder != null) { int index = holder.getFeatureIndex(topAnnot); // get next neighbor up that has whole sequence for (int i = index-1; i >= 0 && neighbor_up==null; i--) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_up = trans; } } // get next neighbor down that has whole sequence for (int i = index+1; i < holder.size() && neighbor_down==null; i++) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_down = trans; } } } upstream_button.setLabel (neighbor_up == null ? "" : "Go to next 5' annotation (" + neighbor_up.getParent().getName()+")"); upstream_button.setVisible (neighbor_up != null); downstream_button.setLabel (neighbor_down == null ? "" : "Go to next 3' annotation (" + neighbor_down.getParent().getName()+")"); downstream_button.setVisible (neighbor_down != null); //} // todo - translationViewer take in 1 level annot if (currentAnnot.isTranscript()) translationViewer.setTranscript((Transcript)currentAnnot, editorPanel.getSelectedTier()); } /** Sets up transcriptComboBox (pulldown list) with transcript and * its parent gene's other transcripts, with transcript selected */ private void setupTranscriptComboBox(AnnotatedFeatureI annot) { // could also check for gene change before doing a removeAll if (transcriptComboBox.getSelectedItem() == annot) return; // adding and removing items causes item events to fire so need to remove // listener here - is there any other way to supress firing? transcriptComboBox.removeItemListener(transItemListener); transcriptComboBox.removeAllItems(); if (annot==null) { transcriptComboBox.addItem("<no feature selected>"); return; } // 1 LEVEL ANNOT if (annot.isAnnotTop()) { transcriptComboBox.addItem(annot); return; } // TRANSCRIPT SeqFeatureI gene = annot.getRefFeature(); Vector transcripts = gene.getFeatures(); for (int i=0; i<transcripts.size(); i++) transcriptComboBox.addItem(transcripts.elementAt(i)); transcriptComboBox.setSelectedItem(annot); // transcript transcriptComboBox.addItemListener(transItemListener); } private TranscriptComboBoxItemListener transItemListener = new TranscriptComboBoxItemListener(); private class TranscriptComboBoxItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && e.getItem() instanceof Transcript) selectAnnot((Transcript)e.getItem()); } } /** AssemblyFeature is the only GAI at the moment that has no relation to // a transcript. Dont think they can end up in ede (??). // Would be nice to have an interface that was solely for the exon // trans gene heirarchy? Should we actively make sure AssemblyFeatures dont // get into ede? (filter in AnnotationMenu?) returns null if no transcript can be found. */ private AnnotatedFeatureI getTransOrOneLevelAnn(AnnotatedFeatureI af) { if (af != null) { if (af.isTranscript()) return af; if (af.isExon()) return af.getRefFeature().getAnnotatedFeature(); if (af.isAnnotTop()) { if (af.hasKids()) return af.getFeatureAt(0).getAnnotatedFeature(); // transcript else // 1 level annot return af; } } return null; } }
154314_8
package org.getalp.dbnary.languages.nld; import org.getalp.dbnary.LexinfoOnt; import org.getalp.dbnary.languages.OntolexBasedRDFDataHandler; import org.getalp.dbnary.OntolexOnt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author malick */ public class WiktionaryDataHandler extends OntolexBasedRDFDataHandler { private Logger log = LoggerFactory.getLogger(WiktionaryDataHandler.class); static { // DONE: dutch POS posAndTypeValueMap.put("abbr", new PosAndType(LexinfoOnt.abbreviation, LexinfoOnt.AbbreviatedForm)); posAndTypeValueMap.put("adjc", new PosAndType(LexinfoOnt.adjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("adverb", new PosAndType(LexinfoOnt.adverb, LexinfoOnt.Adverb)); posAndTypeValueMap.put("adverb-num", new PosAndType(LexinfoOnt.adverb, LexinfoOnt.Adverb)); // ? posAndTypeValueMap.put("art", new PosAndType(LexinfoOnt.article, LexinfoOnt.Article)); posAndTypeValueMap.put("cijfer", new PosAndType(LexinfoOnt.numeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("circumf", new PosAndType(LexinfoOnt.circumposition, LexinfoOnt.Adposition)); posAndTypeValueMap.put("conj", new PosAndType(LexinfoOnt.conjunction, LexinfoOnt.Conjunction)); posAndTypeValueMap.put("cont", new PosAndType(LexinfoOnt.contraction, LexinfoOnt.AbbreviatedForm)); // not for Dutch... // posAndTypeValueMap.put("ideo", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("interf", new PosAndType(LexinfoOnt.infix, LexinfoOnt.Infix)); posAndTypeValueMap.put("interj", new PosAndType(LexinfoOnt.interjection, LexinfoOnt.Interjection)); posAndTypeValueMap.put("leesteken", new PosAndType(LexinfoOnt.punctuation, LexinfoOnt.Symbol)); posAndTypeValueMap.put("letter", new PosAndType(LexinfoOnt.letter, LexinfoOnt.Symbol)); posAndTypeValueMap.put("name", new PosAndType(LexinfoOnt.properNoun, LexinfoOnt.ProperNoun)); posAndTypeValueMap.put("noun", new PosAndType(LexinfoOnt.noun, LexinfoOnt.Noun)); posAndTypeValueMap.put("num", new PosAndType(LexinfoOnt.cardinalNumeral, LexinfoOnt.Numeral)); // not for Dutch... // posAndTypeValueMap.put("num-distr", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("num-indef", new PosAndType(LexinfoOnt.indefiniteCardinalNumeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("num-int", new PosAndType(LexinfoOnt.interrogativeCardinalNumeral, LexinfoOnt.Numeral)); // Not for Dutch // posAndTypeValueMap.put("num-srt", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("ordn", new PosAndType(LexinfoOnt.ordinalAdjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("ordn-indef", new PosAndType(LexinfoOnt.indefiniteOrdinalNumeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("prcp", new PosAndType(LexinfoOnt.participleAdjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("phrase", new PosAndType(LexinfoOnt.phraseologicalUnit, OntolexOnt.MultiWordExpression)); posAndTypeValueMap.put("post", new PosAndType(LexinfoOnt.postposition, LexinfoOnt.Postposition)); posAndTypeValueMap.put("pref", new PosAndType(LexinfoOnt.prefix, LexinfoOnt.Prefix)); posAndTypeValueMap.put("prep", new PosAndType(LexinfoOnt.preposition, LexinfoOnt.Preposition)); // Not in Dutch // posAndTypeValueMap.put("prep-form", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("pron-adv", new PosAndType(LexinfoOnt.adverbialPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-dem", new PosAndType(LexinfoOnt.demonstrativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-excl", new PosAndType(LexinfoOnt.exclamativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-indef", new PosAndType(LexinfoOnt.indefinitePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-int", new PosAndType(LexinfoOnt.interrogativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-pers", new PosAndType(LexinfoOnt.personalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-pos", new PosAndType(LexinfoOnt.possessivePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-rec", new PosAndType(LexinfoOnt.reciprocalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-refl", new PosAndType(LexinfoOnt.reflexivePersonalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-rel", new PosAndType(LexinfoOnt.relativePronoun, LexinfoOnt.Pronoun)); // posAndTypeValueMap.put("pronom-temp", new PosAndType(LexinfoOnt.noun, // LexinfoOnt.LexicalEntry)); posAndTypeValueMap.put("pronoun", new PosAndType(LexinfoOnt.pronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("prtc", new PosAndType(LexinfoOnt.particle, LexinfoOnt.Particle)); posAndTypeValueMap.put("suff", new PosAndType(LexinfoOnt.suffix, LexinfoOnt.Suffix)); posAndTypeValueMap.put("symbool", new PosAndType(LexinfoOnt.symbol, LexinfoOnt.Symbol)); posAndTypeValueMap.put("verb", new PosAndType(LexinfoOnt.verb, LexinfoOnt.Verb)); } public WiktionaryDataHandler(String lang, String tdbDir) { super(lang, tdbDir); } public static boolean isValidPOS(String pos) { return posAndTypeValueMap.containsKey(pos); } }
serasset/dbnary
dbnary-extractor/src/main/java/org/getalp/dbnary/languages/nld/WiktionaryDataHandler.java
2,011
// Not in Dutch
line_comment
nl
package org.getalp.dbnary.languages.nld; import org.getalp.dbnary.LexinfoOnt; import org.getalp.dbnary.languages.OntolexBasedRDFDataHandler; import org.getalp.dbnary.OntolexOnt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author malick */ public class WiktionaryDataHandler extends OntolexBasedRDFDataHandler { private Logger log = LoggerFactory.getLogger(WiktionaryDataHandler.class); static { // DONE: dutch POS posAndTypeValueMap.put("abbr", new PosAndType(LexinfoOnt.abbreviation, LexinfoOnt.AbbreviatedForm)); posAndTypeValueMap.put("adjc", new PosAndType(LexinfoOnt.adjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("adverb", new PosAndType(LexinfoOnt.adverb, LexinfoOnt.Adverb)); posAndTypeValueMap.put("adverb-num", new PosAndType(LexinfoOnt.adverb, LexinfoOnt.Adverb)); // ? posAndTypeValueMap.put("art", new PosAndType(LexinfoOnt.article, LexinfoOnt.Article)); posAndTypeValueMap.put("cijfer", new PosAndType(LexinfoOnt.numeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("circumf", new PosAndType(LexinfoOnt.circumposition, LexinfoOnt.Adposition)); posAndTypeValueMap.put("conj", new PosAndType(LexinfoOnt.conjunction, LexinfoOnt.Conjunction)); posAndTypeValueMap.put("cont", new PosAndType(LexinfoOnt.contraction, LexinfoOnt.AbbreviatedForm)); // not for Dutch... // posAndTypeValueMap.put("ideo", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("interf", new PosAndType(LexinfoOnt.infix, LexinfoOnt.Infix)); posAndTypeValueMap.put("interj", new PosAndType(LexinfoOnt.interjection, LexinfoOnt.Interjection)); posAndTypeValueMap.put("leesteken", new PosAndType(LexinfoOnt.punctuation, LexinfoOnt.Symbol)); posAndTypeValueMap.put("letter", new PosAndType(LexinfoOnt.letter, LexinfoOnt.Symbol)); posAndTypeValueMap.put("name", new PosAndType(LexinfoOnt.properNoun, LexinfoOnt.ProperNoun)); posAndTypeValueMap.put("noun", new PosAndType(LexinfoOnt.noun, LexinfoOnt.Noun)); posAndTypeValueMap.put("num", new PosAndType(LexinfoOnt.cardinalNumeral, LexinfoOnt.Numeral)); // not for Dutch... // posAndTypeValueMap.put("num-distr", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("num-indef", new PosAndType(LexinfoOnt.indefiniteCardinalNumeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("num-int", new PosAndType(LexinfoOnt.interrogativeCardinalNumeral, LexinfoOnt.Numeral)); // Not for Dutch // posAndTypeValueMap.put("num-srt", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("ordn", new PosAndType(LexinfoOnt.ordinalAdjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("ordn-indef", new PosAndType(LexinfoOnt.indefiniteOrdinalNumeral, LexinfoOnt.Numeral)); posAndTypeValueMap.put("prcp", new PosAndType(LexinfoOnt.participleAdjective, LexinfoOnt.Adjective)); posAndTypeValueMap.put("phrase", new PosAndType(LexinfoOnt.phraseologicalUnit, OntolexOnt.MultiWordExpression)); posAndTypeValueMap.put("post", new PosAndType(LexinfoOnt.postposition, LexinfoOnt.Postposition)); posAndTypeValueMap.put("pref", new PosAndType(LexinfoOnt.prefix, LexinfoOnt.Prefix)); posAndTypeValueMap.put("prep", new PosAndType(LexinfoOnt.preposition, LexinfoOnt.Preposition)); // Not in<SUF> // posAndTypeValueMap.put("prep-form", new PosAndType(LexinfoOnt., OntolexOnt.LexicalEntry)); posAndTypeValueMap.put("pron-adv", new PosAndType(LexinfoOnt.adverbialPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-dem", new PosAndType(LexinfoOnt.demonstrativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-excl", new PosAndType(LexinfoOnt.exclamativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-indef", new PosAndType(LexinfoOnt.indefinitePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-int", new PosAndType(LexinfoOnt.interrogativePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-pers", new PosAndType(LexinfoOnt.personalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-pos", new PosAndType(LexinfoOnt.possessivePronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-rec", new PosAndType(LexinfoOnt.reciprocalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-refl", new PosAndType(LexinfoOnt.reflexivePersonalPronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("pronom-rel", new PosAndType(LexinfoOnt.relativePronoun, LexinfoOnt.Pronoun)); // posAndTypeValueMap.put("pronom-temp", new PosAndType(LexinfoOnt.noun, // LexinfoOnt.LexicalEntry)); posAndTypeValueMap.put("pronoun", new PosAndType(LexinfoOnt.pronoun, LexinfoOnt.Pronoun)); posAndTypeValueMap.put("prtc", new PosAndType(LexinfoOnt.particle, LexinfoOnt.Particle)); posAndTypeValueMap.put("suff", new PosAndType(LexinfoOnt.suffix, LexinfoOnt.Suffix)); posAndTypeValueMap.put("symbool", new PosAndType(LexinfoOnt.symbol, LexinfoOnt.Symbol)); posAndTypeValueMap.put("verb", new PosAndType(LexinfoOnt.verb, LexinfoOnt.Verb)); } public WiktionaryDataHandler(String lang, String tdbDir) { super(lang, tdbDir); } public static boolean isValidPOS(String pos) { return posAndTypeValueMap.containsKey(pos); } }
157736_1
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.phd; import java.util.Comparator; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.fenixedu.academic.domain.ExternalUser; import org.fenixedu.academic.domain.Person; import org.fenixedu.academic.domain.accessControl.AcademicAuthorizationGroup; import org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicOperationType; import org.fenixedu.academic.domain.exceptions.DomainException; import org.fenixedu.academic.util.FileUtils; import org.fenixedu.bennu.core.domain.User; import org.fenixedu.bennu.io.servlet.FileDownloadServlet; public class PhdProgramProcessDocument extends PhdProgramProcessDocument_Base { public static Comparator<PhdProgramProcessDocument> COMPARATOR_BY_UPLOAD_TIME = new Comparator<PhdProgramProcessDocument>() { @Override public int compare(PhdProgramProcessDocument left, PhdProgramProcessDocument right) { int comparationResult = left.getCreationDate().compareTo(right.getCreationDate()); return (comparationResult == 0) ? left.getExternalId().compareTo(right.getExternalId()) : comparationResult; } }; public static Comparator<PhdProgramProcessDocument> COMPARATOR_BY_VERSION = new Comparator<PhdProgramProcessDocument>() { @Override public int compare(PhdProgramProcessDocument left, PhdProgramProcessDocument right) { return left.getDocumentVersion().compareTo(right.getDocumentVersion()) * -1; } }; protected PhdProgramProcessDocument() { super(); } public PhdProgramProcessDocument(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { this(); init(process, documentType, remarks, content, filename, uploader); } protected void init(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { checkParameters(process, documentType, content, filename, uploader); setDocumentVersion(process, documentType); super.setPhdProgramProcess(process); super.setDocumentType(documentType); super.setRemarks(remarks); super.setUploader(uploader); super.setDocumentAccepted(true); super.init(filename, filename, content); } @Override public void setFilename(String filename) { super.setFilename(FileUtils.cleanupUserInputFilename(filename)); } @Override public void setDisplayName(String displayName) { super.setDisplayName(FileUtils.cleanupUserInputFileDisplayName(displayName)); } protected void setDocumentVersion(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType) { if (documentType.isVersioned()) { super.setDocumentVersion(process.getLastVersionNumber(documentType)); } else { super.setDocumentVersion(1); } } protected void checkParameters(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, byte[] content, String filename, Person uploader) { String[] args = {}; if (process == null) { throw new DomainException("error.phd.PhdProgramProcessDocument.process.cannot.be.null", args); } String[] args1 = {}; if (uploader == null) { throw new DomainException( "error.org.fenixedu.academic.domain.phd.candidacy.PhdProgramCandidacyProcessDocument.uploader.cannot.be.null", args1); } if (documentType == null || content == null || content.length == 0 || StringUtils.isEmpty(filename)) { throw new DomainException("error.phd.PhdProgramProcessDocument.documentType.and.file.cannot.be.null"); } } // Delete jsp usages and delete this method @Deprecated public String getDownloadUrl() { return FileDownloadServlet.getDownloadUrl(this); } @Override public void delete() { setUploader(null); setPhdProgramProcess(null); super.delete(); } // /* // * This method works properly because disconnect is re-implemented and // * super.disconnect is called first // */ // @Override // protected void createDeleteFileRequest() { // Person person = AccessControl.getPerson(); // if (person == null) { // person = getPhdProgramProcess().getPerson(); // } // new DeleteFileRequest(person, getExternalStorageIdentification()); // } public boolean hasType(final PhdIndividualProgramDocumentType type) { return getDocumentType().equals(type); } @Override public boolean isAccessible(User user) { if (user != null && user.getPerson() != null) { if (getPhdProgramProcess().getPerson() == user.getPerson() || AcademicAuthorizationGroup.get(AcademicOperationType.MANAGE_PHD_PROCESSES).isMember(user) || getPhdProgramProcess().getIndividualProgramProcess().isCoordinatorForPhdProgram(user.getPerson()) || getPhdProgramProcess().getIndividualProgramProcess().isGuiderOrAssistentGuider(user.getPerson()) || ExternalUser.isExternalUser(user.getUsername())) { return true; } } return false; } @Override public boolean isPrivate() { return true; } public PhdProgramProcessDocument replaceDocument(PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { if (!this.getClass().equals(PhdProgramProcessDocument.class)) { throw new DomainException("error.phd.PhdProgramProcessDocument.override.replaceDocument.method.on.this.class"); } if (!getDocumentType().equals(documentType)) { throw new DomainException("error.phd.PhdProgramProcessDocument.type.must.be.equal"); } return new PhdProgramProcessDocument(getPhdProgramProcess(), documentType, remarks, content, filename, uploader); } public boolean isReplaceable() { return isVersioned(); } public boolean isReplaceableAndNotJuryReportFeedbackType() { return isVersioned() && !isJuryReportFeedbackType(); } public boolean isOtherType() { return hasType(PhdIndividualProgramDocumentType.OTHER); } public boolean isJuryReportFeedbackType() { return hasType(PhdIndividualProgramDocumentType.JURY_REPORT_FEEDBACK); } public boolean isVersioned() { return getDocumentType().isVersioned(); } public boolean isLast() { return !isVersioned() || getPhdProgramProcess().getLatestDocumentVersionFor(getDocumentType()) == this; } public PhdProgramProcessDocument getLastVersion() { if (!isVersioned()) { return this; } return getPhdProgramProcess().getLatestDocumentVersionFor(getDocumentType()); } public Set<PhdProgramProcessDocument> getAllVersions() { return getPhdProgramProcess().getAllDocumentVersionsOfType(getDocumentType()); } public void removeFromProcess() { if (!isVersioned()) { setDocumentAccepted(false); return; } Set<PhdProgramProcessDocument> versions = getAllVersions(); for (PhdProgramProcessDocument version : versions) { version.setDocumentAccepted(false); } } }
sergiofbsilva/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/phd/PhdProgramProcessDocument.java
2,262
// Delete jsp usages and delete this method
line_comment
nl
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.phd; import java.util.Comparator; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.fenixedu.academic.domain.ExternalUser; import org.fenixedu.academic.domain.Person; import org.fenixedu.academic.domain.accessControl.AcademicAuthorizationGroup; import org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicOperationType; import org.fenixedu.academic.domain.exceptions.DomainException; import org.fenixedu.academic.util.FileUtils; import org.fenixedu.bennu.core.domain.User; import org.fenixedu.bennu.io.servlet.FileDownloadServlet; public class PhdProgramProcessDocument extends PhdProgramProcessDocument_Base { public static Comparator<PhdProgramProcessDocument> COMPARATOR_BY_UPLOAD_TIME = new Comparator<PhdProgramProcessDocument>() { @Override public int compare(PhdProgramProcessDocument left, PhdProgramProcessDocument right) { int comparationResult = left.getCreationDate().compareTo(right.getCreationDate()); return (comparationResult == 0) ? left.getExternalId().compareTo(right.getExternalId()) : comparationResult; } }; public static Comparator<PhdProgramProcessDocument> COMPARATOR_BY_VERSION = new Comparator<PhdProgramProcessDocument>() { @Override public int compare(PhdProgramProcessDocument left, PhdProgramProcessDocument right) { return left.getDocumentVersion().compareTo(right.getDocumentVersion()) * -1; } }; protected PhdProgramProcessDocument() { super(); } public PhdProgramProcessDocument(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { this(); init(process, documentType, remarks, content, filename, uploader); } protected void init(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { checkParameters(process, documentType, content, filename, uploader); setDocumentVersion(process, documentType); super.setPhdProgramProcess(process); super.setDocumentType(documentType); super.setRemarks(remarks); super.setUploader(uploader); super.setDocumentAccepted(true); super.init(filename, filename, content); } @Override public void setFilename(String filename) { super.setFilename(FileUtils.cleanupUserInputFilename(filename)); } @Override public void setDisplayName(String displayName) { super.setDisplayName(FileUtils.cleanupUserInputFileDisplayName(displayName)); } protected void setDocumentVersion(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType) { if (documentType.isVersioned()) { super.setDocumentVersion(process.getLastVersionNumber(documentType)); } else { super.setDocumentVersion(1); } } protected void checkParameters(PhdProgramProcess process, PhdIndividualProgramDocumentType documentType, byte[] content, String filename, Person uploader) { String[] args = {}; if (process == null) { throw new DomainException("error.phd.PhdProgramProcessDocument.process.cannot.be.null", args); } String[] args1 = {}; if (uploader == null) { throw new DomainException( "error.org.fenixedu.academic.domain.phd.candidacy.PhdProgramCandidacyProcessDocument.uploader.cannot.be.null", args1); } if (documentType == null || content == null || content.length == 0 || StringUtils.isEmpty(filename)) { throw new DomainException("error.phd.PhdProgramProcessDocument.documentType.and.file.cannot.be.null"); } } // Delete jsp<SUF> @Deprecated public String getDownloadUrl() { return FileDownloadServlet.getDownloadUrl(this); } @Override public void delete() { setUploader(null); setPhdProgramProcess(null); super.delete(); } // /* // * This method works properly because disconnect is re-implemented and // * super.disconnect is called first // */ // @Override // protected void createDeleteFileRequest() { // Person person = AccessControl.getPerson(); // if (person == null) { // person = getPhdProgramProcess().getPerson(); // } // new DeleteFileRequest(person, getExternalStorageIdentification()); // } public boolean hasType(final PhdIndividualProgramDocumentType type) { return getDocumentType().equals(type); } @Override public boolean isAccessible(User user) { if (user != null && user.getPerson() != null) { if (getPhdProgramProcess().getPerson() == user.getPerson() || AcademicAuthorizationGroup.get(AcademicOperationType.MANAGE_PHD_PROCESSES).isMember(user) || getPhdProgramProcess().getIndividualProgramProcess().isCoordinatorForPhdProgram(user.getPerson()) || getPhdProgramProcess().getIndividualProgramProcess().isGuiderOrAssistentGuider(user.getPerson()) || ExternalUser.isExternalUser(user.getUsername())) { return true; } } return false; } @Override public boolean isPrivate() { return true; } public PhdProgramProcessDocument replaceDocument(PhdIndividualProgramDocumentType documentType, String remarks, byte[] content, String filename, Person uploader) { if (!this.getClass().equals(PhdProgramProcessDocument.class)) { throw new DomainException("error.phd.PhdProgramProcessDocument.override.replaceDocument.method.on.this.class"); } if (!getDocumentType().equals(documentType)) { throw new DomainException("error.phd.PhdProgramProcessDocument.type.must.be.equal"); } return new PhdProgramProcessDocument(getPhdProgramProcess(), documentType, remarks, content, filename, uploader); } public boolean isReplaceable() { return isVersioned(); } public boolean isReplaceableAndNotJuryReportFeedbackType() { return isVersioned() && !isJuryReportFeedbackType(); } public boolean isOtherType() { return hasType(PhdIndividualProgramDocumentType.OTHER); } public boolean isJuryReportFeedbackType() { return hasType(PhdIndividualProgramDocumentType.JURY_REPORT_FEEDBACK); } public boolean isVersioned() { return getDocumentType().isVersioned(); } public boolean isLast() { return !isVersioned() || getPhdProgramProcess().getLatestDocumentVersionFor(getDocumentType()) == this; } public PhdProgramProcessDocument getLastVersion() { if (!isVersioned()) { return this; } return getPhdProgramProcess().getLatestDocumentVersionFor(getDocumentType()); } public Set<PhdProgramProcessDocument> getAllVersions() { return getPhdProgramProcess().getAllDocumentVersionsOfType(getDocumentType()); } public void removeFromProcess() { if (!isVersioned()) { setDocumentAccepted(false); return; } Set<PhdProgramProcessDocument> versions = getAllVersions(); for (PhdProgramProcessDocument version : versions) { version.setDocumentAccepted(false); } } }
201440_14
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord value this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
sethmenghi/boolean-forest
src/Objects/Owl.java
884
// initialize yCoord value
line_comment
nl
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord<SUF> this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
209699_18
/* * Static methods dealing with the Atmosphere * ===================================================================== * This file is part of JSatTrak. * * Copyright 2007-2013 Shawn E. Gano * * 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 name.gano.astro; import name.gano.astro.bodies.Sun; /** * * @author sgano */ public class Atmosphere { /** * Computes the acceleration due to the atmospheric drag. * (uses modified Harris-Priester model) * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r Satellite position vector in the inertial system [m] * @param v Satellite velocity vector in the inertial system [m/s] * @param T Transformation matrix to true-of-date inertial system * @param Area Cross-section [m^2] * @param mass Spacecraft mass [kg] * @param CD Drag coefficient * @return Acceleration (a=d^2r/dt^2) [m/s^2] */ public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v, final double[][] T, double Area, double mass, double CD) { // Constants // Earth angular velocity vector [rad/s] final double[] omega = {0.0, 0.0, 7.29212e-5}; // Variables double v_abs, dens; double[] r_tod = new double[3]; double[] v_tod = new double[3]; double[] v_rel = new double[3]; double[] a_tod = new double[3]; double[][] T_trp = new double[3][3]; // Transformation matrix to ICRF/EME2000 system T_trp = MathUtils.transpose(T); // Position and velocity in true-of-date system r_tod = MathUtils.mult(T, r); v_tod = MathUtils.mult(T, v); // Velocity relative to the Earth's atmosphere v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod)); v_abs = MathUtils.norm(v_rel); // Atmospheric density due to modified Harris-Priester model dens = Density_HP(Mjd_TT, r_tod); // Acceleration a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs); return MathUtils.mult(T_trp, a_tod); } // accellDrag /** * Computes the atmospheric density for the modified Harris-Priester model. * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r_tod Satellite position vector in the inertial system [m] * @return Density [kg/m^3] */ public static double Density_HP(double Mjd_TT, final double[] r_tod) { // Constants final double upper_limit = 1000.0; // Upper height limit [km] final double lower_limit = 100.0; // Lower height limit [km] final double ra_lag = 0.523599; // Right ascension lag [rad] final int n_prm = 3; // Harris-Priester parameter // 2(6) low(high) inclination // Harris-Priester atmospheric density model parameters // Height [km], minimum density, maximum density [gm/km^3] final int N_Coef = 50; final double[] h = { 100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0, 210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0, 320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0, 520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0, 720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0 }; final double[] c_min = { 4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03, 8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02, 9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01, 2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00, 2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01, 2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02, 4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02, 1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03, 1.560e-03, 1.150e-03 }; final double[] c_max = { 4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03, 8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02, 1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01, 4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00, 7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00, 1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01, 4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01, 1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02, 2.360e-02, 1.810e-02 }; // Variables int i, ih; // Height section variables double height; // Earth flattening double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc. double c_psi2; // Harris-Priester modification double density, h_min, h_max, d_min, d_max;// Height, density parameters double[] r_Sun = new double[3]; // Sun position double[] u = new double[3]; // Apex of diurnal bulge // Satellite height (in km) height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km] // Exit with zero density outside height model limits if (height >= upper_limit || height <= lower_limit) { return 0.0; } // Sun right ascension, declination r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT); ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]); dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2))); // Unit vector u towards the apex of the diurnal bulge // in inertial geocentric coordinates c_dec = Math.cos(dec_Sun); u[0] = c_dec * Math.cos(ra_Sun + ra_lag); u[1] = c_dec * Math.sin(ra_Sun + ra_lag); u[2] = Math.sin(dec_Sun); // Cosine of half angle between satellite position vector and // apex of diurnal bulge c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod); // Height index search and exponential density interpolation ih = 0; // section index reset for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes { if (height >= h[i] && height < h[i + 1]) { ih = i; // ih identifies height section break; } } h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]); h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]); d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min); d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max); // Density computation density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm); return density * 1.0e-12; // [kg/m^3] } // Density_HP }
sgano/JSatTrak
src/name/gano/astro/Atmosphere.java
3,164
// Height, density parameters
line_comment
nl
/* * Static methods dealing with the Atmosphere * ===================================================================== * This file is part of JSatTrak. * * Copyright 2007-2013 Shawn E. Gano * * 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 name.gano.astro; import name.gano.astro.bodies.Sun; /** * * @author sgano */ public class Atmosphere { /** * Computes the acceleration due to the atmospheric drag. * (uses modified Harris-Priester model) * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r Satellite position vector in the inertial system [m] * @param v Satellite velocity vector in the inertial system [m/s] * @param T Transformation matrix to true-of-date inertial system * @param Area Cross-section [m^2] * @param mass Spacecraft mass [kg] * @param CD Drag coefficient * @return Acceleration (a=d^2r/dt^2) [m/s^2] */ public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v, final double[][] T, double Area, double mass, double CD) { // Constants // Earth angular velocity vector [rad/s] final double[] omega = {0.0, 0.0, 7.29212e-5}; // Variables double v_abs, dens; double[] r_tod = new double[3]; double[] v_tod = new double[3]; double[] v_rel = new double[3]; double[] a_tod = new double[3]; double[][] T_trp = new double[3][3]; // Transformation matrix to ICRF/EME2000 system T_trp = MathUtils.transpose(T); // Position and velocity in true-of-date system r_tod = MathUtils.mult(T, r); v_tod = MathUtils.mult(T, v); // Velocity relative to the Earth's atmosphere v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod)); v_abs = MathUtils.norm(v_rel); // Atmospheric density due to modified Harris-Priester model dens = Density_HP(Mjd_TT, r_tod); // Acceleration a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs); return MathUtils.mult(T_trp, a_tod); } // accellDrag /** * Computes the atmospheric density for the modified Harris-Priester model. * * @param Mjd_TT Terrestrial Time (Modified Julian Date) * @param r_tod Satellite position vector in the inertial system [m] * @return Density [kg/m^3] */ public static double Density_HP(double Mjd_TT, final double[] r_tod) { // Constants final double upper_limit = 1000.0; // Upper height limit [km] final double lower_limit = 100.0; // Lower height limit [km] final double ra_lag = 0.523599; // Right ascension lag [rad] final int n_prm = 3; // Harris-Priester parameter // 2(6) low(high) inclination // Harris-Priester atmospheric density model parameters // Height [km], minimum density, maximum density [gm/km^3] final int N_Coef = 50; final double[] h = { 100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0, 210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0, 320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0, 520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0, 720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0 }; final double[] c_min = { 4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03, 8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02, 9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01, 2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00, 2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01, 2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02, 4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02, 1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03, 1.560e-03, 1.150e-03 }; final double[] c_max = { 4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03, 8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02, 1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01, 4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00, 7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00, 1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01, 4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01, 1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02, 2.360e-02, 1.810e-02 }; // Variables int i, ih; // Height section variables double height; // Earth flattening double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc. double c_psi2; // Harris-Priester modification double density, h_min, h_max, d_min, d_max;// Height, density<SUF> double[] r_Sun = new double[3]; // Sun position double[] u = new double[3]; // Apex of diurnal bulge // Satellite height (in km) height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km] // Exit with zero density outside height model limits if (height >= upper_limit || height <= lower_limit) { return 0.0; } // Sun right ascension, declination r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT); ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]); dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2))); // Unit vector u towards the apex of the diurnal bulge // in inertial geocentric coordinates c_dec = Math.cos(dec_Sun); u[0] = c_dec * Math.cos(ra_Sun + ra_lag); u[1] = c_dec * Math.sin(ra_Sun + ra_lag); u[2] = Math.sin(dec_Sun); // Cosine of half angle between satellite position vector and // apex of diurnal bulge c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod); // Height index search and exponential density interpolation ih = 0; // section index reset for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes { if (height >= h[i] && height < h[i + 1]) { ih = i; // ih identifies height section break; } } h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]); h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]); d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min); d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max); // Density computation density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm); return density * 1.0e-12; // [kg/m^3] } // Density_HP }
19807_8
package rekenen; import rekenen.plugins.Plugin; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; /** * PEER TUTORING * P2W3 */ public class Rekenmachine { private final int MAX_AANTAL_PLUGINS = 10; private Plugin[] ingeladenPlugins; private int aantalPlugins; private StringBuilder log; private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS"); public Rekenmachine() { this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS]; aantalPlugins = 0; initLog(); } public void installeer(Plugin teInstallerenPlugin) { //Opgave 2.1.a // Simpele oplossing: boolean isInstalled = false; for (int i = 0; i < aantalPlugins; i++) { if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) { isInstalled = true; break; } } if (!isInstalled) ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin; // Java 8 Streams oplossing: /* Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream .filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is) .isPresent() -> is er een element dat de filter overleefd heeft? */ // if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) { // ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin; // } } public double bereken(String command, double x, double y) { //Opgave 2.1.b // Simpele oplossing: Plugin plugin = null; for (int i = 0; i < aantalPlugins; i++) { if(ingeladenPlugins[i].getCommand().equals(command.trim())){ plugin = ingeladenPlugins[i]; break; } } if(plugin!= null){ double result = plugin.bereken(x,y); log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur())); return result; } else { System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command)); return Double.POSITIVE_INFINITY; } // Java 8 Streams: // Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny(); // if (plugin.isPresent()) { // double result = plugin.get().bereken(x, y); // log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur())); // return result; // } else { // System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command)); // return Double.POSITIVE_INFINITY; // } } @Override public String toString() { //Opgave 2.1c // Simpele oplossing: String result = "Geïnstalleerde Plugins:"; for (int i = 0; i < aantalPlugins; i++) { result += " " + ingeladenPlugins[i].getCommand(); } return result; // Java 8 Streams: /* .map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin. .collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar. */ // return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining("")); } public String getLog() { String result = log.toString(); initLog(); return result; } private void initLog() { this.log = new StringBuilder(); this.log.append("==== LOG ===="); } }
sgentens/Peer-Tutoring-Sessie7
Sessie7/src/rekenen/Rekenmachine.java
1,405
// double result = plugin.get().bereken(x, y);
line_comment
nl
package rekenen; import rekenen.plugins.Plugin; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; /** * PEER TUTORING * P2W3 */ public class Rekenmachine { private final int MAX_AANTAL_PLUGINS = 10; private Plugin[] ingeladenPlugins; private int aantalPlugins; private StringBuilder log; private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS"); public Rekenmachine() { this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS]; aantalPlugins = 0; initLog(); } public void installeer(Plugin teInstallerenPlugin) { //Opgave 2.1.a // Simpele oplossing: boolean isInstalled = false; for (int i = 0; i < aantalPlugins; i++) { if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) { isInstalled = true; break; } } if (!isInstalled) ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin; // Java 8 Streams oplossing: /* Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream .filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is) .isPresent() -> is er een element dat de filter overleefd heeft? */ // if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) { // ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin; // } } public double bereken(String command, double x, double y) { //Opgave 2.1.b // Simpele oplossing: Plugin plugin = null; for (int i = 0; i < aantalPlugins; i++) { if(ingeladenPlugins[i].getCommand().equals(command.trim())){ plugin = ingeladenPlugins[i]; break; } } if(plugin!= null){ double result = plugin.bereken(x,y); log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur())); return result; } else { System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command)); return Double.POSITIVE_INFINITY; } // Java 8 Streams: // Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny(); // if (plugin.isPresent()) { // double result<SUF> // log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur())); // return result; // } else { // System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command)); // return Double.POSITIVE_INFINITY; // } } @Override public String toString() { //Opgave 2.1c // Simpele oplossing: String result = "Geïnstalleerde Plugins:"; for (int i = 0; i < aantalPlugins; i++) { result += " " + ingeladenPlugins[i].getCommand(); } return result; // Java 8 Streams: /* .map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin. .collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar. */ // return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining("")); } public String getLog() { String result = log.toString(); initLog(); return result; } private void initLog() { this.log = new StringBuilder(); this.log.append("==== LOG ===="); } }
33438_2
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo 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, version 3. iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; /** 3D vector filed defined by normal vector of mesh vertices @author Satoru Sugihara */ public class ILinkedNodeMeshField extends I3DField{ public ILinkedNodeMeshField(IMeshI m){ super(new ILinkedNodeMeshFieldGeo(m)); } public static class ILinkedNodeMeshFieldGeo extends IMeshFieldGeo{ public ILinkedDataAgent<IVecI>[] linkedAgents; public IVectorObject[] vectorObjects; // to visualize public ILinkedNodeMeshFieldGeo(IMeshI m){ super(m); initField(); } public void initField(){ @SuppressWarnings("unchecked") ILinkedDataAgent<IVecI>[] agents = ILinkedDataAgent.<IVecI>create(mesh); linkedAgents = agents; for(int i=0; i<linkedAgents.length; i++){ linkedAgents[i].setData(new IVec()); } } public ILinkedNodeMeshFieldGeo setForce(int vertexIndex, IVecI vec){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return this; linkedAgents[vertexIndex].setData(vec); return this; } public IVecI getForce(int vertexIndex){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return new IVec(); return linkedAgents[vertexIndex].getData(); } public ILinkedNodeMeshFieldGeo addForce(int vertexIndex, IVecI vec){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return this; linkedAgents[vertexIndex].addData(vec); return this; } /* public ILinkedVecAgent<IVecI> getNode(int vertexIndex){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return null; return linkedAgents[vertexIndex]; } */ public IVecI get(int vertexIdx){ return getForce(vertexIdx); } public ILinkedNodeMeshFieldGeo showVector(){ if(linkedAgents==null||mesh==null) return this; vectorObjects = new IVectorObject[mesh.vertexNum()]; for(int i=0; i<mesh.vertexNum(); i++){ vectorObjects[i] = new IVectorObject(linkedAgents[i].getData(), mesh.vertex(i)); } return this; } public ILinkedNodeMeshFieldGeo linkFriction(double fric){ if(linkedAgents==null) return this; for(int i=0; i<linkedAgents.length; i++){ linkedAgents[i].fric(fric); } return this; } public ILinkedNodeMeshFieldGeo linkFriction(int vertexIndex, double fric){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return null; linkedAgents[vertexIndex].fric(fric); return this; } } public IVecI getForce(int vertexIndex){ return ((ILinkedNodeMeshFieldGeo)field).getForce(vertexIndex); } public ILinkedNodeMeshField setForce(int vertexIndex,IVecI force){ ((ILinkedNodeMeshFieldGeo)field).setForce(vertexIndex,force); return this; } public ILinkedNodeMeshField addForce(int vertexIndex,IVecI force){ ((ILinkedNodeMeshFieldGeo)field).addForce(vertexIndex,force); return this; } public ILinkedNodeMeshField showVector(){ ((ILinkedNodeMeshFieldGeo)field).showVector(); return this; } public ILinkedNodeMeshField linkFriction(double fric){ ((ILinkedNodeMeshFieldGeo)field).linkFriction(fric); return this; } public ILinkedNodeMeshField linkFriction(int vertexIndex, double fric){ ((ILinkedNodeMeshFieldGeo)field).linkFriction(vertexIndex, fric); return this; } public ILinkedNodeMeshField noDecay(){ super.noDecay(); return this; } public ILinkedNodeMeshField linearDecay(double threshold){ super.linearDecay(threshold); return this; } public ILinkedNodeMeshField linear(double threshold){ super.linear(threshold); return this; } public ILinkedNodeMeshField gaussianDecay(double threshold){ super.gaussianDecay(threshold); return this; } public ILinkedNodeMeshField gaussian(double threshold){ super.gaussian(threshold); return this; } public ILinkedNodeMeshField gauss(double threshold){ super.gauss(threshold); return this; } public ILinkedNodeMeshField decay(IDecay decay, double threshold){ super.decay(decay,threshold); return this; } public ILinkedNodeMeshField constantIntensity(boolean b){ super.constantIntensity(b); return this; } /** if bidirectional is on, field force vector is flipped when velocity of particle is going opposite */ public ILinkedNodeMeshField bidirectional(boolean b){ super.bidirectional(b); return this; } public ILinkedNodeMeshField threshold(double t){ super.threshold(t); return this; } public ILinkedNodeMeshField intensity(double i){ super.intensity(i); return this; } }
sghr/iGeo
ILinkedNodeMeshField.java
1,678
/* public ILinkedVecAgent<IVecI> getNode(int vertexIndex){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return null; return linkedAgents[vertexIndex]; } */
block_comment
nl
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo 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, version 3. iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; /** 3D vector filed defined by normal vector of mesh vertices @author Satoru Sugihara */ public class ILinkedNodeMeshField extends I3DField{ public ILinkedNodeMeshField(IMeshI m){ super(new ILinkedNodeMeshFieldGeo(m)); } public static class ILinkedNodeMeshFieldGeo extends IMeshFieldGeo{ public ILinkedDataAgent<IVecI>[] linkedAgents; public IVectorObject[] vectorObjects; // to visualize public ILinkedNodeMeshFieldGeo(IMeshI m){ super(m); initField(); } public void initField(){ @SuppressWarnings("unchecked") ILinkedDataAgent<IVecI>[] agents = ILinkedDataAgent.<IVecI>create(mesh); linkedAgents = agents; for(int i=0; i<linkedAgents.length; i++){ linkedAgents[i].setData(new IVec()); } } public ILinkedNodeMeshFieldGeo setForce(int vertexIndex, IVecI vec){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return this; linkedAgents[vertexIndex].setData(vec); return this; } public IVecI getForce(int vertexIndex){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return new IVec(); return linkedAgents[vertexIndex].getData(); } public ILinkedNodeMeshFieldGeo addForce(int vertexIndex, IVecI vec){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return this; linkedAgents[vertexIndex].addData(vec); return this; } /* public ILinkedVecAgent<IVecI> getNode(int<SUF>*/ public IVecI get(int vertexIdx){ return getForce(vertexIdx); } public ILinkedNodeMeshFieldGeo showVector(){ if(linkedAgents==null||mesh==null) return this; vectorObjects = new IVectorObject[mesh.vertexNum()]; for(int i=0; i<mesh.vertexNum(); i++){ vectorObjects[i] = new IVectorObject(linkedAgents[i].getData(), mesh.vertex(i)); } return this; } public ILinkedNodeMeshFieldGeo linkFriction(double fric){ if(linkedAgents==null) return this; for(int i=0; i<linkedAgents.length; i++){ linkedAgents[i].fric(fric); } return this; } public ILinkedNodeMeshFieldGeo linkFriction(int vertexIndex, double fric){ if(linkedAgents==null || vertexIndex<0 || vertexIndex>=linkedAgents.length) return null; linkedAgents[vertexIndex].fric(fric); return this; } } public IVecI getForce(int vertexIndex){ return ((ILinkedNodeMeshFieldGeo)field).getForce(vertexIndex); } public ILinkedNodeMeshField setForce(int vertexIndex,IVecI force){ ((ILinkedNodeMeshFieldGeo)field).setForce(vertexIndex,force); return this; } public ILinkedNodeMeshField addForce(int vertexIndex,IVecI force){ ((ILinkedNodeMeshFieldGeo)field).addForce(vertexIndex,force); return this; } public ILinkedNodeMeshField showVector(){ ((ILinkedNodeMeshFieldGeo)field).showVector(); return this; } public ILinkedNodeMeshField linkFriction(double fric){ ((ILinkedNodeMeshFieldGeo)field).linkFriction(fric); return this; } public ILinkedNodeMeshField linkFriction(int vertexIndex, double fric){ ((ILinkedNodeMeshFieldGeo)field).linkFriction(vertexIndex, fric); return this; } public ILinkedNodeMeshField noDecay(){ super.noDecay(); return this; } public ILinkedNodeMeshField linearDecay(double threshold){ super.linearDecay(threshold); return this; } public ILinkedNodeMeshField linear(double threshold){ super.linear(threshold); return this; } public ILinkedNodeMeshField gaussianDecay(double threshold){ super.gaussianDecay(threshold); return this; } public ILinkedNodeMeshField gaussian(double threshold){ super.gaussian(threshold); return this; } public ILinkedNodeMeshField gauss(double threshold){ super.gauss(threshold); return this; } public ILinkedNodeMeshField decay(IDecay decay, double threshold){ super.decay(decay,threshold); return this; } public ILinkedNodeMeshField constantIntensity(boolean b){ super.constantIntensity(b); return this; } /** if bidirectional is on, field force vector is flipped when velocity of particle is going opposite */ public ILinkedNodeMeshField bidirectional(boolean b){ super.bidirectional(b); return this; } public ILinkedNodeMeshField threshold(double t){ super.threshold(t); return this; } public ILinkedNodeMeshField intensity(double i){ super.intensity(i); return this; } }
200227_3
/* * Drifting Souls 2 * Copyright (c) 2006 Christopher Jung * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.driftingsouls.ds2.server.entities; import net.driftingsouls.ds2.server.Locatable; import net.driftingsouls.ds2.server.Location; import net.driftingsouls.ds2.server.MutableLocation; import net.driftingsouls.ds2.server.WellKnownConfigValue; import net.driftingsouls.ds2.server.framework.ConfigService; import net.driftingsouls.ds2.server.framework.Context; import net.driftingsouls.ds2.server.framework.ContextMap; import net.driftingsouls.ds2.server.repositories.NebulaRepository; import net.driftingsouls.ds2.server.ships.Ship; import net.driftingsouls.ds2.server.ships.ShipTypeData; import net.driftingsouls.ds2.server.ships.Ships; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Index; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.Table; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntConsumer; import java.util.stream.Collectors; /** * Ein Nebel. * @author Christopher Jung * */ @Entity @Table(name="nebel") @Immutable @BatchSize(size=50) public class Nebel implements Locatable { /** * Gibt den Nebeltyp an der angegebenen Position zurueck. Sollte sich an der Position kein * Nebel befinden, wird <code>null</code> zurueckgegeben. * @param loc Die Position * @return Der Nebeltyp oder <code>null</code> */ @SuppressWarnings("unchecked") public static synchronized Typ getNebula(Location loc) { return NebulaRepository.getInstance().getNebula(loc); } /** * Nebeltyp. */ public enum Typ { /** * Normaler Deutnebel. */ MEDIUM_DEUT(0, 7, false, 0, 0,"normaler Deuteriumnebel"), /** * Schwacher Deutnebel. */ LOW_DEUT(1, 5, false, -1, 0,"schwacher Deuteriumnebel"), /** * Dichter Deutnebel. */ STRONG_DEUT(2, 11, false, 1, 0,"starker Deuteriumnebel"), /** * Schwacher EMP-Nebel. */ LOW_EMP(3, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"schwacher EMP-Nebel"), /** * Normaler EMP-Nebel. */ MEDIUM_EMP(4, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"normaler EMP-Nebel"), /** * Dichter EMP-Nebel. */ STRONG_EMP(5, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"dichter EMP-Nebel" ), /** * Schadensnebel. */ DAMAGE(6, 7, false, Integer.MIN_VALUE, 0, "Schadensnebel"); private final int code; private final int minScansize; private final boolean emp; private final int deutfaktor; private final String beschreibung; Typ(int code, int minScansize, boolean emp, int deutfaktor, int minScanbareSchiffsgroesse, String beschreibung) { this.code = code; this.minScansize = minScansize; this.emp = emp; this.deutfaktor = deutfaktor; this.beschreibung = beschreibung; } /** * Erzeugt aus Typenids (Datenbank) enums. * * @param type Typenid. * @return Passendes enum. */ public static Typ getType(int type) { switch(type) { case 0: return MEDIUM_DEUT; case 1: return LOW_DEUT; case 2: return STRONG_DEUT; case 3: return LOW_EMP; case 4: return MEDIUM_EMP; case 5: return STRONG_EMP; case 6: return DAMAGE; default: throw new IllegalArgumentException("There's no nebula with type:" + type); } } /** * @return Die Beschreibung des Nebels. */ public String getDescription() { return this.beschreibung; } /** * @return Der Typcode des Nebels. */ public int getCode() { return this.code; } /** * @return Die Groesse ab der ein Schiff sichtbar ist in dem Nebel. */ public int getMinScansize() { return this.minScansize; } /** * Gibt zurueck, ob es sich um einen EMP-Nebel handelt. * @return <code>true</code> falls dem so ist */ public boolean isEmp() { return emp; } public boolean isDamage() { return getCode() == 6; } /** * Gibt zurueck, ob ein Nebel diesen Typs das Sammeln * von Deuterium ermoeglicht. * @return <code>true</code> falls dem so ist */ public boolean isDeuteriumNebel() { return this.deutfaktor > Integer.MIN_VALUE; } /** * Gibt den durch die Eigenschaften des Nebels modifizierten * Deuterium-Faktor beim Sammeln von Deuterium * in einem Nebel diesem Typs zurueck. Falls der modifizierte * Faktor <code>0</code> betraegt ist kein Sammeln moeglich. * Falls es sich nicht um einen Nebel handelt, * der das Sammeln von Deuterium erlaubt, wird * der Faktor immer auf <code>0</code> reduziert. * @param faktor Der zu modifizierende Faktor * @return Der modifizierte Deuteriumfaktor */ public long modifiziereDeutFaktor(long faktor) { if( faktor <= 0 ) { return 0; } long modfaktor = faktor + this.deutfaktor; if( modfaktor < 0 ) { return 0; } return modfaktor; } /** * Gibt alle Nebeltypen zurueck, die die Eigenschaft * EMP haben. * @return Die Liste * @see #isEmp() */ public static Set<Typ> getEmpNebula() { return Arrays.stream(values()) .filter(Typ::isEmp) .collect(Collectors.toCollection(HashSet::new)); } public static Set<Typ> getDamageNebula() { Set<Typ> nebula = new HashSet<>(); nebula.add(DAMAGE); return nebula; } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return !this.emp; } /** * Gibt das Bild des Nebeltyps zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return "data/starmap/fog"+this.ordinal()+"/fog"+this.ordinal()+".png"; } /** * Damage the ship according to the nebula type. * * @param ship The ship to be damaged. */ public void damageShip(Ship ship, ConfigService config) { // Currently only damage nebula do damage and we only have one type of damage nebula // so no different effects if(this != DAMAGE) { return; } //gedockte Schiffe werden bereits ueber ihr Traegerschiff verarbeitet (siehe damageInternal()) if(ship.isDocked()) { return; } double shieldDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SHIELD)/100.d; double ablativeDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_ABLATIVE)/100.d; double hullDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_HULL)/100.d; double subsystemDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SUBSYSTEM)/100.d; damageInternal(ship, 1.0d, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } /** * Damage a ship for flying into a damage nebula. * * @param ship Ship to damage * @param globalDamageFactor Dampens initial damage to this ship (needed for docked ships, which should not take more damage than their carrier) */ private void damageInternal(Ship ship, double globalDamageFactor, double shieldDamageFactor, double ablativeDamageFactor, double hullDamageFactor, double subsystemDamageFactor) { /* Damage is applied according to the following formula ("ship type" always includes modules here): - Find the maximum shield of this ship type - Remove damage from shields - If ships shields are at zero find how much damage remains and apply it as percentage on the next level, e.g. We want to damage the shields for 1000, but only 900 shields remain, so we calculate the armor damage (according to the armor formula) and then only remove 10% (the remainder from shields) When shields are down externally attached ships (e.g. containers) start taking damage. */ double modifiedShieldDamageFactor = shieldDamageFactor * globalDamageFactor; ShipTypeData shipType = ship.getTypeData(); int shieldDamage = (int)Math.floor(shipType.getShields() * modifiedShieldDamageFactor); int shieldsRemaining = ship.getShields() - shieldDamage; //Damage we wanted to do, but couldn't cause there wasn't enough shield strength left int shieldOverflow = 0; if(shieldsRemaining < 0) { shieldOverflow = Math.abs(shieldsRemaining); shieldsRemaining = 0; } ship.setShields(shieldsRemaining); //No damage left after shields if(shieldOverflow == 0 && shipType.getShields() != 0) { return; } double shieldOverflowFactor = 1.0d; if(shipType.getShields() != 0) { shieldOverflowFactor = (double)shieldOverflow / (double)shieldDamage; } int ablativeDamage = (int)Math.floor(shipType.getAblativeArmor() * ablativeDamageFactor * shieldOverflowFactor); int ablativeRemaining = ship.getAblativeArmor() - ablativeDamage; int ablativeOverflow = 0; if(ablativeRemaining < 0) { ablativeOverflow = Math.abs(ablativeRemaining); ablativeRemaining = 0; } ship.setAblativeArmor(ablativeRemaining); // No more shields left to save them -> also damage docked ships for (Ship dockedShip : ship.getDockedShips()) { damageInternal(dockedShip, shieldOverflowFactor, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } //No damage left after ablative armor if(ablativeOverflow == 0 && shipType.getAblativeArmor() != 0) { return; } double ablativeOverflowFactor = 1.0d; if(shipType.getAblativeArmor() != 0) { ablativeOverflowFactor = (double)ablativeOverflow / (double)ablativeDamage; } int hullDamage = (int)Math.floor(shipType.getHull() * hullDamageFactor * ablativeOverflowFactor); int hullRemaining = ship.getHull() - hullDamage; if(hullRemaining <= 0) { ship.destroy(); return; } else { ship.setHull(hullRemaining); } //Damage each subsystem individually, so you don't get very good or bad results based on one roll damageSubsystem(subsystemDamageFactor, ship.getComm(), ship::setComm); damageSubsystem(subsystemDamageFactor, ship.getEngine(), ship::setEngine); damageSubsystem(subsystemDamageFactor, ship.getSensors(), ship::setSensors); damageSubsystem(subsystemDamageFactor, ship.getWeapons(), ship::setWeapons); } private void damageSubsystem(double subsystemDamageFactor, int subsystemBefore, IntConsumer subsystem) { double modifiedSubsystemDamageFactor = ThreadLocalRandom.current().nextDouble() * subsystemDamageFactor; int subsystemDamage = (int)Math.floor(100 * modifiedSubsystemDamageFactor); int subsystemRemaining = Math.max(0, subsystemBefore - subsystemDamage); subsystem.accept(subsystemRemaining); } } @EmbeddedId private MutableLocation loc; @Index(name="idx_nebulatype") @Enumerated @Column(nullable = false) private Typ type; public MutableLocation getLoc() { return loc; } public void setLoc(MutableLocation loc) { this.loc = loc; } /** * Konstruktor. * */ public Nebel() { // EMPTY } /** * Erstellt einen neuen Nebel. * @param loc Die Position des Nebels * @param type Der Typ */ public Nebel(MutableLocation loc, Typ type) { this.loc = loc; this.type = type; } /** * Gibt das System des Nebels zurueck. * @return Das System */ public int getSystem() { return loc.getSystem(); } /** * Gibt den Typ des Nebels zurueck. * @return Der Typ */ public Typ getType() { return this.type; } /** * Gibt die X-Koordinate zurueck. * @return Die X-Koordinate */ public int getX() { return loc.getX(); } /** * Gibt die Y-Koordinate zurueck. * @return Die Y-Koordinate */ public int getY() { return loc.getY(); } /** * Gibt die Position des Nebels zurueck. * @return Die Position */ @Override public Location getLocation() { return loc.getLocation(); } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return this.type.allowsScan(); } /** * Gibt das Bild des Nebels zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return this.type.getImage(); } }
sgift/driftingsouls
game/src/main/java/net/driftingsouls/ds2/server/entities/Nebel.java
4,641
/** * Nebeltyp. */
block_comment
nl
/* * Drifting Souls 2 * Copyright (c) 2006 Christopher Jung * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.driftingsouls.ds2.server.entities; import net.driftingsouls.ds2.server.Locatable; import net.driftingsouls.ds2.server.Location; import net.driftingsouls.ds2.server.MutableLocation; import net.driftingsouls.ds2.server.WellKnownConfigValue; import net.driftingsouls.ds2.server.framework.ConfigService; import net.driftingsouls.ds2.server.framework.Context; import net.driftingsouls.ds2.server.framework.ContextMap; import net.driftingsouls.ds2.server.repositories.NebulaRepository; import net.driftingsouls.ds2.server.ships.Ship; import net.driftingsouls.ds2.server.ships.ShipTypeData; import net.driftingsouls.ds2.server.ships.Ships; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Index; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.Table; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntConsumer; import java.util.stream.Collectors; /** * Ein Nebel. * @author Christopher Jung * */ @Entity @Table(name="nebel") @Immutable @BatchSize(size=50) public class Nebel implements Locatable { /** * Gibt den Nebeltyp an der angegebenen Position zurueck. Sollte sich an der Position kein * Nebel befinden, wird <code>null</code> zurueckgegeben. * @param loc Die Position * @return Der Nebeltyp oder <code>null</code> */ @SuppressWarnings("unchecked") public static synchronized Typ getNebula(Location loc) { return NebulaRepository.getInstance().getNebula(loc); } /** * Nebeltyp. <SUF>*/ public enum Typ { /** * Normaler Deutnebel. */ MEDIUM_DEUT(0, 7, false, 0, 0,"normaler Deuteriumnebel"), /** * Schwacher Deutnebel. */ LOW_DEUT(1, 5, false, -1, 0,"schwacher Deuteriumnebel"), /** * Dichter Deutnebel. */ STRONG_DEUT(2, 11, false, 1, 0,"starker Deuteriumnebel"), /** * Schwacher EMP-Nebel. */ LOW_EMP(3, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"schwacher EMP-Nebel"), /** * Normaler EMP-Nebel. */ MEDIUM_EMP(4, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"normaler EMP-Nebel"), /** * Dichter EMP-Nebel. */ STRONG_EMP(5, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"dichter EMP-Nebel" ), /** * Schadensnebel. */ DAMAGE(6, 7, false, Integer.MIN_VALUE, 0, "Schadensnebel"); private final int code; private final int minScansize; private final boolean emp; private final int deutfaktor; private final String beschreibung; Typ(int code, int minScansize, boolean emp, int deutfaktor, int minScanbareSchiffsgroesse, String beschreibung) { this.code = code; this.minScansize = minScansize; this.emp = emp; this.deutfaktor = deutfaktor; this.beschreibung = beschreibung; } /** * Erzeugt aus Typenids (Datenbank) enums. * * @param type Typenid. * @return Passendes enum. */ public static Typ getType(int type) { switch(type) { case 0: return MEDIUM_DEUT; case 1: return LOW_DEUT; case 2: return STRONG_DEUT; case 3: return LOW_EMP; case 4: return MEDIUM_EMP; case 5: return STRONG_EMP; case 6: return DAMAGE; default: throw new IllegalArgumentException("There's no nebula with type:" + type); } } /** * @return Die Beschreibung des Nebels. */ public String getDescription() { return this.beschreibung; } /** * @return Der Typcode des Nebels. */ public int getCode() { return this.code; } /** * @return Die Groesse ab der ein Schiff sichtbar ist in dem Nebel. */ public int getMinScansize() { return this.minScansize; } /** * Gibt zurueck, ob es sich um einen EMP-Nebel handelt. * @return <code>true</code> falls dem so ist */ public boolean isEmp() { return emp; } public boolean isDamage() { return getCode() == 6; } /** * Gibt zurueck, ob ein Nebel diesen Typs das Sammeln * von Deuterium ermoeglicht. * @return <code>true</code> falls dem so ist */ public boolean isDeuteriumNebel() { return this.deutfaktor > Integer.MIN_VALUE; } /** * Gibt den durch die Eigenschaften des Nebels modifizierten * Deuterium-Faktor beim Sammeln von Deuterium * in einem Nebel diesem Typs zurueck. Falls der modifizierte * Faktor <code>0</code> betraegt ist kein Sammeln moeglich. * Falls es sich nicht um einen Nebel handelt, * der das Sammeln von Deuterium erlaubt, wird * der Faktor immer auf <code>0</code> reduziert. * @param faktor Der zu modifizierende Faktor * @return Der modifizierte Deuteriumfaktor */ public long modifiziereDeutFaktor(long faktor) { if( faktor <= 0 ) { return 0; } long modfaktor = faktor + this.deutfaktor; if( modfaktor < 0 ) { return 0; } return modfaktor; } /** * Gibt alle Nebeltypen zurueck, die die Eigenschaft * EMP haben. * @return Die Liste * @see #isEmp() */ public static Set<Typ> getEmpNebula() { return Arrays.stream(values()) .filter(Typ::isEmp) .collect(Collectors.toCollection(HashSet::new)); } public static Set<Typ> getDamageNebula() { Set<Typ> nebula = new HashSet<>(); nebula.add(DAMAGE); return nebula; } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return !this.emp; } /** * Gibt das Bild des Nebeltyps zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return "data/starmap/fog"+this.ordinal()+"/fog"+this.ordinal()+".png"; } /** * Damage the ship according to the nebula type. * * @param ship The ship to be damaged. */ public void damageShip(Ship ship, ConfigService config) { // Currently only damage nebula do damage and we only have one type of damage nebula // so no different effects if(this != DAMAGE) { return; } //gedockte Schiffe werden bereits ueber ihr Traegerschiff verarbeitet (siehe damageInternal()) if(ship.isDocked()) { return; } double shieldDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SHIELD)/100.d; double ablativeDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_ABLATIVE)/100.d; double hullDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_HULL)/100.d; double subsystemDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SUBSYSTEM)/100.d; damageInternal(ship, 1.0d, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } /** * Damage a ship for flying into a damage nebula. * * @param ship Ship to damage * @param globalDamageFactor Dampens initial damage to this ship (needed for docked ships, which should not take more damage than their carrier) */ private void damageInternal(Ship ship, double globalDamageFactor, double shieldDamageFactor, double ablativeDamageFactor, double hullDamageFactor, double subsystemDamageFactor) { /* Damage is applied according to the following formula ("ship type" always includes modules here): - Find the maximum shield of this ship type - Remove damage from shields - If ships shields are at zero find how much damage remains and apply it as percentage on the next level, e.g. We want to damage the shields for 1000, but only 900 shields remain, so we calculate the armor damage (according to the armor formula) and then only remove 10% (the remainder from shields) When shields are down externally attached ships (e.g. containers) start taking damage. */ double modifiedShieldDamageFactor = shieldDamageFactor * globalDamageFactor; ShipTypeData shipType = ship.getTypeData(); int shieldDamage = (int)Math.floor(shipType.getShields() * modifiedShieldDamageFactor); int shieldsRemaining = ship.getShields() - shieldDamage; //Damage we wanted to do, but couldn't cause there wasn't enough shield strength left int shieldOverflow = 0; if(shieldsRemaining < 0) { shieldOverflow = Math.abs(shieldsRemaining); shieldsRemaining = 0; } ship.setShields(shieldsRemaining); //No damage left after shields if(shieldOverflow == 0 && shipType.getShields() != 0) { return; } double shieldOverflowFactor = 1.0d; if(shipType.getShields() != 0) { shieldOverflowFactor = (double)shieldOverflow / (double)shieldDamage; } int ablativeDamage = (int)Math.floor(shipType.getAblativeArmor() * ablativeDamageFactor * shieldOverflowFactor); int ablativeRemaining = ship.getAblativeArmor() - ablativeDamage; int ablativeOverflow = 0; if(ablativeRemaining < 0) { ablativeOverflow = Math.abs(ablativeRemaining); ablativeRemaining = 0; } ship.setAblativeArmor(ablativeRemaining); // No more shields left to save them -> also damage docked ships for (Ship dockedShip : ship.getDockedShips()) { damageInternal(dockedShip, shieldOverflowFactor, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } //No damage left after ablative armor if(ablativeOverflow == 0 && shipType.getAblativeArmor() != 0) { return; } double ablativeOverflowFactor = 1.0d; if(shipType.getAblativeArmor() != 0) { ablativeOverflowFactor = (double)ablativeOverflow / (double)ablativeDamage; } int hullDamage = (int)Math.floor(shipType.getHull() * hullDamageFactor * ablativeOverflowFactor); int hullRemaining = ship.getHull() - hullDamage; if(hullRemaining <= 0) { ship.destroy(); return; } else { ship.setHull(hullRemaining); } //Damage each subsystem individually, so you don't get very good or bad results based on one roll damageSubsystem(subsystemDamageFactor, ship.getComm(), ship::setComm); damageSubsystem(subsystemDamageFactor, ship.getEngine(), ship::setEngine); damageSubsystem(subsystemDamageFactor, ship.getSensors(), ship::setSensors); damageSubsystem(subsystemDamageFactor, ship.getWeapons(), ship::setWeapons); } private void damageSubsystem(double subsystemDamageFactor, int subsystemBefore, IntConsumer subsystem) { double modifiedSubsystemDamageFactor = ThreadLocalRandom.current().nextDouble() * subsystemDamageFactor; int subsystemDamage = (int)Math.floor(100 * modifiedSubsystemDamageFactor); int subsystemRemaining = Math.max(0, subsystemBefore - subsystemDamage); subsystem.accept(subsystemRemaining); } } @EmbeddedId private MutableLocation loc; @Index(name="idx_nebulatype") @Enumerated @Column(nullable = false) private Typ type; public MutableLocation getLoc() { return loc; } public void setLoc(MutableLocation loc) { this.loc = loc; } /** * Konstruktor. * */ public Nebel() { // EMPTY } /** * Erstellt einen neuen Nebel. * @param loc Die Position des Nebels * @param type Der Typ */ public Nebel(MutableLocation loc, Typ type) { this.loc = loc; this.type = type; } /** * Gibt das System des Nebels zurueck. * @return Das System */ public int getSystem() { return loc.getSystem(); } /** * Gibt den Typ des Nebels zurueck. * @return Der Typ */ public Typ getType() { return this.type; } /** * Gibt die X-Koordinate zurueck. * @return Die X-Koordinate */ public int getX() { return loc.getX(); } /** * Gibt die Y-Koordinate zurueck. * @return Die Y-Koordinate */ public int getY() { return loc.getY(); } /** * Gibt die Position des Nebels zurueck. * @return Die Position */ @Override public Location getLocation() { return loc.getLocation(); } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return this.type.allowsScan(); } /** * Gibt das Bild des Nebels zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return this.type.getImage(); } }
29633_4
package de.l3s.eventkg.nlp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import de.l3s.eventkg.meta.Language; import jep.Interpreter; import jep.JepException; import jep.SharedInterpreter; import opennlp.tools.util.Span; public class NLPCubeUtils implements NLPUtils { private Interpreter interp; // // returns sentence annotations - but just the strings // public String[] sentenceSplitter(String text) { // String[] sentences = sentenceDetector.sentDetect(text); // return sentences; // } // -Djava.library.path=/home/simon/.local/lib/python3.5/site-packages/jep // -Djava.library.path=/usr/local/lib/python2.7/dist-packages/jep // What was done? // Jep in maven // pip install jep public static void main(String[] args) throws JepException { System.out.println( "res = ''\nfor sentence in sentencesDe :\n\tfor token in sentence:\n\t\tline += token.word + '\t'\n\t\tline += token.space_after\n\t\tres += line + '\\n'"); Set<String> sentences = new HashSet<String>(); // sentences.add("Dies ist ein Satz. Und hier ist noch ein Satz."); // sentences.add("Morgen ist's Wochenende. Ich weiß, das ist gut."); // sentences.add("Pius II. ging nach Hause. Das war in Rom."); sentences.add("Die Skulpturenmeile in Hannover ist ein zwischen 1986 und 2000 geschaffener Skulpturenweg entlang der Straßen Brühlstraße und Leibnizufer in Hannover. Er besteht aus übergroßen Skulpturen und Plastiken im öffentlichen Straßenraum. Die Kunstwerke sind auf einer Länge von etwa 1.200 Meter zwischen dem Königsworther Platz und dem Niedersächsischen Landtag aufgestellt. Die sehr unterschiedlichen Arbeiten befinden sich überwiegend auf der grünen Mittelinsel des sechsspurigen, stark befahrenen Straßenzuges."); NLPCubeUtils nlpUtils = new NLPCubeUtils(Language.DE); for (String sentence : sentences) { for (Span span : nlpUtils.sentenceSplitterPositions(sentence)) { System.out.println(span.getCoveredText(sentence)); System.out.println(" " + span.getStart() + ", " + span.getEnd()); } } } public NLPCubeUtils(Language language) throws JepException { this.interp = new SharedInterpreter(); interp.eval("import sys"); interp.eval("if not hasattr(sys, 'argv'):\n sys.argv = ['']"); interp.eval("import sys"); interp.eval("from cube.api import Cube"); interp.eval("cube=Cube(verbose=True)"); interp.eval("cube.load('" + language.getLanguageLowerCase() + "')"); } // returns sentence annotations - but just the spans public Span[] sentenceSplitterPositions(String text) { System.out.println("Split: "+text); try { text=text.replace("'", "\\'"); interp.eval("text='" + text + "'"); interp.eval("sentences=cube(text)"); Object result1 = interp.getValue("sentences"); String res = result1.toString(); List<Span> spans = new ArrayList<Span>(); int startPosition = 0; int endPosition = 0; for (String sentenceRes : res.split("\\], \\[")) { // sentenceRes = sentenceRes.substring(2, // sentenceRes.length() - 2); String[] parts = sentenceRes.split("\t"); String space = null; for (int i = 1; i < parts.length; i += 9) { space = parts[i + 8]; if (space.contains(",")) space = space.substring(0, space.indexOf(",")); endPosition += parts[i].length(); if (!space.contains("SpaceAfter=No")) endPosition += 1; } if (!space.contains("SpaceAfter=No")) endPosition -= 1; Span span = new Span(startPosition, endPosition); spans.add(span); if (!space.contains("SpaceAfter=No")) endPosition += 1; startPosition = endPosition; } Span[] spanArray = new Span[spans.size()]; for (int i = 0; i < spanArray.length; i++) spanArray[i] = spans.get(i); return spanArray; } catch (JepException e) { e.printStackTrace(); } return null; } }
sgottsch/eventkg
src/de/l3s/eventkg/nlp/NLPCubeUtils.java
1,321
// Jep in maven
line_comment
nl
package de.l3s.eventkg.nlp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import de.l3s.eventkg.meta.Language; import jep.Interpreter; import jep.JepException; import jep.SharedInterpreter; import opennlp.tools.util.Span; public class NLPCubeUtils implements NLPUtils { private Interpreter interp; // // returns sentence annotations - but just the strings // public String[] sentenceSplitter(String text) { // String[] sentences = sentenceDetector.sentDetect(text); // return sentences; // } // -Djava.library.path=/home/simon/.local/lib/python3.5/site-packages/jep // -Djava.library.path=/usr/local/lib/python2.7/dist-packages/jep // What was done? // Jep in<SUF> // pip install jep public static void main(String[] args) throws JepException { System.out.println( "res = ''\nfor sentence in sentencesDe :\n\tfor token in sentence:\n\t\tline += token.word + '\t'\n\t\tline += token.space_after\n\t\tres += line + '\\n'"); Set<String> sentences = new HashSet<String>(); // sentences.add("Dies ist ein Satz. Und hier ist noch ein Satz."); // sentences.add("Morgen ist's Wochenende. Ich weiß, das ist gut."); // sentences.add("Pius II. ging nach Hause. Das war in Rom."); sentences.add("Die Skulpturenmeile in Hannover ist ein zwischen 1986 und 2000 geschaffener Skulpturenweg entlang der Straßen Brühlstraße und Leibnizufer in Hannover. Er besteht aus übergroßen Skulpturen und Plastiken im öffentlichen Straßenraum. Die Kunstwerke sind auf einer Länge von etwa 1.200 Meter zwischen dem Königsworther Platz und dem Niedersächsischen Landtag aufgestellt. Die sehr unterschiedlichen Arbeiten befinden sich überwiegend auf der grünen Mittelinsel des sechsspurigen, stark befahrenen Straßenzuges."); NLPCubeUtils nlpUtils = new NLPCubeUtils(Language.DE); for (String sentence : sentences) { for (Span span : nlpUtils.sentenceSplitterPositions(sentence)) { System.out.println(span.getCoveredText(sentence)); System.out.println(" " + span.getStart() + ", " + span.getEnd()); } } } public NLPCubeUtils(Language language) throws JepException { this.interp = new SharedInterpreter(); interp.eval("import sys"); interp.eval("if not hasattr(sys, 'argv'):\n sys.argv = ['']"); interp.eval("import sys"); interp.eval("from cube.api import Cube"); interp.eval("cube=Cube(verbose=True)"); interp.eval("cube.load('" + language.getLanguageLowerCase() + "')"); } // returns sentence annotations - but just the spans public Span[] sentenceSplitterPositions(String text) { System.out.println("Split: "+text); try { text=text.replace("'", "\\'"); interp.eval("text='" + text + "'"); interp.eval("sentences=cube(text)"); Object result1 = interp.getValue("sentences"); String res = result1.toString(); List<Span> spans = new ArrayList<Span>(); int startPosition = 0; int endPosition = 0; for (String sentenceRes : res.split("\\], \\[")) { // sentenceRes = sentenceRes.substring(2, // sentenceRes.length() - 2); String[] parts = sentenceRes.split("\t"); String space = null; for (int i = 1; i < parts.length; i += 9) { space = parts[i + 8]; if (space.contains(",")) space = space.substring(0, space.indexOf(",")); endPosition += parts[i].length(); if (!space.contains("SpaceAfter=No")) endPosition += 1; } if (!space.contains("SpaceAfter=No")) endPosition -= 1; Span span = new Span(startPosition, endPosition); spans.add(span); if (!space.contains("SpaceAfter=No")) endPosition += 1; startPosition = endPosition; } Span[] spanArray = new Span[spans.size()]; for (int i = 0; i < spanArray.length; i++) spanArray[i] = spans.get(i); return spanArray; } catch (JepException e) { e.printStackTrace(); } return null; } }
209717_10
/* * Emulator game server Aion 2.7 from the command of developers 'Aion-Knight Dev. Team' is * free software; you can redistribute it and/or modify it under the terms of * GNU affero general Public License (GNU GPL)as published by the free software * security (FSF), or to License version 3 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 warranties related to * CONSUMER PROPERTIES and SUITABILITY FOR CERTAIN PURPOSES. For details, see * General Public License is the GNU. * * You should have received a copy of the GNU affero general Public License along with this program. * If it is not, write to the Free Software Foundation, Inc., 675 Mass Ave, * Cambridge, MA 02139, USA * * Web developers : http://aion-knight.ru * Support of the game client : Aion 2.7- 'Arena of Death' (Innova) * The version of the server : Aion-Knight 2.7 (Beta version) */ package usercommands; import gameserver.model.Race; import gameserver.model.gameobjects.Item; import gameserver.model.gameobjects.player.Player; import gameserver.model.gameobjects.stats.StatEnum; import gameserver.model.group.PlayerGroup; import gameserver.model.legion.Legion; import gameserver.network.aion.serverpackets.SM_QUESTIONNAIRE; import gameserver.utils.PacketSendUtility; import gameserver.utils.Util; import gameserver.utils.chathandlers.UserCommand; import gameserver.utils.idfactory.IDFactory; import gameserver.world.World; import java.util.Iterator; import java.util.List; public class PlayerInfo extends UserCommand { public PlayerInfo() { super("playerinfo"); } @Override public void executeCommand(Player player, String params) { String[] args = params.split(" "); Player target = World.getInstance().findPlayer(Util.convertName(args[0])); if (target == null) { PacketSendUtility.sendMessage(player, "The player with this name is not on a network or do not exist."); return; } StringBuilder sb = new StringBuilder(); sb.append("<poll>\n"); sb.append("<poll_introduction>\n"); sb.append(" <![CDATA[<font color='4CB1E5'>Player Info - Aion-Knight Dev.</font>]]>\n"); sb.append("</poll_introduction>\n"); sb.append("<poll_title>\n"); sb.append(" <font color='ffc519'></font>\n"); sb.append("</poll_title>\n"); sb.append("<start_date></start_date>\n"); sb.append("<end_date></end_date>\n"); sb.append("<servers></servers>\n"); sb.append("<order_num></order_num>\n"); sb.append("<race></race>\n"); sb.append("<main_class></main_class>\n"); sb.append("<world_id></world_id>\n"); sb.append("<item_id></item_id>\n"); sb.append("<item_cnt></item_cnt>\n"); sb.append("<level>1~55</level>\n"); sb.append("<questions>\n"); sb.append(" <question>\n"); sb.append(" <title>\n"); sb.append(" <![CDATA[\n"); sb.append("<br><br>\n"); if (target.getCommonData().getRace() == Race.ELYOS) { sb.append("Information about the player " + target.getName() + ": <img src='http://www.aion-destination.de/_images/elyos.png'><br><hr><br><br>\n"); } else { sb.append("Information about the player " + target.getName() + ": <img src='http://sites.google.com/site/aioninfos/bilder/sonstiges/Asmodier-Symbol-35x40.png'><br><hr><br><br>\n"); } //Falls sie die selbe Rasse haben bzw. es ein GM ist, wird der HP/MP/DP Status in % ausgegeben if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0) { int hpinPercent = target.getLifeStats().getCurrentHp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXHP); int mpinPercent = target.getLifeStats().getCurrentMp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXMP); int dpinPercent = target.getCommonData().getDp()*100/4000; //Gesundheit grafisch darstellen sb.append("Gesundheit: [<font color ='00FF00'>"); int i = 1; for (i = 1; i < hpinPercent/5; i++) { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); int k = 20-i; for (i = 1; i < k; i++) { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + hpinPercent + "%) (" + target.getLifeStats().getCurrentHp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXHP) + " TP)<br>"); if (hpinPercent == 0) //Falls der Spieler keine Gesundheit mehr hat also tot ist sind alle Balken rot und es erscheint Tot neben dem Leben { sb.append(" <font color ='FF0000'>Tot</font>"); sb.append("<br>Mana: [<font color='FF0000'>|||||||||| ||||||||||</font>]"); sb.append("<br>G&ouml;ttliche Kraft: [font color='FF0000'>|||||||||| ||||||||||</font>"); } else //ansonsten werden Mana und G�ttliche Kraft berechnet { sb.append("<br>"); //Mana grafisch darstellen sb.append("Mana: [<font color ='00FFFF'>"); for (i = 1; i < mpinPercent/5; i++) //gr�ne Gesundheitsbalken { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); k = 20-i; for (i = 1; i < k; i++) //Rote Gesundheitsbalken { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + mpinPercent + "%) (" + target.getLifeStats().getCurrentMp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXMP) + " MP)<br>"); //G�ttliche Kraft grafisch darstellen sb.append("G&ouml;ttliche Kraft: [<font color='FFCC00'>"); for (i = 1; i < dpinPercent/5; i++) { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); k = 20-i; for (i = 1; i < k; i++) { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + dpinPercent + "%) (" + target.getCommonData().getDp() + "/4000 GK)<br>"); } } sb.append("Level: " + target.getLevel() + "<br>\n"); //sb.append("Online: " + (System.currentTimeMillis() - target.getCommonData().getLastOnline().getTime()) / 60000 + " Minuten<br>\n"); if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0) { //PacketSendUtility.broadcastPacket(((Player) player), new SM_MESSAGE(((Player) player),"Position von [Pos:" + target.getName() + ";" + target.getPosition().getMapId() + " " + target.getPosition().getX() + " " + target.getPosition().getY() + " 0.0 -1]" , ChatType.NORMAL), true); //TODO Post des Ortes via Chat... Umwandlung in Ortsbezogene Markierung?? } sb.append("Klasse: "); int targetclass = target.getPlayerClass().getClassId(); if (targetclass == 0) { sb.append("Krieger"); } else if (targetclass == 1) { sb.append("Gladiator"); } else if (targetclass == 2) { sb.append("Templer"); } else if (targetclass == 3) { sb.append("Sp&auml;her"); } else if (targetclass == 4) { sb.append("Assassine"); } else if (targetclass == 5) { sb.append("J&auml;ger"); } else if (targetclass == 6) { sb.append("Magier"); } else if (targetclass == 7) { sb.append("Zauberer"); } else if (targetclass == 8) { sb.append("Beschw&ouml;rer"); } else if (targetclass == 9) { sb.append("Priester"); } else if (targetclass == 10) { sb.append("Kleriker"); } else if (targetclass == 11) { sb.append("Kantor"); } sb.append("<br>"); if (target.getCommonData().getRace() == Race.ELYOS) { sb.append("Rasse: Elyos<br>\n"); } else { sb.append("Rasse: Asmodier<br>\n"); } StringBuilder strbld = new StringBuilder("Gruppe: <br>--Leitung: \n"); PlayerGroup group = target.getPlayerGroup(); if (group == null) sb.append("Gruppe: keine<br>\n"); else { Iterator<Player> it = group.getMembers().iterator(); strbld.append(group.getGroupLeader().getName() + "<br>--Mitglieder:<br>\n"); while (it.hasNext()) { Player act = (Player) it.next(); strbld.append("----" + act.getName() + "<br>\n"); } sb.append(strbld.toString()); } Legion legion = target.getLegion(); if (legion == null) { sb.append("Legion: keine<br>\n"); } else { sb.append("Legion: " + legion.getLegionName() + "<br>\n"); } if (player.getAccessLevel() > 0) { sb.append("<hr>"); sb.append("Zus&auml;tzliche Informationen f&uuml;r Teammitglieder:<br><br>"); sb.append("Account Name: " + target.getClientConnection().getAccount().getName() + "<br>\n"); //sb.append("IP: " + target.getClientConnection.getIP() + "<br>\n"); try { if (args[1].equals("+items")) { sb.append("<br><hr><br>Item Informationen:<br><br>"); StringBuilder itstrbld = new StringBuilder("-- Inventar:<br>"); List<Item> items = target.getInventory().getAllItems(); Iterator<Item> it = items.iterator(); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>"); } } items.clear(); items = target.getEquipment().getEquippedItems(); it = items.iterator(); itstrbld.append("<br>-- Ausger&uuml;stet:<br>"); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>"); } } items.clear(); items = target.getWarehouse().getAllItems(); it = items.iterator(); itstrbld.append("<br>-- Lagerhaus:<br>"); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]" + "<br>"); } } sb.append(itstrbld.toString()); } } catch (Exception e) { } } else if (player.getAccessLevel() == 0 && args[1].equals("+items")) { sb.append("<br><hr><br>Du hast nicht genug Rechte, um Item Informationen abzurufen.<br><br>"); } sb.append("<br><br><br>\n"); sb.append(" ]]>\n"); sb.append(" </title>\n"); sb.append(" <select>\n"); sb.append("<input type='radio'>"); sb.append("Danke f&uuml;r die Info!"); sb.append("</input>\n"); sb.append(" </select>\n"); sb.append(" </question>\n"); sb.append("</questions>\n"); sb.append("</poll>\n"); String html = sb.toString(); final int messageId = IDFactory.getInstance().nextId(); byte packet_count = (byte) Math.ceil(html.length() / (Short.MAX_VALUE - 8) + 1); if (packet_count < 256) { for (byte i = 0; i < packet_count; i++) { try { int from = i * (Short.MAX_VALUE - 8), to = (i + 1) * (Short.MAX_VALUE - 8); if (from < 0) from = 0; if (to > html.length()) to = html.length(); String sub = html.substring(from, to); player.getClientConnection().sendPacket(new SM_QUESTIONNAIRE(messageId, i, packet_count, sub)); } catch (Exception e) { } } } } }
shanecode/aionknight
gameserver/data/scripts/system/handlers/usercommands/PlayerInfo.java
4,306
//sb.append("IP: " + target.getClientConnection.getIP() + "<br>\n");
line_comment
nl
/* * Emulator game server Aion 2.7 from the command of developers 'Aion-Knight Dev. Team' is * free software; you can redistribute it and/or modify it under the terms of * GNU affero general Public License (GNU GPL)as published by the free software * security (FSF), or to License version 3 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 warranties related to * CONSUMER PROPERTIES and SUITABILITY FOR CERTAIN PURPOSES. For details, see * General Public License is the GNU. * * You should have received a copy of the GNU affero general Public License along with this program. * If it is not, write to the Free Software Foundation, Inc., 675 Mass Ave, * Cambridge, MA 02139, USA * * Web developers : http://aion-knight.ru * Support of the game client : Aion 2.7- 'Arena of Death' (Innova) * The version of the server : Aion-Knight 2.7 (Beta version) */ package usercommands; import gameserver.model.Race; import gameserver.model.gameobjects.Item; import gameserver.model.gameobjects.player.Player; import gameserver.model.gameobjects.stats.StatEnum; import gameserver.model.group.PlayerGroup; import gameserver.model.legion.Legion; import gameserver.network.aion.serverpackets.SM_QUESTIONNAIRE; import gameserver.utils.PacketSendUtility; import gameserver.utils.Util; import gameserver.utils.chathandlers.UserCommand; import gameserver.utils.idfactory.IDFactory; import gameserver.world.World; import java.util.Iterator; import java.util.List; public class PlayerInfo extends UserCommand { public PlayerInfo() { super("playerinfo"); } @Override public void executeCommand(Player player, String params) { String[] args = params.split(" "); Player target = World.getInstance().findPlayer(Util.convertName(args[0])); if (target == null) { PacketSendUtility.sendMessage(player, "The player with this name is not on a network or do not exist."); return; } StringBuilder sb = new StringBuilder(); sb.append("<poll>\n"); sb.append("<poll_introduction>\n"); sb.append(" <![CDATA[<font color='4CB1E5'>Player Info - Aion-Knight Dev.</font>]]>\n"); sb.append("</poll_introduction>\n"); sb.append("<poll_title>\n"); sb.append(" <font color='ffc519'></font>\n"); sb.append("</poll_title>\n"); sb.append("<start_date></start_date>\n"); sb.append("<end_date></end_date>\n"); sb.append("<servers></servers>\n"); sb.append("<order_num></order_num>\n"); sb.append("<race></race>\n"); sb.append("<main_class></main_class>\n"); sb.append("<world_id></world_id>\n"); sb.append("<item_id></item_id>\n"); sb.append("<item_cnt></item_cnt>\n"); sb.append("<level>1~55</level>\n"); sb.append("<questions>\n"); sb.append(" <question>\n"); sb.append(" <title>\n"); sb.append(" <![CDATA[\n"); sb.append("<br><br>\n"); if (target.getCommonData().getRace() == Race.ELYOS) { sb.append("Information about the player " + target.getName() + ": <img src='http://www.aion-destination.de/_images/elyos.png'><br><hr><br><br>\n"); } else { sb.append("Information about the player " + target.getName() + ": <img src='http://sites.google.com/site/aioninfos/bilder/sonstiges/Asmodier-Symbol-35x40.png'><br><hr><br><br>\n"); } //Falls sie die selbe Rasse haben bzw. es ein GM ist, wird der HP/MP/DP Status in % ausgegeben if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0) { int hpinPercent = target.getLifeStats().getCurrentHp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXHP); int mpinPercent = target.getLifeStats().getCurrentMp()*100/target.getGameStats().getCurrentStat(StatEnum.MAXMP); int dpinPercent = target.getCommonData().getDp()*100/4000; //Gesundheit grafisch darstellen sb.append("Gesundheit: [<font color ='00FF00'>"); int i = 1; for (i = 1; i < hpinPercent/5; i++) { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); int k = 20-i; for (i = 1; i < k; i++) { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + hpinPercent + "%) (" + target.getLifeStats().getCurrentHp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXHP) + " TP)<br>"); if (hpinPercent == 0) //Falls der Spieler keine Gesundheit mehr hat also tot ist sind alle Balken rot und es erscheint Tot neben dem Leben { sb.append(" <font color ='FF0000'>Tot</font>"); sb.append("<br>Mana: [<font color='FF0000'>|||||||||| ||||||||||</font>]"); sb.append("<br>G&ouml;ttliche Kraft: [font color='FF0000'>|||||||||| ||||||||||</font>"); } else //ansonsten werden Mana und G�ttliche Kraft berechnet { sb.append("<br>"); //Mana grafisch darstellen sb.append("Mana: [<font color ='00FFFF'>"); for (i = 1; i < mpinPercent/5; i++) //gr�ne Gesundheitsbalken { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); k = 20-i; for (i = 1; i < k; i++) //Rote Gesundheitsbalken { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + mpinPercent + "%) (" + target.getLifeStats().getCurrentMp() + "/" + target.getGameStats().getCurrentStat(StatEnum.MAXMP) + " MP)<br>"); //G�ttliche Kraft grafisch darstellen sb.append("G&ouml;ttliche Kraft: [<font color='FFCC00'>"); for (i = 1; i < dpinPercent/5; i++) { sb.append("|"); if (i == 10) { sb.append(" "); } } sb.append("</font><font color ='FF0000'>"); k = 20-i; for (i = 1; i < k; i++) { sb.append("|"); if (20-k+i == 10) { sb.append(" "); } } sb.append("</font>] (" + dpinPercent + "%) (" + target.getCommonData().getDp() + "/4000 GK)<br>"); } } sb.append("Level: " + target.getLevel() + "<br>\n"); //sb.append("Online: " + (System.currentTimeMillis() - target.getCommonData().getLastOnline().getTime()) / 60000 + " Minuten<br>\n"); if (target.getCommonData().getRace() == player.getCommonData().getRace() || player.getAccessLevel() > 0) { //PacketSendUtility.broadcastPacket(((Player) player), new SM_MESSAGE(((Player) player),"Position von [Pos:" + target.getName() + ";" + target.getPosition().getMapId() + " " + target.getPosition().getX() + " " + target.getPosition().getY() + " 0.0 -1]" , ChatType.NORMAL), true); //TODO Post des Ortes via Chat... Umwandlung in Ortsbezogene Markierung?? } sb.append("Klasse: "); int targetclass = target.getPlayerClass().getClassId(); if (targetclass == 0) { sb.append("Krieger"); } else if (targetclass == 1) { sb.append("Gladiator"); } else if (targetclass == 2) { sb.append("Templer"); } else if (targetclass == 3) { sb.append("Sp&auml;her"); } else if (targetclass == 4) { sb.append("Assassine"); } else if (targetclass == 5) { sb.append("J&auml;ger"); } else if (targetclass == 6) { sb.append("Magier"); } else if (targetclass == 7) { sb.append("Zauberer"); } else if (targetclass == 8) { sb.append("Beschw&ouml;rer"); } else if (targetclass == 9) { sb.append("Priester"); } else if (targetclass == 10) { sb.append("Kleriker"); } else if (targetclass == 11) { sb.append("Kantor"); } sb.append("<br>"); if (target.getCommonData().getRace() == Race.ELYOS) { sb.append("Rasse: Elyos<br>\n"); } else { sb.append("Rasse: Asmodier<br>\n"); } StringBuilder strbld = new StringBuilder("Gruppe: <br>--Leitung: \n"); PlayerGroup group = target.getPlayerGroup(); if (group == null) sb.append("Gruppe: keine<br>\n"); else { Iterator<Player> it = group.getMembers().iterator(); strbld.append(group.getGroupLeader().getName() + "<br>--Mitglieder:<br>\n"); while (it.hasNext()) { Player act = (Player) it.next(); strbld.append("----" + act.getName() + "<br>\n"); } sb.append(strbld.toString()); } Legion legion = target.getLegion(); if (legion == null) { sb.append("Legion: keine<br>\n"); } else { sb.append("Legion: " + legion.getLegionName() + "<br>\n"); } if (player.getAccessLevel() > 0) { sb.append("<hr>"); sb.append("Zus&auml;tzliche Informationen f&uuml;r Teammitglieder:<br><br>"); sb.append("Account Name: " + target.getClientConnection().getAccount().getName() + "<br>\n"); //sb.append("IP: "<SUF> try { if (args[1].equals("+items")) { sb.append("<br><hr><br>Item Informationen:<br><br>"); StringBuilder itstrbld = new StringBuilder("-- Inventar:<br>"); List<Item> items = target.getInventory().getAllItems(); Iterator<Item> it = items.iterator(); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>"); } } items.clear(); items = target.getEquipment().getEquippedItems(); it = items.iterator(); itstrbld.append("<br>-- Ausger&uuml;stet:<br>"); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]<br>"); } } items.clear(); items = target.getWarehouse().getAllItems(); it = items.iterator(); itstrbld.append("<br>-- Lagerhaus:<br>"); if (items.isEmpty()) itstrbld.append("---- Keine"); else { while (it.hasNext()) { Item act = (Item) it.next(); itstrbld.append("---- " + act.getItemCount() + "mal " + "[item:" + act.getItemTemplate().getTemplateId() + "]" + "<br>"); } } sb.append(itstrbld.toString()); } } catch (Exception e) { } } else if (player.getAccessLevel() == 0 && args[1].equals("+items")) { sb.append("<br><hr><br>Du hast nicht genug Rechte, um Item Informationen abzurufen.<br><br>"); } sb.append("<br><br><br>\n"); sb.append(" ]]>\n"); sb.append(" </title>\n"); sb.append(" <select>\n"); sb.append("<input type='radio'>"); sb.append("Danke f&uuml;r die Info!"); sb.append("</input>\n"); sb.append(" </select>\n"); sb.append(" </question>\n"); sb.append("</questions>\n"); sb.append("</poll>\n"); String html = sb.toString(); final int messageId = IDFactory.getInstance().nextId(); byte packet_count = (byte) Math.ceil(html.length() / (Short.MAX_VALUE - 8) + 1); if (packet_count < 256) { for (byte i = 0; i < packet_count; i++) { try { int from = i * (Short.MAX_VALUE - 8), to = (i + 1) * (Short.MAX_VALUE - 8); if (from < 0) from = 0; if (to > html.length()) to = html.length(); String sub = html.substring(from, to); player.getClientConnection().sendPacket(new SM_QUESTIONNAIRE(messageId, i, packet_count, sub)); } catch (Exception e) { } } } } }
140637_15
package org.xmlvm.ios; import java.util.*; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class CMTimeRange { /* * Variables */ public CMTime start; public CMTime duration; /* * Static methods */ /** * CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ; */ public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){ throw new RuntimeException("Stub"); } /** * CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ; */ public static CMTimeRange makeFromDictionary(CFDictionary dict){ throw new RuntimeException("Stub"); } /** * CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ; */ public static String copyDescription(CFAllocator allocator, CMTimeRange range){ throw new RuntimeException("Stub"); } /* * Constructors */ /** * CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ; */ public CMTimeRange(CMTime start, CMTime duration) {} /** Default constructor */ CMTimeRange() {} /* * Instance methods */ /** * CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ; */ public CMTimeRange getUnion(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ; */ public CMTimeRange getIntersection(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ; */ public byte equal(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ; */ public byte containsTime(CMTime time){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ; */ public byte containsTimeRange(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * CMTime CMTimeRangeGetEnd( CMTimeRange range) ; */ public CMTime getEnd(){ throw new RuntimeException("Stub"); } /** * CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ; */ public CFDictionary copyAsDictionary(CFAllocator allocator){ throw new RuntimeException("Stub"); } /** * void CMTimeRangeShow( CMTimeRange range) ; */ public void show(){ throw new RuntimeException("Stub"); } }
shannah/cn1
Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CMTimeRange.java
783
/** * void CMTimeRangeShow( CMTimeRange range) ; */
block_comment
nl
package org.xmlvm.ios; import java.util.*; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class CMTimeRange { /* * Variables */ public CMTime start; public CMTime duration; /* * Static methods */ /** * CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ; */ public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){ throw new RuntimeException("Stub"); } /** * CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ; */ public static CMTimeRange makeFromDictionary(CFDictionary dict){ throw new RuntimeException("Stub"); } /** * CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ; */ public static String copyDescription(CFAllocator allocator, CMTimeRange range){ throw new RuntimeException("Stub"); } /* * Constructors */ /** * CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ; */ public CMTimeRange(CMTime start, CMTime duration) {} /** Default constructor */ CMTimeRange() {} /* * Instance methods */ /** * CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ; */ public CMTimeRange getUnion(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ; */ public CMTimeRange getIntersection(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ; */ public byte equal(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ; */ public byte containsTime(CMTime time){ throw new RuntimeException("Stub"); } /** * Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ; */ public byte containsTimeRange(CMTimeRange range2){ throw new RuntimeException("Stub"); } /** * CMTime CMTimeRangeGetEnd( CMTimeRange range) ; */ public CMTime getEnd(){ throw new RuntimeException("Stub"); } /** * CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ; */ public CFDictionary copyAsDictionary(CFAllocator allocator){ throw new RuntimeException("Stub"); } /** * void CMTimeRangeShow( CMTimeRange<SUF>*/ public void show(){ throw new RuntimeException("Stub"); } }
103341_18
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package networking; import guiGame.GameOberflaeche; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import general.Language; import guiLauncher.LauncherOberflaeche; import guiLobby.LobbyOberflaeche; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Optional; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.stage.Stage; /** * * @author Josua Frank */ public class ClientManager { private static final String saltConstant = "H2Gq7p@H!9a"; private Stage stage; private Language languages = new Language(); private LauncherOberflaeche launcher; private LobbyOberflaeche lobby; private GameOberflaeche game; public Socket socket = null; private ExecutorService threadPool; public boolean bereitsAngemeldet = false; private String username; private HashMap<String, Integer> onlineUsers; public Boolean serverReachable = false; private int aktiveScene = 0; private String ip = "localhost"; //private String ip = "ns323149.ip-213-251-184.eu"; //private String ip= "frankdns.selfhost.eu"; /** * Ist die Verbindung zum Server * * @param pOberflaeche Die Oberfläche, die dieses Objekt erzeugt hat * @param pStage Die Stage, damit auf Ihr die Scenes gewechselt werden * können */ public ClientManager(LauncherOberflaeche pOberflaeche, Stage pStage) { this.launcher = pOberflaeche; this.stage = pStage; launcher.setStatusFeld(" ");//Damit die Leiste nicht erst später erscheint, während er versucht, zu connecten } /** * Hier wird versucht, eine Verbindug zum Server herzustellen */ public void connect() { try { socket = new Socket(); socket.connect(new InetSocketAddress(ip, 3141), 500); threadPool = Executors.newCachedThreadPool(); threadPool.submit(new InputListener(socket, this)); System.out.println("Erfolgreich verbunden"); launcher.setStatusFeld("Erfolgreich zu Server verbunden"); serverReachable = true; } catch (UnknownHostException e) { System.err.println("Unbekannter Host: " + e.getMessage()); launcher.setStatusFeld("Unbekannter Host: " + e.getMessage()); this.showServerUnreachableDialog(); } catch (IOException e) { System.err.println("Server konnte nicht erreicht werden: " + e.getMessage()); launcher.setStatusFeld(languages.getString(6) + ": " + e.getMessage()); this.showServerUnreachableDialog(); } } /** * Wandelt saltet ein Passwort und wandelt es dann in einen Hash-Wert (512 * Bit SHA) um * * @param value Das umzuwandelnde Passwort * @return Der 512 Bit SHA String */ public String getHash(String value) { MessageDigest md; StringBuilder sb = new StringBuilder(); String saltedPW; System.out.println("username " + username + " Value: " + value); saltedPW = value + saltConstant + username; try { md = MessageDigest.getInstance("SHA-512"); md.update(saltedPW.getBytes()); byte byteData[] = md.digest(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException ex) { System.err.println("Algorithmus nicht verfügbar: " + ex.getMessage()); } return sb.toString(); } /** * Meldet sich mit Benutzername und Passwort am Server an * * @param pUsername Der Benutzername zum anmelden * @param pPassword Das Passwort zum anmelden */ public void login(String pUsername, String pPassword) { if (socket == null) { this.connect(); } if (bereitsAngemeldet) {//Prüft, ob bereits jemand an diesem Clienten angemeldet ist launcher.setStatusFeld(languages.getString(10)); return; } if (socket != null) {//Prüft, ob eine Verbindung besteht username = pUsername; String hashedPassword = getHash(pPassword); String[] befehl = {"login", username, hashedPassword}; sendObject(befehl);//Username darf KEINE Leerzeichen beinhalten } } /** * Falls der Anmeldevorgang erfolgerich war, wird hier das Spiel gestartet */ public void loginErfolgreich() { bereitsAngemeldet = true; //Hier startet dann das Spiel lobby = new LobbyOberflaeche(this, stage); setScene(1); } /** * Hier wird die Registrierungsbenachrichtigung an den Server geschickt * * @param username Der Benutzername * @param firstname Der Vorname * @param name Der Nachname * @param password Sein Passwort als Hash-Wert * @param password2 Das wiederholte Passwort * @param email Seine E-Mailadresse * @param language Seine gewählte Sprache * @return true, wenn alles geklappt hat */ public boolean register(String username, String firstname, String name, String password, String password2, String email, String language) { if (socket == null) { this.connect(); } if (socket != null) { this.username = username; String hashedPassword = getHash(password); String hashedPassword2 = getHash(password2); String[] befehl = {"register", username, firstname, name, hashedPassword, hashedPassword2, email, language}; sendObject(befehl); return true; } else { launcher.setStatusFeld(languages.getString(7)); return false; } } /** * Hier wird vom Server ein neues Passwort angefordert * * @param email Die Emailadresse zur verifizierung * @param username Dessen Benutzername */ public void requestNewPassword(String email, String username) { if (socket == null) { this.connect(); } if (socket != null) { String[] command = {"passwordforgotten", email, username}; sendObject(command); } } public void sendNewPassword(String pCode, String password1, String password2) { if (socket == null) { this.connect(); } if (socket != null) { String hashedPassword1 = getHash(password1); String hashedPassword2 = getHash(password2); String[] befehl = {"newpassword", pCode, hashedPassword1, hashedPassword2}; sendObject(befehl); } } /** * Hier wird die Verbindung zum Server getrennt */ public void verbindungTrennen() { if (socket == null) { System.out.println("Server unerreichbar, beende daher sofort..."); System.exit(0); } else { String[] befehl = {"disconnect"}; sendObject(befehl); try { socket.close(); System.out.println("Habe mich abgemeldet und beende mich jetzt..."); System.exit(0); } catch (IOException ex) { System.out.println("Konnte Socket nicht schliessen!"); } } } /** * Sended Nachrichten zum Clienten. * * @param object Das Object, das zum Client geschickt werden soll */ public void sendObject(Object object) { // if (object.getClass(). > 1000) { // this.zeigeFehlerAn("Command too long"); // return; // } if (socket == null) { this.connect(); } try { ObjectOutputStream raus = new ObjectOutputStream(socket.getOutputStream()); raus.writeObject(object); raus.flush(); if (object instanceof String[]) { String array[] = (String[]) object; System.out.print("Gesendet: "); for (String parameter : array) { System.out.print(parameter + " "); } System.out.println(); } } catch (Exception e) { System.err.println("Object konnte nicht gesendet werden, da der Server unerreichbar ist: " + e); this.showServerUnreachableDialog(); } } /** * Hier empfängt er aus der Klasse InputListener Nachrichten * * @param message Die empfangene Nachricht */ public void receiveStringArray(String[] message) { System.out.print("Empfangen: "); for (String parameter : message) { System.out.print(parameter + " "); } System.out.println(); try { new Command(message, this, launcher, lobby, game); } catch (Throwable ex) { System.err.println("Konnte Command nicht ausführen: " + ex); } } /** * Hier empfängt er aus der Klasse InputListener Objekte * * @param object Das empfangene Objekt */ public void receiveObject(Object object) { if (object instanceof HashMap) { if (((HashMap) object).containsKey(999)) { System.out.println("Gamefield empfangen"); HashMap<Integer, String> gameField = (HashMap<Integer, String>) object; gameField.remove(999); if (bereitsAngemeldet) { game.buildGameField(gameField); } } else if (((HashMap) object).containsKey("online users")) { System.out.println("Online Users empfangen"); this.onlineUsers = (HashMap<String, Integer>) object; this.onlineUsers.remove("online users"); if (bereitsAngemeldet) { lobby.buildList(onlineUsers); if (game != null) { game.buildList(onlineUsers); } } } else if (((HashMap) object).containsKey("users score")) { System.out.println("User Score empfangen"); HashMap<String, int[]> usersScore = (HashMap<String, int[]>) object; usersScore.remove("users score"); if (bereitsAngemeldet) { lobby.buildScore(usersScore); } } else { System.err.println("Object nicht erkannt!"); } } else if (object instanceof ArrayList) { if (game != null) { game.overrideStatusOfPlayers((ArrayList<String>) object); } else { System.err.println("Fehler, Game noch null!!"); } } } /** * Hier gibt er das Language-Object zurück, damit diese die selbe Main * Language haben * * @return Das Object von Language */ public Language getLanguages() { return this.languages; } /** * Hier gibt er den Benutzernamen zurück, gegebenfalls auch null; * * @return */ public String getUsername() { return this.username; } /** * Hier öffnet er den Server-Unerreichbar-Dialog mit den Optionan Programm * schließen und erneut versuchen */ public void showServerUnreachableDialog() { Platform.runLater(() -> { try { socket.close(); } catch (Exception e) { System.err.println("Konnte Socket nicht schließen"); } Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(languages.getString(46)); alert.setHeaderText(null); alert.setContentText(languages.getString(40)); ButtonType retry = new ButtonType(languages.getString(70)); ButtonType buttonTypeCancel = new ButtonType(languages.getString(71), ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(retry, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == retry) { this.connect(); } else { System.out.println("BEENDE, weil auf knopf schliesen geklickt wurde"); System.exit(0); } }); } /** * Hier setzt er die jeweilige Szene (z.B. Game, Launcher oder Lobby) in den * Vordergrund * * @param number 0 = Launcher 1 = Lobby 2 = Game */ public void setScene(int number) { switch (number) { case 0: Platform.runLater(() -> { launcher.setSize(getSizeFromActiveScene()); game = null; stage.setScene(launcher.getScene()); aktiveScene = 0; }); break; case 1: Platform.runLater(() -> { stage.setTitle(username); lobby.setSize(getSizeFromActiveScene()); game = null;//Brauche game noch bei getSizeFrom... stage.setScene(lobby.getScene()); lobby.executescheduledTasks(); aktiveScene = 1; }); break; case 2: game = new GameOberflaeche(this, stage, lobby); Platform.runLater(() -> { game.setSize(getSizeFromActiveScene()); stage.setScene(game.getScene()); aktiveScene = 2; }); break; } } /** * Holt die Größe der gerade Aktiven Szene und gibt diese zurück * * @return die Größe als int-Array(int[0] = x, int[1] = y) zurück */ private int[] getSizeFromActiveScene() { switch (aktiveScene) { case 0: int[] size = launcher.getSize(); System.out.println("Launchergröße: " + size[0] + ", " + size[1]); return launcher.getSize(); case 1: System.out.println("Lobbygröße: " + lobby.getSize().toString()); return lobby.getSize(); case 2: return game.getSize(); } return null; } /** * Zeigt ein einfaches Fehlerfesnter an * * @param string Die anzuzeigende Nachricht */ public void zeigeFehlerAn(String string) { Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(languages.getString(44)); alert.setHeaderText(null); alert.setContentText(string); alert.showAndWait(); }); } public void setUsername(String pUsername) { this.username = pUsername; } }
sharknoon/TicTacToe
TicTacToeClient/src/main/java/networking/ClientManager.java
4,475
// if (object.getClass(). > 1000) {
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package networking; import guiGame.GameOberflaeche; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import general.Language; import guiLauncher.LauncherOberflaeche; import guiLobby.LobbyOberflaeche; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Optional; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.stage.Stage; /** * * @author Josua Frank */ public class ClientManager { private static final String saltConstant = "H2Gq7p@H!9a"; private Stage stage; private Language languages = new Language(); private LauncherOberflaeche launcher; private LobbyOberflaeche lobby; private GameOberflaeche game; public Socket socket = null; private ExecutorService threadPool; public boolean bereitsAngemeldet = false; private String username; private HashMap<String, Integer> onlineUsers; public Boolean serverReachable = false; private int aktiveScene = 0; private String ip = "localhost"; //private String ip = "ns323149.ip-213-251-184.eu"; //private String ip= "frankdns.selfhost.eu"; /** * Ist die Verbindung zum Server * * @param pOberflaeche Die Oberfläche, die dieses Objekt erzeugt hat * @param pStage Die Stage, damit auf Ihr die Scenes gewechselt werden * können */ public ClientManager(LauncherOberflaeche pOberflaeche, Stage pStage) { this.launcher = pOberflaeche; this.stage = pStage; launcher.setStatusFeld(" ");//Damit die Leiste nicht erst später erscheint, während er versucht, zu connecten } /** * Hier wird versucht, eine Verbindug zum Server herzustellen */ public void connect() { try { socket = new Socket(); socket.connect(new InetSocketAddress(ip, 3141), 500); threadPool = Executors.newCachedThreadPool(); threadPool.submit(new InputListener(socket, this)); System.out.println("Erfolgreich verbunden"); launcher.setStatusFeld("Erfolgreich zu Server verbunden"); serverReachable = true; } catch (UnknownHostException e) { System.err.println("Unbekannter Host: " + e.getMessage()); launcher.setStatusFeld("Unbekannter Host: " + e.getMessage()); this.showServerUnreachableDialog(); } catch (IOException e) { System.err.println("Server konnte nicht erreicht werden: " + e.getMessage()); launcher.setStatusFeld(languages.getString(6) + ": " + e.getMessage()); this.showServerUnreachableDialog(); } } /** * Wandelt saltet ein Passwort und wandelt es dann in einen Hash-Wert (512 * Bit SHA) um * * @param value Das umzuwandelnde Passwort * @return Der 512 Bit SHA String */ public String getHash(String value) { MessageDigest md; StringBuilder sb = new StringBuilder(); String saltedPW; System.out.println("username " + username + " Value: " + value); saltedPW = value + saltConstant + username; try { md = MessageDigest.getInstance("SHA-512"); md.update(saltedPW.getBytes()); byte byteData[] = md.digest(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException ex) { System.err.println("Algorithmus nicht verfügbar: " + ex.getMessage()); } return sb.toString(); } /** * Meldet sich mit Benutzername und Passwort am Server an * * @param pUsername Der Benutzername zum anmelden * @param pPassword Das Passwort zum anmelden */ public void login(String pUsername, String pPassword) { if (socket == null) { this.connect(); } if (bereitsAngemeldet) {//Prüft, ob bereits jemand an diesem Clienten angemeldet ist launcher.setStatusFeld(languages.getString(10)); return; } if (socket != null) {//Prüft, ob eine Verbindung besteht username = pUsername; String hashedPassword = getHash(pPassword); String[] befehl = {"login", username, hashedPassword}; sendObject(befehl);//Username darf KEINE Leerzeichen beinhalten } } /** * Falls der Anmeldevorgang erfolgerich war, wird hier das Spiel gestartet */ public void loginErfolgreich() { bereitsAngemeldet = true; //Hier startet dann das Spiel lobby = new LobbyOberflaeche(this, stage); setScene(1); } /** * Hier wird die Registrierungsbenachrichtigung an den Server geschickt * * @param username Der Benutzername * @param firstname Der Vorname * @param name Der Nachname * @param password Sein Passwort als Hash-Wert * @param password2 Das wiederholte Passwort * @param email Seine E-Mailadresse * @param language Seine gewählte Sprache * @return true, wenn alles geklappt hat */ public boolean register(String username, String firstname, String name, String password, String password2, String email, String language) { if (socket == null) { this.connect(); } if (socket != null) { this.username = username; String hashedPassword = getHash(password); String hashedPassword2 = getHash(password2); String[] befehl = {"register", username, firstname, name, hashedPassword, hashedPassword2, email, language}; sendObject(befehl); return true; } else { launcher.setStatusFeld(languages.getString(7)); return false; } } /** * Hier wird vom Server ein neues Passwort angefordert * * @param email Die Emailadresse zur verifizierung * @param username Dessen Benutzername */ public void requestNewPassword(String email, String username) { if (socket == null) { this.connect(); } if (socket != null) { String[] command = {"passwordforgotten", email, username}; sendObject(command); } } public void sendNewPassword(String pCode, String password1, String password2) { if (socket == null) { this.connect(); } if (socket != null) { String hashedPassword1 = getHash(password1); String hashedPassword2 = getHash(password2); String[] befehl = {"newpassword", pCode, hashedPassword1, hashedPassword2}; sendObject(befehl); } } /** * Hier wird die Verbindung zum Server getrennt */ public void verbindungTrennen() { if (socket == null) { System.out.println("Server unerreichbar, beende daher sofort..."); System.exit(0); } else { String[] befehl = {"disconnect"}; sendObject(befehl); try { socket.close(); System.out.println("Habe mich abgemeldet und beende mich jetzt..."); System.exit(0); } catch (IOException ex) { System.out.println("Konnte Socket nicht schliessen!"); } } } /** * Sended Nachrichten zum Clienten. * * @param object Das Object, das zum Client geschickt werden soll */ public void sendObject(Object object) { // if (object.getClass().<SUF> // this.zeigeFehlerAn("Command too long"); // return; // } if (socket == null) { this.connect(); } try { ObjectOutputStream raus = new ObjectOutputStream(socket.getOutputStream()); raus.writeObject(object); raus.flush(); if (object instanceof String[]) { String array[] = (String[]) object; System.out.print("Gesendet: "); for (String parameter : array) { System.out.print(parameter + " "); } System.out.println(); } } catch (Exception e) { System.err.println("Object konnte nicht gesendet werden, da der Server unerreichbar ist: " + e); this.showServerUnreachableDialog(); } } /** * Hier empfängt er aus der Klasse InputListener Nachrichten * * @param message Die empfangene Nachricht */ public void receiveStringArray(String[] message) { System.out.print("Empfangen: "); for (String parameter : message) { System.out.print(parameter + " "); } System.out.println(); try { new Command(message, this, launcher, lobby, game); } catch (Throwable ex) { System.err.println("Konnte Command nicht ausführen: " + ex); } } /** * Hier empfängt er aus der Klasse InputListener Objekte * * @param object Das empfangene Objekt */ public void receiveObject(Object object) { if (object instanceof HashMap) { if (((HashMap) object).containsKey(999)) { System.out.println("Gamefield empfangen"); HashMap<Integer, String> gameField = (HashMap<Integer, String>) object; gameField.remove(999); if (bereitsAngemeldet) { game.buildGameField(gameField); } } else if (((HashMap) object).containsKey("online users")) { System.out.println("Online Users empfangen"); this.onlineUsers = (HashMap<String, Integer>) object; this.onlineUsers.remove("online users"); if (bereitsAngemeldet) { lobby.buildList(onlineUsers); if (game != null) { game.buildList(onlineUsers); } } } else if (((HashMap) object).containsKey("users score")) { System.out.println("User Score empfangen"); HashMap<String, int[]> usersScore = (HashMap<String, int[]>) object; usersScore.remove("users score"); if (bereitsAngemeldet) { lobby.buildScore(usersScore); } } else { System.err.println("Object nicht erkannt!"); } } else if (object instanceof ArrayList) { if (game != null) { game.overrideStatusOfPlayers((ArrayList<String>) object); } else { System.err.println("Fehler, Game noch null!!"); } } } /** * Hier gibt er das Language-Object zurück, damit diese die selbe Main * Language haben * * @return Das Object von Language */ public Language getLanguages() { return this.languages; } /** * Hier gibt er den Benutzernamen zurück, gegebenfalls auch null; * * @return */ public String getUsername() { return this.username; } /** * Hier öffnet er den Server-Unerreichbar-Dialog mit den Optionan Programm * schließen und erneut versuchen */ public void showServerUnreachableDialog() { Platform.runLater(() -> { try { socket.close(); } catch (Exception e) { System.err.println("Konnte Socket nicht schließen"); } Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(languages.getString(46)); alert.setHeaderText(null); alert.setContentText(languages.getString(40)); ButtonType retry = new ButtonType(languages.getString(70)); ButtonType buttonTypeCancel = new ButtonType(languages.getString(71), ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(retry, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == retry) { this.connect(); } else { System.out.println("BEENDE, weil auf knopf schliesen geklickt wurde"); System.exit(0); } }); } /** * Hier setzt er die jeweilige Szene (z.B. Game, Launcher oder Lobby) in den * Vordergrund * * @param number 0 = Launcher 1 = Lobby 2 = Game */ public void setScene(int number) { switch (number) { case 0: Platform.runLater(() -> { launcher.setSize(getSizeFromActiveScene()); game = null; stage.setScene(launcher.getScene()); aktiveScene = 0; }); break; case 1: Platform.runLater(() -> { stage.setTitle(username); lobby.setSize(getSizeFromActiveScene()); game = null;//Brauche game noch bei getSizeFrom... stage.setScene(lobby.getScene()); lobby.executescheduledTasks(); aktiveScene = 1; }); break; case 2: game = new GameOberflaeche(this, stage, lobby); Platform.runLater(() -> { game.setSize(getSizeFromActiveScene()); stage.setScene(game.getScene()); aktiveScene = 2; }); break; } } /** * Holt die Größe der gerade Aktiven Szene und gibt diese zurück * * @return die Größe als int-Array(int[0] = x, int[1] = y) zurück */ private int[] getSizeFromActiveScene() { switch (aktiveScene) { case 0: int[] size = launcher.getSize(); System.out.println("Launchergröße: " + size[0] + ", " + size[1]); return launcher.getSize(); case 1: System.out.println("Lobbygröße: " + lobby.getSize().toString()); return lobby.getSize(); case 2: return game.getSize(); } return null; } /** * Zeigt ein einfaches Fehlerfesnter an * * @param string Die anzuzeigende Nachricht */ public void zeigeFehlerAn(String string) { Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(languages.getString(44)); alert.setHeaderText(null); alert.setContentText(string); alert.showAndWait(); }); } public void setUsername(String pUsername) { this.username = pUsername; } }
162760_6
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.Service; import org.neo4j.kernel.impl.core.KernelPanicEventGenerator; import org.neo4j.kernel.impl.core.LastCommittedTxIdSetter; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.kernel.impl.core.RelationshipTypeCreator; import org.neo4j.kernel.impl.core.TransactionEventsSyncHook; import org.neo4j.kernel.impl.core.TxEventSyncHookFactory; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.TxFinishHook; import org.neo4j.kernel.impl.transaction.TxModule; import org.neo4j.kernel.impl.transaction.xaframework.LogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGeneratorFactory; import org.neo4j.kernel.impl.util.StringLogger; import android.content.Context; class EmbeddedGraphDbImpl { private static final long MAX_NODE_ID = IdType.NODE.getMaxValue(); private static final long MAX_RELATIONSHIP_ID = IdType.RELATIONSHIP.getMaxValue(); private static Logger log = Logger.getLogger( EmbeddedGraphDbImpl.class.getName() ); private Transaction placeboTransaction = null; private final GraphDbInstance graphDbInstance; private final GraphDatabaseService graphDbService; private final NodeManager nodeManager; private final String storeDir; private final List<KernelEventHandler> kernelEventHandlers = new CopyOnWriteArrayList<KernelEventHandler>(); private final Collection<TransactionEventHandler<?>> transactionEventHandlers = new CopyOnWriteArraySet<TransactionEventHandler<?>>(); private final KernelPanicEventGenerator kernelPanicEventGenerator = new KernelPanicEventGenerator( kernelEventHandlers ); private final KernelData extensions; private final IndexManagerImpl indexManager; private final StringLogger msgLog; /** * A non-standard way of creating an embedded {@link GraphDatabaseService} * with a set of configuration parameters. Will most likely be removed in * future releases. * * @param storeDir the store directory for the db files * @param fileSystem * @param config configuration parameters */ public EmbeddedGraphDbImpl( Context context, String storeDir, StoreId storeId, Map<String, String> inputParams, GraphDatabaseService graphDbService, LockManagerFactory lockManagerFactory, IdGeneratorFactory idGeneratorFactory, RelationshipTypeCreator relTypeCreator, TxIdGeneratorFactory txIdFactory, TxFinishHook finishHook, LastCommittedTxIdSetter lastCommittedTxIdSetter, FileSystemAbstraction fileSystem ) { this.storeDir = storeDir; TxModule txModule = newTxModule( inputParams, finishHook ); LockManager lockManager = lockManagerFactory.create( txModule ); LockReleaser lockReleaser = new LockReleaser( lockManager, txModule.getTxManager() ); final Config config = new Config( context, graphDbService, storeDir, storeId, inputParams, kernelPanicEventGenerator, txModule, lockManager, lockReleaser, idGeneratorFactory, new SyncHookFactory(), relTypeCreator, txIdFactory.create( txModule.getTxManager() ), lastCommittedTxIdSetter, fileSystem ); /* * LogBufferFactory needs access to the parameters so it has to be added after the default and * user supplied configurations are consolidated */ config.getParams().put( LogBufferFactory.class, CommonFactories.defaultLogBufferFactory() ); graphDbInstance = new GraphDbInstance( storeDir, true, config ); this.msgLog = StringLogger.getLogger( storeDir ); this.graphDbService = graphDbService; IndexStore indexStore = graphDbInstance.getConfig().getIndexStore(); this.indexManager = new IndexManagerImpl( this, indexStore ); extensions = new KernelData() { @Override public Version version() { return Version.getKernel(); } @Override public Config getConfig() { return config; } @Override public Map<Object, Object> getConfigParams() { return config.getParams(); } @Override public GraphDatabaseService graphDatabase() { return EmbeddedGraphDbImpl.this.graphDbService; } }; boolean started = false; try { final KernelExtensionLoader extensionLoader; if ( "false".equalsIgnoreCase( inputParams.get( Config.LOAD_EXTENSIONS ) ) ) { extensionLoader = KernelExtensionLoader.DONT_LOAD; } else { extensionLoader = new KernelExtensionLoader() { private Collection<KernelExtension<?>> loaded; @Override public void configureKernelExtensions() { loaded = extensions.loadExtensionConfigurations( msgLog ); } @Override public void initializeIndexProviders() { extensions.loadIndexImplementations( indexManager, msgLog ); } @Override public void load() { extensions.loadExtensions( loaded, msgLog ); } }; } graphDbInstance.start( graphDbService, extensionLoader ); nodeManager = config.getGraphDbModule().getNodeManager(); /* * IndexManager has to exist before extensions load (so that * it is present and taken into consideration) but after * graphDbInstance is started so that there is access to the * nodeManager. In other words, the start() below has to be here. */ indexManager.start(); extensionLoader.load(); started = true; // must be last } catch ( Error cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } catch ( RuntimeException cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } finally { // If startup failed, cleanup the extensions - or they will leak if ( !started ) extensions.shutdown( msgLog ); } } private TxModule newTxModule( Map<String, String> inputParams, TxFinishHook rollbackHook ) { return Boolean.parseBoolean( inputParams.get( Config.READ_ONLY ) ) ? new TxModule( true, kernelPanicEventGenerator ) : new TxModule( this.storeDir, kernelPanicEventGenerator, rollbackHook, inputParams.get(Config.TXMANAGER_IMPLEMENTATION) ); } <T> Collection<T> getManagementBeans( Class<T> beanClass ) { KernelExtension<?> jmx = Service.load( KernelExtension.class, "kernel jmx" ); if ( jmx != null ) { Method getManagementBeans = null; Object state = jmx.getState( extensions ); if ( state != null ) { try { getManagementBeans = state.getClass().getMethod( "getManagementBeans", Class.class ); } catch ( Exception e ) { // getManagementBean will be null } } if ( getManagementBeans != null ) { try { @SuppressWarnings( "unchecked" ) Collection<T> result = (Collection<T>) getManagementBeans.invoke( state, beanClass ); if ( result == null ) return Collections.emptySet(); return result; } catch ( InvocationTargetException ex ) { Throwable cause = ex.getTargetException(); if ( cause instanceof Error ) { throw (Error) cause; } if ( cause instanceof RuntimeException ) { throw (RuntimeException) cause; } } catch ( Exception ignored ) { // exception thrown below } } } throw new UnsupportedOperationException( "Neo4j JMX support not enabled" ); } /** * A non-standard Convenience method that loads a standard property file and * converts it into a generic <Code>Map<String,String></CODE>. Will most * likely be removed in future releases. * * @param file the property file to load * @return a map containing the properties from the file * @throws IllegalArgumentException if file does not exist */ public static Map<String,String> loadConfigurations( String file ) { Properties props = new Properties(); try { FileInputStream stream = new FileInputStream( new File( file ) ); try { props.load( stream ); } finally { stream.close(); } } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to load " + file, e ); } Set<Entry<Object,Object>> entries = props.entrySet(); Map<String,String> stringProps = new HashMap<String,String>(); for ( Entry<Object,Object> entry : entries ) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); stringProps.put( key, value ); } return stringProps; } public Node createNode() { return nodeManager.createNode(); } public Node getNodeById( long id ) { if ( id < 0 || id > MAX_NODE_ID ) { throw new NotFoundException( "Node[" + id + "]" ); } return nodeManager.getNodeById( id ); } public Relationship getRelationshipById( long id ) { if ( id < 0 || id > MAX_RELATIONSHIP_ID ) { throw new NotFoundException( "Relationship[" + id + "]" ); } return nodeManager.getRelationshipById( id ); } public Node getReferenceNode() { return nodeManager.getReferenceNode(); } private boolean inShutdown = false; public synchronized void shutdown() { if ( inShutdown ) return; inShutdown = true; try { if ( graphDbInstance.started() ) { try { sendShutdownEvent(); } finally { extensions.shutdown( msgLog ); } } graphDbInstance.shutdown(); } finally { inShutdown = false; } } private void sendShutdownEvent() { for ( KernelEventHandler handler : this.kernelEventHandlers ) { handler.beforeShutdown(); } } public Iterable<RelationshipType> getRelationshipTypes() { return graphDbInstance.getRelationshipTypes(); } /** * @throws TransactionFailureException if unable to start transaction */ public Transaction beginTx() { if ( graphDbInstance.transactionRunning() ) { if ( placeboTransaction == null ) { placeboTransaction = new PlaceboTransaction( graphDbInstance.getTransactionManager() ); } return placeboTransaction; } TransactionManager txManager = graphDbInstance.getTransactionManager(); Transaction result = null; try { txManager.begin(); result = new TopLevelTransaction( txManager, txManager.getTransaction() ); } catch ( Exception e ) { throw new TransactionFailureException( "Unable to begin transaction", e ); } return result; } /** * Returns a non-standard configuration object. Will most likely be removed * in future releases. * * @return a configuration object */ public Config getConfig() { return graphDbInstance.getConfig(); } @Override public String toString() { return super.toString() + " [" + storeDir + "]"; } public String getStoreDir() { return storeDir; } public Iterable<Node> getAllNodes() { return new Iterable<Node>() { @Override public Iterator<Node> iterator() { long highId = nodeManager.getHighestPossibleIdInUse( Node.class ); return new AllNodesIterator( highId ); } }; } // TODO: temporary all nodes getter, fix this with better implementation // (no NotFoundException to control flow) private class AllNodesIterator implements Iterator<Node> { private final long highId; private long currentNodeId = 0; private Node currentNode = null; AllNodesIterator( long highId ) { this.highId = highId; } @Override public synchronized boolean hasNext() { while ( currentNode == null && currentNodeId <= highId ) { try { currentNode = getNodeById( currentNodeId++ ); } catch ( NotFoundException e ) { // ok we try next } } return currentNode != null; } @Override public synchronized Node next() { if ( !hasNext() ) { throw new NoSuchElementException(); } Node nextNode = currentNode; currentNode = null; return nextNode; } @Override public void remove() { throw new UnsupportedOperationException(); } } <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { this.transactionEventHandlers.add( handler ); return handler; } <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return unregisterHandler( this.transactionEventHandlers, handler ); } KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { if ( this.kernelEventHandlers.contains( handler ) ) { return handler; } // Some algo for putting it in the right place for ( KernelEventHandler registeredHandler : this.kernelEventHandlers ) { KernelEventHandler.ExecutionOrder order = handler.orderComparedTo( registeredHandler ); int index = this.kernelEventHandlers.indexOf( registeredHandler ); if ( order == KernelEventHandler.ExecutionOrder.BEFORE ) { this.kernelEventHandlers.add( index, handler ); return handler; } else if ( order == KernelEventHandler.ExecutionOrder.AFTER ) { this.kernelEventHandlers.add( index + 1, handler ); return handler; } } this.kernelEventHandlers.add( handler ); return handler; } KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return unregisterHandler( this.kernelEventHandlers, handler ); } private <T> T unregisterHandler( Collection<?> setOfHandlers, T handler ) { if ( !setOfHandlers.remove( handler ) ) { throw new IllegalStateException( handler + " isn't registered" ); } return handler; } private class SyncHookFactory implements TxEventSyncHookFactory { @Override public TransactionEventsSyncHook create() { return transactionEventHandlers.isEmpty() ? null : new TransactionEventsSyncHook( nodeManager, transactionEventHandlers, getConfig().getTxModule().getTxManager() ); } } IndexManager index() { return this.indexManager; } KernelData getKernelData() { return extensions; } }
sharop/neo4j-mobile-android
neo4j-android/kernel-src/org/neo4j/kernel/EmbeddedGraphDbImpl.java
4,857
// getManagementBean will be null
line_comment
nl
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.Service; import org.neo4j.kernel.impl.core.KernelPanicEventGenerator; import org.neo4j.kernel.impl.core.LastCommittedTxIdSetter; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.kernel.impl.core.RelationshipTypeCreator; import org.neo4j.kernel.impl.core.TransactionEventsSyncHook; import org.neo4j.kernel.impl.core.TxEventSyncHookFactory; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.TxFinishHook; import org.neo4j.kernel.impl.transaction.TxModule; import org.neo4j.kernel.impl.transaction.xaframework.LogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGeneratorFactory; import org.neo4j.kernel.impl.util.StringLogger; import android.content.Context; class EmbeddedGraphDbImpl { private static final long MAX_NODE_ID = IdType.NODE.getMaxValue(); private static final long MAX_RELATIONSHIP_ID = IdType.RELATIONSHIP.getMaxValue(); private static Logger log = Logger.getLogger( EmbeddedGraphDbImpl.class.getName() ); private Transaction placeboTransaction = null; private final GraphDbInstance graphDbInstance; private final GraphDatabaseService graphDbService; private final NodeManager nodeManager; private final String storeDir; private final List<KernelEventHandler> kernelEventHandlers = new CopyOnWriteArrayList<KernelEventHandler>(); private final Collection<TransactionEventHandler<?>> transactionEventHandlers = new CopyOnWriteArraySet<TransactionEventHandler<?>>(); private final KernelPanicEventGenerator kernelPanicEventGenerator = new KernelPanicEventGenerator( kernelEventHandlers ); private final KernelData extensions; private final IndexManagerImpl indexManager; private final StringLogger msgLog; /** * A non-standard way of creating an embedded {@link GraphDatabaseService} * with a set of configuration parameters. Will most likely be removed in * future releases. * * @param storeDir the store directory for the db files * @param fileSystem * @param config configuration parameters */ public EmbeddedGraphDbImpl( Context context, String storeDir, StoreId storeId, Map<String, String> inputParams, GraphDatabaseService graphDbService, LockManagerFactory lockManagerFactory, IdGeneratorFactory idGeneratorFactory, RelationshipTypeCreator relTypeCreator, TxIdGeneratorFactory txIdFactory, TxFinishHook finishHook, LastCommittedTxIdSetter lastCommittedTxIdSetter, FileSystemAbstraction fileSystem ) { this.storeDir = storeDir; TxModule txModule = newTxModule( inputParams, finishHook ); LockManager lockManager = lockManagerFactory.create( txModule ); LockReleaser lockReleaser = new LockReleaser( lockManager, txModule.getTxManager() ); final Config config = new Config( context, graphDbService, storeDir, storeId, inputParams, kernelPanicEventGenerator, txModule, lockManager, lockReleaser, idGeneratorFactory, new SyncHookFactory(), relTypeCreator, txIdFactory.create( txModule.getTxManager() ), lastCommittedTxIdSetter, fileSystem ); /* * LogBufferFactory needs access to the parameters so it has to be added after the default and * user supplied configurations are consolidated */ config.getParams().put( LogBufferFactory.class, CommonFactories.defaultLogBufferFactory() ); graphDbInstance = new GraphDbInstance( storeDir, true, config ); this.msgLog = StringLogger.getLogger( storeDir ); this.graphDbService = graphDbService; IndexStore indexStore = graphDbInstance.getConfig().getIndexStore(); this.indexManager = new IndexManagerImpl( this, indexStore ); extensions = new KernelData() { @Override public Version version() { return Version.getKernel(); } @Override public Config getConfig() { return config; } @Override public Map<Object, Object> getConfigParams() { return config.getParams(); } @Override public GraphDatabaseService graphDatabase() { return EmbeddedGraphDbImpl.this.graphDbService; } }; boolean started = false; try { final KernelExtensionLoader extensionLoader; if ( "false".equalsIgnoreCase( inputParams.get( Config.LOAD_EXTENSIONS ) ) ) { extensionLoader = KernelExtensionLoader.DONT_LOAD; } else { extensionLoader = new KernelExtensionLoader() { private Collection<KernelExtension<?>> loaded; @Override public void configureKernelExtensions() { loaded = extensions.loadExtensionConfigurations( msgLog ); } @Override public void initializeIndexProviders() { extensions.loadIndexImplementations( indexManager, msgLog ); } @Override public void load() { extensions.loadExtensions( loaded, msgLog ); } }; } graphDbInstance.start( graphDbService, extensionLoader ); nodeManager = config.getGraphDbModule().getNodeManager(); /* * IndexManager has to exist before extensions load (so that * it is present and taken into consideration) but after * graphDbInstance is started so that there is access to the * nodeManager. In other words, the start() below has to be here. */ indexManager.start(); extensionLoader.load(); started = true; // must be last } catch ( Error cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } catch ( RuntimeException cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } finally { // If startup failed, cleanup the extensions - or they will leak if ( !started ) extensions.shutdown( msgLog ); } } private TxModule newTxModule( Map<String, String> inputParams, TxFinishHook rollbackHook ) { return Boolean.parseBoolean( inputParams.get( Config.READ_ONLY ) ) ? new TxModule( true, kernelPanicEventGenerator ) : new TxModule( this.storeDir, kernelPanicEventGenerator, rollbackHook, inputParams.get(Config.TXMANAGER_IMPLEMENTATION) ); } <T> Collection<T> getManagementBeans( Class<T> beanClass ) { KernelExtension<?> jmx = Service.load( KernelExtension.class, "kernel jmx" ); if ( jmx != null ) { Method getManagementBeans = null; Object state = jmx.getState( extensions ); if ( state != null ) { try { getManagementBeans = state.getClass().getMethod( "getManagementBeans", Class.class ); } catch ( Exception e ) { // getManagementBean will<SUF> } } if ( getManagementBeans != null ) { try { @SuppressWarnings( "unchecked" ) Collection<T> result = (Collection<T>) getManagementBeans.invoke( state, beanClass ); if ( result == null ) return Collections.emptySet(); return result; } catch ( InvocationTargetException ex ) { Throwable cause = ex.getTargetException(); if ( cause instanceof Error ) { throw (Error) cause; } if ( cause instanceof RuntimeException ) { throw (RuntimeException) cause; } } catch ( Exception ignored ) { // exception thrown below } } } throw new UnsupportedOperationException( "Neo4j JMX support not enabled" ); } /** * A non-standard Convenience method that loads a standard property file and * converts it into a generic <Code>Map<String,String></CODE>. Will most * likely be removed in future releases. * * @param file the property file to load * @return a map containing the properties from the file * @throws IllegalArgumentException if file does not exist */ public static Map<String,String> loadConfigurations( String file ) { Properties props = new Properties(); try { FileInputStream stream = new FileInputStream( new File( file ) ); try { props.load( stream ); } finally { stream.close(); } } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to load " + file, e ); } Set<Entry<Object,Object>> entries = props.entrySet(); Map<String,String> stringProps = new HashMap<String,String>(); for ( Entry<Object,Object> entry : entries ) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); stringProps.put( key, value ); } return stringProps; } public Node createNode() { return nodeManager.createNode(); } public Node getNodeById( long id ) { if ( id < 0 || id > MAX_NODE_ID ) { throw new NotFoundException( "Node[" + id + "]" ); } return nodeManager.getNodeById( id ); } public Relationship getRelationshipById( long id ) { if ( id < 0 || id > MAX_RELATIONSHIP_ID ) { throw new NotFoundException( "Relationship[" + id + "]" ); } return nodeManager.getRelationshipById( id ); } public Node getReferenceNode() { return nodeManager.getReferenceNode(); } private boolean inShutdown = false; public synchronized void shutdown() { if ( inShutdown ) return; inShutdown = true; try { if ( graphDbInstance.started() ) { try { sendShutdownEvent(); } finally { extensions.shutdown( msgLog ); } } graphDbInstance.shutdown(); } finally { inShutdown = false; } } private void sendShutdownEvent() { for ( KernelEventHandler handler : this.kernelEventHandlers ) { handler.beforeShutdown(); } } public Iterable<RelationshipType> getRelationshipTypes() { return graphDbInstance.getRelationshipTypes(); } /** * @throws TransactionFailureException if unable to start transaction */ public Transaction beginTx() { if ( graphDbInstance.transactionRunning() ) { if ( placeboTransaction == null ) { placeboTransaction = new PlaceboTransaction( graphDbInstance.getTransactionManager() ); } return placeboTransaction; } TransactionManager txManager = graphDbInstance.getTransactionManager(); Transaction result = null; try { txManager.begin(); result = new TopLevelTransaction( txManager, txManager.getTransaction() ); } catch ( Exception e ) { throw new TransactionFailureException( "Unable to begin transaction", e ); } return result; } /** * Returns a non-standard configuration object. Will most likely be removed * in future releases. * * @return a configuration object */ public Config getConfig() { return graphDbInstance.getConfig(); } @Override public String toString() { return super.toString() + " [" + storeDir + "]"; } public String getStoreDir() { return storeDir; } public Iterable<Node> getAllNodes() { return new Iterable<Node>() { @Override public Iterator<Node> iterator() { long highId = nodeManager.getHighestPossibleIdInUse( Node.class ); return new AllNodesIterator( highId ); } }; } // TODO: temporary all nodes getter, fix this with better implementation // (no NotFoundException to control flow) private class AllNodesIterator implements Iterator<Node> { private final long highId; private long currentNodeId = 0; private Node currentNode = null; AllNodesIterator( long highId ) { this.highId = highId; } @Override public synchronized boolean hasNext() { while ( currentNode == null && currentNodeId <= highId ) { try { currentNode = getNodeById( currentNodeId++ ); } catch ( NotFoundException e ) { // ok we try next } } return currentNode != null; } @Override public synchronized Node next() { if ( !hasNext() ) { throw new NoSuchElementException(); } Node nextNode = currentNode; currentNode = null; return nextNode; } @Override public void remove() { throw new UnsupportedOperationException(); } } <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { this.transactionEventHandlers.add( handler ); return handler; } <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return unregisterHandler( this.transactionEventHandlers, handler ); } KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { if ( this.kernelEventHandlers.contains( handler ) ) { return handler; } // Some algo for putting it in the right place for ( KernelEventHandler registeredHandler : this.kernelEventHandlers ) { KernelEventHandler.ExecutionOrder order = handler.orderComparedTo( registeredHandler ); int index = this.kernelEventHandlers.indexOf( registeredHandler ); if ( order == KernelEventHandler.ExecutionOrder.BEFORE ) { this.kernelEventHandlers.add( index, handler ); return handler; } else if ( order == KernelEventHandler.ExecutionOrder.AFTER ) { this.kernelEventHandlers.add( index + 1, handler ); return handler; } } this.kernelEventHandlers.add( handler ); return handler; } KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return unregisterHandler( this.kernelEventHandlers, handler ); } private <T> T unregisterHandler( Collection<?> setOfHandlers, T handler ) { if ( !setOfHandlers.remove( handler ) ) { throw new IllegalStateException( handler + " isn't registered" ); } return handler; } private class SyncHookFactory implements TxEventSyncHookFactory { @Override public TransactionEventsSyncHook create() { return transactionEventHandlers.isEmpty() ? null : new TransactionEventsSyncHook( nodeManager, transactionEventHandlers, getConfig().getTxModule().getTxManager() ); } } IndexManager index() { return this.indexManager; } KernelData getKernelData() { return extensions; } }
28735_13
package net.minecraft.client.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.util.Random; import net.minecraft.client.resources.I18n; import net.minecraft.stats.StatList; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumGameType; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.WorldInfo; import org.lwjgl.input.Keyboard; @SideOnly(Side.CLIENT) public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode = "survival"; private boolean generateStructures = true; private boolean commandsAllowed; /** True iif player has clicked buttonAllowCommands at least once */ private boolean commandsToggled; /** toggles when GUIButton 7 is pressed */ private boolean bonusItems; /** True if and only if gameMode.equals("hardcore") */ private boolean isHardcore; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton buttonGameMode; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton buttonGenerateStructures; private GuiButton buttonBonusItems; /** The GuiButton in the more world options screen. */ private GuiButton buttonWorldType; private GuiButton buttonAllowCommands; /** GuiButton in the more world options screen. */ private GuiButton buttonCustomize; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ private String localizedNewWorldText; private int worldTypeId; /** Generator options to use when creating the world. */ public String generatorOptionsToUse = ""; /** * If the world name is one of these, it'll be surrounded with underscores. */ private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public GuiCreateWorld(GuiScreen par1GuiScreen) { this.parentGuiScreen = par1GuiScreen; this.seed = ""; this.localizedNewWorldText = I18n.func_135053_a("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { this.textboxWorldName.updateCursorCounter(); this.textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.func_135053_a("selectWorld.create"))); this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.func_135053_a("gui.cancel"))); this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.func_135053_a("selectWorld.gameMode"))); this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.func_135053_a("selectWorld.moreWorldOptions"))); this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.func_135053_a("selectWorld.mapFeatures"))); this.buttonGenerateStructures.drawButton = false; this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.func_135053_a("selectWorld.bonusItems"))); this.buttonBonusItems.drawButton = false; this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.func_135053_a("selectWorld.mapType"))); this.buttonWorldType.drawButton = false; this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.func_135053_a("selectWorld.allowCommands"))); this.buttonAllowCommands.drawButton = false; this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.func_135053_a("selectWorld.customizeType"))); this.buttonCustomize.drawButton = false; this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxWorldName.setFocused(true); this.textboxWorldName.setText(this.localizedNewWorldText); this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxSeed.setText(this.seed); this.func_82288_a(this.moreOptions); this.makeUseableName(); this.updateButtonText(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { this.folderName = this.textboxWorldName.getText().trim(); char[] achar = ChatAllowedCharacters.allowedCharactersArray; int i = achar.length; for (int j = 0; j < i; ++j) { char c0 = achar[j]; this.folderName = this.folderName.replace(c0, '_'); } if (MathHelper.stringNullOrLengthZero(this.folderName)) { this.folderName = "World"; } this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName); } private void updateButtonText() { this.buttonGameMode.displayString = I18n.func_135053_a("selectWorld.gameMode") + " " + I18n.func_135053_a("selectWorld.gameMode." + this.gameMode); this.gameModeDescriptionLine1 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line1"); this.gameModeDescriptionLine2 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line2"); this.buttonGenerateStructures.displayString = I18n.func_135053_a("selectWorld.mapFeatures") + " "; if (this.generateStructures) { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.on"); } else { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.off"); } this.buttonBonusItems.displayString = I18n.func_135053_a("selectWorld.bonusItems") + " "; if (this.bonusItems && !this.isHardcore) { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.on"); } else { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.off"); } this.buttonWorldType.displayString = I18n.func_135053_a("selectWorld.mapType") + " " + I18n.func_135053_a(WorldType.worldTypes[this.worldTypeId].getTranslateName()); this.buttonAllowCommands.displayString = I18n.func_135053_a("selectWorld.allowCommands") + " "; if (this.commandsAllowed && !this.isHardcore) { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.on"); } else { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.off"); } } public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str) { par1Str = par1Str.replaceAll("[\\./\"]", "_"); String[] astring = ILLEGAL_WORLD_NAMES; int i = astring.length; for (int j = 0; j < i; ++j) { String s1 = astring[j]; if (par1Str.equalsIgnoreCase(s1)) { par1Str = "_" + par1Str + "_"; } } while (par0ISaveFormat.getWorldInfo(par1Str) != null) { par1Str = par1Str + "-"; } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 1) { this.mc.displayGuiScreen(this.parentGuiScreen); } else if (par1GuiButton.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); if (this.createClicked) { return; } this.createClicked = true; long i = (new Random()).nextLong(); String s = this.textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long j = Long.parseLong(s); if (j != 0L) { i = j; } } catch (NumberFormatException numberformatexception) { i = (long)s.hashCode(); } } WorldType.worldTypes[this.worldTypeId].onGUICreateWorldPress(); EnumGameType enumgametype = EnumGameType.getByName(this.gameMode); WorldSettings worldsettings = new WorldSettings(i, enumgametype, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]); worldsettings.func_82750_a(this.generatorOptionsToUse); if (this.bonusItems && !this.isHardcore) { worldsettings.enableBonusChest(); } if (this.commandsAllowed && !this.isHardcore) { worldsettings.enableCommands(); } this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), worldsettings); this.mc.statFileWriter.readStat(StatList.createWorldStat, 1); } else if (par1GuiButton.id == 3) { this.func_82287_i(); } else if (par1GuiButton.id == 2) { if (this.gameMode.equals("survival")) { if (!this.commandsToggled) { this.commandsAllowed = false; } this.isHardcore = false; this.gameMode = "hardcore"; this.isHardcore = true; this.buttonAllowCommands.enabled = false; this.buttonBonusItems.enabled = false; this.updateButtonText(); } else if (this.gameMode.equals("hardcore")) { if (!this.commandsToggled) { this.commandsAllowed = true; } this.isHardcore = false; this.gameMode = "creative"; this.updateButtonText(); this.isHardcore = false; this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; } else { if (!this.commandsToggled) { this.commandsAllowed = false; } this.gameMode = "survival"; this.updateButtonText(); this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; this.isHardcore = false; } this.updateButtonText(); } else if (par1GuiButton.id == 4) { this.generateStructures = !this.generateStructures; this.updateButtonText(); } else if (par1GuiButton.id == 7) { this.bonusItems = !this.bonusItems; this.updateButtonText(); } else if (par1GuiButton.id == 5) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated()) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } } this.generatorOptionsToUse = ""; this.updateButtonText(); this.func_82288_a(this.moreOptions); } else if (par1GuiButton.id == 6) { this.commandsToggled = true; this.commandsAllowed = !this.commandsAllowed; this.updateButtonText(); } else if (par1GuiButton.id == 8) { WorldType.worldTypes[this.worldTypeId].onCustomizeButton(this.mc, this); } } } private void func_82287_i() { this.func_82288_a(!this.moreOptions); } private void func_82288_a(boolean par1) { this.moreOptions = par1; this.buttonGameMode.drawButton = !this.moreOptions; this.buttonGenerateStructures.drawButton = this.moreOptions; this.buttonBonusItems.drawButton = this.moreOptions; this.buttonWorldType.drawButton = this.moreOptions; this.buttonAllowCommands.drawButton = this.moreOptions; this.buttonCustomize.drawButton = this.moreOptions && (WorldType.worldTypes[this.worldTypeId].isCustomizable()); if (this.moreOptions) { this.moreWorldOptions.displayString = I18n.func_135053_a("gui.done"); } else { this.moreWorldOptions.displayString = I18n.func_135053_a("selectWorld.moreWorldOptions"); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (this.textboxWorldName.isFocused() && !this.moreOptions) { this.textboxWorldName.textboxKeyTyped(par1, par2); this.localizedNewWorldText = this.textboxWorldName.getText(); } else if (this.textboxSeed.isFocused() && this.moreOptions) { this.textboxSeed.textboxKeyTyped(par1, par2); this.seed = this.textboxSeed.getText(); } if (par2 == 28 || par2 == 156) { this.actionPerformed((GuiButton)this.buttonList.get(0)); } ((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0; this.makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (this.moreOptions) { this.textboxSeed.mouseClicked(par1, par2, par3); } else { this.textboxWorldName.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRenderer, I18n.func_135053_a("selectWorld.create"), this.width / 2, 20, 16777215); if (this.moreOptions) { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880); this.textboxSeed.drawTextBox(); } else { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880); this.textboxWorldName.drawTextBox(); this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880); this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880); } super.drawScreen(par1, par2, par3); } public void func_82286_a(WorldInfo par1WorldInfo) { this.localizedNewWorldText = I18n.func_135052_a("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()}); this.seed = par1WorldInfo.getSeed() + ""; this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID(); this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions(); this.generateStructures = par1WorldInfo.isMapFeaturesEnabled(); this.commandsAllowed = par1WorldInfo.areCommandsAllowed(); if (par1WorldInfo.isHardcoreModeEnabled()) { this.gameMode = "hardcore"; } else if (par1WorldInfo.getGameType().isSurvivalOrAdventure()) { this.gameMode = "survival"; } else if (par1WorldInfo.getGameType().isCreative()) { this.gameMode = "creative"; } } }
shawndeprey/bms
net/minecraft/client/gui/GuiCreateWorld.java
6,074
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
block_comment
nl
package net.minecraft.client.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.util.Random; import net.minecraft.client.resources.I18n; import net.minecraft.stats.StatList; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumGameType; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.WorldInfo; import org.lwjgl.input.Keyboard; @SideOnly(Side.CLIENT) public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode = "survival"; private boolean generateStructures = true; private boolean commandsAllowed; /** True iif player has clicked buttonAllowCommands at least once */ private boolean commandsToggled; /** toggles when GUIButton 7 is pressed */ private boolean bonusItems; /** True if and only if gameMode.equals("hardcore") */ private boolean isHardcore; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton buttonGameMode; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton buttonGenerateStructures; private GuiButton buttonBonusItems; /** The GuiButton in the more world options screen. */ private GuiButton buttonWorldType; private GuiButton buttonAllowCommands; /** GuiButton in the more world options screen. */ private GuiButton buttonCustomize; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World,<SUF>*/ private String localizedNewWorldText; private int worldTypeId; /** Generator options to use when creating the world. */ public String generatorOptionsToUse = ""; /** * If the world name is one of these, it'll be surrounded with underscores. */ private static final String[] ILLEGAL_WORLD_NAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public GuiCreateWorld(GuiScreen par1GuiScreen) { this.parentGuiScreen = par1GuiScreen; this.seed = ""; this.localizedNewWorldText = I18n.func_135053_a("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { this.textboxWorldName.updateCursorCounter(); this.textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.func_135053_a("selectWorld.create"))); this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.func_135053_a("gui.cancel"))); this.buttonList.add(this.buttonGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.func_135053_a("selectWorld.gameMode"))); this.buttonList.add(this.moreWorldOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.func_135053_a("selectWorld.moreWorldOptions"))); this.buttonList.add(this.buttonGenerateStructures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.func_135053_a("selectWorld.mapFeatures"))); this.buttonGenerateStructures.drawButton = false; this.buttonList.add(this.buttonBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.func_135053_a("selectWorld.bonusItems"))); this.buttonBonusItems.drawButton = false; this.buttonList.add(this.buttonWorldType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.func_135053_a("selectWorld.mapType"))); this.buttonWorldType.drawButton = false; this.buttonList.add(this.buttonAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.func_135053_a("selectWorld.allowCommands"))); this.buttonAllowCommands.drawButton = false; this.buttonList.add(this.buttonCustomize = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.func_135053_a("selectWorld.customizeType"))); this.buttonCustomize.drawButton = false; this.textboxWorldName = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxWorldName.setFocused(true); this.textboxWorldName.setText(this.localizedNewWorldText); this.textboxSeed = new GuiTextField(this.fontRenderer, this.width / 2 - 100, 60, 200, 20); this.textboxSeed.setText(this.seed); this.func_82288_a(this.moreOptions); this.makeUseableName(); this.updateButtonText(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { this.folderName = this.textboxWorldName.getText().trim(); char[] achar = ChatAllowedCharacters.allowedCharactersArray; int i = achar.length; for (int j = 0; j < i; ++j) { char c0 = achar[j]; this.folderName = this.folderName.replace(c0, '_'); } if (MathHelper.stringNullOrLengthZero(this.folderName)) { this.folderName = "World"; } this.folderName = func_73913_a(this.mc.getSaveLoader(), this.folderName); } private void updateButtonText() { this.buttonGameMode.displayString = I18n.func_135053_a("selectWorld.gameMode") + " " + I18n.func_135053_a("selectWorld.gameMode." + this.gameMode); this.gameModeDescriptionLine1 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line1"); this.gameModeDescriptionLine2 = I18n.func_135053_a("selectWorld.gameMode." + this.gameMode + ".line2"); this.buttonGenerateStructures.displayString = I18n.func_135053_a("selectWorld.mapFeatures") + " "; if (this.generateStructures) { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.on"); } else { this.buttonGenerateStructures.displayString = this.buttonGenerateStructures.displayString + I18n.func_135053_a("options.off"); } this.buttonBonusItems.displayString = I18n.func_135053_a("selectWorld.bonusItems") + " "; if (this.bonusItems && !this.isHardcore) { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.on"); } else { this.buttonBonusItems.displayString = this.buttonBonusItems.displayString + I18n.func_135053_a("options.off"); } this.buttonWorldType.displayString = I18n.func_135053_a("selectWorld.mapType") + " " + I18n.func_135053_a(WorldType.worldTypes[this.worldTypeId].getTranslateName()); this.buttonAllowCommands.displayString = I18n.func_135053_a("selectWorld.allowCommands") + " "; if (this.commandsAllowed && !this.isHardcore) { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.on"); } else { this.buttonAllowCommands.displayString = this.buttonAllowCommands.displayString + I18n.func_135053_a("options.off"); } } public static String func_73913_a(ISaveFormat par0ISaveFormat, String par1Str) { par1Str = par1Str.replaceAll("[\\./\"]", "_"); String[] astring = ILLEGAL_WORLD_NAMES; int i = astring.length; for (int j = 0; j < i; ++j) { String s1 = astring[j]; if (par1Str.equalsIgnoreCase(s1)) { par1Str = "_" + par1Str + "_"; } } while (par0ISaveFormat.getWorldInfo(par1Str) != null) { par1Str = par1Str + "-"; } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 1) { this.mc.displayGuiScreen(this.parentGuiScreen); } else if (par1GuiButton.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); if (this.createClicked) { return; } this.createClicked = true; long i = (new Random()).nextLong(); String s = this.textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long j = Long.parseLong(s); if (j != 0L) { i = j; } } catch (NumberFormatException numberformatexception) { i = (long)s.hashCode(); } } WorldType.worldTypes[this.worldTypeId].onGUICreateWorldPress(); EnumGameType enumgametype = EnumGameType.getByName(this.gameMode); WorldSettings worldsettings = new WorldSettings(i, enumgametype, this.generateStructures, this.isHardcore, WorldType.worldTypes[this.worldTypeId]); worldsettings.func_82750_a(this.generatorOptionsToUse); if (this.bonusItems && !this.isHardcore) { worldsettings.enableBonusChest(); } if (this.commandsAllowed && !this.isHardcore) { worldsettings.enableCommands(); } this.mc.launchIntegratedServer(this.folderName, this.textboxWorldName.getText().trim(), worldsettings); this.mc.statFileWriter.readStat(StatList.createWorldStat, 1); } else if (par1GuiButton.id == 3) { this.func_82287_i(); } else if (par1GuiButton.id == 2) { if (this.gameMode.equals("survival")) { if (!this.commandsToggled) { this.commandsAllowed = false; } this.isHardcore = false; this.gameMode = "hardcore"; this.isHardcore = true; this.buttonAllowCommands.enabled = false; this.buttonBonusItems.enabled = false; this.updateButtonText(); } else if (this.gameMode.equals("hardcore")) { if (!this.commandsToggled) { this.commandsAllowed = true; } this.isHardcore = false; this.gameMode = "creative"; this.updateButtonText(); this.isHardcore = false; this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; } else { if (!this.commandsToggled) { this.commandsAllowed = false; } this.gameMode = "survival"; this.updateButtonText(); this.buttonAllowCommands.enabled = true; this.buttonBonusItems.enabled = true; this.isHardcore = false; } this.updateButtonText(); } else if (par1GuiButton.id == 4) { this.generateStructures = !this.generateStructures; this.updateButtonText(); } else if (par1GuiButton.id == 7) { this.bonusItems = !this.bonusItems; this.updateButtonText(); } else if (par1GuiButton.id == 5) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } while (WorldType.worldTypes[this.worldTypeId] == null || !WorldType.worldTypes[this.worldTypeId].getCanBeCreated()) { ++this.worldTypeId; if (this.worldTypeId >= WorldType.worldTypes.length) { this.worldTypeId = 0; } } this.generatorOptionsToUse = ""; this.updateButtonText(); this.func_82288_a(this.moreOptions); } else if (par1GuiButton.id == 6) { this.commandsToggled = true; this.commandsAllowed = !this.commandsAllowed; this.updateButtonText(); } else if (par1GuiButton.id == 8) { WorldType.worldTypes[this.worldTypeId].onCustomizeButton(this.mc, this); } } } private void func_82287_i() { this.func_82288_a(!this.moreOptions); } private void func_82288_a(boolean par1) { this.moreOptions = par1; this.buttonGameMode.drawButton = !this.moreOptions; this.buttonGenerateStructures.drawButton = this.moreOptions; this.buttonBonusItems.drawButton = this.moreOptions; this.buttonWorldType.drawButton = this.moreOptions; this.buttonAllowCommands.drawButton = this.moreOptions; this.buttonCustomize.drawButton = this.moreOptions && (WorldType.worldTypes[this.worldTypeId].isCustomizable()); if (this.moreOptions) { this.moreWorldOptions.displayString = I18n.func_135053_a("gui.done"); } else { this.moreWorldOptions.displayString = I18n.func_135053_a("selectWorld.moreWorldOptions"); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (this.textboxWorldName.isFocused() && !this.moreOptions) { this.textboxWorldName.textboxKeyTyped(par1, par2); this.localizedNewWorldText = this.textboxWorldName.getText(); } else if (this.textboxSeed.isFocused() && this.moreOptions) { this.textboxSeed.textboxKeyTyped(par1, par2); this.seed = this.textboxSeed.getText(); } if (par2 == 28 || par2 == 156) { this.actionPerformed((GuiButton)this.buttonList.get(0)); } ((GuiButton)this.buttonList.get(0)).enabled = this.textboxWorldName.getText().length() > 0; this.makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (this.moreOptions) { this.textboxSeed.mouseClicked(par1, par2, par3); } else { this.textboxWorldName.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRenderer, I18n.func_135053_a("selectWorld.create"), this.width / 2, 20, 16777215); if (this.moreOptions) { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterSeed"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.seedInfo"), this.width / 2 - 100, 85, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.mapFeatures.info"), this.width / 2 - 150, 122, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.allowCommands.info"), this.width / 2 - 150, 172, 10526880); this.textboxSeed.drawTextBox(); } else { this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.enterName"), this.width / 2 - 100, 47, 10526880); this.drawString(this.fontRenderer, I18n.func_135053_a("selectWorld.resultFolder") + " " + this.folderName, this.width / 2 - 100, 85, 10526880); this.textboxWorldName.drawTextBox(); this.drawString(this.fontRenderer, this.gameModeDescriptionLine1, this.width / 2 - 100, 137, 10526880); this.drawString(this.fontRenderer, this.gameModeDescriptionLine2, this.width / 2 - 100, 149, 10526880); } super.drawScreen(par1, par2, par3); } public void func_82286_a(WorldInfo par1WorldInfo) { this.localizedNewWorldText = I18n.func_135052_a("selectWorld.newWorld.copyOf", new Object[] {par1WorldInfo.getWorldName()}); this.seed = par1WorldInfo.getSeed() + ""; this.worldTypeId = par1WorldInfo.getTerrainType().getWorldTypeID(); this.generatorOptionsToUse = par1WorldInfo.getGeneratorOptions(); this.generateStructures = par1WorldInfo.isMapFeaturesEnabled(); this.commandsAllowed = par1WorldInfo.areCommandsAllowed(); if (par1WorldInfo.isHardcoreModeEnabled()) { this.gameMode = "hardcore"; } else if (par1WorldInfo.getGameType().isSurvivalOrAdventure()) { this.gameMode = "survival"; } else if (par1WorldInfo.getGameType().isCreative()) { this.gameMode = "creative"; } } }