index
int64
0
4.83k
file_id
stringlengths
5
10
content
stringlengths
110
32.8k
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
32.8k
Inclusion
stringclasses
4 values
2,188
73378_4
package staticfactory; import java.util.ArrayList; import java.util.Iterator; // instance controlled class public class ManagedResource { static ArrayList<ManagedResource> instances = new ArrayList<>(); static final int MAX_POOL_SIZE = 10; private ManagedResource () { System.out.println("Creating managed resource number " +instances.size()); } private boolean isReady() { System.out.println("Checking whether this resource is ready."); if (Math.random() < .5) { System.out.println("Resource busy; try again later."); return false; } else { System.out.println("Resource ready to be used again."); return true; } } static ManagedResource getInstance() { // eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn. if (instances.size()<=MAX_POOL_SIZE) { ManagedResource foo = new ManagedResource(); instances.add(foo); return foo; } // in het andere geval zou je iets moeten doen met // lock and wait; en geef je de eerste instantie terug die niets te doen heeft // (dit is uiteraard een slechts realisatie, alleen voor de demonstratie) boolean found = false; ManagedResource tmp=null;; while (!found) { Iterator<ManagedResource> itr = instances.iterator(); while(itr.hasNext()) { tmp = itr.next(); if (tmp.isReady()) { found = true; break; } } } return tmp; } }
bart314/practicum.2.3
week4/staticfactory/ManagedResource.java
433
// (dit is uiteraard een slechts realisatie, alleen voor de demonstratie)
line_comment
nl
package staticfactory; import java.util.ArrayList; import java.util.Iterator; // instance controlled class public class ManagedResource { static ArrayList<ManagedResource> instances = new ArrayList<>(); static final int MAX_POOL_SIZE = 10; private ManagedResource () { System.out.println("Creating managed resource number " +instances.size()); } private boolean isReady() { System.out.println("Checking whether this resource is ready."); if (Math.random() < .5) { System.out.println("Resource busy; try again later."); return false; } else { System.out.println("Resource ready to be used again."); return true; } } static ManagedResource getInstance() { // eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn. if (instances.size()<=MAX_POOL_SIZE) { ManagedResource foo = new ManagedResource(); instances.add(foo); return foo; } // in het andere geval zou je iets moeten doen met // lock and wait; en geef je de eerste instantie terug die niets te doen heeft // (dit is<SUF> boolean found = false; ManagedResource tmp=null;; while (!found) { Iterator<ManagedResource> itr = instances.iterator(); while(itr.hasNext()) { tmp = itr.next(); if (tmp.isReady()) { found = true; break; } } } return tmp; } }
False
1,030
172967_3
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP
Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java
367
// wacht tot alle bitmaps geladen zijn
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot<SUF> } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
True
447
41675_17
/**_x000D_ * EGroupware - Notifications Java Desktop App_x000D_ *_x000D_ * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License_x000D_ * @package notifications_x000D_ * @subpackage jdesk_x000D_ * @link http://www.egroupware.org_x000D_ * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>_x000D_ * @author Maik Hüttner <maik.huettner@hw-softwareentwicklung.de>_x000D_ */_x000D_ _x000D_ package egroupwaretray;_x000D_ _x000D_ import java.awt.event.ActionListener;_x000D_ import java.net.InetAddress;_x000D_ import java.util.*;_x000D_ import java.util.logging.Level;_x000D_ import org.json.simple.parser.ContainerFactory;_x000D_ import org.json.simple.parser.JSONParser;_x000D_ import org.json.simple.parser.ParseException;_x000D_ _x000D_ /**_x000D_ * jegwhttp_x000D_ * _x000D_ * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>_x000D_ */_x000D_ public class jegwhttp_x000D_ {_x000D_ public static final String EGWHTTP_INDEXSCRIPT = "index.php";_x000D_ public static final String EGWHTTP_LOGINSCRIPT = "login.php";_x000D_ public static final String EGWHTTP_LOGOUTSCRIPT = "logout.php";_x000D_ public static final String EGWHTTP_TRAYMODUL = "egwnotifier/index.php";_x000D_ public static final String EGWHTTP_TRAYLOGIN = "notifierlogin.php";_x000D_ public static final String EGWHTTP_LOGINLINK = "login.php?cd=";_x000D_ _x000D_ public static final String EGWHTTP_POST_VAR_PASSWORD_TYPE = "passwd_type";_x000D_ public static final String EGWHTTP_POST_VAR_ACCOUNT_TYPE = "account_type";_x000D_ public static final String EGWHTTP_POST_VAR_LOGINDOMAIN = "logindomain";_x000D_ _x000D_ public static final String EGWHTTP_POST_VAR_LOGIN = "login";_x000D_ public static final String EGWHTTP_POST_VAR_PASSWD = "passwd";_x000D_ public static final String EGWHTTP_POST_VAR_SUBMITIT = "submitit";_x000D_ _x000D_ public static final String EGWHTTP_POST_PASSWORD_TYPE_TEXT = "text";_x000D_ public static final String EGWHTTP_POST_ACCOUNT_TYPE_U = "u";_x000D_ public static final String EGWHTTP_POST_LOGINDOMAIN_DEFAULT = "default";_x000D_ public static final String EGWHTTP_POST_SUBMITIT = "++Anmelden++";_x000D_ _x000D_ public static final String EGWHTTP_TAG_SECURITYID = "egwcheckid";_x000D_ _x000D_ public static final String EGWHTTP_GET_VAR_MAKE_SECURITYID = "makecheck";_x000D_ public static final String EGWHTTP_GET_VAR_SECURITYID = "checkid";_x000D_ public static final String EGWHTTP_GET_MAKE_SECURITYID = "1";_x000D_ public static final String EGWHTTP_GET_PHPGW_FORWARD = "phpgw_forward";_x000D_ _x000D_ // new EPL Notifications_x000D_ public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION = _x000D_ "json.php?menuaction=notifications.notifications_jdesk_ajax.get_notifications";_x000D_ _x000D_ // new EPL Notifications_x000D_ public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM = _x000D_ "json.php?menuaction=notifications.notifications_jdesk_ajax.confirm_message";_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_COOKIE = new String[]{_x000D_ "sessionid", "kp3", "last_loginid", "last_domain", "domain"};_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_APP = new String[]{_x000D_ "name", "title", "infotext", "variables", "appdialogtext" };_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_NOTIFY = new String[]{_x000D_ "app", "title", "msghtml", "link", "notify_id" };_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_APP_VAR = new String[]{_x000D_ "vname", "value", "vtype" };_x000D_ _x000D_ private BaseHttp httpcon = new BaseHttp();_x000D_ private Boolean loginstatus = false;_x000D_ _x000D_ public jegwhttp(ActionListener lister) {_x000D_ _x000D_ this.httpcon.setSocketTimeOut(_x000D_ Integer.parseInt(_x000D_ jegwConst.getConstTag("egw_dc_timeout_socket")));_x000D_ }_x000D_ _x000D_ /**_x000D_ * CheckDir_x000D_ * Überprüft ob hinten ein String (wie bei Verzeichnisen mit "/" abschließt),_x000D_ * wenn nicht wird dieser hinten drangesetzt und der String zurück geben_x000D_ *_x000D_ * @param dir_x000D_ * @return_x000D_ */_x000D_ static public String checkDir(String dir)_x000D_ {_x000D_ if(dir.length() > 0)_x000D_ {_x000D_ if(dir.charAt(dir.length()-1) != "/".charAt(0) )_x000D_ {_x000D_ dir = dir + "/";_x000D_ }_x000D_ }_x000D_ _x000D_ return dir;_x000D_ }_x000D_ _x000D_ public void egwUrlLinkParser(KeyArray Config) throws Exception_x000D_ {_x000D_ String url = Config.getString("egwurl");_x000D_ _x000D_ boolean ssl = false;_x000D_ _x000D_ if( url.indexOf("https://") > -1 )_x000D_ {_x000D_ ssl = true;_x000D_ url = url.replaceAll("https://", "");_x000D_ }_x000D_ else_x000D_ {_x000D_ url = url.replaceAll("http://", "");_x000D_ }_x000D_ _x000D_ if( url.length() == 0 )_x000D_ {_x000D_ throw new Exception("NOURL");_x000D_ }_x000D_ _x000D_ String[] tmp = url.split("/");_x000D_ _x000D_ String host = tmp[0];_x000D_ String port = "";_x000D_ String paht = "";_x000D_ _x000D_ if( tmp[0].indexOf(":") != -1 )_x000D_ {_x000D_ String[] ttmp = tmp[0].split(":");_x000D_ host = ttmp[0];_x000D_ port = ttmp[1];_x000D_ }_x000D_ _x000D_ /**_x000D_ * Host auflösen_x000D_ */_x000D_ try_x000D_ {_x000D_ InetAddress addr = InetAddress.getByName(host);_x000D_ }_x000D_ catch( Exception exp)_x000D_ {_x000D_ egwDebuging.log.log(Level.SEVERE, null, exp);_x000D_ throw new Exception("HOSTNOTFOUND");_x000D_ }_x000D_ _x000D_ for( int i=1; i<tmp.length; i++ )_x000D_ {_x000D_ paht = paht + tmp[i] + "/";_x000D_ }_x000D_ _x000D_ /*if( paht.length() == 0 )_x000D_ {_x000D_ paht = "/";_x000D_ }*/_x000D_ _x000D_ Config.add("host", host);_x000D_ _x000D_ if( port.length() != 0 )_x000D_ {_x000D_ Config.add("port", port);_x000D_ }_x000D_ _x000D_ Config.add("subdir", paht);_x000D_ Config.add("ssl", ssl);_x000D_ _x000D_ /**_x000D_ * SSL Enable_x000D_ */_x000D_ this.httpcon.setIsSSL(ssl);_x000D_ _x000D_ if( port.length() != 0 )_x000D_ {_x000D_ host = host + ":" + port;_x000D_ }_x000D_ _x000D_ String moved = this.httpcon.isHostMoved(host, "/" + paht);_x000D_ _x000D_ if( !moved.equals("") )_x000D_ {_x000D_ Config.add("egwurl", moved);_x000D_ this.egwUrlLinkParser(Config);_x000D_ }_x000D_ }_x000D_ _x000D_ public String[] getEgwLoginDomains(KeyArray Config) throws Exception_x000D_ {_x000D_ this.egwUrlLinkParser(Config);_x000D_ _x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ /**_x000D_ * Hidden Logindomain_x000D_ */_x000D_ int begin = -1;_x000D_ int end = -1;_x000D_ String search = "<input type=\"hidden\" name=\"logindomain\" value=\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("\"", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ return new String[]{tmp};_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Select Logindomain_x000D_ */_x000D_ _x000D_ begin = -1;_x000D_ end = -1;_x000D_ search = "<select name=\"logindomain\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("</select>", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ tmp = tmp.trim();_x000D_ _x000D_ String ltmp[] = tmp.split("</option>");_x000D_ String treturn[] = new String[ltmp.length];_x000D_ _x000D_ for( int i=0; i<ltmp.length; i++ )_x000D_ {_x000D_ String tbuffer = ltmp[i];_x000D_ String tsearch = "value=\"";_x000D_ _x000D_ int tbegin = -1;_x000D_ int tend = -1; _x000D_ _x000D_ if( (tbegin = tbuffer.indexOf(tsearch)) > -1 )_x000D_ {_x000D_ tend = tbuffer.indexOf("\"", tbegin + tsearch.length());_x000D_ _x000D_ if( (begin != -1) && (tend != -1) )_x000D_ {_x000D_ String ttmp = tbuffer.substring( tbegin +_x000D_ tsearch.length(), tend);_x000D_ _x000D_ treturn[i] = ttmp;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return treturn;_x000D_ }_x000D_ }_x000D_ _x000D_ return null;_x000D_ }_x000D_ _x000D_ public void egwCheckLoginDomains(KeyArray Config) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ /**_x000D_ * Hidden Logindomain_x000D_ */_x000D_ int begin = -1;_x000D_ int end = -1;_x000D_ String search = "<input type=\"hidden\" name=\"logindomain\" value=\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("\"", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ Config.add("logindomain", tmp);_x000D_ _x000D_ return;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Select Logindomain_x000D_ */_x000D_ _x000D_ begin = -1;_x000D_ end = -1;_x000D_ search = "<select name=\"logindomain\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("</select>", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ System.out.println(tmp);_x000D_ }_x000D_ }_x000D_ _x000D_ //Config.Add("logindomain", EGWHTTP_POST_LOGINDOMAIN_DEFAULT);_x000D_ Config.add("logindomain", urlhost);_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwLogin_x000D_ * logt sich im eGroupware ein mit den Benutzerdaten aus einer Config_x000D_ * und gibt den Cookieinhalt zurück_x000D_ *_x000D_ * @param Config Konfigurations Einstellungen_x000D_ * @return Cookieinhalt_x000D_ */_x000D_ public KeyArray egwLogin(KeyArray Config) throws Exception_x000D_ {_x000D_ this.egwUrlLinkParser(Config);_x000D_ //this.egwCheckLoginDomains(Config);_x000D_ _x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String urlpost = EGWHTTP_POST_VAR_PASSWORD_TYPE + "=" +_x000D_ EGWHTTP_POST_PASSWORD_TYPE_TEXT + "&" + EGWHTTP_POST_VAR_ACCOUNT_TYPE +_x000D_ "=" + EGWHTTP_POST_ACCOUNT_TYPE_U + "&" + EGWHTTP_POST_VAR_LOGINDOMAIN +_x000D_ "=" + Config.getString("logindomain") + "&" + EGWHTTP_POST_VAR_LOGIN +_x000D_ "=" + Config.getString("user") + "&" + EGWHTTP_POST_VAR_PASSWD + "=" +_x000D_ Config.getString("password") + "&" + EGWHTTP_POST_VAR_SUBMITIT + "=" +_x000D_ EGWHTTP_POST_SUBMITIT;_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSitePost(urlhost + urllink, urlpost);_x000D_ _x000D_ if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }_x000D_ _x000D_ if( this.httpcon.isNotFound() )_x000D_ {_x000D_ throw new Exception("PAGENOTFOUND");_x000D_ }_x000D_ _x000D_ int status = this.egwCheckLoginStatus();_x000D_ _x000D_ if( status > -1 )_x000D_ {_x000D_ throw new Exception("LOGIN:" + Integer.toString(status));_x000D_ }_x000D_ _x000D_ KeyArray egwcookie = new KeyArray(EGWHTTP_EGW_COOKIE);_x000D_ String[] keys = egwcookie.getKeys();_x000D_ _x000D_ for( int i=0; i<keys.length; i++ )_x000D_ {_x000D_ String value = this.httpcon.getSocketHeaderField(this.httpcon.getCookie(), keys[i]);_x000D_ _x000D_ if( value.length() == 0 )_x000D_ {_x000D_ // Login fehlgeschlagen_x000D_ return null;_x000D_ }_x000D_ _x000D_ egwcookie.add(keys[i], value);_x000D_ }_x000D_ _x000D_ this.loginstatus = true;_x000D_ return egwcookie;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwIsLogin_x000D_ * Überprüft ob eine egw Benutzer noch angemeldet ist_x000D_ *_x000D_ * @param buffer Rückgabe eines HTTP aufrufes muss hier angeben werden,_x000D_ * der Inhalt würd dann drauf überprüft_x000D_ * @param cookie Cookie Informationen zum Überprüfen_x000D_ * @return true = noch Angemeldet, false = nicht mehr Angemeldet_x000D_ */_x000D_ private boolean egwIsLogin(KeyArray cookie)_x000D_ {_x000D_ String sess = this.httpcon.getCookieVariable(this.httpcon.getCookie(), "sessionid");_x000D_ String location = this.httpcon.getLocation();_x000D_ _x000D_ if( sess.length() > 0 )_x000D_ {_x000D_ if( sess.compareTo(cookie.getString("sessionid")) != 0 )_x000D_ {_x000D_ this.loginstatus = false;_x000D_ return false;_x000D_ }_x000D_ }_x000D_ else if( (location != null) && (location.indexOf("login.php") != -1) )_x000D_ {_x000D_ this.loginstatus = false;_x000D_ return false;_x000D_ }_x000D_ _x000D_ this.loginstatus = true;_x000D_ return true;_x000D_ }_x000D_ _x000D_ private int egwCheckLoginStatus()_x000D_ {_x000D_ String back = "";_x000D_ String buffer = this.httpcon.getLocation();_x000D_ _x000D_ if( buffer == null )_x000D_ {_x000D_ buffer = "";_x000D_ }_x000D_ _x000D_ int pos = buffer.indexOf(jegwhttp.EGWHTTP_LOGINLINK);_x000D_ int end = buffer.length();_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buffer.substring( pos +_x000D_ jegwhttp.EGWHTTP_LOGINLINK.length(), end);_x000D_ }_x000D_ else if( (buffer.indexOf("http://") != -1) || (buffer.indexOf("https://") != -1) )_x000D_ {_x000D_ if( buffer.indexOf("index.php?cd=yes") == -1 )_x000D_ {_x000D_ return 999;_x000D_ }_x000D_ else_x000D_ {_x000D_ return -1;_x000D_ }_x000D_ }_x000D_ else_x000D_ {_x000D_ return -1;_x000D_ }_x000D_ _x000D_ return Integer.valueOf(back).intValue();_x000D_ }_x000D_ _x000D_ public boolean egwIsEGWLogin()_x000D_ {_x000D_ return this.loginstatus;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetTagValue_x000D_ * Sucht Inhalte erraus (nach der notation vom html/xml)_x000D_ *_x000D_ * @param buff HTTP Inhalt_x000D_ * @param tag Inhalt umschließer_x000D_ * @return Inhalt_x000D_ */_x000D_ private String egwGetTagValue(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( pos + tag.length() +2, end);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ private String egwGetTagValueWithTag(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( pos, end + tag.length() +3);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ private String egwGetNoneTagText(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( 0, pos);_x000D_ back = back + buff.substring( end + tag.length() +3, buff.length()-1);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetEGWCookieStr_x000D_ * erstellt den Cookie String aus dem cookie(Array)_x000D_ *_x000D_ * @param cookie_x000D_ * @return_x000D_ */_x000D_ private String egwGetEGWCookieStr(KeyArray cookie)_x000D_ {_x000D_ String cookiestr = "";_x000D_ _x000D_ String[] keys = cookie.getKeys();_x000D_ _x000D_ for( int i=0; i<cookie.size(); i++ )_x000D_ {_x000D_ String tmp = keys[i] + "=" + cookie.getString(keys[i]) + ";";_x000D_ _x000D_ if(cookiestr.length() == 0)_x000D_ {_x000D_ cookiestr = cookiestr + tmp;_x000D_ }_x000D_ else_x000D_ {_x000D_ cookiestr = cookiestr + " " + tmp;_x000D_ }_x000D_ }_x000D_ _x000D_ cookiestr = cookiestr + " storedlang=de; last_loginid=; last_domain=default; ConfigLang=de";_x000D_ _x000D_ return cookiestr;_x000D_ }_x000D_ _x000D_ public ArrayList egwLoadEGWData(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ ArrayList msglist = new ArrayList();_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_GET_NOTIFICATIONS_ACTION;_x000D_ _x000D_ this.httpcon.setIsAjax(true);_x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ String buffer = this.httpcon.openHttpContentSitePost(_x000D_ urlhost + urllink, _x000D_ "json_data={\"request\":{\"parameters\":[null]}}"_x000D_ );_x000D_ _x000D_ this.httpcon.setIsAjax(false);_x000D_ _x000D_ /**_x000D_ * Fehler Behandlung_x000D_ */_x000D_ /*if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }*/_x000D_ _x000D_ if( this.egwIsLogin(cookie) )_x000D_ {_x000D_ int status = this.egwCheckLoginStatus();_x000D_ _x000D_ if( status > -1 )_x000D_ {_x000D_ throw new Exception("LOGIN:" + Integer.toString(status));_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Check auf Rechte (Permission denied!)_x000D_ */_x000D_ String permission = "<title>Permission denied!</title>";_x000D_ _x000D_ if( buffer.indexOf(permission) > -1 )_x000D_ {_x000D_ throw new Exception("PERMISSIONDENIED");_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * JSON_x000D_ */_x000D_ _x000D_ JSONParser parser = new JSONParser();_x000D_ ContainerFactory containerFactory = new ContainerFactory(){_x000D_ public List creatArrayContainer() {_x000D_ return new LinkedList();_x000D_ }_x000D_ _x000D_ public Map createObjectContainer() {_x000D_ return new LinkedHashMap();_x000D_ }_x000D_ };_x000D_ _x000D_ try _x000D_ {_x000D_ Map json = (Map)parser.parse(buffer.trim(), containerFactory);_x000D_ Iterator iter = json.entrySet().iterator();_x000D_ _x000D_ while( iter.hasNext() )_x000D_ {_x000D_ Map.Entry entry = (Map.Entry)iter.next();_x000D_ _x000D_ if( entry.getKey().toString().compareTo("response") == 0 )_x000D_ {_x000D_ LinkedList response = (LinkedList) entry.getValue();_x000D_ _x000D_ for( Integer i=0; i<response.size(); i++ )_x000D_ {_x000D_ Map jmsg = (Map) response.get(i);_x000D_ Iterator jmsgiter = jmsg.entrySet().iterator();_x000D_ _x000D_ while( jmsgiter.hasNext() )_x000D_ {_x000D_ Map.Entry jmsgentry = (Map.Entry)jmsgiter.next();_x000D_ _x000D_ if( (jmsgentry.getKey().toString().compareTo("type") == 0) &&_x000D_ (jmsgentry.getValue().toString().compareTo("data") == 0) && _x000D_ jmsgiter.hasNext() )_x000D_ {_x000D_ jmsgentry = (Map.Entry)jmsgiter.next();_x000D_ _x000D_ if( jmsgentry.getKey().toString().compareTo("data") == 0 )_x000D_ {_x000D_ KeyArray notifymsg = new KeyArray(EGWHTTP_EGW_NOTIFY);_x000D_ _x000D_ Map msgdata = (Map) jmsgentry.getValue();_x000D_ Iterator dataiter = msgdata.entrySet().iterator();_x000D_ _x000D_ while( dataiter.hasNext() )_x000D_ {_x000D_ Map.Entry dataentry = (Map.Entry)dataiter.next();_x000D_ String tkey = dataentry.getKey().toString();_x000D_ Object tovalue = dataentry.getValue(); _x000D_ _x000D_ String tvalue = "";_x000D_ _x000D_ if( tovalue != null )_x000D_ {_x000D_ tvalue = tovalue.toString();_x000D_ }_x000D_ _x000D_ if( notifymsg.existKey(tkey) )_x000D_ {_x000D_ notifymsg.add(tkey, tvalue);_x000D_ }_x000D_ }_x000D_ _x000D_ if( notifymsg.get("notify_id") != null )_x000D_ {_x000D_ msglist.add(notifymsg);_x000D_ _x000D_ this.egwRemoveEGWData(_x000D_ Config, cookie, notifymsg.getString("notify_id"));_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ catch( ParseException pe )_x000D_ {_x000D_ egwDebuging.log.log(Level.SEVERE, null, pe);_x000D_ _x000D_ throw new Exception("NOAPPS");_x000D_ }_x000D_ }_x000D_ _x000D_ return msglist;_x000D_ }_x000D_ _x000D_ public Boolean egwRemoveEGWData(KeyArray Config, KeyArray cookie, String notifiy_id) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM;_x000D_ _x000D_ this.httpcon.setIsAjax(true);_x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ String buffer = this.httpcon.openHttpContentSitePost(_x000D_ urlhost + urllink, _x000D_ "json_data={\"request\":{\"parameters\":[\"" + notifiy_id + "\"]}}"_x000D_ );_x000D_ _x000D_ this.httpcon.setIsAjax(false);_x000D_ _x000D_ return true;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetSecurityID_x000D_ * beantragt eine Sicherheitsid zum Einlogen_x000D_ *_x000D_ * @param Config Konfiguration eines Accounts_x000D_ * @param cookie Cookie vom einlogen_x000D_ * @return Sicherheitsid, war man nicht eingelogt so ist der String Leer_x000D_ */_x000D_ public String egwGetSecurityID(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_TRAYMODUL + "?" + EGWHTTP_GET_VAR_MAKE_SECURITYID +_x000D_ "=" + EGWHTTP_GET_MAKE_SECURITYID;_x000D_ _x000D_ String securityid = "";_x000D_ _x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ if( this.egwIsLogin(cookie) )_x000D_ {_x000D_ securityid = this.egwGetTagValue(buffer, EGWHTTP_TAG_SECURITYID);_x000D_ }_x000D_ _x000D_ return securityid;_x000D_ }_x000D_ _x000D_ public String egwGetOpenEGWLink(KeyArray Config, KeyArray cookie, String menuaction)_x000D_ {_x000D_ String urllink = "";_x000D_ String urlhost = Config.getString("host");_x000D_ String protocol = "http://";_x000D_ _x000D_ if( Config.getString("egwurl").startsWith("https") )_x000D_ {_x000D_ protocol = "https://";_x000D_ }_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ urllink = urllink + protocol + jegwhttp.checkDir(urlhost) +_x000D_ jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_INDEXSCRIPT;_x000D_ _x000D_ urllink = urllink + "?notifiy=1";_x000D_ _x000D_ if( (menuaction != null) && (menuaction.length() > 0) )_x000D_ {_x000D_ urllink = urllink + "&" + menuaction;_x000D_ }_x000D_ _x000D_ String[] keys = cookie.getKeys();_x000D_ _x000D_ for( int i=0; i<cookie.size(); i++ )_x000D_ {_x000D_ urllink = urllink + "&" + keys[i] + "=" + cookie.getString(keys[i]);_x000D_ }_x000D_ _x000D_ return urllink;_x000D_ }_x000D_ _x000D_ public boolean egwLogout(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = jegwhttp.checkDir(urlhost) +_x000D_ jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGOUTSCRIPT;_x000D_ _x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ String buffer = this.httpcon.openHttpContentSite(urllink);_x000D_ _x000D_ _x000D_ if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }_x000D_ _x000D_ if( !this.egwIsLogin(cookie) )_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ }_x000D_
EGroupware/egroupware
notifications/java/src/egroupwaretray/jegwhttp.java
8,113
/**_x000D_ * egwGetEGWCookieStr_x000D_ * erstellt den Cookie String aus dem cookie(Array)_x000D_ *_x000D_ * @param cookie_x000D_ * @return_x000D_ */
block_comment
nl
/**_x000D_ * EGroupware - Notifications Java Desktop App_x000D_ *_x000D_ * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License_x000D_ * @package notifications_x000D_ * @subpackage jdesk_x000D_ * @link http://www.egroupware.org_x000D_ * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>_x000D_ * @author Maik Hüttner <maik.huettner@hw-softwareentwicklung.de>_x000D_ */_x000D_ _x000D_ package egroupwaretray;_x000D_ _x000D_ import java.awt.event.ActionListener;_x000D_ import java.net.InetAddress;_x000D_ import java.util.*;_x000D_ import java.util.logging.Level;_x000D_ import org.json.simple.parser.ContainerFactory;_x000D_ import org.json.simple.parser.JSONParser;_x000D_ import org.json.simple.parser.ParseException;_x000D_ _x000D_ /**_x000D_ * jegwhttp_x000D_ * _x000D_ * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>_x000D_ */_x000D_ public class jegwhttp_x000D_ {_x000D_ public static final String EGWHTTP_INDEXSCRIPT = "index.php";_x000D_ public static final String EGWHTTP_LOGINSCRIPT = "login.php";_x000D_ public static final String EGWHTTP_LOGOUTSCRIPT = "logout.php";_x000D_ public static final String EGWHTTP_TRAYMODUL = "egwnotifier/index.php";_x000D_ public static final String EGWHTTP_TRAYLOGIN = "notifierlogin.php";_x000D_ public static final String EGWHTTP_LOGINLINK = "login.php?cd=";_x000D_ _x000D_ public static final String EGWHTTP_POST_VAR_PASSWORD_TYPE = "passwd_type";_x000D_ public static final String EGWHTTP_POST_VAR_ACCOUNT_TYPE = "account_type";_x000D_ public static final String EGWHTTP_POST_VAR_LOGINDOMAIN = "logindomain";_x000D_ _x000D_ public static final String EGWHTTP_POST_VAR_LOGIN = "login";_x000D_ public static final String EGWHTTP_POST_VAR_PASSWD = "passwd";_x000D_ public static final String EGWHTTP_POST_VAR_SUBMITIT = "submitit";_x000D_ _x000D_ public static final String EGWHTTP_POST_PASSWORD_TYPE_TEXT = "text";_x000D_ public static final String EGWHTTP_POST_ACCOUNT_TYPE_U = "u";_x000D_ public static final String EGWHTTP_POST_LOGINDOMAIN_DEFAULT = "default";_x000D_ public static final String EGWHTTP_POST_SUBMITIT = "++Anmelden++";_x000D_ _x000D_ public static final String EGWHTTP_TAG_SECURITYID = "egwcheckid";_x000D_ _x000D_ public static final String EGWHTTP_GET_VAR_MAKE_SECURITYID = "makecheck";_x000D_ public static final String EGWHTTP_GET_VAR_SECURITYID = "checkid";_x000D_ public static final String EGWHTTP_GET_MAKE_SECURITYID = "1";_x000D_ public static final String EGWHTTP_GET_PHPGW_FORWARD = "phpgw_forward";_x000D_ _x000D_ // new EPL Notifications_x000D_ public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION = _x000D_ "json.php?menuaction=notifications.notifications_jdesk_ajax.get_notifications";_x000D_ _x000D_ // new EPL Notifications_x000D_ public static final String EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM = _x000D_ "json.php?menuaction=notifications.notifications_jdesk_ajax.confirm_message";_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_COOKIE = new String[]{_x000D_ "sessionid", "kp3", "last_loginid", "last_domain", "domain"};_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_APP = new String[]{_x000D_ "name", "title", "infotext", "variables", "appdialogtext" };_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_NOTIFY = new String[]{_x000D_ "app", "title", "msghtml", "link", "notify_id" };_x000D_ _x000D_ public static final String[] EGWHTTP_EGW_APP_VAR = new String[]{_x000D_ "vname", "value", "vtype" };_x000D_ _x000D_ private BaseHttp httpcon = new BaseHttp();_x000D_ private Boolean loginstatus = false;_x000D_ _x000D_ public jegwhttp(ActionListener lister) {_x000D_ _x000D_ this.httpcon.setSocketTimeOut(_x000D_ Integer.parseInt(_x000D_ jegwConst.getConstTag("egw_dc_timeout_socket")));_x000D_ }_x000D_ _x000D_ /**_x000D_ * CheckDir_x000D_ * Überprüft ob hinten ein String (wie bei Verzeichnisen mit "/" abschließt),_x000D_ * wenn nicht wird dieser hinten drangesetzt und der String zurück geben_x000D_ *_x000D_ * @param dir_x000D_ * @return_x000D_ */_x000D_ static public String checkDir(String dir)_x000D_ {_x000D_ if(dir.length() > 0)_x000D_ {_x000D_ if(dir.charAt(dir.length()-1) != "/".charAt(0) )_x000D_ {_x000D_ dir = dir + "/";_x000D_ }_x000D_ }_x000D_ _x000D_ return dir;_x000D_ }_x000D_ _x000D_ public void egwUrlLinkParser(KeyArray Config) throws Exception_x000D_ {_x000D_ String url = Config.getString("egwurl");_x000D_ _x000D_ boolean ssl = false;_x000D_ _x000D_ if( url.indexOf("https://") > -1 )_x000D_ {_x000D_ ssl = true;_x000D_ url = url.replaceAll("https://", "");_x000D_ }_x000D_ else_x000D_ {_x000D_ url = url.replaceAll("http://", "");_x000D_ }_x000D_ _x000D_ if( url.length() == 0 )_x000D_ {_x000D_ throw new Exception("NOURL");_x000D_ }_x000D_ _x000D_ String[] tmp = url.split("/");_x000D_ _x000D_ String host = tmp[0];_x000D_ String port = "";_x000D_ String paht = "";_x000D_ _x000D_ if( tmp[0].indexOf(":") != -1 )_x000D_ {_x000D_ String[] ttmp = tmp[0].split(":");_x000D_ host = ttmp[0];_x000D_ port = ttmp[1];_x000D_ }_x000D_ _x000D_ /**_x000D_ * Host auflösen_x000D_ */_x000D_ try_x000D_ {_x000D_ InetAddress addr = InetAddress.getByName(host);_x000D_ }_x000D_ catch( Exception exp)_x000D_ {_x000D_ egwDebuging.log.log(Level.SEVERE, null, exp);_x000D_ throw new Exception("HOSTNOTFOUND");_x000D_ }_x000D_ _x000D_ for( int i=1; i<tmp.length; i++ )_x000D_ {_x000D_ paht = paht + tmp[i] + "/";_x000D_ }_x000D_ _x000D_ /*if( paht.length() == 0 )_x000D_ {_x000D_ paht = "/";_x000D_ }*/_x000D_ _x000D_ Config.add("host", host);_x000D_ _x000D_ if( port.length() != 0 )_x000D_ {_x000D_ Config.add("port", port);_x000D_ }_x000D_ _x000D_ Config.add("subdir", paht);_x000D_ Config.add("ssl", ssl);_x000D_ _x000D_ /**_x000D_ * SSL Enable_x000D_ */_x000D_ this.httpcon.setIsSSL(ssl);_x000D_ _x000D_ if( port.length() != 0 )_x000D_ {_x000D_ host = host + ":" + port;_x000D_ }_x000D_ _x000D_ String moved = this.httpcon.isHostMoved(host, "/" + paht);_x000D_ _x000D_ if( !moved.equals("") )_x000D_ {_x000D_ Config.add("egwurl", moved);_x000D_ this.egwUrlLinkParser(Config);_x000D_ }_x000D_ }_x000D_ _x000D_ public String[] getEgwLoginDomains(KeyArray Config) throws Exception_x000D_ {_x000D_ this.egwUrlLinkParser(Config);_x000D_ _x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ /**_x000D_ * Hidden Logindomain_x000D_ */_x000D_ int begin = -1;_x000D_ int end = -1;_x000D_ String search = "<input type=\"hidden\" name=\"logindomain\" value=\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("\"", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ return new String[]{tmp};_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Select Logindomain_x000D_ */_x000D_ _x000D_ begin = -1;_x000D_ end = -1;_x000D_ search = "<select name=\"logindomain\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("</select>", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ tmp = tmp.trim();_x000D_ _x000D_ String ltmp[] = tmp.split("</option>");_x000D_ String treturn[] = new String[ltmp.length];_x000D_ _x000D_ for( int i=0; i<ltmp.length; i++ )_x000D_ {_x000D_ String tbuffer = ltmp[i];_x000D_ String tsearch = "value=\"";_x000D_ _x000D_ int tbegin = -1;_x000D_ int tend = -1; _x000D_ _x000D_ if( (tbegin = tbuffer.indexOf(tsearch)) > -1 )_x000D_ {_x000D_ tend = tbuffer.indexOf("\"", tbegin + tsearch.length());_x000D_ _x000D_ if( (begin != -1) && (tend != -1) )_x000D_ {_x000D_ String ttmp = tbuffer.substring( tbegin +_x000D_ tsearch.length(), tend);_x000D_ _x000D_ treturn[i] = ttmp;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ return treturn;_x000D_ }_x000D_ }_x000D_ _x000D_ return null;_x000D_ }_x000D_ _x000D_ public void egwCheckLoginDomains(KeyArray Config) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ /**_x000D_ * Hidden Logindomain_x000D_ */_x000D_ int begin = -1;_x000D_ int end = -1;_x000D_ String search = "<input type=\"hidden\" name=\"logindomain\" value=\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("\"", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ Config.add("logindomain", tmp);_x000D_ _x000D_ return;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Select Logindomain_x000D_ */_x000D_ _x000D_ begin = -1;_x000D_ end = -1;_x000D_ search = "<select name=\"logindomain\"";_x000D_ _x000D_ if( (begin = buffer.indexOf(search)) > -1 )_x000D_ {_x000D_ end = buffer.indexOf("</select>", begin + search.length());_x000D_ _x000D_ if( (begin != -1) && (end != -1) )_x000D_ {_x000D_ String tmp = buffer.substring( begin +_x000D_ search.length(), end);_x000D_ _x000D_ System.out.println(tmp);_x000D_ }_x000D_ }_x000D_ _x000D_ //Config.Add("logindomain", EGWHTTP_POST_LOGINDOMAIN_DEFAULT);_x000D_ Config.add("logindomain", urlhost);_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwLogin_x000D_ * logt sich im eGroupware ein mit den Benutzerdaten aus einer Config_x000D_ * und gibt den Cookieinhalt zurück_x000D_ *_x000D_ * @param Config Konfigurations Einstellungen_x000D_ * @return Cookieinhalt_x000D_ */_x000D_ public KeyArray egwLogin(KeyArray Config) throws Exception_x000D_ {_x000D_ this.egwUrlLinkParser(Config);_x000D_ //this.egwCheckLoginDomains(Config);_x000D_ _x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGINSCRIPT + "?" + EGWHTTP_GET_PHPGW_FORWARD + "=";_x000D_ _x000D_ String urlpost = EGWHTTP_POST_VAR_PASSWORD_TYPE + "=" +_x000D_ EGWHTTP_POST_PASSWORD_TYPE_TEXT + "&" + EGWHTTP_POST_VAR_ACCOUNT_TYPE +_x000D_ "=" + EGWHTTP_POST_ACCOUNT_TYPE_U + "&" + EGWHTTP_POST_VAR_LOGINDOMAIN +_x000D_ "=" + Config.getString("logindomain") + "&" + EGWHTTP_POST_VAR_LOGIN +_x000D_ "=" + Config.getString("user") + "&" + EGWHTTP_POST_VAR_PASSWD + "=" +_x000D_ Config.getString("password") + "&" + EGWHTTP_POST_VAR_SUBMITIT + "=" +_x000D_ EGWHTTP_POST_SUBMITIT;_x000D_ _x000D_ String buffer = this.httpcon.openHttpContentSitePost(urlhost + urllink, urlpost);_x000D_ _x000D_ if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }_x000D_ _x000D_ if( this.httpcon.isNotFound() )_x000D_ {_x000D_ throw new Exception("PAGENOTFOUND");_x000D_ }_x000D_ _x000D_ int status = this.egwCheckLoginStatus();_x000D_ _x000D_ if( status > -1 )_x000D_ {_x000D_ throw new Exception("LOGIN:" + Integer.toString(status));_x000D_ }_x000D_ _x000D_ KeyArray egwcookie = new KeyArray(EGWHTTP_EGW_COOKIE);_x000D_ String[] keys = egwcookie.getKeys();_x000D_ _x000D_ for( int i=0; i<keys.length; i++ )_x000D_ {_x000D_ String value = this.httpcon.getSocketHeaderField(this.httpcon.getCookie(), keys[i]);_x000D_ _x000D_ if( value.length() == 0 )_x000D_ {_x000D_ // Login fehlgeschlagen_x000D_ return null;_x000D_ }_x000D_ _x000D_ egwcookie.add(keys[i], value);_x000D_ }_x000D_ _x000D_ this.loginstatus = true;_x000D_ return egwcookie;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwIsLogin_x000D_ * Überprüft ob eine egw Benutzer noch angemeldet ist_x000D_ *_x000D_ * @param buffer Rückgabe eines HTTP aufrufes muss hier angeben werden,_x000D_ * der Inhalt würd dann drauf überprüft_x000D_ * @param cookie Cookie Informationen zum Überprüfen_x000D_ * @return true = noch Angemeldet, false = nicht mehr Angemeldet_x000D_ */_x000D_ private boolean egwIsLogin(KeyArray cookie)_x000D_ {_x000D_ String sess = this.httpcon.getCookieVariable(this.httpcon.getCookie(), "sessionid");_x000D_ String location = this.httpcon.getLocation();_x000D_ _x000D_ if( sess.length() > 0 )_x000D_ {_x000D_ if( sess.compareTo(cookie.getString("sessionid")) != 0 )_x000D_ {_x000D_ this.loginstatus = false;_x000D_ return false;_x000D_ }_x000D_ }_x000D_ else if( (location != null) && (location.indexOf("login.php") != -1) )_x000D_ {_x000D_ this.loginstatus = false;_x000D_ return false;_x000D_ }_x000D_ _x000D_ this.loginstatus = true;_x000D_ return true;_x000D_ }_x000D_ _x000D_ private int egwCheckLoginStatus()_x000D_ {_x000D_ String back = "";_x000D_ String buffer = this.httpcon.getLocation();_x000D_ _x000D_ if( buffer == null )_x000D_ {_x000D_ buffer = "";_x000D_ }_x000D_ _x000D_ int pos = buffer.indexOf(jegwhttp.EGWHTTP_LOGINLINK);_x000D_ int end = buffer.length();_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buffer.substring( pos +_x000D_ jegwhttp.EGWHTTP_LOGINLINK.length(), end);_x000D_ }_x000D_ else if( (buffer.indexOf("http://") != -1) || (buffer.indexOf("https://") != -1) )_x000D_ {_x000D_ if( buffer.indexOf("index.php?cd=yes") == -1 )_x000D_ {_x000D_ return 999;_x000D_ }_x000D_ else_x000D_ {_x000D_ return -1;_x000D_ }_x000D_ }_x000D_ else_x000D_ {_x000D_ return -1;_x000D_ }_x000D_ _x000D_ return Integer.valueOf(back).intValue();_x000D_ }_x000D_ _x000D_ public boolean egwIsEGWLogin()_x000D_ {_x000D_ return this.loginstatus;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetTagValue_x000D_ * Sucht Inhalte erraus (nach der notation vom html/xml)_x000D_ *_x000D_ * @param buff HTTP Inhalt_x000D_ * @param tag Inhalt umschließer_x000D_ * @return Inhalt_x000D_ */_x000D_ private String egwGetTagValue(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( pos + tag.length() +2, end);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ private String egwGetTagValueWithTag(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( pos, end + tag.length() +3);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ private String egwGetNoneTagText(String buff, String tag)_x000D_ {_x000D_ String back = "";_x000D_ _x000D_ int pos = buff.indexOf("<" + tag + ">");_x000D_ int end = buff.indexOf("</" + tag + ">", pos);_x000D_ _x000D_ if( (pos != -1) && (end != -1) )_x000D_ {_x000D_ back = buff.substring( 0, pos);_x000D_ back = back + buff.substring( end + tag.length() +3, buff.length()-1);_x000D_ }_x000D_ _x000D_ return back;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetEGWCookieStr_x000D_ <SUF>*/_x000D_ private String egwGetEGWCookieStr(KeyArray cookie)_x000D_ {_x000D_ String cookiestr = "";_x000D_ _x000D_ String[] keys = cookie.getKeys();_x000D_ _x000D_ for( int i=0; i<cookie.size(); i++ )_x000D_ {_x000D_ String tmp = keys[i] + "=" + cookie.getString(keys[i]) + ";";_x000D_ _x000D_ if(cookiestr.length() == 0)_x000D_ {_x000D_ cookiestr = cookiestr + tmp;_x000D_ }_x000D_ else_x000D_ {_x000D_ cookiestr = cookiestr + " " + tmp;_x000D_ }_x000D_ }_x000D_ _x000D_ cookiestr = cookiestr + " storedlang=de; last_loginid=; last_domain=default; ConfigLang=de";_x000D_ _x000D_ return cookiestr;_x000D_ }_x000D_ _x000D_ public ArrayList egwLoadEGWData(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ ArrayList msglist = new ArrayList();_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_GET_NOTIFICATIONS_ACTION;_x000D_ _x000D_ this.httpcon.setIsAjax(true);_x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ String buffer = this.httpcon.openHttpContentSitePost(_x000D_ urlhost + urllink, _x000D_ "json_data={\"request\":{\"parameters\":[null]}}"_x000D_ );_x000D_ _x000D_ this.httpcon.setIsAjax(false);_x000D_ _x000D_ /**_x000D_ * Fehler Behandlung_x000D_ */_x000D_ /*if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }*/_x000D_ _x000D_ if( this.egwIsLogin(cookie) )_x000D_ {_x000D_ int status = this.egwCheckLoginStatus();_x000D_ _x000D_ if( status > -1 )_x000D_ {_x000D_ throw new Exception("LOGIN:" + Integer.toString(status));_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Check auf Rechte (Permission denied!)_x000D_ */_x000D_ String permission = "<title>Permission denied!</title>";_x000D_ _x000D_ if( buffer.indexOf(permission) > -1 )_x000D_ {_x000D_ throw new Exception("PERMISSIONDENIED");_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * JSON_x000D_ */_x000D_ _x000D_ JSONParser parser = new JSONParser();_x000D_ ContainerFactory containerFactory = new ContainerFactory(){_x000D_ public List creatArrayContainer() {_x000D_ return new LinkedList();_x000D_ }_x000D_ _x000D_ public Map createObjectContainer() {_x000D_ return new LinkedHashMap();_x000D_ }_x000D_ };_x000D_ _x000D_ try _x000D_ {_x000D_ Map json = (Map)parser.parse(buffer.trim(), containerFactory);_x000D_ Iterator iter = json.entrySet().iterator();_x000D_ _x000D_ while( iter.hasNext() )_x000D_ {_x000D_ Map.Entry entry = (Map.Entry)iter.next();_x000D_ _x000D_ if( entry.getKey().toString().compareTo("response") == 0 )_x000D_ {_x000D_ LinkedList response = (LinkedList) entry.getValue();_x000D_ _x000D_ for( Integer i=0; i<response.size(); i++ )_x000D_ {_x000D_ Map jmsg = (Map) response.get(i);_x000D_ Iterator jmsgiter = jmsg.entrySet().iterator();_x000D_ _x000D_ while( jmsgiter.hasNext() )_x000D_ {_x000D_ Map.Entry jmsgentry = (Map.Entry)jmsgiter.next();_x000D_ _x000D_ if( (jmsgentry.getKey().toString().compareTo("type") == 0) &&_x000D_ (jmsgentry.getValue().toString().compareTo("data") == 0) && _x000D_ jmsgiter.hasNext() )_x000D_ {_x000D_ jmsgentry = (Map.Entry)jmsgiter.next();_x000D_ _x000D_ if( jmsgentry.getKey().toString().compareTo("data") == 0 )_x000D_ {_x000D_ KeyArray notifymsg = new KeyArray(EGWHTTP_EGW_NOTIFY);_x000D_ _x000D_ Map msgdata = (Map) jmsgentry.getValue();_x000D_ Iterator dataiter = msgdata.entrySet().iterator();_x000D_ _x000D_ while( dataiter.hasNext() )_x000D_ {_x000D_ Map.Entry dataentry = (Map.Entry)dataiter.next();_x000D_ String tkey = dataentry.getKey().toString();_x000D_ Object tovalue = dataentry.getValue(); _x000D_ _x000D_ String tvalue = "";_x000D_ _x000D_ if( tovalue != null )_x000D_ {_x000D_ tvalue = tovalue.toString();_x000D_ }_x000D_ _x000D_ if( notifymsg.existKey(tkey) )_x000D_ {_x000D_ notifymsg.add(tkey, tvalue);_x000D_ }_x000D_ }_x000D_ _x000D_ if( notifymsg.get("notify_id") != null )_x000D_ {_x000D_ msglist.add(notifymsg);_x000D_ _x000D_ this.egwRemoveEGWData(_x000D_ Config, cookie, notifymsg.getString("notify_id"));_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ catch( ParseException pe )_x000D_ {_x000D_ egwDebuging.log.log(Level.SEVERE, null, pe);_x000D_ _x000D_ throw new Exception("NOAPPS");_x000D_ }_x000D_ }_x000D_ _x000D_ return msglist;_x000D_ }_x000D_ _x000D_ public Boolean egwRemoveEGWData(KeyArray Config, KeyArray cookie, String notifiy_id) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_GET_NOTIFICATIONS_ACTION_CONFIRM;_x000D_ _x000D_ this.httpcon.setIsAjax(true);_x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ //String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ String buffer = this.httpcon.openHttpContentSitePost(_x000D_ urlhost + urllink, _x000D_ "json_data={\"request\":{\"parameters\":[\"" + notifiy_id + "\"]}}"_x000D_ );_x000D_ _x000D_ this.httpcon.setIsAjax(false);_x000D_ _x000D_ return true;_x000D_ }_x000D_ _x000D_ /**_x000D_ * egwGetSecurityID_x000D_ * beantragt eine Sicherheitsid zum Einlogen_x000D_ *_x000D_ * @param Config Konfiguration eines Accounts_x000D_ * @param cookie Cookie vom einlogen_x000D_ * @return Sicherheitsid, war man nicht eingelogt so ist der String Leer_x000D_ */_x000D_ public String egwGetSecurityID(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = "/" + jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_TRAYMODUL + "?" + EGWHTTP_GET_VAR_MAKE_SECURITYID +_x000D_ "=" + EGWHTTP_GET_MAKE_SECURITYID;_x000D_ _x000D_ String securityid = "";_x000D_ _x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ String buffer = this.httpcon.openHttpContentSite(urlhost + urllink);_x000D_ _x000D_ if( this.egwIsLogin(cookie) )_x000D_ {_x000D_ securityid = this.egwGetTagValue(buffer, EGWHTTP_TAG_SECURITYID);_x000D_ }_x000D_ _x000D_ return securityid;_x000D_ }_x000D_ _x000D_ public String egwGetOpenEGWLink(KeyArray Config, KeyArray cookie, String menuaction)_x000D_ {_x000D_ String urllink = "";_x000D_ String urlhost = Config.getString("host");_x000D_ String protocol = "http://";_x000D_ _x000D_ if( Config.getString("egwurl").startsWith("https") )_x000D_ {_x000D_ protocol = "https://";_x000D_ }_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ urllink = urllink + protocol + jegwhttp.checkDir(urlhost) +_x000D_ jegwhttp.checkDir(Config.getString("subdir")) + EGWHTTP_INDEXSCRIPT;_x000D_ _x000D_ urllink = urllink + "?notifiy=1";_x000D_ _x000D_ if( (menuaction != null) && (menuaction.length() > 0) )_x000D_ {_x000D_ urllink = urllink + "&" + menuaction;_x000D_ }_x000D_ _x000D_ String[] keys = cookie.getKeys();_x000D_ _x000D_ for( int i=0; i<cookie.size(); i++ )_x000D_ {_x000D_ urllink = urllink + "&" + keys[i] + "=" + cookie.getString(keys[i]);_x000D_ }_x000D_ _x000D_ return urllink;_x000D_ }_x000D_ _x000D_ public boolean egwLogout(KeyArray Config, KeyArray cookie) throws Exception_x000D_ {_x000D_ String urlhost = Config.getString("host");_x000D_ _x000D_ if( Config.getString("port").length() > 0 )_x000D_ {_x000D_ urlhost = urlhost + ":" + Config.getString("port");_x000D_ }_x000D_ _x000D_ String urllink = jegwhttp.checkDir(urlhost) +_x000D_ jegwhttp.checkDir(Config.getString("subdir")) +_x000D_ EGWHTTP_LOGOUTSCRIPT;_x000D_ _x000D_ this.httpcon.setCookie(this.egwGetEGWCookieStr(cookie));_x000D_ String buffer = this.httpcon.openHttpContentSite(urllink);_x000D_ _x000D_ _x000D_ if( buffer.length() == 0 )_x000D_ {_x000D_ // Verbindungsfehler_x000D_ throw new Exception("NETERROR");_x000D_ }_x000D_ _x000D_ if( !this.egwIsLogin(cookie) )_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ return false;_x000D_ }_x000D_ }_x000D_
False
3,375
25539_21
// Copyright 2014 theaigames.com (developers@theaigames.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. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. package conquest.engine; import java.awt.Point; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import conquest.engine.Engine.EngineConfig; import conquest.engine.Robot.RobotConfig; import conquest.engine.replay.FileGameLog; import conquest.engine.replay.GameLog; import conquest.engine.replay.ReplayHandler; import conquest.engine.robot.HumanRobot; import conquest.engine.robot.IORobot; import conquest.engine.robot.InternalRobot; import conquest.engine.robot.ProcessRobot; import conquest.game.ContinentData; import conquest.game.GameMap; import conquest.game.EnginePlayer; import conquest.game.RegionData; import conquest.game.Team; import conquest.game.move.MoveResult; import conquest.game.world.Continent; import conquest.game.world.Region; import conquest.view.GUI; public class RunGame { public static class Config implements Cloneable { public String gameId = "GAME"; public String playerName1 = "PLR1"; public String playerName2 = "PLR2"; public String bot1Id = "Bot1"; public String bot2Id = "Bot2"; public String bot1Init; public String bot2Init; public boolean visualize = true; /** * Optimize region circle positions for human controls. */ public boolean forceHumanVisualization = false; public File replayLog = null; public EngineConfig engine = new EngineConfig(); public String asString() { return gameId + ";" + playerName1 + ";" + playerName2 + ";" + bot1Id + ";" + bot2Id + ";" + visualize + ";" + forceHumanVisualization + ";" + engine.asString(); } @Override public Config clone() { Config result = fromString(asString()); result.replayLog = replayLog; result.bot1Init = bot1Init; result.bot2Init = bot2Init; return result; } public String getCSVHeader() { return "ID;Bot1;Bot2;" + engine.getCSVHeader(); } public String getCSV() { return gameId + ";" + bot1Id + ";" + bot2Id + ";" + engine.getCSV(); } public static Config fromString(String line) { String[] parts = line.split(";"); Config result = new Config(); result.gameId = parts[0]; result.playerName1 = parts[1]; result.playerName2 = parts[2]; result.bot1Id = parts[3]; result.bot2Id = parts[4]; result.visualize = Boolean.parseBoolean(parts[5]); result.forceHumanVisualization = Boolean.parseBoolean(parts[6]); int engineConfigStart = 0; for (int i = 0; i < 7; ++i) { engineConfigStart = line.indexOf(";", engineConfigStart); ++engineConfigStart; } result.engine = EngineConfig.fromString(line.substring(engineConfigStart)); return result; } } public static class GameResult { public Config config; public int player1Regions; public int player1Armies; public int player2Regions; public int player2Armies; public Team winner = null; /** * Number of the round the game ended. */ public int round; public String getWinnerName() { if (winner == null) return "NONE"; switch (winner) { case NEUTRAL: return "NONE"; case PLAYER_1: return config == null ? "Player1" : config.playerName1; case PLAYER_2: return config == null ? "Player2" : config.playerName2; } return null; } public String getWinnerId() { if (winner == null) return "NONE"; switch (winner) { case NEUTRAL: return "NONE"; case PLAYER_1: return config == null ? "Bot1" : config.bot1Id; case PLAYER_2: return config == null ? "Bot2" : config.bot2Id; } return null; } public String asString() { return getWinnerName() + ";" + player1Regions + ";" + player1Armies + ";" + player2Regions + ";" + player2Armies + ";" + round; } public String getHumanString() { return "Winner: " + getWinnerName() + "[" + getWinnerId() + "] in round " + round + "\nPlayer1: " + player1Regions + " regions / " + player1Armies + " armies\nPlayer2: " + player2Regions + " regions / " + player2Armies + " armies"; } public String getCSVHeader() { return "winnerId;winner;winnerName;player1Regions;player1Armies;player2Regions;player2Armies;round;" + config.getCSVHeader(); } public String getCSV() { return getWinnerId() + ";" + (winner == null || winner == Team.NEUTRAL ? "NONE" : winner) + ";" + getWinnerName() + ";" + player1Regions + ";" + player1Armies + ";" + player2Regions + ";" + player2Armies + ";" + round + ";" + config.getCSV(); } } Config config; LinkedList<MoveResult> fullPlayedGame; LinkedList<MoveResult> player1PlayedGame; LinkedList<MoveResult> player2PlayedGame; int gameIndex = 1; Engine engine; public RunGame(Config config) { this.config = config; } public GameResult goReplay(File replayFile) { try { System.out.println("starting replay " + replayFile.getAbsolutePath()); ReplayHandler replay = new ReplayHandler(replayFile); this.config.engine = replay.getConfig().engine; EnginePlayer player1, player2; Robot robot1, robot2; //setup the bots: bot1, bot2 robot1 = new IORobot(replay); robot2 = new IORobot(replay); player1 = new EnginePlayer(config.playerName1, robot1, config.engine.startingArmies); player2 = new EnginePlayer(config.playerName2, robot2, config.engine.startingArmies); return go(null, player1, player2, robot1, robot2); } catch (Exception e) { throw new RuntimeException("Failed to replay the game.", e); } } public GameResult go() { try { GameLog log = null; if (config.replayLog != null) { log = new FileGameLog(config.replayLog); } System.out.println("starting game " + config.gameId); EnginePlayer player1, player2; Robot robot1, robot2; //setup the bots: bot1, bot2 robot1 = setupRobot(config.playerName1, config.bot1Init); robot2 = setupRobot(config.playerName2, config.bot2Init); player1 = new EnginePlayer(config.playerName1, robot1, config.engine.startingArmies); player2 = new EnginePlayer(config.playerName2, robot2, config.engine.startingArmies); return go(log, player1, player2, robot1, robot2); } catch (Exception e) { throw new RuntimeException("Failed to run/finish the game.", e); } } private GameResult go(GameLog log, EnginePlayer player1, EnginePlayer player2, Robot robot1, Robot robot2) throws InterruptedException { //setup the map GameMap initMap, map; initMap = makeInitMap(); map = setupMap(initMap); // setup GUI GUI gui = null; if (config.visualize) { if (config.forceHumanVisualization) { gui.positions = gui.positionsHuman; } gui = new GUI(config.playerName1, config.playerName2, robot1.getRobotName(), robot2.getRobotName()); } //start the engine this.engine = new Engine(map, player1, player2, gui, config.engine); if (log != null) { log.start(config); } // setup robots RobotConfig robot1Cfg = new RobotConfig(player1.getName(), Team.PLAYER_1, config.engine.botCommandTimeoutMillis, log, gui); RobotConfig robot2Cfg = new RobotConfig(player2.getName(), Team.PLAYER_2, config.engine.botCommandTimeoutMillis, log, gui); robot1.setup(robot1Cfg); robot2.setup(robot2Cfg); //send the bots the info they need to start robot1.writeInfo("settings your_bot " + player1.getName()); robot1.writeInfo("settings opponent_bot " + player2.getName()); robot2.writeInfo("settings your_bot " + player2.getName()); robot2.writeInfo("settings opponent_bot " + player1.getName()); sendSetupMapInfo(player1.getBot(), initMap); sendSetupMapInfo(player2.getBot(), initMap); this.engine.distributeStartingRegions(); //decide the player's starting regions this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions) this.engine.sendAllInfo(); //play the game while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= config.engine.maxGameRounds) { if (log != null) { log.logComment("Engine", "Round " + this.engine.getRoundNr()); } this.engine.playRound(); } fullPlayedGame = this.engine.getFullPlayedGame(); player1PlayedGame = this.engine.getPlayer1PlayedGame(); player2PlayedGame = this.engine.getPlayer2PlayedGame(); GameResult result = finish(map, robot1, robot2); if (log != null) { log.finish(result); } return result; } private Robot setupRobot(String playerName, String botInit) throws IOException { if (botInit.startsWith("dir;process:")) { String cmd = botInit.substring(12); int semicolon = cmd.indexOf(";"); if (semicolon < 0) throw new RuntimeException("Invalid bot torrent (does not contain ';' separating directory and commmend): " + botInit); String dir = cmd.substring(0, semicolon); String process = cmd.substring(semicolon+1); return new ProcessRobot(playerName, dir, process); } if (botInit.startsWith("process:")) { String cmd = botInit.substring(8); return new ProcessRobot(playerName, cmd); } if (botInit.startsWith("internal:")) { String botFQCN = botInit.substring(9); return new InternalRobot(playerName, botFQCN); } if (botInit.startsWith("human")) { config.visualize = true; config.forceHumanVisualization = true; return new HumanRobot(playerName); } throw new RuntimeException("Invalid init string for player '" + playerName + "', must start either with 'process:' or 'internal:' or 'human', passed value was: " + botInit); } //aanpassen en een QPlayer class maken? met eigen finish private GameResult finish(GameMap map, Robot bot1, Robot bot2) throws InterruptedException { System.out.println("GAME FINISHED: stopping bots..."); try { bot1.finish(); } catch (Exception e) { } try { bot2.finish(); } catch (Exception e) { } return this.saveGame(map, bot1, bot2); } //tijdelijk handmatig invoeren private GameMap makeInitMap() { GameMap map = new GameMap(); // INIT SUPER REGIONS // ORIGINAL CODE // SuperRegion northAmerica = new SuperRegion(1, 5); // SuperRegion southAmerica = new SuperRegion(2, 2); // SuperRegion europe = new SuperRegion(3, 5); // SuperRegion afrika = new SuperRegion(4, 3); // SuperRegion azia = new SuperRegion(5, 7); // SuperRegion australia = new SuperRegion(6, 2); Map<Continent, ContinentData> continents = new TreeMap<Continent, ContinentData>(new Comparator<Continent>() { @Override public int compare(Continent o1, Continent o2) { return o1.id - o2.id; } }); for (Continent continent : Continent.values()) { ContinentData continentData = new ContinentData(continent, continent.id, continent.reward); continents.put(continent, continentData); } // INIT REGIONS // ORIGINAL CODE // Region region1 = new Region(1, northAmerica); // Region region2 = new Region(2, northAmerica); // Region region3 = new Region(3, northAmerica); // Region region4 = new Region(4, northAmerica); // Region region5 = new Region(5, northAmerica); // Region region6 = new Region(6, northAmerica); // Region region7 = new Region(7, northAmerica); // Region region8 = new Region(8, northAmerica); // Region region9 = new Region(9, northAmerica); // // Region region10 = new Region(10, southAmerica); // Region region11 = new Region(11, southAmerica); // Region region12 = new Region(12, southAmerica); // Region region13 = new Region(13, southAmerica); // // Region region14 = new Region(14, europe); // Region region15 = new Region(15, europe); // Region region16 = new Region(16, europe); // Region region17 = new Region(17, europe); // Region region18 = new Region(18, europe); // Region region19 = new Region(19, europe); // Region region20 = new Region(20, europe); // // Region region21 = new Region(21, afrika); // Region region22 = new Region(22, afrika); // Region region23 = new Region(23, afrika); // Region region24 = new Region(24, afrika); // Region region25 = new Region(25, afrika); // Region region26 = new Region(26, afrika); // // Region region27 = new Region(27, azia); // Region region28 = new Region(28, azia); // Region region29 = new Region(29, azia); // Region region30 = new Region(30, azia); // Region region31 = new Region(31, azia); // Region region32 = new Region(32, azia); // Region region33 = new Region(33, azia); // Region region34 = new Region(34, azia); // Region region35 = new Region(35, azia); // Region region36 = new Region(36, azia); // Region region37 = new Region(37, azia); // Region region38 = new Region(38, azia); // // Region region39 = new Region(39, australia); // Region region40 = new Region(40, australia); // Region region41 = new Region(41, australia); // Region region42 = new Region(42, australia); Map<Region, RegionData> regions = new TreeMap<Region, RegionData>(new Comparator<Region>() { @Override public int compare(Region o1, Region o2) { return o1.id - o2.id; } }); for (Region region : Region.values()) { RegionData regionData = new RegionData(region, region.id, continents.get(region.continent)); regions.put(region, regionData); } // INIT NEIGHBOURS // ORIGINAL CODE // region1.addNeighbor(region2); region1.addNeighbor(region4); region1.addNeighbor(region30); // region2.addNeighbor(region4); region2.addNeighbor(region3); region2.addNeighbor(region5); // region3.addNeighbor(region5); region3.addNeighbor(region6); region3.addNeighbor(region14); // region4.addNeighbor(region5); region4.addNeighbor(region7); // region5.addNeighbor(region6); region5.addNeighbor(region7); region5.addNeighbor(region8); // region6.addNeighbor(region8); // region7.addNeighbor(region8); region7.addNeighbor(region9); // region8.addNeighbor(region9); // region9.addNeighbor(region10); // region10.addNeighbor(region11);region10.addNeighbor(region12); // region11.addNeighbor(region12);region11.addNeighbor(region13); // region12.addNeighbor(region13);region12.addNeighbor(region21); // region14.addNeighbor(region15);region14.addNeighbor(region16); // region15.addNeighbor(region16);region15.addNeighbor(region18); // region15.addNeighbor(region19);region16.addNeighbor(region17); // region17.addNeighbor(region19);region17.addNeighbor(region20);region17.addNeighbor(region27);region17.addNeighbor(region32);region17.addNeighbor(region36); // region18.addNeighbor(region19);region18.addNeighbor(region20);region18.addNeighbor(region21); // region19.addNeighbor(region20); // region20.addNeighbor(region21);region20.addNeighbor(region22);region20.addNeighbor(region36); // region21.addNeighbor(region22);region21.addNeighbor(region23);region21.addNeighbor(region24); // region22.addNeighbor(region23);region22.addNeighbor(region36); // region23.addNeighbor(region24);region23.addNeighbor(region25);region23.addNeighbor(region26);region23.addNeighbor(region36); // region24.addNeighbor(region25); // region25.addNeighbor(region26); // region27.addNeighbor(region28);region27.addNeighbor(region32);region27.addNeighbor(region33); // region28.addNeighbor(region29);region28.addNeighbor(region31);region28.addNeighbor(region33);region28.addNeighbor(region34); // region29.addNeighbor(region30);region29.addNeighbor(region31); // region30.addNeighbor(region31);region30.addNeighbor(region34);region30.addNeighbor(region35); // region31.addNeighbor(region34); // region32.addNeighbor(region33);region32.addNeighbor(region36);region32.addNeighbor(region37); // region33.addNeighbor(region34);region33.addNeighbor(region37);region33.addNeighbor(region38); // region34.addNeighbor(region35); // region36.addNeighbor(region37); // region37.addNeighbor(region38); // region38.addNeighbor(region39); // region39.addNeighbor(region40);region39.addNeighbor(region41); // region40.addNeighbor(region41);region40.addNeighbor(region42); // region41.addNeighbor(region42); for (Region regionName : Region.values()) { RegionData region = regions.get(regionName); for (Region neighbour : regionName.getForwardNeighbours()) { region.addNeighbor(regions.get(neighbour)); } } // ADD REGIONS TO THE MAP // ORIGINAL CODE // map.add(region1); map.add(region2); map.add(region3); // map.add(region4); map.add(region5); map.add(region6); // map.add(region7); map.add(region8); map.add(region9); // map.add(region10); map.add(region11); map.add(region12); // map.add(region13); map.add(region14); map.add(region15); // map.add(region16); map.add(region17); map.add(region18); // map.add(region19); map.add(region20); map.add(region21); // map.add(region22); map.add(region23); map.add(region24); // map.add(region25); map.add(region26); map.add(region27); // map.add(region28); map.add(region29); map.add(region30); // map.add(region31); map.add(region32); map.add(region33); // map.add(region34); map.add(region35); map.add(region36); // map.add(region37); map.add(region38); map.add(region39); // map.add(region40); map.add(region41); map.add(region42); for (RegionData region : regions.values()) { map.add(region); } // ADD SUPER REGIONS TO THE MAP // ORIGINAL CODE // map.add(northAmerica); // map.add(southAmerica); // map.add(europe); // map.add(afrika); // map.add(azia); // map.add(australia); for (ContinentData superRegion : continents.values()) { map.add(superRegion); } return map; } //Make every region neutral with 2 armies to start with private GameMap setupMap(GameMap initMap) { GameMap map = initMap; for(RegionData region : map.regions) { region.setPlayerName("neutral"); region.setArmies(2); } return map; } private void sendSetupMapInfo(Robot bot, GameMap initMap) { String setupSuperRegionsString, setupRegionsString, setupNeighborsString; setupSuperRegionsString = getSuperRegionsString(initMap); setupRegionsString = getRegionsString(initMap); setupNeighborsString = getNeighborsString(initMap); bot.writeInfo(setupSuperRegionsString); // System.out.println(setupSuperRegionsString); bot.writeInfo(setupRegionsString); // System.out.println(setupRegionsString); bot.writeInfo(setupNeighborsString); // System.out.println(setupNeighborsString); } private String getSuperRegionsString(GameMap map) { String superRegionsString = "setup_map super_regions"; for(ContinentData superRegion : map.continents) { int id = superRegion.getId(); int reward = superRegion.getArmiesReward(); superRegionsString = superRegionsString.concat(" " + id + " " + reward); } return superRegionsString; } private String getRegionsString(GameMap map) { String regionsString = "setup_map regions"; for(RegionData region : map.regions) { int id = region.getId(); int superRegionId = region.getContinentData().getId(); regionsString = regionsString.concat(" " + id + " " + superRegionId); } return regionsString; } //beetje inefficiente methode, maar kan niet sneller wss private String getNeighborsString(GameMap map) { String neighborsString = "setup_map neighbors"; ArrayList<Point> doneList = new ArrayList<Point>(); for(RegionData region : map.regions) { int id = region.getId(); String neighbors = ""; for(RegionData neighbor : region.getNeighbors()) { if(checkDoneList(doneList, id, neighbor.getId())) { neighbors = neighbors.concat("," + neighbor.getId()); doneList.add(new Point(id,neighbor.getId())); } } if(neighbors.length() != 0) { neighbors = neighbors.replaceFirst(","," "); neighborsString = neighborsString.concat(" " + id + neighbors); } } return neighborsString; } private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId) { for(Point p : doneList) if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId)) return false; return true; } public GameResult saveGame(GameMap map, Robot bot1, Robot bot2) { GameResult result = new GameResult(); result.config = config; for (RegionData region : map.regions) { if (region.ownedByPlayer(config.playerName1)) { ++result.player1Regions; result.player1Armies += region.getArmies(); } if (region.ownedByPlayer(config.playerName2)) { ++result.player2Regions; result.player2Armies += region.getArmies(); } } if (engine.winningPlayer() != null) { if (config.playerName1.equals(engine.winningPlayer().getName())) { result.winner = Team.PLAYER_1; } else if (config.playerName2.equals(engine.winningPlayer().getName())) { result.winner = Team.PLAYER_2; } } else { result.winner = null; } result.round = engine.getRoundNr()-1; System.out.println(result.getHumanString()); return result; } public static void main(String args[]) throws Exception { Config config = new Config(); config.bot1Init = "internal:conquest.bot.BotStarter"; //config.bot1Init = "human"; config.bot2Init = "internal:conquest.bot.BotStarter"; //config.bot2Init = "process:java -cp bin conquest.bot.BotStarter"; //config.bot2Init = "dir;process:c:/my_bot/;java -cp bin conquest.bot.BotStarter"; config.engine.botCommandTimeoutMillis = 24*60*60*1000; config.engine.maxGameRounds = 100; // visualize the map, if turned off, the simulation would run headless config.visualize = true; // if false, not all human controls would be accessible (when hijacking bots via 'H' or 'J') config.forceHumanVisualization = true; config.replayLog = new File("./replay.log"); RunGame run = new RunGame(config); GameResult result = run.go(); System.exit(0); } }
km3r/WarlightAI
Conquest/src/conquest/engine/RunGame.java
7,711
//aanpassen en een QPlayer class maken? met eigen finish
line_comment
nl
// Copyright 2014 theaigames.com (developers@theaigames.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. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. package conquest.engine; import java.awt.Point; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import conquest.engine.Engine.EngineConfig; import conquest.engine.Robot.RobotConfig; import conquest.engine.replay.FileGameLog; import conquest.engine.replay.GameLog; import conquest.engine.replay.ReplayHandler; import conquest.engine.robot.HumanRobot; import conquest.engine.robot.IORobot; import conquest.engine.robot.InternalRobot; import conquest.engine.robot.ProcessRobot; import conquest.game.ContinentData; import conquest.game.GameMap; import conquest.game.EnginePlayer; import conquest.game.RegionData; import conquest.game.Team; import conquest.game.move.MoveResult; import conquest.game.world.Continent; import conquest.game.world.Region; import conquest.view.GUI; public class RunGame { public static class Config implements Cloneable { public String gameId = "GAME"; public String playerName1 = "PLR1"; public String playerName2 = "PLR2"; public String bot1Id = "Bot1"; public String bot2Id = "Bot2"; public String bot1Init; public String bot2Init; public boolean visualize = true; /** * Optimize region circle positions for human controls. */ public boolean forceHumanVisualization = false; public File replayLog = null; public EngineConfig engine = new EngineConfig(); public String asString() { return gameId + ";" + playerName1 + ";" + playerName2 + ";" + bot1Id + ";" + bot2Id + ";" + visualize + ";" + forceHumanVisualization + ";" + engine.asString(); } @Override public Config clone() { Config result = fromString(asString()); result.replayLog = replayLog; result.bot1Init = bot1Init; result.bot2Init = bot2Init; return result; } public String getCSVHeader() { return "ID;Bot1;Bot2;" + engine.getCSVHeader(); } public String getCSV() { return gameId + ";" + bot1Id + ";" + bot2Id + ";" + engine.getCSV(); } public static Config fromString(String line) { String[] parts = line.split(";"); Config result = new Config(); result.gameId = parts[0]; result.playerName1 = parts[1]; result.playerName2 = parts[2]; result.bot1Id = parts[3]; result.bot2Id = parts[4]; result.visualize = Boolean.parseBoolean(parts[5]); result.forceHumanVisualization = Boolean.parseBoolean(parts[6]); int engineConfigStart = 0; for (int i = 0; i < 7; ++i) { engineConfigStart = line.indexOf(";", engineConfigStart); ++engineConfigStart; } result.engine = EngineConfig.fromString(line.substring(engineConfigStart)); return result; } } public static class GameResult { public Config config; public int player1Regions; public int player1Armies; public int player2Regions; public int player2Armies; public Team winner = null; /** * Number of the round the game ended. */ public int round; public String getWinnerName() { if (winner == null) return "NONE"; switch (winner) { case NEUTRAL: return "NONE"; case PLAYER_1: return config == null ? "Player1" : config.playerName1; case PLAYER_2: return config == null ? "Player2" : config.playerName2; } return null; } public String getWinnerId() { if (winner == null) return "NONE"; switch (winner) { case NEUTRAL: return "NONE"; case PLAYER_1: return config == null ? "Bot1" : config.bot1Id; case PLAYER_2: return config == null ? "Bot2" : config.bot2Id; } return null; } public String asString() { return getWinnerName() + ";" + player1Regions + ";" + player1Armies + ";" + player2Regions + ";" + player2Armies + ";" + round; } public String getHumanString() { return "Winner: " + getWinnerName() + "[" + getWinnerId() + "] in round " + round + "\nPlayer1: " + player1Regions + " regions / " + player1Armies + " armies\nPlayer2: " + player2Regions + " regions / " + player2Armies + " armies"; } public String getCSVHeader() { return "winnerId;winner;winnerName;player1Regions;player1Armies;player2Regions;player2Armies;round;" + config.getCSVHeader(); } public String getCSV() { return getWinnerId() + ";" + (winner == null || winner == Team.NEUTRAL ? "NONE" : winner) + ";" + getWinnerName() + ";" + player1Regions + ";" + player1Armies + ";" + player2Regions + ";" + player2Armies + ";" + round + ";" + config.getCSV(); } } Config config; LinkedList<MoveResult> fullPlayedGame; LinkedList<MoveResult> player1PlayedGame; LinkedList<MoveResult> player2PlayedGame; int gameIndex = 1; Engine engine; public RunGame(Config config) { this.config = config; } public GameResult goReplay(File replayFile) { try { System.out.println("starting replay " + replayFile.getAbsolutePath()); ReplayHandler replay = new ReplayHandler(replayFile); this.config.engine = replay.getConfig().engine; EnginePlayer player1, player2; Robot robot1, robot2; //setup the bots: bot1, bot2 robot1 = new IORobot(replay); robot2 = new IORobot(replay); player1 = new EnginePlayer(config.playerName1, robot1, config.engine.startingArmies); player2 = new EnginePlayer(config.playerName2, robot2, config.engine.startingArmies); return go(null, player1, player2, robot1, robot2); } catch (Exception e) { throw new RuntimeException("Failed to replay the game.", e); } } public GameResult go() { try { GameLog log = null; if (config.replayLog != null) { log = new FileGameLog(config.replayLog); } System.out.println("starting game " + config.gameId); EnginePlayer player1, player2; Robot robot1, robot2; //setup the bots: bot1, bot2 robot1 = setupRobot(config.playerName1, config.bot1Init); robot2 = setupRobot(config.playerName2, config.bot2Init); player1 = new EnginePlayer(config.playerName1, robot1, config.engine.startingArmies); player2 = new EnginePlayer(config.playerName2, robot2, config.engine.startingArmies); return go(log, player1, player2, robot1, robot2); } catch (Exception e) { throw new RuntimeException("Failed to run/finish the game.", e); } } private GameResult go(GameLog log, EnginePlayer player1, EnginePlayer player2, Robot robot1, Robot robot2) throws InterruptedException { //setup the map GameMap initMap, map; initMap = makeInitMap(); map = setupMap(initMap); // setup GUI GUI gui = null; if (config.visualize) { if (config.forceHumanVisualization) { gui.positions = gui.positionsHuman; } gui = new GUI(config.playerName1, config.playerName2, robot1.getRobotName(), robot2.getRobotName()); } //start the engine this.engine = new Engine(map, player1, player2, gui, config.engine); if (log != null) { log.start(config); } // setup robots RobotConfig robot1Cfg = new RobotConfig(player1.getName(), Team.PLAYER_1, config.engine.botCommandTimeoutMillis, log, gui); RobotConfig robot2Cfg = new RobotConfig(player2.getName(), Team.PLAYER_2, config.engine.botCommandTimeoutMillis, log, gui); robot1.setup(robot1Cfg); robot2.setup(robot2Cfg); //send the bots the info they need to start robot1.writeInfo("settings your_bot " + player1.getName()); robot1.writeInfo("settings opponent_bot " + player2.getName()); robot2.writeInfo("settings your_bot " + player2.getName()); robot2.writeInfo("settings opponent_bot " + player1.getName()); sendSetupMapInfo(player1.getBot(), initMap); sendSetupMapInfo(player2.getBot(), initMap); this.engine.distributeStartingRegions(); //decide the player's starting regions this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions) this.engine.sendAllInfo(); //play the game while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= config.engine.maxGameRounds) { if (log != null) { log.logComment("Engine", "Round " + this.engine.getRoundNr()); } this.engine.playRound(); } fullPlayedGame = this.engine.getFullPlayedGame(); player1PlayedGame = this.engine.getPlayer1PlayedGame(); player2PlayedGame = this.engine.getPlayer2PlayedGame(); GameResult result = finish(map, robot1, robot2); if (log != null) { log.finish(result); } return result; } private Robot setupRobot(String playerName, String botInit) throws IOException { if (botInit.startsWith("dir;process:")) { String cmd = botInit.substring(12); int semicolon = cmd.indexOf(";"); if (semicolon < 0) throw new RuntimeException("Invalid bot torrent (does not contain ';' separating directory and commmend): " + botInit); String dir = cmd.substring(0, semicolon); String process = cmd.substring(semicolon+1); return new ProcessRobot(playerName, dir, process); } if (botInit.startsWith("process:")) { String cmd = botInit.substring(8); return new ProcessRobot(playerName, cmd); } if (botInit.startsWith("internal:")) { String botFQCN = botInit.substring(9); return new InternalRobot(playerName, botFQCN); } if (botInit.startsWith("human")) { config.visualize = true; config.forceHumanVisualization = true; return new HumanRobot(playerName); } throw new RuntimeException("Invalid init string for player '" + playerName + "', must start either with 'process:' or 'internal:' or 'human', passed value was: " + botInit); } //aanpassen en<SUF> private GameResult finish(GameMap map, Robot bot1, Robot bot2) throws InterruptedException { System.out.println("GAME FINISHED: stopping bots..."); try { bot1.finish(); } catch (Exception e) { } try { bot2.finish(); } catch (Exception e) { } return this.saveGame(map, bot1, bot2); } //tijdelijk handmatig invoeren private GameMap makeInitMap() { GameMap map = new GameMap(); // INIT SUPER REGIONS // ORIGINAL CODE // SuperRegion northAmerica = new SuperRegion(1, 5); // SuperRegion southAmerica = new SuperRegion(2, 2); // SuperRegion europe = new SuperRegion(3, 5); // SuperRegion afrika = new SuperRegion(4, 3); // SuperRegion azia = new SuperRegion(5, 7); // SuperRegion australia = new SuperRegion(6, 2); Map<Continent, ContinentData> continents = new TreeMap<Continent, ContinentData>(new Comparator<Continent>() { @Override public int compare(Continent o1, Continent o2) { return o1.id - o2.id; } }); for (Continent continent : Continent.values()) { ContinentData continentData = new ContinentData(continent, continent.id, continent.reward); continents.put(continent, continentData); } // INIT REGIONS // ORIGINAL CODE // Region region1 = new Region(1, northAmerica); // Region region2 = new Region(2, northAmerica); // Region region3 = new Region(3, northAmerica); // Region region4 = new Region(4, northAmerica); // Region region5 = new Region(5, northAmerica); // Region region6 = new Region(6, northAmerica); // Region region7 = new Region(7, northAmerica); // Region region8 = new Region(8, northAmerica); // Region region9 = new Region(9, northAmerica); // // Region region10 = new Region(10, southAmerica); // Region region11 = new Region(11, southAmerica); // Region region12 = new Region(12, southAmerica); // Region region13 = new Region(13, southAmerica); // // Region region14 = new Region(14, europe); // Region region15 = new Region(15, europe); // Region region16 = new Region(16, europe); // Region region17 = new Region(17, europe); // Region region18 = new Region(18, europe); // Region region19 = new Region(19, europe); // Region region20 = new Region(20, europe); // // Region region21 = new Region(21, afrika); // Region region22 = new Region(22, afrika); // Region region23 = new Region(23, afrika); // Region region24 = new Region(24, afrika); // Region region25 = new Region(25, afrika); // Region region26 = new Region(26, afrika); // // Region region27 = new Region(27, azia); // Region region28 = new Region(28, azia); // Region region29 = new Region(29, azia); // Region region30 = new Region(30, azia); // Region region31 = new Region(31, azia); // Region region32 = new Region(32, azia); // Region region33 = new Region(33, azia); // Region region34 = new Region(34, azia); // Region region35 = new Region(35, azia); // Region region36 = new Region(36, azia); // Region region37 = new Region(37, azia); // Region region38 = new Region(38, azia); // // Region region39 = new Region(39, australia); // Region region40 = new Region(40, australia); // Region region41 = new Region(41, australia); // Region region42 = new Region(42, australia); Map<Region, RegionData> regions = new TreeMap<Region, RegionData>(new Comparator<Region>() { @Override public int compare(Region o1, Region o2) { return o1.id - o2.id; } }); for (Region region : Region.values()) { RegionData regionData = new RegionData(region, region.id, continents.get(region.continent)); regions.put(region, regionData); } // INIT NEIGHBOURS // ORIGINAL CODE // region1.addNeighbor(region2); region1.addNeighbor(region4); region1.addNeighbor(region30); // region2.addNeighbor(region4); region2.addNeighbor(region3); region2.addNeighbor(region5); // region3.addNeighbor(region5); region3.addNeighbor(region6); region3.addNeighbor(region14); // region4.addNeighbor(region5); region4.addNeighbor(region7); // region5.addNeighbor(region6); region5.addNeighbor(region7); region5.addNeighbor(region8); // region6.addNeighbor(region8); // region7.addNeighbor(region8); region7.addNeighbor(region9); // region8.addNeighbor(region9); // region9.addNeighbor(region10); // region10.addNeighbor(region11);region10.addNeighbor(region12); // region11.addNeighbor(region12);region11.addNeighbor(region13); // region12.addNeighbor(region13);region12.addNeighbor(region21); // region14.addNeighbor(region15);region14.addNeighbor(region16); // region15.addNeighbor(region16);region15.addNeighbor(region18); // region15.addNeighbor(region19);region16.addNeighbor(region17); // region17.addNeighbor(region19);region17.addNeighbor(region20);region17.addNeighbor(region27);region17.addNeighbor(region32);region17.addNeighbor(region36); // region18.addNeighbor(region19);region18.addNeighbor(region20);region18.addNeighbor(region21); // region19.addNeighbor(region20); // region20.addNeighbor(region21);region20.addNeighbor(region22);region20.addNeighbor(region36); // region21.addNeighbor(region22);region21.addNeighbor(region23);region21.addNeighbor(region24); // region22.addNeighbor(region23);region22.addNeighbor(region36); // region23.addNeighbor(region24);region23.addNeighbor(region25);region23.addNeighbor(region26);region23.addNeighbor(region36); // region24.addNeighbor(region25); // region25.addNeighbor(region26); // region27.addNeighbor(region28);region27.addNeighbor(region32);region27.addNeighbor(region33); // region28.addNeighbor(region29);region28.addNeighbor(region31);region28.addNeighbor(region33);region28.addNeighbor(region34); // region29.addNeighbor(region30);region29.addNeighbor(region31); // region30.addNeighbor(region31);region30.addNeighbor(region34);region30.addNeighbor(region35); // region31.addNeighbor(region34); // region32.addNeighbor(region33);region32.addNeighbor(region36);region32.addNeighbor(region37); // region33.addNeighbor(region34);region33.addNeighbor(region37);region33.addNeighbor(region38); // region34.addNeighbor(region35); // region36.addNeighbor(region37); // region37.addNeighbor(region38); // region38.addNeighbor(region39); // region39.addNeighbor(region40);region39.addNeighbor(region41); // region40.addNeighbor(region41);region40.addNeighbor(region42); // region41.addNeighbor(region42); for (Region regionName : Region.values()) { RegionData region = regions.get(regionName); for (Region neighbour : regionName.getForwardNeighbours()) { region.addNeighbor(regions.get(neighbour)); } } // ADD REGIONS TO THE MAP // ORIGINAL CODE // map.add(region1); map.add(region2); map.add(region3); // map.add(region4); map.add(region5); map.add(region6); // map.add(region7); map.add(region8); map.add(region9); // map.add(region10); map.add(region11); map.add(region12); // map.add(region13); map.add(region14); map.add(region15); // map.add(region16); map.add(region17); map.add(region18); // map.add(region19); map.add(region20); map.add(region21); // map.add(region22); map.add(region23); map.add(region24); // map.add(region25); map.add(region26); map.add(region27); // map.add(region28); map.add(region29); map.add(region30); // map.add(region31); map.add(region32); map.add(region33); // map.add(region34); map.add(region35); map.add(region36); // map.add(region37); map.add(region38); map.add(region39); // map.add(region40); map.add(region41); map.add(region42); for (RegionData region : regions.values()) { map.add(region); } // ADD SUPER REGIONS TO THE MAP // ORIGINAL CODE // map.add(northAmerica); // map.add(southAmerica); // map.add(europe); // map.add(afrika); // map.add(azia); // map.add(australia); for (ContinentData superRegion : continents.values()) { map.add(superRegion); } return map; } //Make every region neutral with 2 armies to start with private GameMap setupMap(GameMap initMap) { GameMap map = initMap; for(RegionData region : map.regions) { region.setPlayerName("neutral"); region.setArmies(2); } return map; } private void sendSetupMapInfo(Robot bot, GameMap initMap) { String setupSuperRegionsString, setupRegionsString, setupNeighborsString; setupSuperRegionsString = getSuperRegionsString(initMap); setupRegionsString = getRegionsString(initMap); setupNeighborsString = getNeighborsString(initMap); bot.writeInfo(setupSuperRegionsString); // System.out.println(setupSuperRegionsString); bot.writeInfo(setupRegionsString); // System.out.println(setupRegionsString); bot.writeInfo(setupNeighborsString); // System.out.println(setupNeighborsString); } private String getSuperRegionsString(GameMap map) { String superRegionsString = "setup_map super_regions"; for(ContinentData superRegion : map.continents) { int id = superRegion.getId(); int reward = superRegion.getArmiesReward(); superRegionsString = superRegionsString.concat(" " + id + " " + reward); } return superRegionsString; } private String getRegionsString(GameMap map) { String regionsString = "setup_map regions"; for(RegionData region : map.regions) { int id = region.getId(); int superRegionId = region.getContinentData().getId(); regionsString = regionsString.concat(" " + id + " " + superRegionId); } return regionsString; } //beetje inefficiente methode, maar kan niet sneller wss private String getNeighborsString(GameMap map) { String neighborsString = "setup_map neighbors"; ArrayList<Point> doneList = new ArrayList<Point>(); for(RegionData region : map.regions) { int id = region.getId(); String neighbors = ""; for(RegionData neighbor : region.getNeighbors()) { if(checkDoneList(doneList, id, neighbor.getId())) { neighbors = neighbors.concat("," + neighbor.getId()); doneList.add(new Point(id,neighbor.getId())); } } if(neighbors.length() != 0) { neighbors = neighbors.replaceFirst(","," "); neighborsString = neighborsString.concat(" " + id + neighbors); } } return neighborsString; } private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId) { for(Point p : doneList) if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId)) return false; return true; } public GameResult saveGame(GameMap map, Robot bot1, Robot bot2) { GameResult result = new GameResult(); result.config = config; for (RegionData region : map.regions) { if (region.ownedByPlayer(config.playerName1)) { ++result.player1Regions; result.player1Armies += region.getArmies(); } if (region.ownedByPlayer(config.playerName2)) { ++result.player2Regions; result.player2Armies += region.getArmies(); } } if (engine.winningPlayer() != null) { if (config.playerName1.equals(engine.winningPlayer().getName())) { result.winner = Team.PLAYER_1; } else if (config.playerName2.equals(engine.winningPlayer().getName())) { result.winner = Team.PLAYER_2; } } else { result.winner = null; } result.round = engine.getRoundNr()-1; System.out.println(result.getHumanString()); return result; } public static void main(String args[]) throws Exception { Config config = new Config(); config.bot1Init = "internal:conquest.bot.BotStarter"; //config.bot1Init = "human"; config.bot2Init = "internal:conquest.bot.BotStarter"; //config.bot2Init = "process:java -cp bin conquest.bot.BotStarter"; //config.bot2Init = "dir;process:c:/my_bot/;java -cp bin conquest.bot.BotStarter"; config.engine.botCommandTimeoutMillis = 24*60*60*1000; config.engine.maxGameRounds = 100; // visualize the map, if turned off, the simulation would run headless config.visualize = true; // if false, not all human controls would be accessible (when hijacking bots via 'H' or 'J') config.forceHumanVisualization = true; config.replayLog = new File("./replay.log"); RunGame run = new RunGame(config); GameResult result = run.go(); System.exit(0); } }
False
600
11641_4
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer van de huidige Slide_x000D_ // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
GertSallaerts/jabbertest
Presentation.java
935
// het slidenummer van de huidige Slide_x000D_
line_comment
nl
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer<SUF> // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
True
1,533
191337_14
/* * @(#)MathConstants.java 4.2.0 2018-01-28 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2018 MARIUSZ GROMADA. 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 <MARIUSZ GROMADA> ``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> 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.mathcollection; /** * MathConstants - class representing the most important math constants. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 4.2.0 */ public final class MathConstants { /** * Pi, Archimedes' constant or Ludolph's number */ public static final double PI = 3.14159265358979323846264338327950288; /** * Napier's constant, or Euler's number, base of Natural logarithm */ public static final double E = 2.71828182845904523536028747135266249; /** * Euler-Mascheroni constant */ public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243; /** * Golden ratio */ public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811; /** * Plastic constant */ public static final double PLASTIC = 1.32471795724474602596090885447809734; /** * Embree-Trefethen constant */ public static final double EMBREE_TREFETHEN = 0.70258; /** * Feigenbaum constant */ public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161; /** * Feigenbaum constant */ public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578; /** * Feigenbaum constant */ public static final double TWIN_PRIME = 0.66016181584686957392781211001455577; /** * Meissel-Mertens constant */ public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585; /** * Brun's constant for twin primes */ public static final double BRAUN_TWIN_PRIME = 1.9021605823; /** * Brun's constant for prime quadruplets */ public static final double BRAUN_PRIME_QUADR = 0.8705883800; /** * de Bruijn-Newman constant */ public static final double BRUIJN_NEWMAN = -2.7E-9; /** * Catalan's constant */ public static final double CATALAN = 0.91596559417721901505460351493238411; /** * Landau-Ramanujan constant */ public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232; /** * Viswanath's constant */ public static final double VISWANATH = 1.13198824; /** * Legendre's constant */ public static final double LEGENDRE = 1.0; /** * Ramanujan-Soldner constant */ public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744; /** * Erdos-Borwein constant */ public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458; /** * Bernstein's constant */ public static final double BERNSTEIN = 0.28016949902386913303; /** * Gauss-Kuzmin-Wirsing constant */ public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623; /** * Hafner-Sarnak-McCurley constant */ public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454; /** * Golomb-Dickman constant */ public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724; /** * Cahen's constant */ public static final double CAHEN = 0.6434105463; /** * Laplace limit */ public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290; /** * Alladi-Grinstead constant */ public static final double ALLADI_GRINSTEAD = 0.8093940205; /** * Lengyel's constant */ public static final double LENGYEL = 1.0986858055; /** * Levy's constant */ public static final double LEVY = 3.27582291872181115978768188245384386; /** * Apery's constant */ public static final double APERY = 1.20205690315959428539973816151144999; /** * Mills' constant */ public static final double MILLS = 1.30637788386308069046861449260260571; /** * Backhouse's constant */ public static final double BACKHOUSE = 1.45607494858268967139959535111654356; /** * Porter's constant */ public static final double PORTER = 1.4670780794; /** * Porter's constant */ public static final double LIEB_QUARE_ICE = 1.5396007178; /** * Niven's constant */ public static final double NIVEN = 1.70521114010536776428855145343450816; /** * Sierpiński's constant */ public static final double SIERPINSKI = 2.58498175957925321706589358738317116; /** * Khinchin's constant */ public static final double KHINCHIN = 2.68545200106530644530971483548179569; /** * Fransén-Robinson constant */ public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293; /** * Landau's constant */ public static final double LANDAU = 0.5; /** * Parabolic constant */ public static final double PARABOLIC = 2.29558714939263807403429804918949039; /** * Omega constant */ public static final double OMEGA = 0.56714329040978387299996866221035555; /** * MRB constant */ public static final double MRB = 0.187859; /** * A069284 - Logarithmic integral function li(2) */ public static final double LI2 = 1.045163780117492784844588889194613136522615578151; /** * Gompertz Constant OEIS A073003 */ public static final double GOMPERTZ = 0.596347362323194074341078499369279376074; /** * Square root of 2 */ public static final double SQRT2 = 1.4142135623730950488016887242096980785696718753769d; /** * Square root of pi */ public static final double SQRTPi = 1.772453850905516027298167483341145182797549456122387128213d; /** * Square root of 2*pi */ public static final double SQRT2Pi = 2.5066282746310005024157652848110452530069867406099d; /** * Natural logarithm of pi */ public static final double LNPI = MathFunctions.ln(PI); /** * Tetration left convergence limit */ public static final double EXP_MINUS_E = Math.pow(E, -E); /** * Tetration right convergence limit */ public static final double EXP_1_OVER_E = Math.pow(E, 1.0/E); /** * 1 over e */ public static final double EXP_MINUS_1 = 1.0 / Math.E; /** * Natural logarithm of sqrt(2) */ public static final double LN_SQRT2 = MathFunctions.ln(SQRT2); /** * Not-a-Number */ public static final double NOT_A_NUMBER = Double.NaN; }
SaadArdati/MathParser.org-mXparser
src/main/java/org/mariuszgromada/math/mxparser/mathcollection/MathConstants.java
3,541
/** * de Bruijn-Newman constant */
block_comment
nl
/* * @(#)MathConstants.java 4.2.0 2018-01-28 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2018 MARIUSZ GROMADA. 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 <MARIUSZ GROMADA> ``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> 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.mathcollection; /** * MathConstants - class representing the most important math constants. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 4.2.0 */ public final class MathConstants { /** * Pi, Archimedes' constant or Ludolph's number */ public static final double PI = 3.14159265358979323846264338327950288; /** * Napier's constant, or Euler's number, base of Natural logarithm */ public static final double E = 2.71828182845904523536028747135266249; /** * Euler-Mascheroni constant */ public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243; /** * Golden ratio */ public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811; /** * Plastic constant */ public static final double PLASTIC = 1.32471795724474602596090885447809734; /** * Embree-Trefethen constant */ public static final double EMBREE_TREFETHEN = 0.70258; /** * Feigenbaum constant */ public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161; /** * Feigenbaum constant */ public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578; /** * Feigenbaum constant */ public static final double TWIN_PRIME = 0.66016181584686957392781211001455577; /** * Meissel-Mertens constant */ public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585; /** * Brun's constant for twin primes */ public static final double BRAUN_TWIN_PRIME = 1.9021605823; /** * Brun's constant for prime quadruplets */ public static final double BRAUN_PRIME_QUADR = 0.8705883800; /** * de Bruijn-Newman constant<SUF>*/ public static final double BRUIJN_NEWMAN = -2.7E-9; /** * Catalan's constant */ public static final double CATALAN = 0.91596559417721901505460351493238411; /** * Landau-Ramanujan constant */ public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232; /** * Viswanath's constant */ public static final double VISWANATH = 1.13198824; /** * Legendre's constant */ public static final double LEGENDRE = 1.0; /** * Ramanujan-Soldner constant */ public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744; /** * Erdos-Borwein constant */ public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458; /** * Bernstein's constant */ public static final double BERNSTEIN = 0.28016949902386913303; /** * Gauss-Kuzmin-Wirsing constant */ public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623; /** * Hafner-Sarnak-McCurley constant */ public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454; /** * Golomb-Dickman constant */ public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724; /** * Cahen's constant */ public static final double CAHEN = 0.6434105463; /** * Laplace limit */ public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290; /** * Alladi-Grinstead constant */ public static final double ALLADI_GRINSTEAD = 0.8093940205; /** * Lengyel's constant */ public static final double LENGYEL = 1.0986858055; /** * Levy's constant */ public static final double LEVY = 3.27582291872181115978768188245384386; /** * Apery's constant */ public static final double APERY = 1.20205690315959428539973816151144999; /** * Mills' constant */ public static final double MILLS = 1.30637788386308069046861449260260571; /** * Backhouse's constant */ public static final double BACKHOUSE = 1.45607494858268967139959535111654356; /** * Porter's constant */ public static final double PORTER = 1.4670780794; /** * Porter's constant */ public static final double LIEB_QUARE_ICE = 1.5396007178; /** * Niven's constant */ public static final double NIVEN = 1.70521114010536776428855145343450816; /** * Sierpiński's constant */ public static final double SIERPINSKI = 2.58498175957925321706589358738317116; /** * Khinchin's constant */ public static final double KHINCHIN = 2.68545200106530644530971483548179569; /** * Fransén-Robinson constant */ public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293; /** * Landau's constant */ public static final double LANDAU = 0.5; /** * Parabolic constant */ public static final double PARABOLIC = 2.29558714939263807403429804918949039; /** * Omega constant */ public static final double OMEGA = 0.56714329040978387299996866221035555; /** * MRB constant */ public static final double MRB = 0.187859; /** * A069284 - Logarithmic integral function li(2) */ public static final double LI2 = 1.045163780117492784844588889194613136522615578151; /** * Gompertz Constant OEIS A073003 */ public static final double GOMPERTZ = 0.596347362323194074341078499369279376074; /** * Square root of 2 */ public static final double SQRT2 = 1.4142135623730950488016887242096980785696718753769d; /** * Square root of pi */ public static final double SQRTPi = 1.772453850905516027298167483341145182797549456122387128213d; /** * Square root of 2*pi */ public static final double SQRT2Pi = 2.5066282746310005024157652848110452530069867406099d; /** * Natural logarithm of pi */ public static final double LNPI = MathFunctions.ln(PI); /** * Tetration left convergence limit */ public static final double EXP_MINUS_E = Math.pow(E, -E); /** * Tetration right convergence limit */ public static final double EXP_1_OVER_E = Math.pow(E, 1.0/E); /** * 1 over e */ public static final double EXP_MINUS_1 = 1.0 / Math.E; /** * Natural logarithm of sqrt(2) */ public static final double LN_SQRT2 = MathFunctions.ln(SQRT2); /** * Not-a-Number */ public static final double NOT_A_NUMBER = Double.NaN; }
False
2,850
65568_3
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.spellchecker.xml; import com.intellij.codeInspection.SuppressQuickFix; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.*; import com.intellij.spellchecker.inspections.PlainTextSplitter; import com.intellij.spellchecker.inspections.Splitter; import com.intellij.spellchecker.tokenizer.LanguageSpellchecking; import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy; import com.intellij.spellchecker.tokenizer.TokenConsumer; import com.intellij.spellchecker.tokenizer.Tokenizer; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.xml.util.XmlEnumeratedValueReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy { private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer(); private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer(); @Override public @NotNull Tokenizer getTokenizer(PsiElement element) { if (element instanceof XmlText) { return myXmlTextTokenizer; } if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS && !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) { // Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI if (isInTemplateLanguageFile(element)) return EMPTY_TOKENIZER; return TEXT_TOKENIZER; } if (element instanceof XmlAttributeValue) { return myXmlAttributeTokenizer; } return super.getTokenizer(element); } @Override public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) { DomElement domElement = DomUtil.getDomElement(element); if (domElement != null) { if (domElement.getAnnotation(NoSpellchecking.class) != null) { return true; } } return false; } @Override public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) { return SuppressQuickFix.EMPTY_ARRAY; } protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() { return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance()); } private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) { if (parent == null) return false; var strategy = ContainerUtil.findInstance( LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()), XmlSpellcheckingStrategy.class); return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent) : isXmlDataCharactersParentHandled(parent); } protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) { return parent instanceof XmlText || parent.getNode().getElementType() == XmlElementType.XML_CDATA; } protected boolean isInTemplateLanguageFile(PsiElement element) { PsiFile file = element.getContainingFile(); return file == null || file.getLanguage() instanceof TemplateLanguage; } protected Tokenizer<? extends PsiElement> createTextTokenizer() { return new XmlTextTokenizer(PlainTextSplitter.getInstance()); } protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> { public XmlTextContentTokenizer(Splitter splitter) { super(splitter); } protected abstract boolean isContentToken(IElementType tokenType); @Override protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) { List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element)); element.acceptChildren(new XmlElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { if (element.getNode().getElementType() == XmlElementType.XML_CDATA) { element.acceptChildren(this); } else if (!(element instanceof LeafPsiElement) || !isContentToken(element.getNode().getElementType())) { result.add(element.getTextRangeInParent()); } } }); return result; } } protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> { public XmlTextTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_DATA_CHARACTERS || tokenType == XmlTokenType.XML_CDATA_START || tokenType == XmlTokenType.XML_CDATA_END || XmlTokenType.WHITESPACES.contains(tokenType); } } protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> { public XmlAttributeValueTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || XmlTokenType.WHITESPACES.contains(tokenType); } @Override protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) { TextRange range = ElementManipulators.getValueTextRange(element); if (range.isEmpty()) return emptyList(); String text = ElementManipulators.getValueText(element); return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text))); } @Override public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) { PsiReference[] references = element.getReferences(); for (PsiReference reference : references) { if (reference instanceof XmlEnumeratedValueReference) { if (reference.resolve() != null) { // this is probably valid enumeration value from XSD/RNG schema, such as SVG return; } } } final String valueTextTrimmed = element.getValue().trim(); // do not inspect colors like #00aaFF if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) { return; } super.tokenize(element, consumer); } private static boolean isHexString(final String s) { for (int i = 0; i < s.length(); i++) { if (!StringUtil.isHexDigit(s.charAt(i))) { return false; } } return true; } } }
google/intellij-community
xml/impl/src/com/intellij/spellchecker/xml/XmlSpellcheckingStrategy.java
2,180
// do not inspect colors like #00aaFF
line_comment
nl
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.spellchecker.xml; import com.intellij.codeInspection.SuppressQuickFix; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.*; import com.intellij.spellchecker.inspections.PlainTextSplitter; import com.intellij.spellchecker.inspections.Splitter; import com.intellij.spellchecker.tokenizer.LanguageSpellchecking; import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy; import com.intellij.spellchecker.tokenizer.TokenConsumer; import com.intellij.spellchecker.tokenizer.Tokenizer; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.xml.util.XmlEnumeratedValueReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy { private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer(); private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer(); @Override public @NotNull Tokenizer getTokenizer(PsiElement element) { if (element instanceof XmlText) { return myXmlTextTokenizer; } if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS && !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) { // Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI if (isInTemplateLanguageFile(element)) return EMPTY_TOKENIZER; return TEXT_TOKENIZER; } if (element instanceof XmlAttributeValue) { return myXmlAttributeTokenizer; } return super.getTokenizer(element); } @Override public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) { DomElement domElement = DomUtil.getDomElement(element); if (domElement != null) { if (domElement.getAnnotation(NoSpellchecking.class) != null) { return true; } } return false; } @Override public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) { return SuppressQuickFix.EMPTY_ARRAY; } protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() { return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance()); } private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) { if (parent == null) return false; var strategy = ContainerUtil.findInstance( LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()), XmlSpellcheckingStrategy.class); return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent) : isXmlDataCharactersParentHandled(parent); } protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) { return parent instanceof XmlText || parent.getNode().getElementType() == XmlElementType.XML_CDATA; } protected boolean isInTemplateLanguageFile(PsiElement element) { PsiFile file = element.getContainingFile(); return file == null || file.getLanguage() instanceof TemplateLanguage; } protected Tokenizer<? extends PsiElement> createTextTokenizer() { return new XmlTextTokenizer(PlainTextSplitter.getInstance()); } protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> { public XmlTextContentTokenizer(Splitter splitter) { super(splitter); } protected abstract boolean isContentToken(IElementType tokenType); @Override protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) { List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element)); element.acceptChildren(new XmlElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { if (element.getNode().getElementType() == XmlElementType.XML_CDATA) { element.acceptChildren(this); } else if (!(element instanceof LeafPsiElement) || !isContentToken(element.getNode().getElementType())) { result.add(element.getTextRangeInParent()); } } }); return result; } } protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> { public XmlTextTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_DATA_CHARACTERS || tokenType == XmlTokenType.XML_CDATA_START || tokenType == XmlTokenType.XML_CDATA_END || XmlTokenType.WHITESPACES.contains(tokenType); } } protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> { public XmlAttributeValueTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || XmlTokenType.WHITESPACES.contains(tokenType); } @Override protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) { TextRange range = ElementManipulators.getValueTextRange(element); if (range.isEmpty()) return emptyList(); String text = ElementManipulators.getValueText(element); return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text))); } @Override public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) { PsiReference[] references = element.getReferences(); for (PsiReference reference : references) { if (reference instanceof XmlEnumeratedValueReference) { if (reference.resolve() != null) { // this is probably valid enumeration value from XSD/RNG schema, such as SVG return; } } } final String valueTextTrimmed = element.getValue().trim(); // do not<SUF> if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) { return; } super.tokenize(element, consumer); } private static boolean isHexString(final String s) { for (int i = 0; i < s.length(); i++) { if (!StringUtil.isHexDigit(s.charAt(i))) { return false; } } return true; } } }
False
4,476
193877_8
/** * This file is part of RefactorGuidance project. Which explores possibilities to generate context based * instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students) * * Copyright (C) 2018, Patrick de Beer, p.debeer@fontys.nl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package analysis.context; import aig.AdaptiveInstructionGraph; import aig.CodeContext; import analysis.ICodeAnalyzer; import analysis.MethodAnalyzer.ClassMethodFinder; import analysis.dataflow.MethodDataFlowAnalyzer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * Class builds up a set of context detectors that are needed to detect contextual situations * in a given adaptive instruction graph. The list of detectors can be provided to the procedural * guidance generator */ public class ContextDetectorSetBuilder { private AdaptiveInstructionGraph _aig = null; private ContextConfiguration _analyzerConfig = null; private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>(); private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>(); public void SetAIT(AdaptiveInstructionGraph aig) { setAIT(aig); } public void setAIT(AdaptiveInstructionGraph aig) { this._aig = aig; } public List<IContextDetector> getContextDetectors() throws Exception { if(_analyzerConfig == null) { throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first"); } EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph(); String refactoringProcessName = this._aig.getRefactorMechanic(); if(refactoringProcessName.contentEquals("Rename Method")) { // Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen // They can be directly initialized if contextanalyzerconfiguration object is present // voor deze specifieke method // uitlezen cu + methodname of line numers // initieren ClassMethodFinder analyzer (en evt. andere analyzers) // instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector // intern weet op te vragen. // Voeg de analuzers toe aan ContextAnalyzerCOnfiguration BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input } else if(refactoringProcessName.contentEquals("Extract Method") ) { BuildExtractMethodContextDetectors(completeCodeContext); } return this._contextDetectors; } /** * Through the returned configuration object, the created analyzers can be accessed * - to initialize from the outside * - to be used by the detectors to access necessary information * @return */ public ContextConfiguration getContextAnalyzerConfiguration() { return _analyzerConfig; } public void setContextConfiguration(ContextConfiguration config) { _analyzerConfig = config; } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); _analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer()); _analyzerConfig.getMethodDataFlowAnalyzer().initialize( _analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(), _analyzerConfig.getCodeSection()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } /** * A set of context detectors is build based on the context set that is provided. * The @ContextConfiguration object is used to provide detectors with necessary input in a generic way * * @param completeCodeContext Context detectors that should be instantiated * @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers */ private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext, ContextConfiguration analyzerConfig) { if (ContextDetectorForAllContextDecisions(completeCodeContext)) { try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) { Class<?> classCtxt = Class.forName("analysis.context." + context.name()); Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration"); Constructor<?> constructor = classCtxt.getConstructor(classConfig); IContextDetector instance = (IContextDetector) constructor.newInstance(analyzerConfig); _contextDetectors.add(instance); } } } catch(ClassNotFoundException cnfe) { System.out.println(cnfe.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } } /** * Internally used to validate if all requested detectors in the context set are actually * present as classes in our java project * * @param completeCodeContext * @return True, when all necessary classes could be found */ private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { boolean allDefined = true; try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) Class.forName("analysis.context." + context.name()); } } catch(ClassNotFoundException cnfe) { System.out.println("class " + cnfe.getMessage() + " not defined"); allDefined = false; } return allDefined; } public void setConfiguration(ContextConfiguration configuration) { this._analyzerConfig = configuration; } }
the-refactorers/RefactorGuidanceTool
src/main/java/analysis/context/ContextDetectorSetBuilder.java
2,084
// intern weet op te vragen.
line_comment
nl
/** * This file is part of RefactorGuidance project. Which explores possibilities to generate context based * instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students) * * Copyright (C) 2018, Patrick de Beer, p.debeer@fontys.nl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package analysis.context; import aig.AdaptiveInstructionGraph; import aig.CodeContext; import analysis.ICodeAnalyzer; import analysis.MethodAnalyzer.ClassMethodFinder; import analysis.dataflow.MethodDataFlowAnalyzer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * Class builds up a set of context detectors that are needed to detect contextual situations * in a given adaptive instruction graph. The list of detectors can be provided to the procedural * guidance generator */ public class ContextDetectorSetBuilder { private AdaptiveInstructionGraph _aig = null; private ContextConfiguration _analyzerConfig = null; private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>(); private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>(); public void SetAIT(AdaptiveInstructionGraph aig) { setAIT(aig); } public void setAIT(AdaptiveInstructionGraph aig) { this._aig = aig; } public List<IContextDetector> getContextDetectors() throws Exception { if(_analyzerConfig == null) { throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first"); } EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph(); String refactoringProcessName = this._aig.getRefactorMechanic(); if(refactoringProcessName.contentEquals("Rename Method")) { // Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen // They can be directly initialized if contextanalyzerconfiguration object is present // voor deze specifieke method // uitlezen cu + methodname of line numers // initieren ClassMethodFinder analyzer (en evt. andere analyzers) // instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector // intern weet<SUF> // Voeg de analuzers toe aan ContextAnalyzerCOnfiguration BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input } else if(refactoringProcessName.contentEquals("Extract Method") ) { BuildExtractMethodContextDetectors(completeCodeContext); } return this._contextDetectors; } /** * Through the returned configuration object, the created analyzers can be accessed * - to initialize from the outside * - to be used by the detectors to access necessary information * @return */ public ContextConfiguration getContextAnalyzerConfiguration() { return _analyzerConfig; } public void setContextConfiguration(ContextConfiguration config) { _analyzerConfig = config; } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); _analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer()); _analyzerConfig.getMethodDataFlowAnalyzer().initialize( _analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(), _analyzerConfig.getCodeSection()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } /** * A set of context detectors is build based on the context set that is provided. * The @ContextConfiguration object is used to provide detectors with necessary input in a generic way * * @param completeCodeContext Context detectors that should be instantiated * @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers */ private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext, ContextConfiguration analyzerConfig) { if (ContextDetectorForAllContextDecisions(completeCodeContext)) { try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) { Class<?> classCtxt = Class.forName("analysis.context." + context.name()); Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration"); Constructor<?> constructor = classCtxt.getConstructor(classConfig); IContextDetector instance = (IContextDetector) constructor.newInstance(analyzerConfig); _contextDetectors.add(instance); } } } catch(ClassNotFoundException cnfe) { System.out.println(cnfe.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } } /** * Internally used to validate if all requested detectors in the context set are actually * present as classes in our java project * * @param completeCodeContext * @return True, when all necessary classes could be found */ private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { boolean allDefined = true; try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) Class.forName("analysis.context." + context.name()); } } catch(ClassNotFoundException cnfe) { System.out.println("class " + cnfe.getMessage() + " not defined"); allDefined = false; } return allDefined; } public void setConfiguration(ContextConfiguration configuration) { this._analyzerConfig = configuration; } }
False
3,502
20812_24
/* Copyright (C) 2008 Human Media Interaction - University of Twente * * This file is part of The Virtual Storyteller. * * The Virtual Storyteller 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. * * The Virtual Storyteller 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 The Virtual Storyteller. If not, see <http://www.gnu.org/licenses/>. * */ package vs.plotagent.inspiration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import vs.Config; import vs.knowledge.vocab.Fabula; import vs.utils.UniqueId; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import de.fuberlin.wiwiss.ng4j.Quad; public class InspirationRule { public static String mainGraphVar = "Vmain"; // TODO: make protected public String m_name; public Set<Node> m_subgraphnodes; public Node m_inspirationNode; public Node m_inspirationType; public Set<Node> m_inspirationCausers; public Set<Quad> m_antecedent; public Set<Quad> m_consequent; public Map<Node, String> m_nodeToVarMap; public Set<String> m_uniqueVars; //public Set<String> m_maingraphVars; public String m_maingraphVar; public int m_varCounter; private InspirationRule(Node inspirationNode, Node inspirationType, Set<Node> inspirationCausers, Set<Node> subGraphNodes) { m_antecedent = new HashSet<Quad>(); m_consequent = new HashSet<Quad>(); m_inspirationNode = inspirationNode; m_inspirationType = inspirationType; m_inspirationCausers = inspirationCausers; m_subgraphnodes = subGraphNodes; m_nodeToVarMap = new HashMap<Node, String>(); m_uniqueVars = new HashSet<String>(); //m_maingraphVars = new HashSet<String>(); } public InspirationRule(String name, Node inspirationNode, Node inspirationType, Set<Node> inspirationCausers, Set<Node> subGraphNodes) { this(inspirationNode, inspirationType, inspirationCausers, subGraphNodes); m_name = name; } public void add(InspirationRule r) { m_antecedent.addAll(r.getAntecedent()); m_consequent.addAll(r.getConsequent()); m_inspirationCausers.addAll(r.getInspirationCausers()); //m_nodeToVarMap.putAll(r.getVars()); } /** * Adds a quad to the antecedent (left hand side) of the rule. A rule fires when its antecedent is met. * TODO filter out stuff that a rule is not interested in? (e.g., rdfs:label) * * @param q the quad to add to the antecedent of the rule. */ public void addAntecedent(Quad q) { if (filterAccepts(q)) { m_antecedent.add(q); } } /** * Adds a quad to the consequent (right hand side) of the rule. When a rule fires, it produces the consequent. * @param q the quad to add to the consequent of the rule. */ public void addConsequent(Quad q) { if (filterAccepts(q)) { m_consequent.add(q); } } private String antecedentToString(Set<Quad> quadSet) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (Quad q : quadSet) { if (!firstTime) { sb.append(",\n"); } sb.append(quadToString(q)); firstTime = false; } return sb.toString(); } private String consequentToString(Set<Quad> quadSet) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; sb.append('['); for (Quad q : quadSet) { if (!firstTime) { sb.append(",\n"); } sb.append(" ").append(quadToString(q, true)); firstTime = false; } sb.append("\n]"); return sb.toString(); } /** * Following the steps from http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf * It must be symmetric, transitive and consistent */ @Override public boolean equals(Object o) { // 1. check for equality if (this == o) return true; // 2. check for type if (!(o instanceof InspirationRule)) return false; // 3. typecast InspirationRule ir = (InspirationRule) o; boolean equalCheck = true; // 4. Check for equality of important fields. // We are only interested in the antecedents, consequents, and inspiration-causers. return ir.getAntecedent().equals(this.getAntecedent()) && ir.getConsequent().equals(this.getConsequent()) && ir.getInspirationCausers().equals(this.getInspirationCausers()); } /*public Map<Node,String> getVars() { return m_nodeToVarMap; } public void addVar(Node n, String var) { m_nodeToVarMap.put(n, var); }*/ private boolean filterAccepts(Quad q) { boolean accept = true; if (q.getPredicate().matches(RDFS.label.asNode())) { accept = false; } // Ignore time for now; a rule should fire even if the exact times don't match! // TODO: time does matter, e.g. in determining the interval in which a rule can apply. // If time is specified in the narrative case, then it is relevant; use it sensibly (relative). if (q.getPredicate().matches(Node.createURI(Fabula.time))) { accept = false; } return accept; } public Set<Quad> getAntecedent() { return m_antecedent; } public Set<Quad> getConsequent() { return m_consequent; } public Set<Node> getInspirationCausers() { return m_inspirationCausers; } public Node getInspirationNode() { return m_inspirationNode; } public Node getInspirationType() { return m_inspirationType; } public String getName() { return m_name; } /** * Return the sum of the hashcodes of the important parts. hashCode must be overridden when equals() is used. */ @Override public int hashCode() { int result = 17; // arbitrary result = 37 * result + getAntecedent().hashCode(); // 37 is an odd prime result = 37 * result + getConsequent().hashCode(); result = 37 * result + getInspirationCausers().hashCode(); return result; } private String makeVar(Node elem, boolean isGraph) { // If we're making a variable out of a graph node, and it is the main graph, use dont-care _ if (isGraph && (!m_subgraphnodes.contains(elem))) { return mainGraphVar; } return "V" + elem.getLocalName().replace('.', '_'); } @Deprecated private String makeVarOld(Node elem, boolean isGraph) { // If we're making a variable out of a graph node, and it is the main graph, use dont-care _ if (isGraph && (!m_subgraphnodes.contains(elem))) { return "_"; } String var = (isGraph ? "_V" : "V"); return var + elem.getLocalName().replace('.', '_'); } private Map<Node, String> makeVars(Set<Quad> quadList) { //NamedGraphModel m = m_owner.getNamedGraph().asJenaModel(""); // TODO: niet zomaar alle individuals vervangen door variables! Standaard niet doen, // eventuele casetransformers definieren variaties. Nu verlies je alle semantiek onder // het niveau van OWL classes. // Meer specifiek: als de Individuals al bestaan (in de ontology), gebruik ze, zo niet, maak ze variabel // in dit geval, moet de informatie over de Individual uit de ontology ook in de regel terechtkomen? nah. Zit al in de world knowledge. for (Quad q : quadList) { // Test for RDF:Type if (q.getPredicate().matches(RDF.type.asNode())) { // add subject as variable (because it is an Individual) if (m_nodeToVarMap.get(q.getSubject()) == null) { m_nodeToVarMap.put(q.getSubject(), makeVar(q.getSubject(), false)); } } // Test for graph names // assumption: graph names do not matter. Might be wrong; the main graph name might matter // otherwise the rule can match because a particular subgraph contains the required LHS // TODO: when graph names don't matter, Prolog will unify triples that do not exist! Graph names DO matter. if (m_nodeToVarMap.get(q.getGraphName()) == null) { String var = makeVar(q.getGraphName(), true); m_nodeToVarMap.put(q.getGraphName(), var); if (m_subgraphnodes.contains(q.getGraphName())) { // We're talking about a subgraph; make it unique (two different subgraph variables must not bind to the same named graph URI) m_uniqueVars.add(var); } } } return m_nodeToVarMap; } private String nodeToString(Node n) { return nodeToString(n, false); } /* private String maingraphVarsToString() { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String vm: m_maingraphVars) { for (String vs: m_uniqueVars) { // add rule that the variables must be bound to different values if (! firsttime) { sb.append(','); } sb.append(vm).append(" \\= ").append(vs); firsttime = false; } } return sb.toString(); }*/ private String nodeToString(Node n, boolean isConsequent) { StringBuilder sb = new StringBuilder(); String var = m_nodeToVarMap.get(n); if (var != null) { if (isConsequent) { if (m_subgraphnodes.contains(n)) { // add to new subgraph sb.append(var); } else { if (m_maingraphVar != null) { // if (m_maingraphVars.contains(m_maingraphVar)) { sb.append(m_maingraphVar); } else { sb.append("maingraph"); } } } else { if (var.equals(mainGraphVar)) { // This means, we're talking about a maingraph named graph. // Prolog uses the source of a triple to denote a named graph. However, the source of triples // of the main graph come from ontologies (the setting), or assertions by the application (the changes) // therefore, each maingraph triple gets a different variable, to afford a rule in theory to match with // main graph knowledge from as many different sources as there are main graph triples. // TODO: when we move to SWI-Prolog version 5.6.37 or higher, we can explicitly set the source of triples // (i.e., to "mainGraph"), and we can revert to using one variable again. m_varCounter++; String uniqueVar; if (m_maingraphVar == null) { uniqueVar = "Vmain_" + m_varCounter; m_maingraphVar = uniqueVar; } else { uniqueVar = "_Vmain_" + m_varCounter; } sb.append(uniqueVar); } else { sb.append(var); } } } else { if (m_subgraphnodes.contains(n)) { // make new subgraph node // TODO: is this unique enough? StringBuilder newGraphBuilder = new StringBuilder(); newGraphBuilder.append('\'').append(Config.namespaceMap.get("graph")).append(UniqueId.generateUniqueIndividual("subgraph", "plotagent")).append('\''); m_nodeToVarMap.put(n, newGraphBuilder.toString()); sb.append(newGraphBuilder); } else { if (n.isLiteral()) { sb.append("literal("); sb.append("type("); sb.append('\'').append(n.getLiteralDatatypeURI()).append('\'') .append(','); sb.append('"').append(n.getLiteralValue()).append('"'); sb.append(')'); sb.append(')'); } else { sb.append('\'').append(n).append('\''); } } } return sb.toString(); } private String quadToString(Quad q) { return quadToString(q, false); } private String quadToString(Quad q, boolean isConsequent) { StringBuilder sb = new StringBuilder(); sb.append("rdf("); sb.append(nodeToString(q.getSubject())); sb.append(','); sb.append(nodeToString(q.getPredicate())); sb.append(','); sb.append(nodeToString(q.getObject())); sb.append(','); sb.append(nodeToString(q.getGraphName(), isConsequent)); sb.append(')'); return sb.toString(); } /** * A rule looks like this: * * suggestion('rule_14', (<quada>, <quadb>, <...>)) * :- * ( <quad1>, <quad2>, <...>) */ @Override public String toString() { // TODO: replace individuals by variables. // TODO: make version that compiles into operators makeVars(m_antecedent); //makeVars(m_consequent); StringBuilder sb = new StringBuilder(); sb.append("suggestion("); sb.append('\'').append(getName()).append("', "); sb.append('\'').append(getInspirationNode()).append("', "); sb.append('\'').append(getInspirationType()).append("', "); sb.append('['); boolean firstTime = true; for (Node n: getInspirationCausers()) { if (! firstTime) { sb.append(','); } sb.append(nodeToString(n)); firstTime = false; } sb.append("],\n"); // first process antecedent (because antecedent determines variable bindings for consequent)! String antecedent = antecedentToString(getAntecedent()); sb.append(consequentToString(getConsequent())); sb.append(")\n:- \n"); sb.append(antecedent); if (m_uniqueVars.size() > 1) { sb.append(",\n"); sb.append(uniqueVarsToString()); } /* if (m_maingraphVars.size() > 0 && m_uniqueVars.size()>0 ) { sb.append(",\n"); sb.append(maingraphVarsToString()); }*/ sb.append('.'); return sb.toString(); } /* * Makes sure that the unique vars bind to different values by stating an inequality relationship between them. */ private String uniqueVarsToString() { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String v1: m_uniqueVars) { for (String v2: m_uniqueVars) { if (! v1.equals(v2)) { // add rule that the variables must be bound to different values if (! firsttime) { sb.append(','); } sb.append(v1).append(" \\= ").append(v2); firsttime = false; } } } return sb.toString(); } }
logicmoo/virtstoryteller
src/vs/plotagent/inspiration/InspirationRule.java
4,729
// in dit geval, moet de informatie over de Individual uit de ontology ook in de regel terechtkomen? nah. Zit al in de world knowledge.
line_comment
nl
/* Copyright (C) 2008 Human Media Interaction - University of Twente * * This file is part of The Virtual Storyteller. * * The Virtual Storyteller 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. * * The Virtual Storyteller 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 The Virtual Storyteller. If not, see <http://www.gnu.org/licenses/>. * */ package vs.plotagent.inspiration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import vs.Config; import vs.knowledge.vocab.Fabula; import vs.utils.UniqueId; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import de.fuberlin.wiwiss.ng4j.Quad; public class InspirationRule { public static String mainGraphVar = "Vmain"; // TODO: make protected public String m_name; public Set<Node> m_subgraphnodes; public Node m_inspirationNode; public Node m_inspirationType; public Set<Node> m_inspirationCausers; public Set<Quad> m_antecedent; public Set<Quad> m_consequent; public Map<Node, String> m_nodeToVarMap; public Set<String> m_uniqueVars; //public Set<String> m_maingraphVars; public String m_maingraphVar; public int m_varCounter; private InspirationRule(Node inspirationNode, Node inspirationType, Set<Node> inspirationCausers, Set<Node> subGraphNodes) { m_antecedent = new HashSet<Quad>(); m_consequent = new HashSet<Quad>(); m_inspirationNode = inspirationNode; m_inspirationType = inspirationType; m_inspirationCausers = inspirationCausers; m_subgraphnodes = subGraphNodes; m_nodeToVarMap = new HashMap<Node, String>(); m_uniqueVars = new HashSet<String>(); //m_maingraphVars = new HashSet<String>(); } public InspirationRule(String name, Node inspirationNode, Node inspirationType, Set<Node> inspirationCausers, Set<Node> subGraphNodes) { this(inspirationNode, inspirationType, inspirationCausers, subGraphNodes); m_name = name; } public void add(InspirationRule r) { m_antecedent.addAll(r.getAntecedent()); m_consequent.addAll(r.getConsequent()); m_inspirationCausers.addAll(r.getInspirationCausers()); //m_nodeToVarMap.putAll(r.getVars()); } /** * Adds a quad to the antecedent (left hand side) of the rule. A rule fires when its antecedent is met. * TODO filter out stuff that a rule is not interested in? (e.g., rdfs:label) * * @param q the quad to add to the antecedent of the rule. */ public void addAntecedent(Quad q) { if (filterAccepts(q)) { m_antecedent.add(q); } } /** * Adds a quad to the consequent (right hand side) of the rule. When a rule fires, it produces the consequent. * @param q the quad to add to the consequent of the rule. */ public void addConsequent(Quad q) { if (filterAccepts(q)) { m_consequent.add(q); } } private String antecedentToString(Set<Quad> quadSet) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (Quad q : quadSet) { if (!firstTime) { sb.append(",\n"); } sb.append(quadToString(q)); firstTime = false; } return sb.toString(); } private String consequentToString(Set<Quad> quadSet) { StringBuilder sb = new StringBuilder(); boolean firstTime = true; sb.append('['); for (Quad q : quadSet) { if (!firstTime) { sb.append(",\n"); } sb.append(" ").append(quadToString(q, true)); firstTime = false; } sb.append("\n]"); return sb.toString(); } /** * Following the steps from http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf * It must be symmetric, transitive and consistent */ @Override public boolean equals(Object o) { // 1. check for equality if (this == o) return true; // 2. check for type if (!(o instanceof InspirationRule)) return false; // 3. typecast InspirationRule ir = (InspirationRule) o; boolean equalCheck = true; // 4. Check for equality of important fields. // We are only interested in the antecedents, consequents, and inspiration-causers. return ir.getAntecedent().equals(this.getAntecedent()) && ir.getConsequent().equals(this.getConsequent()) && ir.getInspirationCausers().equals(this.getInspirationCausers()); } /*public Map<Node,String> getVars() { return m_nodeToVarMap; } public void addVar(Node n, String var) { m_nodeToVarMap.put(n, var); }*/ private boolean filterAccepts(Quad q) { boolean accept = true; if (q.getPredicate().matches(RDFS.label.asNode())) { accept = false; } // Ignore time for now; a rule should fire even if the exact times don't match! // TODO: time does matter, e.g. in determining the interval in which a rule can apply. // If time is specified in the narrative case, then it is relevant; use it sensibly (relative). if (q.getPredicate().matches(Node.createURI(Fabula.time))) { accept = false; } return accept; } public Set<Quad> getAntecedent() { return m_antecedent; } public Set<Quad> getConsequent() { return m_consequent; } public Set<Node> getInspirationCausers() { return m_inspirationCausers; } public Node getInspirationNode() { return m_inspirationNode; } public Node getInspirationType() { return m_inspirationType; } public String getName() { return m_name; } /** * Return the sum of the hashcodes of the important parts. hashCode must be overridden when equals() is used. */ @Override public int hashCode() { int result = 17; // arbitrary result = 37 * result + getAntecedent().hashCode(); // 37 is an odd prime result = 37 * result + getConsequent().hashCode(); result = 37 * result + getInspirationCausers().hashCode(); return result; } private String makeVar(Node elem, boolean isGraph) { // If we're making a variable out of a graph node, and it is the main graph, use dont-care _ if (isGraph && (!m_subgraphnodes.contains(elem))) { return mainGraphVar; } return "V" + elem.getLocalName().replace('.', '_'); } @Deprecated private String makeVarOld(Node elem, boolean isGraph) { // If we're making a variable out of a graph node, and it is the main graph, use dont-care _ if (isGraph && (!m_subgraphnodes.contains(elem))) { return "_"; } String var = (isGraph ? "_V" : "V"); return var + elem.getLocalName().replace('.', '_'); } private Map<Node, String> makeVars(Set<Quad> quadList) { //NamedGraphModel m = m_owner.getNamedGraph().asJenaModel(""); // TODO: niet zomaar alle individuals vervangen door variables! Standaard niet doen, // eventuele casetransformers definieren variaties. Nu verlies je alle semantiek onder // het niveau van OWL classes. // Meer specifiek: als de Individuals al bestaan (in de ontology), gebruik ze, zo niet, maak ze variabel // in dit<SUF> for (Quad q : quadList) { // Test for RDF:Type if (q.getPredicate().matches(RDF.type.asNode())) { // add subject as variable (because it is an Individual) if (m_nodeToVarMap.get(q.getSubject()) == null) { m_nodeToVarMap.put(q.getSubject(), makeVar(q.getSubject(), false)); } } // Test for graph names // assumption: graph names do not matter. Might be wrong; the main graph name might matter // otherwise the rule can match because a particular subgraph contains the required LHS // TODO: when graph names don't matter, Prolog will unify triples that do not exist! Graph names DO matter. if (m_nodeToVarMap.get(q.getGraphName()) == null) { String var = makeVar(q.getGraphName(), true); m_nodeToVarMap.put(q.getGraphName(), var); if (m_subgraphnodes.contains(q.getGraphName())) { // We're talking about a subgraph; make it unique (two different subgraph variables must not bind to the same named graph URI) m_uniqueVars.add(var); } } } return m_nodeToVarMap; } private String nodeToString(Node n) { return nodeToString(n, false); } /* private String maingraphVarsToString() { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String vm: m_maingraphVars) { for (String vs: m_uniqueVars) { // add rule that the variables must be bound to different values if (! firsttime) { sb.append(','); } sb.append(vm).append(" \\= ").append(vs); firsttime = false; } } return sb.toString(); }*/ private String nodeToString(Node n, boolean isConsequent) { StringBuilder sb = new StringBuilder(); String var = m_nodeToVarMap.get(n); if (var != null) { if (isConsequent) { if (m_subgraphnodes.contains(n)) { // add to new subgraph sb.append(var); } else { if (m_maingraphVar != null) { // if (m_maingraphVars.contains(m_maingraphVar)) { sb.append(m_maingraphVar); } else { sb.append("maingraph"); } } } else { if (var.equals(mainGraphVar)) { // This means, we're talking about a maingraph named graph. // Prolog uses the source of a triple to denote a named graph. However, the source of triples // of the main graph come from ontologies (the setting), or assertions by the application (the changes) // therefore, each maingraph triple gets a different variable, to afford a rule in theory to match with // main graph knowledge from as many different sources as there are main graph triples. // TODO: when we move to SWI-Prolog version 5.6.37 or higher, we can explicitly set the source of triples // (i.e., to "mainGraph"), and we can revert to using one variable again. m_varCounter++; String uniqueVar; if (m_maingraphVar == null) { uniqueVar = "Vmain_" + m_varCounter; m_maingraphVar = uniqueVar; } else { uniqueVar = "_Vmain_" + m_varCounter; } sb.append(uniqueVar); } else { sb.append(var); } } } else { if (m_subgraphnodes.contains(n)) { // make new subgraph node // TODO: is this unique enough? StringBuilder newGraphBuilder = new StringBuilder(); newGraphBuilder.append('\'').append(Config.namespaceMap.get("graph")).append(UniqueId.generateUniqueIndividual("subgraph", "plotagent")).append('\''); m_nodeToVarMap.put(n, newGraphBuilder.toString()); sb.append(newGraphBuilder); } else { if (n.isLiteral()) { sb.append("literal("); sb.append("type("); sb.append('\'').append(n.getLiteralDatatypeURI()).append('\'') .append(','); sb.append('"').append(n.getLiteralValue()).append('"'); sb.append(')'); sb.append(')'); } else { sb.append('\'').append(n).append('\''); } } } return sb.toString(); } private String quadToString(Quad q) { return quadToString(q, false); } private String quadToString(Quad q, boolean isConsequent) { StringBuilder sb = new StringBuilder(); sb.append("rdf("); sb.append(nodeToString(q.getSubject())); sb.append(','); sb.append(nodeToString(q.getPredicate())); sb.append(','); sb.append(nodeToString(q.getObject())); sb.append(','); sb.append(nodeToString(q.getGraphName(), isConsequent)); sb.append(')'); return sb.toString(); } /** * A rule looks like this: * * suggestion('rule_14', (<quada>, <quadb>, <...>)) * :- * ( <quad1>, <quad2>, <...>) */ @Override public String toString() { // TODO: replace individuals by variables. // TODO: make version that compiles into operators makeVars(m_antecedent); //makeVars(m_consequent); StringBuilder sb = new StringBuilder(); sb.append("suggestion("); sb.append('\'').append(getName()).append("', "); sb.append('\'').append(getInspirationNode()).append("', "); sb.append('\'').append(getInspirationType()).append("', "); sb.append('['); boolean firstTime = true; for (Node n: getInspirationCausers()) { if (! firstTime) { sb.append(','); } sb.append(nodeToString(n)); firstTime = false; } sb.append("],\n"); // first process antecedent (because antecedent determines variable bindings for consequent)! String antecedent = antecedentToString(getAntecedent()); sb.append(consequentToString(getConsequent())); sb.append(")\n:- \n"); sb.append(antecedent); if (m_uniqueVars.size() > 1) { sb.append(",\n"); sb.append(uniqueVarsToString()); } /* if (m_maingraphVars.size() > 0 && m_uniqueVars.size()>0 ) { sb.append(",\n"); sb.append(maingraphVarsToString()); }*/ sb.append('.'); return sb.toString(); } /* * Makes sure that the unique vars bind to different values by stating an inequality relationship between them. */ private String uniqueVarsToString() { StringBuilder sb = new StringBuilder(); boolean firsttime = true; for (String v1: m_uniqueVars) { for (String v2: m_uniqueVars) { if (! v1.equals(v2)) { // add rule that the variables must be bound to different values if (! firsttime) { sb.append(','); } sb.append(v1).append(" \\= ").append(v2); firsttime = false; } } } return sb.toString(); } }
False
645
69594_0
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les_x000D_ student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
HBO-ICT-GP-SD/Laatsteversie
AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java
1,160
//afgemeld_lijst in de les_x000D_
line_comment
nl
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in<SUF> student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
True
4,535
10292_3
package be.kuleuven.cs.distrinet.jnome.core.type; import java.util.ArrayList; import java.util.List; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeReference; import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter; import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint; import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType; import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter; import org.aikodi.chameleon.oo.type.generics.TypeArgument; import org.aikodi.chameleon.oo.type.generics.TypeConstraint; import org.aikodi.chameleon.oo.type.generics.TypeParameter; import org.aikodi.chameleon.oo.view.ObjectOrientedView; import org.aikodi.chameleon.workspace.View; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; public class PureWildcard extends TypeArgument { public PureWildcard() { } public TypeParameter capture(FormalTypeParameter formal) { CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name()); capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c)); return newParameter; } /** * @param constraints * @return */ public List<TypeConstraint> capture(List<TypeConstraint> constraints) { List<TypeConstraint> newConstraints = new ArrayList<>(); for(TypeConstraint constraint: constraints) { TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint); newConstraints.add(clone); } //FIXME This should actually be determined by the type parameter itself. // perhaps it should compute its own upper bound reference if(newConstraints.size() == 0) { Java7 java = language(Java7.class); BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN()); TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace()); newConstraints.add(new ExtendsConstraint(tref)); } return newConstraints; } @Override protected PureWildcard cloneSelf() { return new PureWildcard(); } // TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat // wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad // verplaatst worden. NOPE, niet altijd eerst capturen. @Override public Type lowerBound() throws LookupException { View view = view(); ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class); return l.getNullType(view.namespace()); } @Override public Type type() throws LookupException { ExtendsWildcardType result = new ExtendsWildcardType(upperBound()); result.setUniParent(namespace().defaultNamespace()); return result; // PureWildCardType pureWildCardType = new PureWildCardType(parameterBound()); // pureWildCardType.setUniParent(this); // return pureWildCardType; } // public Type parameterBound() throws LookupException { //// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class); //// List<TypeArgument> args = nearestAncestor.typeArguments(); //// int index = args.indexOf(this); //// // Wrong, this should not be the type constructor, we need to take into account the //// // type instance //// Type typeConstructor = nearestAncestor.typeConstructor(); //// Type typeInstance = nearestAncestor.getElement(); //// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index); //// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index); //// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference(); //// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference); //// clonedUpperBoundReference.setUniParent(actualParameter); //// ////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse //// Type result = clonedUpperBoundReference.getElement(); //// return result; // } @Override public boolean uniSameAs(Element other) throws LookupException { return other instanceof PureWildcard; } @Override public Type upperBound() throws LookupException { //return language(ObjectOrientedLanguage.class).getDefaultSuperClass(); return view(ObjectOrientedView.class).topLevelType(); } @Override public Verification verifySelf() { return Valid.create(); } public String toString(java.util.Set<Element> visited) { return "?"; } @Override public boolean isWildCardBound() { return true; } }
tivervac/jnome
src/be/kuleuven/cs/distrinet/jnome/core/type/PureWildcard.java
1,478
// TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat
line_comment
nl
package be.kuleuven.cs.distrinet.jnome.core.type; import java.util.ArrayList; import java.util.List; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeReference; import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter; import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint; import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType; import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter; import org.aikodi.chameleon.oo.type.generics.TypeArgument; import org.aikodi.chameleon.oo.type.generics.TypeConstraint; import org.aikodi.chameleon.oo.type.generics.TypeParameter; import org.aikodi.chameleon.oo.view.ObjectOrientedView; import org.aikodi.chameleon.workspace.View; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; public class PureWildcard extends TypeArgument { public PureWildcard() { } public TypeParameter capture(FormalTypeParameter formal) { CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name()); capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c)); return newParameter; } /** * @param constraints * @return */ public List<TypeConstraint> capture(List<TypeConstraint> constraints) { List<TypeConstraint> newConstraints = new ArrayList<>(); for(TypeConstraint constraint: constraints) { TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint); newConstraints.add(clone); } //FIXME This should actually be determined by the type parameter itself. // perhaps it should compute its own upper bound reference if(newConstraints.size() == 0) { Java7 java = language(Java7.class); BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN()); TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace()); newConstraints.add(new ExtendsConstraint(tref)); } return newConstraints; } @Override protected PureWildcard cloneSelf() { return new PureWildcard(); } // TypeVariable concept<SUF> // wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad // verplaatst worden. NOPE, niet altijd eerst capturen. @Override public Type lowerBound() throws LookupException { View view = view(); ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class); return l.getNullType(view.namespace()); } @Override public Type type() throws LookupException { ExtendsWildcardType result = new ExtendsWildcardType(upperBound()); result.setUniParent(namespace().defaultNamespace()); return result; // PureWildCardType pureWildCardType = new PureWildCardType(parameterBound()); // pureWildCardType.setUniParent(this); // return pureWildCardType; } // public Type parameterBound() throws LookupException { //// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class); //// List<TypeArgument> args = nearestAncestor.typeArguments(); //// int index = args.indexOf(this); //// // Wrong, this should not be the type constructor, we need to take into account the //// // type instance //// Type typeConstructor = nearestAncestor.typeConstructor(); //// Type typeInstance = nearestAncestor.getElement(); //// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index); //// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index); //// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference(); //// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference); //// clonedUpperBoundReference.setUniParent(actualParameter); //// ////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse //// Type result = clonedUpperBoundReference.getElement(); //// return result; // } @Override public boolean uniSameAs(Element other) throws LookupException { return other instanceof PureWildcard; } @Override public Type upperBound() throws LookupException { //return language(ObjectOrientedLanguage.class).getDefaultSuperClass(); return view(ObjectOrientedView.class).topLevelType(); } @Override public Verification verifySelf() { return Valid.create(); } public String toString(java.util.Set<Element> visited) { return "?"; } @Override public boolean isWildCardBound() { return true; } }
False
2,721
26812_24
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * * @author JSON.org * @version 2012-10-26 */ public class XML { /** * The Character '&amp;'. */ public static final Character AMP = Character.valueOf('&'); /** * The Character '''. */ public static final Character APOS = Character.valueOf('\''); /** * The Character '!'. */ public static final Character BANG = Character.valueOf('!'); /** * The Character '='. */ public static final Character EQ = Character.valueOf('='); /** * The Character '>'. */ public static final Character GT = Character.valueOf('>'); /** * The Character '&lt;'. */ public static final Character LT = Character.valueOf('<'); /** * The Character '?'. */ public static final Character QUEST = Character.valueOf('?'); /** * The Character '"'. */ public static final Character QUOT = Character.valueOf('"'); /** * The Character '/'. */ public static final Character SLASH = Character.valueOf('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; JSONObject jsonobject = null; String string; String tagName; Object token; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << token = x.nextToken(); // <! if (token == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { token = x.nextToken(); if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { context.accumulate("content", string); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == LT) { i += 1; } else if (token == GT) { i -= 1; } } while (i > 0); return false; } else if (token == QUEST) { // <? x.skipPast("?>"); return false; } else if (token == SLASH) { // Close tag </ token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { tagName = (String) token; token = null; jsonobject = new JSONObject(); for (; ; ) { if (token == null) { token = x.nextToken(); } // attribute = value if (token instanceof String) { string = (String) token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, XML.stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); } // Empty tag <.../> } else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); } return false; // Content, between <...> and </...> } else if (token == GT) { for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; } else if (token instanceof String) { string = (String) token; if (string.length() > 0) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element } else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. This is much less ambitious than * JSONObject.stringToValue, especially because it does not attempt to * convert plus forms, octal forms, hex forms, or E forms lacking decimal * points. * * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { if ("".equals(string)) { return string; } if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } if ("0".equals(string)) { return Integer.valueOf(0); } // If it might be a number, try converting it. If that doesn't work, // return the string. try { char initial = string.charAt(0); boolean negative = false; if (initial == '-') { initial = string.charAt(1); negative = true; } if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { return string; } if ((initial >= '0' && initial <= '9')) { if (string.indexOf('.') >= 0) { return Double.valueOf(string); } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { Long myLong = Long.valueOf(string); if (myLong.longValue() == myLong.intValue()) { return Integer.valueOf(myLong.intValue()); } else { return myLong; } } } } catch (Exception ignore) { } return string; } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String key; Iterator keys; int length; String string; Object value; if (object instanceof JSONObject) { // Emit <tagName> if (tagName != null) { sb.append('<'); sb.append(tagName); sb.append('>'); } // Loop thru the keys. jo = (JSONObject) object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); value = jo.opt(key); if (value == null) { value = ""; } if (value instanceof String) { string = (String) value; } else { string = null; } // Emit content in body if ("content".equals(key)) { if (value instanceof JSONArray) { ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { sb.append('\n'); } sb.append(escape(ja.get(i).toString())); } } else { sb.append(escape(value.toString())); } // Emit an array of similar keys } else if (value instanceof JSONArray) { ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); if (value instanceof JSONArray) { sb.append('<'); sb.append(key); sb.append('>'); sb.append(toString(value)); sb.append("</"); sb.append(key); sb.append('>'); } else { sb.append(toString(value, key)); } } } else if ("".equals(value)) { sb.append('<'); sb.append(key); sb.append("/>"); // Emit a new tag <k> } else { sb.append(toString(value, key)); } } if (tagName != null) { // Emit the </tagname> close tag sb.append("</"); sb.append(tagName); sb.append('>'); } return sb.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else { if (object.getClass().isArray()) { object = new JSONArray(object); } if (object instanceof JSONArray) { ja = (JSONArray) object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); } else { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">"; } } } }
foobnix/LibreraReader
Builder/src/main/java/org/json/XML.java
4,528
// Content, between <...> and </...>
line_comment
nl
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * * @author JSON.org * @version 2012-10-26 */ public class XML { /** * The Character '&amp;'. */ public static final Character AMP = Character.valueOf('&'); /** * The Character '''. */ public static final Character APOS = Character.valueOf('\''); /** * The Character '!'. */ public static final Character BANG = Character.valueOf('!'); /** * The Character '='. */ public static final Character EQ = Character.valueOf('='); /** * The Character '>'. */ public static final Character GT = Character.valueOf('>'); /** * The Character '&lt;'. */ public static final Character LT = Character.valueOf('<'); /** * The Character '?'. */ public static final Character QUEST = Character.valueOf('?'); /** * The Character '"'. */ public static final Character QUOT = Character.valueOf('"'); /** * The Character '/'. */ public static final Character SLASH = Character.valueOf('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; JSONObject jsonobject = null; String string; String tagName; Object token; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << token = x.nextToken(); // <! if (token == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { token = x.nextToken(); if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { context.accumulate("content", string); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == LT) { i += 1; } else if (token == GT) { i -= 1; } } while (i > 0); return false; } else if (token == QUEST) { // <? x.skipPast("?>"); return false; } else if (token == SLASH) { // Close tag </ token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { tagName = (String) token; token = null; jsonobject = new JSONObject(); for (; ; ) { if (token == null) { token = x.nextToken(); } // attribute = value if (token instanceof String) { string = (String) token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, XML.stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); } // Empty tag <.../> } else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); } return false; // Content, between<SUF> } else if (token == GT) { for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; } else if (token instanceof String) { string = (String) token; if (string.length() > 0) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element } else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. This is much less ambitious than * JSONObject.stringToValue, especially because it does not attempt to * convert plus forms, octal forms, hex forms, or E forms lacking decimal * points. * * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { if ("".equals(string)) { return string; } if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } if ("0".equals(string)) { return Integer.valueOf(0); } // If it might be a number, try converting it. If that doesn't work, // return the string. try { char initial = string.charAt(0); boolean negative = false; if (initial == '-') { initial = string.charAt(1); negative = true; } if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { return string; } if ((initial >= '0' && initial <= '9')) { if (string.indexOf('.') >= 0) { return Double.valueOf(string); } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { Long myLong = Long.valueOf(string); if (myLong.longValue() == myLong.intValue()) { return Integer.valueOf(myLong.intValue()); } else { return myLong; } } } } catch (Exception ignore) { } return string; } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String key; Iterator keys; int length; String string; Object value; if (object instanceof JSONObject) { // Emit <tagName> if (tagName != null) { sb.append('<'); sb.append(tagName); sb.append('>'); } // Loop thru the keys. jo = (JSONObject) object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); value = jo.opt(key); if (value == null) { value = ""; } if (value instanceof String) { string = (String) value; } else { string = null; } // Emit content in body if ("content".equals(key)) { if (value instanceof JSONArray) { ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { sb.append('\n'); } sb.append(escape(ja.get(i).toString())); } } else { sb.append(escape(value.toString())); } // Emit an array of similar keys } else if (value instanceof JSONArray) { ja = (JSONArray) value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); if (value instanceof JSONArray) { sb.append('<'); sb.append(key); sb.append('>'); sb.append(toString(value)); sb.append("</"); sb.append(key); sb.append('>'); } else { sb.append(toString(value, key)); } } } else if ("".equals(value)) { sb.append('<'); sb.append(key); sb.append("/>"); // Emit a new tag <k> } else { sb.append(toString(value, key)); } } if (tagName != null) { // Emit the </tagname> close tag sb.append("</"); sb.append(tagName); sb.append('>'); } return sb.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else { if (object.getClass().isArray()) { object = new JSONArray(object); } if (object instanceof JSONArray) { ja = (JSONArray) object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); } else { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">"; } } } }
False
3,731
44094_17
package uni.sasjonge.utils; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.jgrapht.Graph; import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.io.ComponentNameProvider; import org.jgrapht.io.ExportException; import org.jgrapht.io.GraphMLExporter; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import uni.sasjonge.Settings; /** * Utility class for different graph exporting methods * * @author Sascha Jongebloed * */ public class GraphExporter { static OntologyHierarchy ontHierachy; static OntologyDescriptor ontDescriptor; static Map<String, Integer> vertexToAxiomsCount = null; /** * Exports g in graphML to outputPath Every node and edge is shown as is in the * graph * * @param g The graph to export * @param outputPath Parth to output to * @throws ExportException */ public static void exportComplexGraph(Graph<String, DefaultEdge> g, String outputPath) throws ExportException { GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>(); // Register additional name attribute for vertices exporter.setVertexLabelProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return OntologyDescriptor.getCleanName(vertex); } }); exporter.setVertexIDProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return OntologyDescriptor.getCleanName(vertex); } }); // exporter.setVertexLabelAttributeName("custom_vertex_label"); // Initizalize Filewriter and export the corresponding graph FileWriter fw; try { fw = new FileWriter(outputPath); exporter.exportGraph(g, fw); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } static int i = 1; /** * Exports g in graphML to outputPath Every node is a connected component, every * edge stands for a ij-property * * @param g The graph to export * @param outputPath Parth to output to * @throws ExportException */ public static void exportCCStructureGraph(Graph<String, DefaultEdge> g, OWLOntology ontology, Map<String, Set<OWLAxiom>> vertexToAxiom, String outputPath) throws ExportException { System.out.println("STEEEEEP 1"); // Classes and individuals of the given ontology long startStep1Time = System.nanoTime(); Set<String> classes = getClassesForOntology(ontology); System.out.println("STEEEEEP 12"); Set<String> individuals = getIndividualsForOntology(ontology); System.out.println("STEEEEEP 13"); // Find the connected components ConnectivityInspector<String, DefaultEdge> ci = new ConnectivityInspector<>(g); // Create the graph we want to output Graph<String, DefaultEdge> ccGraph = new DefaultDirectedGraph<>(DefaultEdge.class); // Maps a name to each cc Map<Set<String>, String> ccToVertexName = new HashMap<>(); // CC's with axioms List<Set<String>> ccWithAxioms = new ArrayList<>(); // Map the vertexes to the corresponding set of axioms, classes, individuals Map<String, Set<String>> vertexToClasses = new HashMap<>(); Map<String, Set<String>> vertexToIndividuals = new HashMap<>(); System.out.println("STEEEEEP 14"); Map<String, Set<OWLAxiom>> vertexToAxioms = null; if (Settings.SHOW_AXIOMS) { vertexToAxioms = getAxiomsToVertex(ci.connectedSets(), vertexToAxiom); GraphExporter.vertexToAxiomsCount = new HashMap<>(); for (Entry<String, Set<OWLAxiom>> e : vertexToAxioms.entrySet()) { vertexToAxiomsCount.put(e.getKey(), e.getValue().size()); } } else { vertexToAxiomsCount = getAxiomsToVertexCount(ci.connectedSets(), vertexToAxiom); } long stopStep1Time = System.nanoTime(); System.out.println("Graphbuilding: Step 1 took " + (stopStep1Time - startStep1Time) / 1000000 + "ms"); System.out.println("STEEEEEP 2"); long startClassIndivTime = System.nanoTime(); // Map vertexes to classes // Map vertexes to individuals for (Set<String> cc : ci.connectedSets()) { // classes and individuals // start with same baseset (alle elements of the cc) Set<String> classesForThisCC = cc.stream().map(e -> OntologyDescriptor.getCleanName(e)) .collect(Collectors.toSet()); Set<String> individualsForThisCC = new HashSet<>(classesForThisCC); classesForThisCC.retainAll(classes); if (classesForThisCC.size() > 0) { vertexToClasses.put(cc.toString() + "", classesForThisCC); if (classesForThisCC.size() == 29) { System.out.println(classesForThisCC); } } // individuals individualsForThisCC.retainAll(individuals); if (individualsForThisCC.size() > 0) { vertexToIndividuals.put(cc.toString() + "", individualsForThisCC); } } // Add vertexes for all connected components for (Set<String> cc : ci.connectedSets()) { // System.out // .println("Number of axioms for " + cc.toString() + " is " + // vertexToAxioms.get(cc.toString() + "")); if (vertexToAxiomsCount.get(cc.toString() + "") != null) { ccToVertexName.put(cc, cc.toString() + ""); ccGraph.addVertex(cc.toString() + ""); ccWithAxioms.add(cc); i++; } } ; long endClassIndivTime = System.nanoTime(); System.out.println("Graphbuilding: Step 2 took " + (endClassIndivTime - startClassIndivTime) / 1000000 + "ms"); System.out.println("STEEEEEP 3"); // Create a map from subconcepts to the cc that contains it Map<String, Set<String>> role0ToCC = new HashMap<>(); Map<String, Set<String>> role1ToCC = new HashMap<>(); ccWithAxioms.stream().forEach(cc -> { cc.stream().forEach(subcon -> { if (subcon.endsWith(Settings.PROPERTY_0_DESIGNATOR)) { role0ToCC.put(subcon, cc); } else if (subcon.endsWith(Settings.PROPERTY_1_DESIGNATOR)) { role1ToCC.put(subcon, cc); } }); }); //find corresponding property nodes (same prefix, ending // with 0 or 1) // remember the name of properties for the edges System.out.println("STEEEEEP 4"); long startPropTime = System.nanoTime(); Map<DefaultEdge, Set<String>> nameForEdge = new HashMap<>(); Map<String, Set<String>> vertexToProperties = new HashMap<>(); System.out.println("!!!! role0ToCC is " + role0ToCC.size()); for (Entry<String, Set<String>> roleToCC : role0ToCC.entrySet()) { String role0 = roleToCC.getKey(); Set<String> ccOfRole1 = role1ToCC.get(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()) + Settings.PROPERTY_1_DESIGNATOR); // If there is a "partner-role" if (ccOfRole1 != null && !ccOfRole1.equals(roleToCC.getValue())) { // if the partner-role is in another cc, add the name to the // edge between the corresponding cc's DefaultEdge edge = null; long startGetEdge = System.currentTimeMillis(); Set<DefaultEdge> edgeList = ccGraph.getAllEdges(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1)); long stopGetEdge = System.currentTimeMillis(); System.out.println("???????????????????? Getting Edge took here " + (stopGetEdge - startGetEdge)/1000000); if (edgeList.isEmpty()) { long startAddEdge = System.currentTimeMillis(); // If there are no edges of this type, add one edge = ccGraph.addEdge(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1)); long stopAddEdge = System.currentTimeMillis(); System.out.println("???????????????????? Adding Edge took here " + (stopAddEdge - startAddEdge)/1000000); } else if (edgeList.size() == 1) { // If the edgelist is not empty it should only contain one element. edge = edgeList.iterator().next(); } // Add the hashset if it doesn't exist already if (nameForEdge.get(edge) == null) { nameForEdge.put(edge, new HashSet<String>()); } System.out.println("!!!!!!!! Adding" + role0.toString()); // Then add the name of the edge // System.out.println(getCleanName(subcon.substring(0, subcon.length() - 1))); nameForEdge.get(edge) .add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_1_DESIGNATOR.length()))); } else { // if there is no "partner" role role0 is a dataproperty // if role0 and role1 have the same cc, they are in the same partition String ccName = ccToVertexName.get(roleToCC.getValue()); if (vertexToProperties.get(ccName) == null) { vertexToProperties.put(ccName, new HashSet<>()); } vertexToProperties.get(ccName) .add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()))); } } long endPropTime = System.nanoTime(); System.out.println( "Graphbuilding: Mapping vertexes to properties took " + (endPropTime - startPropTime) / 1000000 + "ms"); ///////////////////////////////////////////////////////////////////////// // Export the Graph GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>(); System.out.println("STEEEEEP 5"); // Register additional name attribute for vertices exporter.setVertexLabelProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return ontDescriptor.getLabelForConnectedComponent(vertexToAxiomsCount.get(vertex), vertexToClasses.get(vertex), vertexToProperties.get(vertex), vertexToIndividuals.get(vertex)) + (Settings.SHOW_AXIOMS ? "\n" + ontDescriptor.getAxiomString(vertexToAxioms.get(vertex)) : ""); // + ((axioms.size() < 16) ? "_________\n CC: \n" + vertex : ""); } }); System.out.println("STEEEEEP 6"); // Register additional name attribute for edges exporter.setEdgeLabelProvider(new ComponentNameProvider<DefaultEdge>() { @Override public String getName(DefaultEdge edge) { return ontDescriptor.getPropertiesStringForCC(nameForEdge.get(edge)); // return nameForEdge.get(edge).toString(); } }); // exporter.setVertexLabelAttributeName("custom_vertex_label"); // Initizalize Filewriter and export the corresponding graph FileWriter fw; try { long startWriteTime = System.nanoTime(); fw = new FileWriter(outputPath); exporter.exportGraph(ccGraph, fw); fw.flush(); fw.close(); long endWriteTime = System.nanoTime(); System.out .println("Graphbuilding: Writing output took " + (endWriteTime - startWriteTime) / 1000000 + "ms"); } catch (IOException e) { e.printStackTrace(); } } private static Map<String, Set<OWLAxiom>> getAxiomsToVertex(List<Set<String>> connectedSets, Map<String, Set<OWLAxiom>> vertexToAxiom) { long startTimes = System.nanoTime(); Map<String, Set<OWLAxiom>> vertexToAxioms = new HashMap<>(); for (Set<String> cc : connectedSets) { for (String vert : cc) { if (vertexToAxiom.get(vert) != null) { if (!vertexToAxioms.containsKey(cc.toString() + "")) { vertexToAxioms.put(cc.toString() + "", new HashSet<>()); } vertexToAxioms.get(cc.toString() + "").addAll(vertexToAxiom.get(vert)); } } } long endTimes = System.nanoTime(); System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms"); return vertexToAxioms; } private static Map<String, Integer> getAxiomsToVertexCount(List<Set<String>> connectedSets, Map<String, Set<OWLAxiom>> vertexToAxiom) { long startTimes = System.nanoTime(); Map<String, Integer> vertexToAxioms = new HashMap<>(); for (Set<String> cc : connectedSets) { int count = 0; for (String vert : cc) { count = vertexToAxiom.get(vert) != null ? count + vertexToAxiom.get(vert).size() : count; } vertexToAxioms.put(cc.toString() + "",count); } long endTimes = System.nanoTime(); System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms"); return vertexToAxioms; } private static Set<String> getClassesForOntology(OWLOntology ontology) { return ontology.classesInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e)) .collect(Collectors.toSet()); } private static Set<String> getIndividualsForOntology(OWLOntology ontology) { return ontology.individualsInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e)) .collect(Collectors.toSet()); } /** * Initiates mappings * * @param ontology */ public static void init(OWLOntology ontology) { try { System.out.println("STEEEEEP 0x1"); ontHierachy = new OntologyHierarchy(ontology); System.out.println("STEEEEEP 0x2"); ontDescriptor = new OntologyDescriptor(ontHierachy, ontology); // System.out.println(depthToClasses); } catch (OWLOntologyCreationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
mpomarlan/epartition
src/main/java/uni/sasjonge/utils/GraphExporter.java
4,389
// vertexToAxioms.get(cc.toString() + ""));
line_comment
nl
package uni.sasjonge.utils; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.jgrapht.Graph; import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.io.ComponentNameProvider; import org.jgrapht.io.ExportException; import org.jgrapht.io.GraphMLExporter; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import uni.sasjonge.Settings; /** * Utility class for different graph exporting methods * * @author Sascha Jongebloed * */ public class GraphExporter { static OntologyHierarchy ontHierachy; static OntologyDescriptor ontDescriptor; static Map<String, Integer> vertexToAxiomsCount = null; /** * Exports g in graphML to outputPath Every node and edge is shown as is in the * graph * * @param g The graph to export * @param outputPath Parth to output to * @throws ExportException */ public static void exportComplexGraph(Graph<String, DefaultEdge> g, String outputPath) throws ExportException { GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>(); // Register additional name attribute for vertices exporter.setVertexLabelProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return OntologyDescriptor.getCleanName(vertex); } }); exporter.setVertexIDProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return OntologyDescriptor.getCleanName(vertex); } }); // exporter.setVertexLabelAttributeName("custom_vertex_label"); // Initizalize Filewriter and export the corresponding graph FileWriter fw; try { fw = new FileWriter(outputPath); exporter.exportGraph(g, fw); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } static int i = 1; /** * Exports g in graphML to outputPath Every node is a connected component, every * edge stands for a ij-property * * @param g The graph to export * @param outputPath Parth to output to * @throws ExportException */ public static void exportCCStructureGraph(Graph<String, DefaultEdge> g, OWLOntology ontology, Map<String, Set<OWLAxiom>> vertexToAxiom, String outputPath) throws ExportException { System.out.println("STEEEEEP 1"); // Classes and individuals of the given ontology long startStep1Time = System.nanoTime(); Set<String> classes = getClassesForOntology(ontology); System.out.println("STEEEEEP 12"); Set<String> individuals = getIndividualsForOntology(ontology); System.out.println("STEEEEEP 13"); // Find the connected components ConnectivityInspector<String, DefaultEdge> ci = new ConnectivityInspector<>(g); // Create the graph we want to output Graph<String, DefaultEdge> ccGraph = new DefaultDirectedGraph<>(DefaultEdge.class); // Maps a name to each cc Map<Set<String>, String> ccToVertexName = new HashMap<>(); // CC's with axioms List<Set<String>> ccWithAxioms = new ArrayList<>(); // Map the vertexes to the corresponding set of axioms, classes, individuals Map<String, Set<String>> vertexToClasses = new HashMap<>(); Map<String, Set<String>> vertexToIndividuals = new HashMap<>(); System.out.println("STEEEEEP 14"); Map<String, Set<OWLAxiom>> vertexToAxioms = null; if (Settings.SHOW_AXIOMS) { vertexToAxioms = getAxiomsToVertex(ci.connectedSets(), vertexToAxiom); GraphExporter.vertexToAxiomsCount = new HashMap<>(); for (Entry<String, Set<OWLAxiom>> e : vertexToAxioms.entrySet()) { vertexToAxiomsCount.put(e.getKey(), e.getValue().size()); } } else { vertexToAxiomsCount = getAxiomsToVertexCount(ci.connectedSets(), vertexToAxiom); } long stopStep1Time = System.nanoTime(); System.out.println("Graphbuilding: Step 1 took " + (stopStep1Time - startStep1Time) / 1000000 + "ms"); System.out.println("STEEEEEP 2"); long startClassIndivTime = System.nanoTime(); // Map vertexes to classes // Map vertexes to individuals for (Set<String> cc : ci.connectedSets()) { // classes and individuals // start with same baseset (alle elements of the cc) Set<String> classesForThisCC = cc.stream().map(e -> OntologyDescriptor.getCleanName(e)) .collect(Collectors.toSet()); Set<String> individualsForThisCC = new HashSet<>(classesForThisCC); classesForThisCC.retainAll(classes); if (classesForThisCC.size() > 0) { vertexToClasses.put(cc.toString() + "", classesForThisCC); if (classesForThisCC.size() == 29) { System.out.println(classesForThisCC); } } // individuals individualsForThisCC.retainAll(individuals); if (individualsForThisCC.size() > 0) { vertexToIndividuals.put(cc.toString() + "", individualsForThisCC); } } // Add vertexes for all connected components for (Set<String> cc : ci.connectedSets()) { // System.out // .println("Number of axioms for " + cc.toString() + " is " + // vertexToAxioms.get(cc.toString() +<SUF> if (vertexToAxiomsCount.get(cc.toString() + "") != null) { ccToVertexName.put(cc, cc.toString() + ""); ccGraph.addVertex(cc.toString() + ""); ccWithAxioms.add(cc); i++; } } ; long endClassIndivTime = System.nanoTime(); System.out.println("Graphbuilding: Step 2 took " + (endClassIndivTime - startClassIndivTime) / 1000000 + "ms"); System.out.println("STEEEEEP 3"); // Create a map from subconcepts to the cc that contains it Map<String, Set<String>> role0ToCC = new HashMap<>(); Map<String, Set<String>> role1ToCC = new HashMap<>(); ccWithAxioms.stream().forEach(cc -> { cc.stream().forEach(subcon -> { if (subcon.endsWith(Settings.PROPERTY_0_DESIGNATOR)) { role0ToCC.put(subcon, cc); } else if (subcon.endsWith(Settings.PROPERTY_1_DESIGNATOR)) { role1ToCC.put(subcon, cc); } }); }); //find corresponding property nodes (same prefix, ending // with 0 or 1) // remember the name of properties for the edges System.out.println("STEEEEEP 4"); long startPropTime = System.nanoTime(); Map<DefaultEdge, Set<String>> nameForEdge = new HashMap<>(); Map<String, Set<String>> vertexToProperties = new HashMap<>(); System.out.println("!!!! role0ToCC is " + role0ToCC.size()); for (Entry<String, Set<String>> roleToCC : role0ToCC.entrySet()) { String role0 = roleToCC.getKey(); Set<String> ccOfRole1 = role1ToCC.get(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()) + Settings.PROPERTY_1_DESIGNATOR); // If there is a "partner-role" if (ccOfRole1 != null && !ccOfRole1.equals(roleToCC.getValue())) { // if the partner-role is in another cc, add the name to the // edge between the corresponding cc's DefaultEdge edge = null; long startGetEdge = System.currentTimeMillis(); Set<DefaultEdge> edgeList = ccGraph.getAllEdges(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1)); long stopGetEdge = System.currentTimeMillis(); System.out.println("???????????????????? Getting Edge took here " + (stopGetEdge - startGetEdge)/1000000); if (edgeList.isEmpty()) { long startAddEdge = System.currentTimeMillis(); // If there are no edges of this type, add one edge = ccGraph.addEdge(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1)); long stopAddEdge = System.currentTimeMillis(); System.out.println("???????????????????? Adding Edge took here " + (stopAddEdge - startAddEdge)/1000000); } else if (edgeList.size() == 1) { // If the edgelist is not empty it should only contain one element. edge = edgeList.iterator().next(); } // Add the hashset if it doesn't exist already if (nameForEdge.get(edge) == null) { nameForEdge.put(edge, new HashSet<String>()); } System.out.println("!!!!!!!! Adding" + role0.toString()); // Then add the name of the edge // System.out.println(getCleanName(subcon.substring(0, subcon.length() - 1))); nameForEdge.get(edge) .add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_1_DESIGNATOR.length()))); } else { // if there is no "partner" role role0 is a dataproperty // if role0 and role1 have the same cc, they are in the same partition String ccName = ccToVertexName.get(roleToCC.getValue()); if (vertexToProperties.get(ccName) == null) { vertexToProperties.put(ccName, new HashSet<>()); } vertexToProperties.get(ccName) .add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()))); } } long endPropTime = System.nanoTime(); System.out.println( "Graphbuilding: Mapping vertexes to properties took " + (endPropTime - startPropTime) / 1000000 + "ms"); ///////////////////////////////////////////////////////////////////////// // Export the Graph GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>(); System.out.println("STEEEEEP 5"); // Register additional name attribute for vertices exporter.setVertexLabelProvider(new ComponentNameProvider<String>() { @Override public String getName(String vertex) { return ontDescriptor.getLabelForConnectedComponent(vertexToAxiomsCount.get(vertex), vertexToClasses.get(vertex), vertexToProperties.get(vertex), vertexToIndividuals.get(vertex)) + (Settings.SHOW_AXIOMS ? "\n" + ontDescriptor.getAxiomString(vertexToAxioms.get(vertex)) : ""); // + ((axioms.size() < 16) ? "_________\n CC: \n" + vertex : ""); } }); System.out.println("STEEEEEP 6"); // Register additional name attribute for edges exporter.setEdgeLabelProvider(new ComponentNameProvider<DefaultEdge>() { @Override public String getName(DefaultEdge edge) { return ontDescriptor.getPropertiesStringForCC(nameForEdge.get(edge)); // return nameForEdge.get(edge).toString(); } }); // exporter.setVertexLabelAttributeName("custom_vertex_label"); // Initizalize Filewriter and export the corresponding graph FileWriter fw; try { long startWriteTime = System.nanoTime(); fw = new FileWriter(outputPath); exporter.exportGraph(ccGraph, fw); fw.flush(); fw.close(); long endWriteTime = System.nanoTime(); System.out .println("Graphbuilding: Writing output took " + (endWriteTime - startWriteTime) / 1000000 + "ms"); } catch (IOException e) { e.printStackTrace(); } } private static Map<String, Set<OWLAxiom>> getAxiomsToVertex(List<Set<String>> connectedSets, Map<String, Set<OWLAxiom>> vertexToAxiom) { long startTimes = System.nanoTime(); Map<String, Set<OWLAxiom>> vertexToAxioms = new HashMap<>(); for (Set<String> cc : connectedSets) { for (String vert : cc) { if (vertexToAxiom.get(vert) != null) { if (!vertexToAxioms.containsKey(cc.toString() + "")) { vertexToAxioms.put(cc.toString() + "", new HashSet<>()); } vertexToAxioms.get(cc.toString() + "").addAll(vertexToAxiom.get(vert)); } } } long endTimes = System.nanoTime(); System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms"); return vertexToAxioms; } private static Map<String, Integer> getAxiomsToVertexCount(List<Set<String>> connectedSets, Map<String, Set<OWLAxiom>> vertexToAxiom) { long startTimes = System.nanoTime(); Map<String, Integer> vertexToAxioms = new HashMap<>(); for (Set<String> cc : connectedSets) { int count = 0; for (String vert : cc) { count = vertexToAxiom.get(vert) != null ? count + vertexToAxiom.get(vert).size() : count; } vertexToAxioms.put(cc.toString() + "",count); } long endTimes = System.nanoTime(); System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms"); return vertexToAxioms; } private static Set<String> getClassesForOntology(OWLOntology ontology) { return ontology.classesInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e)) .collect(Collectors.toSet()); } private static Set<String> getIndividualsForOntology(OWLOntology ontology) { return ontology.individualsInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e)) .collect(Collectors.toSet()); } /** * Initiates mappings * * @param ontology */ public static void init(OWLOntology ontology) { try { System.out.println("STEEEEEP 0x1"); ontHierachy = new OntologyHierarchy(ontology); System.out.println("STEEEEEP 0x2"); ontDescriptor = new OntologyDescriptor(ontHierachy, ontology); // System.out.println(depthToClasses); } catch (OWLOntologyCreationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
False
2,040
205045_3
package Amresh;_x000D_ import javax.swing.*;_x000D_ import Amresh01.*;_x000D_ import java.awt.*;_x000D_ import java.awt.event.*;_x000D_ import java.io.*;_x000D_ import java.util.*;_x000D_ _x000D_ _x000D_ public class AdmissionForm extends JFrame implements ActionListener {_x000D_ _x000D_ private JTextField nameField, jeeRankField, mark12Field, mark10Field, fatherNameField, collegeNameField, schoolNameField,_x000D_ jeeRollNumberField, addressField, postField, blockField, distField, stateField, pinCodeField,_x000D_ mobileNumberField;_x000D_ private JComboBox<String> admissionTypeComboBox;_x000D_ private JComboBox<String> countryTypeComboBox;_x000D_ private JComboBox<String> genderTypeComboBox;_x000D_ private JComboBox<String> categoryTypeComboBox;_x000D_ private JComboBox<String> religionTypeComboBox;_x000D_ private JComboBox<String> courseTypeComboBox;_x000D_ private JComboBox<String> paymentTypeComboBox;_x000D_ private JComboBox<String> hostelFrameComboBox;_x000D_ private JComboBox<String> dayComboBox, monthComboBox, yearComboBox;_x000D_ private JPanel dobPanel; _x000D_ private JCheckBox acceptAllCheckBox;_x000D_ private JTextArea printTextArea;_x000D_ private JLabel photoLabel; // Added label for displaying the photo_x000D_ private JTextArea finalDetailsTextArea;_x000D_ private JButton backButton;_x000D_ _x000D_ _x000D_ public AdmissionForm() {_x000D_ _x000D_ _x000D_ setTitle("Admission Form - Sambalpur University");_x000D_ setSize(2000, 2000);_x000D_ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);_x000D_ setLocationRelativeTo(null);_x000D_ setLayout(new GridLayout(13, 2));_x000D_ _x000D_ _x000D_ add(new JLabel("Candidate Name(In capital):"));_x000D_ nameField = new JTextField();_x000D_ add(nameField);_x000D_ _x000D_ _x000D_ add(new JLabel("Gender:"));_x000D_ genderTypeComboBox = new JComboBox<>(new String[]{"MALE","FEMALE"});_x000D_ add(genderTypeComboBox);_x000D_ _x000D_ add(new JLabel("Date of Birth:"));_x000D_ _x000D_ dobPanel = new JPanel(); _x000D_ dobPanel.setLayout(new FlowLayout()); _x000D_ _x000D_ // Day ComboBox_x000D_ dayComboBox = new JComboBox<>();_x000D_ for (int i = 1; i <= 31; i++) {_x000D_ dayComboBox.addItem(String.valueOf(i));_x000D_ }_x000D_ dobPanel.add(dayComboBox);_x000D_ _x000D_ // Month ComboBox_x000D_ monthComboBox = new JComboBox<>(new String[]{ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"});_x000D_ dobPanel.add(monthComboBox);_x000D_ _x000D_ // Year ComboBox_x000D_ yearComboBox = new JComboBox<>();_x000D_ int currentYear = Calendar.getInstance().get(Calendar.YEAR);_x000D_ for (int i = currentYear - 60; i <= currentYear; i++) {_x000D_ yearComboBox.addItem(String.valueOf(i));_x000D_ }_x000D_ dobPanel.add(yearComboBox);_x000D_ _x000D_ add(dobPanel); // Add Date of Birth panel to the JFrame_x000D_ _x000D_ _x000D_ add(new JLabel("Category:"));_x000D_ categoryTypeComboBox = new JComboBox<>(new String[]{"GENERAL","OBC","SC","ST"});_x000D_ add(categoryTypeComboBox);_x000D_ _x000D_ add(new JLabel("Religion:"));_x000D_ religionTypeComboBox = new JComboBox<>(new String[]{"HINDU","CHRISTIAN","MUSLIM","ISLAM","SIKH","BUDDHISM","JAINISM"});_x000D_ add(religionTypeComboBox);_x000D_ _x000D_ _x000D_ _x000D_ add(new JLabel("JEE Main Rank:"));_x000D_ jeeRankField = new JTextField();_x000D_ add(jeeRankField);_x000D_ _x000D_ add(new JLabel("12th Marks(%)/Diploma mark(%):"));_x000D_ mark12Field = new JTextField();_x000D_ add(mark12Field);_x000D_ _x000D_ add(new JLabel("10th Marks(%):"));_x000D_ mark10Field = new JTextField();_x000D_ add(mark10Field);_x000D_ _x000D_ add(new JLabel("Father's Name"));_x000D_ fatherNameField = new JTextField();_x000D_ add(fatherNameField);_x000D_ _x000D_ add(new JLabel("College Name:"));_x000D_ collegeNameField = new JTextField();_x000D_ add(collegeNameField);_x000D_ _x000D_ add(new JLabel("10th School Name:"));_x000D_ schoolNameField = new JTextField();_x000D_ add(schoolNameField);_x000D_ _x000D_ add(new JLabel("JEE Main Roll Number:"));_x000D_ jeeRollNumberField = new JTextField();_x000D_ add(jeeRollNumberField);_x000D_ _x000D_ add(new JLabel("Country:"));_x000D_ countryTypeComboBox = new JComboBox<>(new String[]{"India","Bangladesh", "Pakistan", "Nepal", "Bhutan", "China", "Myanmar", "Sri Lanka","United States of America", "United Kingdom", "Canada", "Australia", "Russia", "Japan", "Germany"});_x000D_ add(countryTypeComboBox);_x000D_ _x000D_ add(new JLabel("Address:"));_x000D_ addressField = new JTextField();_x000D_ add(addressField);_x000D_ _x000D_ add(new JLabel("Post:"));_x000D_ postField = new JTextField();_x000D_ add(postField);_x000D_ _x000D_ add(new JLabel("Block:"));_x000D_ blockField = new JTextField();_x000D_ add(blockField);_x000D_ _x000D_ add(new JLabel("District:"));_x000D_ distField = new JTextField();_x000D_ add(distField);_x000D_ _x000D_ add(new JLabel("State:"));_x000D_ stateField = new JTextField();_x000D_ add(stateField);_x000D_ _x000D_ add(new JLabel("Pin Code:"));_x000D_ pinCodeField = new JTextField();_x000D_ add(pinCodeField);_x000D_ _x000D_ add(new JLabel("Mobile Number:"));_x000D_ mobileNumberField = new JTextField();_x000D_ add(mobileNumberField);_x000D_ _x000D_ add(new JLabel("Admission Type:"));_x000D_ admissionTypeComboBox = new JComboBox<>(new String[]{"BTech", "MTech", "Lateral Entry BTech","MCA"});_x000D_ add(admissionTypeComboBox);_x000D_ _x000D_ add(new JLabel("Intrested Course:"));_x000D_ courseTypeComboBox = new JComboBox<>(new String[]{"Computer Science & Engineering","Electrical Engineering","ECE (Electronics and Communications Engineering)","Electronics & Communication Engineering (ECE)","(CSE-AIML)Computer Science & Engineering specialization in Artificial Intelligence and Machine Learning","Computer Science & Engineering specialization with cyber security"});_x000D_ add(courseTypeComboBox);_x000D_ _x000D_ JButton uploadPhotoButton = new JButton("Upload Photo");_x000D_ uploadPhotoButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ JFileChooser fileChooser = new JFileChooser();_x000D_ int returnValue = fileChooser.showOpenDialog(null);_x000D_ _x000D_ if (returnValue == JFileChooser.APPROVE_OPTION) {_x000D_ File selectedFile = fileChooser.getSelectedFile();_x000D_ displaySelectedPhoto(selectedFile);_x000D_ }_x000D_ }_x000D_ });_x000D_ add(uploadPhotoButton);_x000D_ _x000D_ photoLabel = new JLabel();_x000D_ add(photoLabel);_x000D_ _x000D_ _x000D_ acceptAllCheckBox = new JCheckBox("Accept All Conditions\n");_x000D_ add(acceptAllCheckBox);_x000D_ _x000D_ JButton submitButton = new JButton("Submit");_x000D_ submitButton.addActionListener(this);_x000D_ add(submitButton);_x000D_ _x000D_ _x000D_ JButton clearButton = new JButton("Clear");_x000D_ clearButton.addActionListener(this);_x000D_ add(clearButton);_x000D_ _x000D_ backButton = new JButton("Back");_x000D_ backButton.addActionListener(e -> handleBackButton());_x000D_ add(backButton, BorderLayout.SOUTH);_x000D_ _x000D_ finalDetailsTextArea = new JTextArea(30, 50);_x000D_ finalDetailsTextArea.setEditable(false);_x000D_ _x000D_ pack();_x000D_ setVisible(true);_x000D_ _x000D_ }_x000D_ private void handleBackButton() {_x000D_ _x000D_ SwingUtilities.invokeLater(SambalpurUniversityFrontPage::new);_x000D_ _x000D_ this.setVisible(false);_x000D_ }_x000D_ _x000D_ private void displaySelectedPhoto(File file) {_x000D_ ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());_x000D_ Image image = imageIcon.getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH);_x000D_ photoLabel.setIcon(new ImageIcon(image));_x000D_ }_x000D_ _x000D_ public void actionPerformed(ActionEvent e) {_x000D_ if (e.getActionCommand().equals("Submit")) {_x000D_ _x000D_ boolean accepted = acceptAllCheckBox.isSelected();_x000D_ if (isRequiredFieldEmpty()) {_x000D_ JOptionPane.showMessageDialog(this, "Please fill in all the required fields!", "Error", JOptionPane.ERROR_MESSAGE);_x000D_ return;_x000D_ }_x000D_ _x000D_ _x000D_ if (!accepted) {_x000D_ JOptionPane.showMessageDialog(this, "Please accept all conditions before submission!", "Error", JOptionPane.ERROR_MESSAGE);_x000D_ return;_x000D_ }_x000D_ String fileName = "AppliedStudent.txt";_x000D_ String selectedFileName = "SelectedStudents.txt";_x000D_ _x000D_ String name = nameField.getText();_x000D_ String genderType = (String) genderTypeComboBox.getSelectedItem();_x000D_ String categoryType = (String) categoryTypeComboBox.getSelectedItem();_x000D_ String religionType = (String) religionTypeComboBox.getSelectedItem();_x000D_ String courseType = (String) courseTypeComboBox.getSelectedItem();_x000D_ String day = (String) dayComboBox.getSelectedItem();_x000D_ String month = (String) monthComboBox.getSelectedItem();_x000D_ String year = (String) yearComboBox.getSelectedItem();_x000D_ String dob = day + "-" + month + "-" + year;_x000D_ String jeeRank = jeeRankField.getText();_x000D_ String mark12 = mark12Field.getText();_x000D_ String mark10 = mark10Field.getText();_x000D_ String fatherName = fatherNameField.getText();_x000D_ String collegeName = collegeNameField.getText();_x000D_ String schoolName = schoolNameField.getText();_x000D_ String jeeRollNumber = jeeRollNumberField.getText();_x000D_ String countryType = (String) countryTypeComboBox.getSelectedItem();_x000D_ String address = addressField.getText() + ", " + postField.getText() + ", " + blockField.getText() + ", "_x000D_ + distField.getText() + ", " + stateField.getText() + ", " + pinCodeField.getText();_x000D_ String mobileNumber = mobileNumberField.getText();_x000D_ String admissionType = (String) admissionTypeComboBox.getSelectedItem();_x000D_ _x000D_ _x000D_ // Logic for selecting students based on criteria (JEE rank, 12th and 10th marks)_x000D_ boolean selected = false;_x000D_ _x000D_ _x000D_ _x000D_ if (!jeeRank.isEmpty() && !mark12.isEmpty() && !mark10.isEmpty()) {_x000D_ int jeeRankValue = Integer.parseInt(jeeRank);_x000D_ double averageMarks = (Double.parseDouble(mark12) + Double.parseDouble(mark10)) / 2.0;_x000D_ _x000D_ _x000D_ if ((admissionType.equals("BTech") && jeeRankValue <= 1000 && averageMarks >= 80) ||_x000D_ (admissionType.equals("MTech") && jeeRankValue <= 1000 && averageMarks >= 75) ||_x000D_ (admissionType.equals("Lateral Entry BTech") && jeeRankValue <= 1500 && averageMarks >= 70)||_x000D_ (admissionType.equals("MCA") && jeeRankValue <= 1800 && averageMarks >= 80)) {_x000D_ selected = true;_x000D_ JOptionPane.showMessageDialog(this, "Form submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(this, "congratulations you are eligible for admisstion", "Eligible", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ JOptionPane.showMessageDialog(this, "BTech/Leteral BTech : 96,000 \n MTech : 98,000 \n MCA : 90,000 ", "Fee structer", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ showPaymentForm();_x000D_ }_x000D_ else_x000D_ {_x000D_ JOptionPane.showMessageDialog(this, "Form submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(this, "Oops! you are not eligible for admisstion", "NOT Eligible", JOptionPane.INFORMATION_MESSAGE);_x000D_ }_x000D_ }_x000D_ _x000D_ String studentInfo = "\n\nCandidate Name: "+ name + "\nGender: " + genderType + "\nCategory: " + categoryType + "\nRILIGION : " + religionType +"\nDate of Birth: " + dob + "\nJEE Rank: " + jeeRank_x000D_ + "\n12th Marks: " + mark12 + "\n10th Marks: " + mark10 + "\nFather's Name: " + fatherName_x000D_ + "\nCollege Name: " + collegeName + "\nSchool Name: " + schoolName + "\nJEE Roll Number: "_x000D_ + jeeRollNumber + "\nCountry type: " + countryType +"\nAddress: " + address + "\nMobile Number: " + mobileNumber_x000D_ + "\nAdmission Type: " + admissionType + "\n Intrested Course: " + courseType ;_x000D_ _x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));_x000D_ PrintWriter selectedWriter = new PrintWriter(new BufferedWriter(new FileWriter(selectedFileName, true)))) {_x000D_ writer.write(studentInfo);_x000D_ writer.newLine();_x000D_ _x000D_ if (selected) {_x000D_ selectedWriter.println(studentInfo + " - SELECTED");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ clearFields();_x000D_ _x000D_ _x000D_ _x000D_ } _x000D_ else if (e.getActionCommand().equals("Clear")) {_x000D_ clearFields();_x000D_ }_x000D_ _x000D_ }_x000D_ private void clearFields() {_x000D_ nameField.setText("");_x000D_ jeeRankField.setText("");_x000D_ mark12Field.setText("");_x000D_ mark10Field.setText("");_x000D_ fatherNameField.setText("");_x000D_ collegeNameField.setText("");_x000D_ schoolNameField.setText("");_x000D_ jeeRollNumberField.setText("");_x000D_ addressField.setText("");_x000D_ postField.setText("");_x000D_ blockField.setText("");_x000D_ distField.setText("");_x000D_ stateField.setText("");_x000D_ pinCodeField.setText("");_x000D_ mobileNumberField.setText("");_x000D_ _x000D_ }_x000D_ public void showHostelAdmissionForm() {_x000D_ JFrame hostelFrame = new JFrame("Hostel Admission Details");_x000D_ hostelFrame.setSize(400, 300);_x000D_ hostelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ hostelFrame.setLayout(new GridLayout(9, 2));_x000D_ _x000D_ JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"MALE", "FEMALE"});_x000D_ hostelFrame.add(new JLabel("Gender:"));_x000D_ hostelFrame.add(genderComboBox);_x000D_ _x000D_ _x000D_ JTextField hostelNameField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Hostel Name:"));_x000D_ hostelFrame.add(hostelNameField);_x000D_ _x000D_ JTextField roomNumberField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Room Number:"));_x000D_ hostelFrame.add(roomNumberField);_x000D_ _x000D_ JTextField hostelFeeField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Hostel Fee:"));_x000D_ hostelFrame.add(hostelFeeField);_x000D_ _x000D_ JTextField accountNumberField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Your Account number :"));_x000D_ hostelFrame.add(accountNumberField);_x000D_ _x000D_ hostelFrame.add(new JLabel("Payment Mode:"));_x000D_ hostelFrameComboBox = new JComboBox<>(new String[]{"UPI:7854998757@axl", "Account Transfer:35181881560(SBI)", "Through Mobile No:7854998757"});_x000D_ hostelFrame.add( hostelFrameComboBox);_x000D_ _x000D_ JTextField transitionIDField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Transition ID:"));_x000D_ hostelFrame.add(transitionIDField);_x000D_ _x000D_ _x000D_ JCheckBox hostelRequiredCheckBox = new JCheckBox("Hostel Accommodation Required?");_x000D_ hostelFrame.add(hostelRequiredCheckBox);_x000D_ _x000D_ JButton hostelSubmitButton = new JButton("Submit Hostel Admission");_x000D_ hostelSubmitButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ String hostelName = hostelNameField.getText();_x000D_ String roomNumber = roomNumberField.getText();_x000D_ String hostelFee = hostelFeeField.getText();_x000D_ String gender = (String) genderComboBox.getSelectedItem(); // Get selected gender_x000D_ boolean hostelRequired = hostelRequiredCheckBox.isSelected(); // Check whether hostel required or not_x000D_ String accountNumber = accountNumberField.getText();_x000D_ String transitionID= transitionIDField.getText();_x000D_ String paymentType = (String) paymentTypeComboBox.getSelectedItem();_x000D_ _x000D_ String hostelInfo = "\n\n Hostel Name: " + hostelName + "\n Room Number: " + roomNumber + "\n Hostel Fee: " + hostelFee + "\n Gender: " + gender+"\n Payment Method: " + paymentType + "\nAccount Number:"+accountNumber+"\nTransition number"+transitionID;_x000D_ if (hostelRequired) { _x000D_ hostelInfo += "\n Hostel Accommodation Required: Yes";_x000D_ } else {_x000D_ hostelInfo += "\n Hostel Accommodation Required: No";_x000D_ }_x000D_ storeHostelDetails(hostelInfo);_x000D_ _x000D_ _x000D_ JOptionPane.showMessageDialog(hostelFrame, "Hostel admission submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ hostelFrame.dispose();_x000D_ showPrintableForm();_x000D_ }_x000D_ });_x000D_ JButton hostelCancelButton = new JButton("Cancel");_x000D_ hostelCancelButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ hostelFrame.dispose(); // Close hostel admission form on cancel_x000D_ }_x000D_ });_x000D_ _x000D_ hostelFrame.add(hostelSubmitButton);_x000D_ hostelFrame.add(hostelCancelButton);_x000D_ _x000D_ hostelFrame.setVisible(true);_x000D_ _x000D_ }_x000D_ _x000D_ private void storeHostelDetails(String hostelInfo) {_x000D_ String fileName = "student_hostel_details.txt";_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {_x000D_ writer.write(hostelInfo);_x000D_ writer.newLine();_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ private void showPaymentForm() {_x000D_ JFrame paymentFrame = new JFrame("Student Payment Details");_x000D_ paymentFrame.setSize(400, 300);_x000D_ paymentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ paymentFrame.setLayout(new GridLayout(7, 2));_x000D_ _x000D_ JTextField studentNameField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Account Holder's Name:"));_x000D_ paymentFrame.add(studentNameField);_x000D_ _x000D_ paymentFrame.add(new JLabel("Payment Mode:"));_x000D_ paymentTypeComboBox = new JComboBox<>(new String[]{"UPI:7854998757@axl", "Account Transfer:35181881560(SBI)", "Through Mobile No:7854998757"});_x000D_ paymentFrame.add(paymentTypeComboBox);_x000D_ _x000D_ _x000D_ _x000D_ JTextField accountNumberField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Your Account number :"));_x000D_ paymentFrame.add(accountNumberField);_x000D_ _x000D_ JTextField paymentAmountField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Payment Amount:"));_x000D_ paymentFrame.add(paymentAmountField);_x000D_ _x000D_ JTextField transitionIDField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Transition ID:"));_x000D_ paymentFrame.add(transitionIDField);_x000D_ _x000D_ _x000D_ JButton paymentSubmitButton = new JButton("Submit Payment");_x000D_ paymentSubmitButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ String studentName = studentNameField.getText();_x000D_ _x000D_ String paymentAmount = paymentAmountField.getText();_x000D_ _x000D_ String accountNumber = accountNumberField.getText();_x000D_ _x000D_ String transitionID= transitionIDField.getText();_x000D_ _x000D_ _x000D_ String paymentType = (String) paymentTypeComboBox.getSelectedItem();_x000D_ _x000D_ // Perform actions to store payment details in a file_x000D_ String paymentInfo = "\n\n Accound Holder's Name: " + studentName + "\n Payment Amount: " + paymentAmount + "\n Payment Method: " + paymentType + "\nAccount Number:"+accountNumber+"\nTransition number"+transitionID;_x000D_ storePaymentDetails(paymentInfo);_x000D_ _x000D_ JOptionPane.showMessageDialog(paymentFrame, "Payment submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(paymentFrame, "congratulations! welcome to Sambalpur University", "welcome", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(paymentFrame, "MALE : VHR(BTECH,MCA,MTECH)\n : AHR(LETERAL ENTRY BTECH)\n\nFEMALE : MHR(FOR ALL)\n\nFEE STRUCTURE :\n\nHOSTEL SEAT FEE : 10,000.00 RUPPESS\nSECURITY FEE : 2,000.00 RUPEES\nTOTAL HOSTEL FEE : 12,000.00 RUPEES", "HOSTEL NAME AND FEE STRUCTURE", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ paymentFrame.dispose(); // Close payment form after submission_x000D_ showHostelAdmissionForm();_x000D_ _x000D_ }_x000D_ });_x000D_ _x000D_ JButton paymentCancelButton = new JButton("Cancel");_x000D_ paymentCancelButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ paymentFrame.dispose(); // Close payment form on cancel_x000D_ }_x000D_ });_x000D_ _x000D_ paymentFrame.add(paymentSubmitButton);_x000D_ paymentFrame.add(paymentCancelButton);_x000D_ _x000D_ paymentFrame.setVisible(true);_x000D_ _x000D_ }_x000D_ _x000D_ private void storePaymentDetails(String paymentInfo) {_x000D_ String fileName = "student_payments.txt";_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {_x000D_ writer.write(paymentInfo);_x000D_ writer.newLine();_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ private void showPrintableForm() {_x000D_ JFrame printFrame = new JFrame("Printable Form");_x000D_ printFrame.setSize(600, 600);_x000D_ printFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ _x000D_ JPanel printPanel = new JPanel(new BorderLayout());_x000D_ _x000D_ printTextArea = new JTextArea(30, 50);_x000D_ printTextArea.setEditable(false);_x000D_ JScrollPane scrollPane = new JScrollPane(printTextArea);_x000D_ printPanel.add(scrollPane, BorderLayout.CENTER);_x000D_ _x000D_ JButton printButton = new JButton("Print");_x000D_ printButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ try {_x000D_ printTextArea.print(); // Print the text area content_x000D_ } catch (Exception ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ printPanel.add(printButton, BorderLayout.SOUTH);_x000D_ _x000D_ // Adding photo, payment details, and hostel details to the printable form_x000D_ ImageIcon icon = (ImageIcon) photoLabel.getIcon();_x000D_ if (icon != null) {_x000D_ JLabel photoLabelPrint = new JLabel(icon);_x000D_ printPanel.add(photoLabelPrint, BorderLayout.NORTH);_x000D_ }_x000D_ String recentSelectedStudentDetails = getRecentSelectedStudentDetails();_x000D_ if (!recentSelectedStudentDetails.isEmpty()) {_x000D_ printTextArea.append("\n\nCandidate's Details\n");_x000D_ printTextArea.append(recentSelectedStudentDetails);_x000D_ }_x000D_ _x000D_ String paymentInfo = "Payment Details:\n" + getPaymentDetails();_x000D_ printTextArea.append("\n\n" + paymentInfo);_x000D_ String hostelInfo = "Hostel Details:\n" + getHostelDetails();_x000D_ printTextArea.append("\n\n" + hostelInfo);_x000D_ _x000D_ printFrame.add(printPanel);_x000D_ printFrame.setVisible(true);_x000D_ }_x000D_ _x000D_ private String getHostelDetails() {_x000D_ // Fetch hostel details from your stored file or store it directly as per your application logic_x000D_ // Example logic to read from the file_x000D_ StringBuilder hostelDetails = new StringBuilder();_x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("student_hostel_details.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 6) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ hostelDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return hostelDetails.toString();_x000D_ }_x000D_ private String getPaymentDetails() {_x000D_ _x000D_ StringBuilder paymentDetails = new StringBuilder();_x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("student_payments.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 5) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ paymentDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return paymentDetails.toString();_x000D_ } _x000D_ private String getRecentSelectedStudentDetails() {_x000D_ StringBuilder selectedStudentDetails = new StringBuilder();_x000D_ _x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("SelectedStudents.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 17) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ selectedStudentDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return selectedStudentDetails.toString();_x000D_ }_x000D_ private boolean isRequiredFieldEmpty() {_x000D_ return nameField.getText().isEmpty() ||_x000D_ jeeRankField.getText().isEmpty() ||_x000D_ mark12Field.getText().isEmpty() ||_x000D_ mark10Field.getText().isEmpty() ||_x000D_ fatherNameField.getText().isEmpty() ||_x000D_ collegeNameField.getText().isEmpty() ||_x000D_ schoolNameField.getText().isEmpty() ||_x000D_ jeeRollNumberField.getText().isEmpty() ||_x000D_ addressField.getText().isEmpty() ||_x000D_ postField.getText().isEmpty() ||_x000D_ blockField.getText().isEmpty() ||_x000D_ distField.getText().isEmpty() ||_x000D_ stateField.getText().isEmpty() ||_x000D_ pinCodeField.getText().isEmpty() ||_x000D_ mobileNumberField.getText().isEmpty();_x000D_ }_x000D_ public static void main(String[] args) {_x000D_ SwingUtilities.invokeLater(new Runnable() {_x000D_ public void run() {_x000D_ new AdmissionForm();_x000D_ }_x000D_ });_x000D_ }_x000D_ }
amreshbhuya/University-Management.java
Amresh/AdmissionForm.java
7,651
// Get selected gender_x000D_
line_comment
nl
package Amresh;_x000D_ import javax.swing.*;_x000D_ import Amresh01.*;_x000D_ import java.awt.*;_x000D_ import java.awt.event.*;_x000D_ import java.io.*;_x000D_ import java.util.*;_x000D_ _x000D_ _x000D_ public class AdmissionForm extends JFrame implements ActionListener {_x000D_ _x000D_ private JTextField nameField, jeeRankField, mark12Field, mark10Field, fatherNameField, collegeNameField, schoolNameField,_x000D_ jeeRollNumberField, addressField, postField, blockField, distField, stateField, pinCodeField,_x000D_ mobileNumberField;_x000D_ private JComboBox<String> admissionTypeComboBox;_x000D_ private JComboBox<String> countryTypeComboBox;_x000D_ private JComboBox<String> genderTypeComboBox;_x000D_ private JComboBox<String> categoryTypeComboBox;_x000D_ private JComboBox<String> religionTypeComboBox;_x000D_ private JComboBox<String> courseTypeComboBox;_x000D_ private JComboBox<String> paymentTypeComboBox;_x000D_ private JComboBox<String> hostelFrameComboBox;_x000D_ private JComboBox<String> dayComboBox, monthComboBox, yearComboBox;_x000D_ private JPanel dobPanel; _x000D_ private JCheckBox acceptAllCheckBox;_x000D_ private JTextArea printTextArea;_x000D_ private JLabel photoLabel; // Added label for displaying the photo_x000D_ private JTextArea finalDetailsTextArea;_x000D_ private JButton backButton;_x000D_ _x000D_ _x000D_ public AdmissionForm() {_x000D_ _x000D_ _x000D_ setTitle("Admission Form - Sambalpur University");_x000D_ setSize(2000, 2000);_x000D_ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);_x000D_ setLocationRelativeTo(null);_x000D_ setLayout(new GridLayout(13, 2));_x000D_ _x000D_ _x000D_ add(new JLabel("Candidate Name(In capital):"));_x000D_ nameField = new JTextField();_x000D_ add(nameField);_x000D_ _x000D_ _x000D_ add(new JLabel("Gender:"));_x000D_ genderTypeComboBox = new JComboBox<>(new String[]{"MALE","FEMALE"});_x000D_ add(genderTypeComboBox);_x000D_ _x000D_ add(new JLabel("Date of Birth:"));_x000D_ _x000D_ dobPanel = new JPanel(); _x000D_ dobPanel.setLayout(new FlowLayout()); _x000D_ _x000D_ // Day ComboBox_x000D_ dayComboBox = new JComboBox<>();_x000D_ for (int i = 1; i <= 31; i++) {_x000D_ dayComboBox.addItem(String.valueOf(i));_x000D_ }_x000D_ dobPanel.add(dayComboBox);_x000D_ _x000D_ // Month ComboBox_x000D_ monthComboBox = new JComboBox<>(new String[]{ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"});_x000D_ dobPanel.add(monthComboBox);_x000D_ _x000D_ // Year ComboBox_x000D_ yearComboBox = new JComboBox<>();_x000D_ int currentYear = Calendar.getInstance().get(Calendar.YEAR);_x000D_ for (int i = currentYear - 60; i <= currentYear; i++) {_x000D_ yearComboBox.addItem(String.valueOf(i));_x000D_ }_x000D_ dobPanel.add(yearComboBox);_x000D_ _x000D_ add(dobPanel); // Add Date of Birth panel to the JFrame_x000D_ _x000D_ _x000D_ add(new JLabel("Category:"));_x000D_ categoryTypeComboBox = new JComboBox<>(new String[]{"GENERAL","OBC","SC","ST"});_x000D_ add(categoryTypeComboBox);_x000D_ _x000D_ add(new JLabel("Religion:"));_x000D_ religionTypeComboBox = new JComboBox<>(new String[]{"HINDU","CHRISTIAN","MUSLIM","ISLAM","SIKH","BUDDHISM","JAINISM"});_x000D_ add(religionTypeComboBox);_x000D_ _x000D_ _x000D_ _x000D_ add(new JLabel("JEE Main Rank:"));_x000D_ jeeRankField = new JTextField();_x000D_ add(jeeRankField);_x000D_ _x000D_ add(new JLabel("12th Marks(%)/Diploma mark(%):"));_x000D_ mark12Field = new JTextField();_x000D_ add(mark12Field);_x000D_ _x000D_ add(new JLabel("10th Marks(%):"));_x000D_ mark10Field = new JTextField();_x000D_ add(mark10Field);_x000D_ _x000D_ add(new JLabel("Father's Name"));_x000D_ fatherNameField = new JTextField();_x000D_ add(fatherNameField);_x000D_ _x000D_ add(new JLabel("College Name:"));_x000D_ collegeNameField = new JTextField();_x000D_ add(collegeNameField);_x000D_ _x000D_ add(new JLabel("10th School Name:"));_x000D_ schoolNameField = new JTextField();_x000D_ add(schoolNameField);_x000D_ _x000D_ add(new JLabel("JEE Main Roll Number:"));_x000D_ jeeRollNumberField = new JTextField();_x000D_ add(jeeRollNumberField);_x000D_ _x000D_ add(new JLabel("Country:"));_x000D_ countryTypeComboBox = new JComboBox<>(new String[]{"India","Bangladesh", "Pakistan", "Nepal", "Bhutan", "China", "Myanmar", "Sri Lanka","United States of America", "United Kingdom", "Canada", "Australia", "Russia", "Japan", "Germany"});_x000D_ add(countryTypeComboBox);_x000D_ _x000D_ add(new JLabel("Address:"));_x000D_ addressField = new JTextField();_x000D_ add(addressField);_x000D_ _x000D_ add(new JLabel("Post:"));_x000D_ postField = new JTextField();_x000D_ add(postField);_x000D_ _x000D_ add(new JLabel("Block:"));_x000D_ blockField = new JTextField();_x000D_ add(blockField);_x000D_ _x000D_ add(new JLabel("District:"));_x000D_ distField = new JTextField();_x000D_ add(distField);_x000D_ _x000D_ add(new JLabel("State:"));_x000D_ stateField = new JTextField();_x000D_ add(stateField);_x000D_ _x000D_ add(new JLabel("Pin Code:"));_x000D_ pinCodeField = new JTextField();_x000D_ add(pinCodeField);_x000D_ _x000D_ add(new JLabel("Mobile Number:"));_x000D_ mobileNumberField = new JTextField();_x000D_ add(mobileNumberField);_x000D_ _x000D_ add(new JLabel("Admission Type:"));_x000D_ admissionTypeComboBox = new JComboBox<>(new String[]{"BTech", "MTech", "Lateral Entry BTech","MCA"});_x000D_ add(admissionTypeComboBox);_x000D_ _x000D_ add(new JLabel("Intrested Course:"));_x000D_ courseTypeComboBox = new JComboBox<>(new String[]{"Computer Science & Engineering","Electrical Engineering","ECE (Electronics and Communications Engineering)","Electronics & Communication Engineering (ECE)","(CSE-AIML)Computer Science & Engineering specialization in Artificial Intelligence and Machine Learning","Computer Science & Engineering specialization with cyber security"});_x000D_ add(courseTypeComboBox);_x000D_ _x000D_ JButton uploadPhotoButton = new JButton("Upload Photo");_x000D_ uploadPhotoButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ JFileChooser fileChooser = new JFileChooser();_x000D_ int returnValue = fileChooser.showOpenDialog(null);_x000D_ _x000D_ if (returnValue == JFileChooser.APPROVE_OPTION) {_x000D_ File selectedFile = fileChooser.getSelectedFile();_x000D_ displaySelectedPhoto(selectedFile);_x000D_ }_x000D_ }_x000D_ });_x000D_ add(uploadPhotoButton);_x000D_ _x000D_ photoLabel = new JLabel();_x000D_ add(photoLabel);_x000D_ _x000D_ _x000D_ acceptAllCheckBox = new JCheckBox("Accept All Conditions\n");_x000D_ add(acceptAllCheckBox);_x000D_ _x000D_ JButton submitButton = new JButton("Submit");_x000D_ submitButton.addActionListener(this);_x000D_ add(submitButton);_x000D_ _x000D_ _x000D_ JButton clearButton = new JButton("Clear");_x000D_ clearButton.addActionListener(this);_x000D_ add(clearButton);_x000D_ _x000D_ backButton = new JButton("Back");_x000D_ backButton.addActionListener(e -> handleBackButton());_x000D_ add(backButton, BorderLayout.SOUTH);_x000D_ _x000D_ finalDetailsTextArea = new JTextArea(30, 50);_x000D_ finalDetailsTextArea.setEditable(false);_x000D_ _x000D_ pack();_x000D_ setVisible(true);_x000D_ _x000D_ }_x000D_ private void handleBackButton() {_x000D_ _x000D_ SwingUtilities.invokeLater(SambalpurUniversityFrontPage::new);_x000D_ _x000D_ this.setVisible(false);_x000D_ }_x000D_ _x000D_ private void displaySelectedPhoto(File file) {_x000D_ ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());_x000D_ Image image = imageIcon.getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH);_x000D_ photoLabel.setIcon(new ImageIcon(image));_x000D_ }_x000D_ _x000D_ public void actionPerformed(ActionEvent e) {_x000D_ if (e.getActionCommand().equals("Submit")) {_x000D_ _x000D_ boolean accepted = acceptAllCheckBox.isSelected();_x000D_ if (isRequiredFieldEmpty()) {_x000D_ JOptionPane.showMessageDialog(this, "Please fill in all the required fields!", "Error", JOptionPane.ERROR_MESSAGE);_x000D_ return;_x000D_ }_x000D_ _x000D_ _x000D_ if (!accepted) {_x000D_ JOptionPane.showMessageDialog(this, "Please accept all conditions before submission!", "Error", JOptionPane.ERROR_MESSAGE);_x000D_ return;_x000D_ }_x000D_ String fileName = "AppliedStudent.txt";_x000D_ String selectedFileName = "SelectedStudents.txt";_x000D_ _x000D_ String name = nameField.getText();_x000D_ String genderType = (String) genderTypeComboBox.getSelectedItem();_x000D_ String categoryType = (String) categoryTypeComboBox.getSelectedItem();_x000D_ String religionType = (String) religionTypeComboBox.getSelectedItem();_x000D_ String courseType = (String) courseTypeComboBox.getSelectedItem();_x000D_ String day = (String) dayComboBox.getSelectedItem();_x000D_ String month = (String) monthComboBox.getSelectedItem();_x000D_ String year = (String) yearComboBox.getSelectedItem();_x000D_ String dob = day + "-" + month + "-" + year;_x000D_ String jeeRank = jeeRankField.getText();_x000D_ String mark12 = mark12Field.getText();_x000D_ String mark10 = mark10Field.getText();_x000D_ String fatherName = fatherNameField.getText();_x000D_ String collegeName = collegeNameField.getText();_x000D_ String schoolName = schoolNameField.getText();_x000D_ String jeeRollNumber = jeeRollNumberField.getText();_x000D_ String countryType = (String) countryTypeComboBox.getSelectedItem();_x000D_ String address = addressField.getText() + ", " + postField.getText() + ", " + blockField.getText() + ", "_x000D_ + distField.getText() + ", " + stateField.getText() + ", " + pinCodeField.getText();_x000D_ String mobileNumber = mobileNumberField.getText();_x000D_ String admissionType = (String) admissionTypeComboBox.getSelectedItem();_x000D_ _x000D_ _x000D_ // Logic for selecting students based on criteria (JEE rank, 12th and 10th marks)_x000D_ boolean selected = false;_x000D_ _x000D_ _x000D_ _x000D_ if (!jeeRank.isEmpty() && !mark12.isEmpty() && !mark10.isEmpty()) {_x000D_ int jeeRankValue = Integer.parseInt(jeeRank);_x000D_ double averageMarks = (Double.parseDouble(mark12) + Double.parseDouble(mark10)) / 2.0;_x000D_ _x000D_ _x000D_ if ((admissionType.equals("BTech") && jeeRankValue <= 1000 && averageMarks >= 80) ||_x000D_ (admissionType.equals("MTech") && jeeRankValue <= 1000 && averageMarks >= 75) ||_x000D_ (admissionType.equals("Lateral Entry BTech") && jeeRankValue <= 1500 && averageMarks >= 70)||_x000D_ (admissionType.equals("MCA") && jeeRankValue <= 1800 && averageMarks >= 80)) {_x000D_ selected = true;_x000D_ JOptionPane.showMessageDialog(this, "Form submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(this, "congratulations you are eligible for admisstion", "Eligible", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ JOptionPane.showMessageDialog(this, "BTech/Leteral BTech : 96,000 \n MTech : 98,000 \n MCA : 90,000 ", "Fee structer", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ showPaymentForm();_x000D_ }_x000D_ else_x000D_ {_x000D_ JOptionPane.showMessageDialog(this, "Form submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(this, "Oops! you are not eligible for admisstion", "NOT Eligible", JOptionPane.INFORMATION_MESSAGE);_x000D_ }_x000D_ }_x000D_ _x000D_ String studentInfo = "\n\nCandidate Name: "+ name + "\nGender: " + genderType + "\nCategory: " + categoryType + "\nRILIGION : " + religionType +"\nDate of Birth: " + dob + "\nJEE Rank: " + jeeRank_x000D_ + "\n12th Marks: " + mark12 + "\n10th Marks: " + mark10 + "\nFather's Name: " + fatherName_x000D_ + "\nCollege Name: " + collegeName + "\nSchool Name: " + schoolName + "\nJEE Roll Number: "_x000D_ + jeeRollNumber + "\nCountry type: " + countryType +"\nAddress: " + address + "\nMobile Number: " + mobileNumber_x000D_ + "\nAdmission Type: " + admissionType + "\n Intrested Course: " + courseType ;_x000D_ _x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));_x000D_ PrintWriter selectedWriter = new PrintWriter(new BufferedWriter(new FileWriter(selectedFileName, true)))) {_x000D_ writer.write(studentInfo);_x000D_ writer.newLine();_x000D_ _x000D_ if (selected) {_x000D_ selectedWriter.println(studentInfo + " - SELECTED");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ _x000D_ _x000D_ clearFields();_x000D_ _x000D_ _x000D_ _x000D_ } _x000D_ else if (e.getActionCommand().equals("Clear")) {_x000D_ clearFields();_x000D_ }_x000D_ _x000D_ }_x000D_ private void clearFields() {_x000D_ nameField.setText("");_x000D_ jeeRankField.setText("");_x000D_ mark12Field.setText("");_x000D_ mark10Field.setText("");_x000D_ fatherNameField.setText("");_x000D_ collegeNameField.setText("");_x000D_ schoolNameField.setText("");_x000D_ jeeRollNumberField.setText("");_x000D_ addressField.setText("");_x000D_ postField.setText("");_x000D_ blockField.setText("");_x000D_ distField.setText("");_x000D_ stateField.setText("");_x000D_ pinCodeField.setText("");_x000D_ mobileNumberField.setText("");_x000D_ _x000D_ }_x000D_ public void showHostelAdmissionForm() {_x000D_ JFrame hostelFrame = new JFrame("Hostel Admission Details");_x000D_ hostelFrame.setSize(400, 300);_x000D_ hostelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ hostelFrame.setLayout(new GridLayout(9, 2));_x000D_ _x000D_ JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"MALE", "FEMALE"});_x000D_ hostelFrame.add(new JLabel("Gender:"));_x000D_ hostelFrame.add(genderComboBox);_x000D_ _x000D_ _x000D_ JTextField hostelNameField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Hostel Name:"));_x000D_ hostelFrame.add(hostelNameField);_x000D_ _x000D_ JTextField roomNumberField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Room Number:"));_x000D_ hostelFrame.add(roomNumberField);_x000D_ _x000D_ JTextField hostelFeeField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Hostel Fee:"));_x000D_ hostelFrame.add(hostelFeeField);_x000D_ _x000D_ JTextField accountNumberField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Your Account number :"));_x000D_ hostelFrame.add(accountNumberField);_x000D_ _x000D_ hostelFrame.add(new JLabel("Payment Mode:"));_x000D_ hostelFrameComboBox = new JComboBox<>(new String[]{"UPI:7854998757@axl", "Account Transfer:35181881560(SBI)", "Through Mobile No:7854998757"});_x000D_ hostelFrame.add( hostelFrameComboBox);_x000D_ _x000D_ JTextField transitionIDField = new JTextField();_x000D_ hostelFrame.add(new JLabel("Transition ID:"));_x000D_ hostelFrame.add(transitionIDField);_x000D_ _x000D_ _x000D_ JCheckBox hostelRequiredCheckBox = new JCheckBox("Hostel Accommodation Required?");_x000D_ hostelFrame.add(hostelRequiredCheckBox);_x000D_ _x000D_ JButton hostelSubmitButton = new JButton("Submit Hostel Admission");_x000D_ hostelSubmitButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ String hostelName = hostelNameField.getText();_x000D_ String roomNumber = roomNumberField.getText();_x000D_ String hostelFee = hostelFeeField.getText();_x000D_ String gender = (String) genderComboBox.getSelectedItem(); // Get selected<SUF> boolean hostelRequired = hostelRequiredCheckBox.isSelected(); // Check whether hostel required or not_x000D_ String accountNumber = accountNumberField.getText();_x000D_ String transitionID= transitionIDField.getText();_x000D_ String paymentType = (String) paymentTypeComboBox.getSelectedItem();_x000D_ _x000D_ String hostelInfo = "\n\n Hostel Name: " + hostelName + "\n Room Number: " + roomNumber + "\n Hostel Fee: " + hostelFee + "\n Gender: " + gender+"\n Payment Method: " + paymentType + "\nAccount Number:"+accountNumber+"\nTransition number"+transitionID;_x000D_ if (hostelRequired) { _x000D_ hostelInfo += "\n Hostel Accommodation Required: Yes";_x000D_ } else {_x000D_ hostelInfo += "\n Hostel Accommodation Required: No";_x000D_ }_x000D_ storeHostelDetails(hostelInfo);_x000D_ _x000D_ _x000D_ JOptionPane.showMessageDialog(hostelFrame, "Hostel admission submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ hostelFrame.dispose();_x000D_ showPrintableForm();_x000D_ }_x000D_ });_x000D_ JButton hostelCancelButton = new JButton("Cancel");_x000D_ hostelCancelButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ hostelFrame.dispose(); // Close hostel admission form on cancel_x000D_ }_x000D_ });_x000D_ _x000D_ hostelFrame.add(hostelSubmitButton);_x000D_ hostelFrame.add(hostelCancelButton);_x000D_ _x000D_ hostelFrame.setVisible(true);_x000D_ _x000D_ }_x000D_ _x000D_ private void storeHostelDetails(String hostelInfo) {_x000D_ String fileName = "student_hostel_details.txt";_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {_x000D_ writer.write(hostelInfo);_x000D_ writer.newLine();_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ private void showPaymentForm() {_x000D_ JFrame paymentFrame = new JFrame("Student Payment Details");_x000D_ paymentFrame.setSize(400, 300);_x000D_ paymentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ paymentFrame.setLayout(new GridLayout(7, 2));_x000D_ _x000D_ JTextField studentNameField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Account Holder's Name:"));_x000D_ paymentFrame.add(studentNameField);_x000D_ _x000D_ paymentFrame.add(new JLabel("Payment Mode:"));_x000D_ paymentTypeComboBox = new JComboBox<>(new String[]{"UPI:7854998757@axl", "Account Transfer:35181881560(SBI)", "Through Mobile No:7854998757"});_x000D_ paymentFrame.add(paymentTypeComboBox);_x000D_ _x000D_ _x000D_ _x000D_ JTextField accountNumberField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Your Account number :"));_x000D_ paymentFrame.add(accountNumberField);_x000D_ _x000D_ JTextField paymentAmountField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Payment Amount:"));_x000D_ paymentFrame.add(paymentAmountField);_x000D_ _x000D_ JTextField transitionIDField = new JTextField();_x000D_ paymentFrame.add(new JLabel("Transition ID:"));_x000D_ paymentFrame.add(transitionIDField);_x000D_ _x000D_ _x000D_ JButton paymentSubmitButton = new JButton("Submit Payment");_x000D_ paymentSubmitButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ String studentName = studentNameField.getText();_x000D_ _x000D_ String paymentAmount = paymentAmountField.getText();_x000D_ _x000D_ String accountNumber = accountNumberField.getText();_x000D_ _x000D_ String transitionID= transitionIDField.getText();_x000D_ _x000D_ _x000D_ String paymentType = (String) paymentTypeComboBox.getSelectedItem();_x000D_ _x000D_ // Perform actions to store payment details in a file_x000D_ String paymentInfo = "\n\n Accound Holder's Name: " + studentName + "\n Payment Amount: " + paymentAmount + "\n Payment Method: " + paymentType + "\nAccount Number:"+accountNumber+"\nTransition number"+transitionID;_x000D_ storePaymentDetails(paymentInfo);_x000D_ _x000D_ JOptionPane.showMessageDialog(paymentFrame, "Payment submitted successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(paymentFrame, "congratulations! welcome to Sambalpur University", "welcome", JOptionPane.INFORMATION_MESSAGE);_x000D_ JOptionPane.showMessageDialog(paymentFrame, "MALE : VHR(BTECH,MCA,MTECH)\n : AHR(LETERAL ENTRY BTECH)\n\nFEMALE : MHR(FOR ALL)\n\nFEE STRUCTURE :\n\nHOSTEL SEAT FEE : 10,000.00 RUPPESS\nSECURITY FEE : 2,000.00 RUPEES\nTOTAL HOSTEL FEE : 12,000.00 RUPEES", "HOSTEL NAME AND FEE STRUCTURE", JOptionPane.INFORMATION_MESSAGE);_x000D_ _x000D_ paymentFrame.dispose(); // Close payment form after submission_x000D_ showHostelAdmissionForm();_x000D_ _x000D_ }_x000D_ });_x000D_ _x000D_ JButton paymentCancelButton = new JButton("Cancel");_x000D_ paymentCancelButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ paymentFrame.dispose(); // Close payment form on cancel_x000D_ }_x000D_ });_x000D_ _x000D_ paymentFrame.add(paymentSubmitButton);_x000D_ paymentFrame.add(paymentCancelButton);_x000D_ _x000D_ paymentFrame.setVisible(true);_x000D_ _x000D_ }_x000D_ _x000D_ private void storePaymentDetails(String paymentInfo) {_x000D_ String fileName = "student_payments.txt";_x000D_ try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {_x000D_ writer.write(paymentInfo);_x000D_ writer.newLine();_x000D_ } catch (IOException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ private void showPrintableForm() {_x000D_ JFrame printFrame = new JFrame("Printable Form");_x000D_ printFrame.setSize(600, 600);_x000D_ printFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);_x000D_ _x000D_ JPanel printPanel = new JPanel(new BorderLayout());_x000D_ _x000D_ printTextArea = new JTextArea(30, 50);_x000D_ printTextArea.setEditable(false);_x000D_ JScrollPane scrollPane = new JScrollPane(printTextArea);_x000D_ printPanel.add(scrollPane, BorderLayout.CENTER);_x000D_ _x000D_ JButton printButton = new JButton("Print");_x000D_ printButton.addActionListener(new ActionListener() {_x000D_ public void actionPerformed(ActionEvent e) {_x000D_ try {_x000D_ printTextArea.print(); // Print the text area content_x000D_ } catch (Exception ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ }_x000D_ });_x000D_ _x000D_ printPanel.add(printButton, BorderLayout.SOUTH);_x000D_ _x000D_ // Adding photo, payment details, and hostel details to the printable form_x000D_ ImageIcon icon = (ImageIcon) photoLabel.getIcon();_x000D_ if (icon != null) {_x000D_ JLabel photoLabelPrint = new JLabel(icon);_x000D_ printPanel.add(photoLabelPrint, BorderLayout.NORTH);_x000D_ }_x000D_ String recentSelectedStudentDetails = getRecentSelectedStudentDetails();_x000D_ if (!recentSelectedStudentDetails.isEmpty()) {_x000D_ printTextArea.append("\n\nCandidate's Details\n");_x000D_ printTextArea.append(recentSelectedStudentDetails);_x000D_ }_x000D_ _x000D_ String paymentInfo = "Payment Details:\n" + getPaymentDetails();_x000D_ printTextArea.append("\n\n" + paymentInfo);_x000D_ String hostelInfo = "Hostel Details:\n" + getHostelDetails();_x000D_ printTextArea.append("\n\n" + hostelInfo);_x000D_ _x000D_ printFrame.add(printPanel);_x000D_ printFrame.setVisible(true);_x000D_ }_x000D_ _x000D_ private String getHostelDetails() {_x000D_ // Fetch hostel details from your stored file or store it directly as per your application logic_x000D_ // Example logic to read from the file_x000D_ StringBuilder hostelDetails = new StringBuilder();_x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("student_hostel_details.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 6) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ hostelDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return hostelDetails.toString();_x000D_ }_x000D_ private String getPaymentDetails() {_x000D_ _x000D_ StringBuilder paymentDetails = new StringBuilder();_x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("student_payments.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 5) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ paymentDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return paymentDetails.toString();_x000D_ } _x000D_ private String getRecentSelectedStudentDetails() {_x000D_ StringBuilder selectedStudentDetails = new StringBuilder();_x000D_ _x000D_ try (BufferedReader reader = new BufferedReader(new FileReader("SelectedStudents.txt"))) {_x000D_ String line;_x000D_ ArrayList<String> recentLines = new ArrayList<>();_x000D_ while ((line = reader.readLine()) != null) {_x000D_ recentLines.add(line);_x000D_ if (recentLines.size() > 17) {_x000D_ recentLines.remove(0);_x000D_ }_x000D_ }_x000D_ for (String recentLine : recentLines) {_x000D_ selectedStudentDetails.append(recentLine).append("\n");_x000D_ }_x000D_ } catch (IOException ex) {_x000D_ ex.printStackTrace();_x000D_ }_x000D_ return selectedStudentDetails.toString();_x000D_ }_x000D_ private boolean isRequiredFieldEmpty() {_x000D_ return nameField.getText().isEmpty() ||_x000D_ jeeRankField.getText().isEmpty() ||_x000D_ mark12Field.getText().isEmpty() ||_x000D_ mark10Field.getText().isEmpty() ||_x000D_ fatherNameField.getText().isEmpty() ||_x000D_ collegeNameField.getText().isEmpty() ||_x000D_ schoolNameField.getText().isEmpty() ||_x000D_ jeeRollNumberField.getText().isEmpty() ||_x000D_ addressField.getText().isEmpty() ||_x000D_ postField.getText().isEmpty() ||_x000D_ blockField.getText().isEmpty() ||_x000D_ distField.getText().isEmpty() ||_x000D_ stateField.getText().isEmpty() ||_x000D_ pinCodeField.getText().isEmpty() ||_x000D_ mobileNumberField.getText().isEmpty();_x000D_ }_x000D_ public static void main(String[] args) {_x000D_ SwingUtilities.invokeLater(new Runnable() {_x000D_ public void run() {_x000D_ new AdmissionForm();_x000D_ }_x000D_ });_x000D_ }_x000D_ }
False
4,516
147808_16
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox 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. * * The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ /* Bad ones Model 1 = 93,119, Model 2 = 67,98, Classifier MP_ED acc =0.45555555555555555 Model 1 = 84,118, Model 2 = 66,109, */ package statistics.simulators; import fileIO.OutFile; import java.util.*; import java.io.*; import statistics.distributions.NormalDistribution; import statistics.simulators.DictionaryModel.ShapeType; import static statistics.simulators.Model.rand; import statistics.simulators.ShapeletModel.Shape; public class MatrixProfileModelVersion1 extends Model { private int nosLocations=2; // private int shapeLength=29; public static double MINBASE=-2; public static double MINAMP=2; public static double MAXBASE=2; public static double MAXAMP=4; DictionaryModel.Shape shape;//Will change for each series private static int GLOBALSERIESLENGTH=500; private int seriesLength; // Need to set intervals, maybe allow different lengths? private int base=-1; private int amplitude=2; private int shapeCount=0; private boolean invert=false; boolean discord=false; double[] shapeVals; ArrayList<Integer> locations; public static int getGlobalLength(){ return GLOBALSERIESLENGTH;} public MatrixProfileModelVersion1(){ shapeCount=0;//rand.nextInt(ShapeType.values().length); seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } public MatrixProfileModelVersion1(boolean d){ shapeCount=0;//rand.nextInt(ShapeType.values().length); discord=d; if(discord) nosLocations=1; seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } private void generateRandomShapeVals(){ for(int i=0;i<shapeLength;i++) shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); } public void setSeriesLength(int n){ seriesLength=n; } public static void setGlobalSeriesLength(int n){ GLOBALSERIESLENGTH=n; } public void setNonOverlappingIntervals(){ //Use Aarons way ArrayList<Integer> startPoints=new ArrayList<>(); for(int i=shapeLength+1;i<seriesLength-shapeLength;i++) startPoints.add(i); for(int i=0;i<nosLocations;i++){ int pos=rand.nextInt(startPoints.size()); int l=startPoints.get(pos); locations.add(l); //+/- windowSize/2 if(pos<shapeLength) pos=0; else pos=pos-shapeLength; for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++) startPoints.remove(pos); /* //Me giving up and just randomly placing the shapes until they are all non overlapping for(int i=0;i<nosLocations;i++){ boolean ok=false; int l=shapeLength/2; while(!ok){ ok=true; //Search mid points to level the distribution up somewhat // System.out.println("Series length ="+seriesLength); do{ l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2; } while((l+shapeLength/2)>=seriesLength-shapeLength); for(int in:locations){ //I think this is setting them too big if((l>=in-shapeLength && l<in+shapeLength) //l inside ins ||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l ok=false; // System.out.println(l+" overlaps with "+in); break; } } } */ // System.out.println("Adding "+l); } /*//Revert to start points for(int i=0;i<locations.size();i++){ int val=locations.get(i); locations.set(i, val-shapeLength/2); } */ Collections.sort(locations); // System.out.println("MODEL START POINTS ="); // for(int i=0;i<locations.size();i++) // System.out.println(locations.get(i)); } @Override public void setParameters(double[] p) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void setLocations(ArrayList<Integer> l, int length){ locations=new ArrayList<>(l); shapeLength=length; } public ArrayList<Integer> getIntervals(){return locations;} public int getShapeLength(){ return shapeLength;} public void generateBaseShape(){ //Randomise BASE and AMPLITUDE double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); ShapeType[] all=ShapeType.values(); ShapeType st=all[(shapeCount++)%all.length]; shape=new DictionaryModel.Shape(st,shapeLength,b,a); // shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a); // System.out.println("Shape is "+shape); // shape.nextShape(); // shape } @Override public double[] generateSeries(int n) { t=0; double[] d; generateRandomShapeVals(); //Resets the starting locations each time this is called if(invert){ d= new double[n]; for(int i=0;i<n;i++) d[i]=-generate(); invert=false; } else{ generateBaseShape(); d = new double[n]; for(int i=0;i<n;i++) d[i]=generate(); invert=true; } return d; } private double generateConfig1(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=0; //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(point<=t && point+shapeLength>t)//in shape1 value=shapeVals[(int)(t-point)]; else value= error.simulate(); // value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); t++; return value; } private double generateConfig2(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=error.simulate(); //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(insertionPoint>0 && point==t){//New shape, randomise scale // double b=shape.getBase()/5; // double a=shape.getAmp()/5; double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); shape.setAmp(a); shape.setBase(b); // System.out.println("changing second shape"); } if(point<=t && point+shapeLength>t){//in shape1 value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); } t++; return value; } //Generate point t @Override public double generate(){ return generateConfig1(); } public static void generateExampleData(){ int length=500; GLOBALSERIESLENGTH=length; Model.setGlobalRandomSeed(3); Model.setDefaultSigma(0); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[][] d=new double[20][]; for(int i=0;i<10;i++){ d[i]=m1.generateSeries(length); } for(int i=10;i<20;i++){ d[i]=m1.generateSeries(length); } OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv"); for(int i=0;i<length;i++){ for(int j=0;j<10;j++) of.writeString(d[j][i]+","); of.writeString("\n"); } } public String toString(){ String str=""; for(Integer i:locations) str+=i+","; return str; } public static void main(String[] args){ generateExampleData(); System.exit(0); //Set up two models with same intervals but different shapes int length=500; Model.setGlobalRandomSeed(10); Model.setDefaultSigma(0.1); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[] d1=m1.generateSeries(length); double[] d2=m2.generateSeries(length); OutFile of=new OutFile("C:\\temp\\MP_Ex.csv"); for(int i=0;i<length;i++) of.writeLine(d1[i]+","+d2[i]); } }
time-series-machine-learning/tsml-java
src/main/java/statistics/simulators/MatrixProfileModelVersion1.java
3,086
// System.out.println("Error var ="+error.getVariance());
line_comment
nl
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox 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. * * The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ /* Bad ones Model 1 = 93,119, Model 2 = 67,98, Classifier MP_ED acc =0.45555555555555555 Model 1 = 84,118, Model 2 = 66,109, */ package statistics.simulators; import fileIO.OutFile; import java.util.*; import java.io.*; import statistics.distributions.NormalDistribution; import statistics.simulators.DictionaryModel.ShapeType; import static statistics.simulators.Model.rand; import statistics.simulators.ShapeletModel.Shape; public class MatrixProfileModelVersion1 extends Model { private int nosLocations=2; // private int shapeLength=29; public static double MINBASE=-2; public static double MINAMP=2; public static double MAXBASE=2; public static double MAXAMP=4; DictionaryModel.Shape shape;//Will change for each series private static int GLOBALSERIESLENGTH=500; private int seriesLength; // Need to set intervals, maybe allow different lengths? private int base=-1; private int amplitude=2; private int shapeCount=0; private boolean invert=false; boolean discord=false; double[] shapeVals; ArrayList<Integer> locations; public static int getGlobalLength(){ return GLOBALSERIESLENGTH;} public MatrixProfileModelVersion1(){ shapeCount=0;//rand.nextInt(ShapeType.values().length); seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } public MatrixProfileModelVersion1(boolean d){ shapeCount=0;//rand.nextInt(ShapeType.values().length); discord=d; if(discord) nosLocations=1; seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } private void generateRandomShapeVals(){ for(int i=0;i<shapeLength;i++) shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); } public void setSeriesLength(int n){ seriesLength=n; } public static void setGlobalSeriesLength(int n){ GLOBALSERIESLENGTH=n; } public void setNonOverlappingIntervals(){ //Use Aarons way ArrayList<Integer> startPoints=new ArrayList<>(); for(int i=shapeLength+1;i<seriesLength-shapeLength;i++) startPoints.add(i); for(int i=0;i<nosLocations;i++){ int pos=rand.nextInt(startPoints.size()); int l=startPoints.get(pos); locations.add(l); //+/- windowSize/2 if(pos<shapeLength) pos=0; else pos=pos-shapeLength; for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++) startPoints.remove(pos); /* //Me giving up and just randomly placing the shapes until they are all non overlapping for(int i=0;i<nosLocations;i++){ boolean ok=false; int l=shapeLength/2; while(!ok){ ok=true; //Search mid points to level the distribution up somewhat // System.out.println("Series length ="+seriesLength); do{ l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2; } while((l+shapeLength/2)>=seriesLength-shapeLength); for(int in:locations){ //I think this is setting them too big if((l>=in-shapeLength && l<in+shapeLength) //l inside ins ||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l ok=false; // System.out.println(l+" overlaps with "+in); break; } } } */ // System.out.println("Adding "+l); } /*//Revert to start points for(int i=0;i<locations.size();i++){ int val=locations.get(i); locations.set(i, val-shapeLength/2); } */ Collections.sort(locations); // System.out.println("MODEL START POINTS ="); // for(int i=0;i<locations.size();i++) // System.out.println(locations.get(i)); } @Override public void setParameters(double[] p) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void setLocations(ArrayList<Integer> l, int length){ locations=new ArrayList<>(l); shapeLength=length; } public ArrayList<Integer> getIntervals(){return locations;} public int getShapeLength(){ return shapeLength;} public void generateBaseShape(){ //Randomise BASE and AMPLITUDE double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); ShapeType[] all=ShapeType.values(); ShapeType st=all[(shapeCount++)%all.length]; shape=new DictionaryModel.Shape(st,shapeLength,b,a); // shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a); // System.out.println("Shape is "+shape); // shape.nextShape(); // shape } @Override public double[] generateSeries(int n) { t=0; double[] d; generateRandomShapeVals(); //Resets the starting locations each time this is called if(invert){ d= new double[n]; for(int i=0;i<n;i++) d[i]=-generate(); invert=false; } else{ generateBaseShape(); d = new double[n]; for(int i=0;i<n;i++) d[i]=generate(); invert=true; } return d; } private double generateConfig1(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=0; //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(point<=t && point+shapeLength>t)//in shape1 value=shapeVals[(int)(t-point)]; else value= error.simulate(); // value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); t++; return value; } private double generateConfig2(){ //Noise // System.out.println("Error var<SUF> double value=error.simulate(); //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(insertionPoint>0 && point==t){//New shape, randomise scale // double b=shape.getBase()/5; // double a=shape.getAmp()/5; double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); shape.setAmp(a); shape.setBase(b); // System.out.println("changing second shape"); } if(point<=t && point+shapeLength>t){//in shape1 value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); } t++; return value; } //Generate point t @Override public double generate(){ return generateConfig1(); } public static void generateExampleData(){ int length=500; GLOBALSERIESLENGTH=length; Model.setGlobalRandomSeed(3); Model.setDefaultSigma(0); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[][] d=new double[20][]; for(int i=0;i<10;i++){ d[i]=m1.generateSeries(length); } for(int i=10;i<20;i++){ d[i]=m1.generateSeries(length); } OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv"); for(int i=0;i<length;i++){ for(int j=0;j<10;j++) of.writeString(d[j][i]+","); of.writeString("\n"); } } public String toString(){ String str=""; for(Integer i:locations) str+=i+","; return str; } public static void main(String[] args){ generateExampleData(); System.exit(0); //Set up two models with same intervals but different shapes int length=500; Model.setGlobalRandomSeed(10); Model.setDefaultSigma(0.1); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[] d1=m1.generateSeries(length); double[] d2=m2.generateSeries(length); OutFile of=new OutFile("C:\\temp\\MP_Ex.csv"); for(int i=0;i<length;i++) of.writeLine(d1[i]+","+d2[i]); } }
False
222
167130_0
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
Bobster94/Keezen
src/keezen/Decks.java
459
/*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
block_comment
nl
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks<SUF>*/
False
556
77274_2
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_SCALE = 1/1.149604398f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner values for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float COEFF) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= COEFF; } else { s[i] /= COEFF; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
GRSEB9S/Jypec
src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java
1,512
// Predict inner values
line_comment
nl
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_SCALE = 1/1.149604398f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner<SUF> for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float COEFF) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= COEFF; } else { s[i] /= COEFF; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
False
4,470
18288_9
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module geladen, starten rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/game/server/ServerCore.java
3,501
// Alle Module geladen, starten
line_comment
nl
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module<SUF> rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
True
501
15652_9
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package fhv; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = true; static int bufsize; static int available; static int tokenBegin; /** Position in buffer. */ static public int bufpos = -1; static protected int bufline[]; static protected int bufcolumn[]; static protected int column = 0; static protected int line = 1; static protected boolean prevCharIsCR = false; static protected boolean prevCharIsLF = false; static protected java.io.Reader inputStream; static protected char[] buffer; static protected int maxNextCharInd = 0; static protected int inBuf = 0; static protected int tabSize = 8; static protected void setTabSize(int i) { tabSize = i; } static protected int getTabSize(int i) { return tabSize; } static protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ static public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ static public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ static public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ static public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ static public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ static public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ static public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ static public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ static public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { if (inputStream != null) throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" + " You must either use ReInit() or set the JavaCC option STATIC to false\n" + " during the generation of this class."); inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ static public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ static public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ static public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
FHV-ITM13/Just-Language
Justy_Wachter/src/fhv/SimpleCharStream.java
3,932
/** Get token beginning column number. */
block_comment
nl
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package fhv; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = true; static int bufsize; static int available; static int tokenBegin; /** Position in buffer. */ static public int bufpos = -1; static protected int bufline[]; static protected int bufcolumn[]; static protected int column = 0; static protected int line = 1; static protected boolean prevCharIsCR = false; static protected boolean prevCharIsLF = false; static protected java.io.Reader inputStream; static protected char[] buffer; static protected int maxNextCharInd = 0; static protected int inBuf = 0; static protected int tabSize = 8; static protected void setTabSize(int i) { tabSize = i; } static protected int getTabSize(int i) { return tabSize; } static protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ static public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ static public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ static public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ static public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ static public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ static public int getEndLine() { return bufline[bufpos]; } /** Get token beginning<SUF>*/ static public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ static public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ static public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { if (inputStream != null) throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" + " You must either use ReInit() or set the JavaCC option STATIC to false\n" + " during the generation of this class."); inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ static public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ static public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ static public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
False
3,832
169507_0
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken) 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
njtromp/AdventOfCode-2020
src/main/java/nl/njtromp/adventofcode_2020/Infi.java
436
// Schuine zijden (4 halve driehoeken)
line_comment
nl
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden<SUF> 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
True
1,893
30813_5
package shapes; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import properties.Property; import utility.MeasureFetcher; import utility.Util; import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters; public abstract class ShapeGenerator { protected MeasureFetcher measureFetcher; protected Shape[] shapes; protected PolymorphicChartParameters params; private Property<Double> width; private Property<Double> height; private Property<Color> color; public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) { this.measureFetcher=measureFetcher; this.width = width; this.height = height; this.color = color; } /** * This method gives all boxes the correct values. * @param width that should be given to all boxes (number or metric) * @param height that should be given to all boxes (number or metric) * @param color that should be given to all boxes (rgb format or grayscale with metric) * @return */ public Shape[] getShapes() { return this.shapes; } /** * This method returns a list of colors, one for each shape. If * the input is in RGB format, the color is the same for all shapes. If the * format "min<float>max<float>key<string>" is used as input, the color of * each box is dependent on a specific measure of the box. Else, the color * will be set to default color * * @param color * the color/metric to be used * @return a list with a color for each box */ protected List<Color> getShapeColors(String color) { List<Color> result = new ArrayList<Color>(); if(Util.isValidColor(color)){ Color rgb = Util.parseColor(color); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>" try{ String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"}); Double min = Double.parseDouble(splitted[0]); Double max = Double.parseDouble(splitted[1]); String key = splitted[2]; result = getGrayScaleColors(min, max, key); } //Given input is not valid catch (IllegalArgumentException f){ Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } } return result; } /** * This method scales a list of metric values to a new list, with the lowest * value of the metric scaled to min, and the highest scaled to max. * * @param min * the minimum color value of the list with scaled colors * @param max * the maximum color value of the list with scaled colors * @param key * the key that represents the metric that should be scaled * @return a list with the scaled color values */ private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{ //TODO hoe werkt dees eigenlijk. vage opgave Map<String, Double> colors = measureFetcher.getMeasureValues(key); Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max); List<Color> result = new ArrayList<Color>(); try{ for (int i = 0; i < shapes.length; i++) { String name = shapes[i].getName(); int colorValue = scaledColors.get(name).intValue(); Color c = new Color(colorValue, colorValue, colorValue); result.add(c); } return result; } catch(Exception e){ throw new IllegalArgumentException(); } } /** * This method names all the shapes with the correct resource names. */ protected void nameShapes() { List<String> names = measureFetcher.getResourceNames(); int i = 0; for (String s : names) { shapes[i].setName(s); i++; } } }
WoutV/OSS_1415
sonar-polymorphic-views/src/main/java/shapes/ShapeGenerator.java
1,195
//TODO hoe werkt dees eigenlijk. vage opgave
line_comment
nl
package shapes; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import properties.Property; import utility.MeasureFetcher; import utility.Util; import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters; public abstract class ShapeGenerator { protected MeasureFetcher measureFetcher; protected Shape[] shapes; protected PolymorphicChartParameters params; private Property<Double> width; private Property<Double> height; private Property<Color> color; public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) { this.measureFetcher=measureFetcher; this.width = width; this.height = height; this.color = color; } /** * This method gives all boxes the correct values. * @param width that should be given to all boxes (number or metric) * @param height that should be given to all boxes (number or metric) * @param color that should be given to all boxes (rgb format or grayscale with metric) * @return */ public Shape[] getShapes() { return this.shapes; } /** * This method returns a list of colors, one for each shape. If * the input is in RGB format, the color is the same for all shapes. If the * format "min<float>max<float>key<string>" is used as input, the color of * each box is dependent on a specific measure of the box. Else, the color * will be set to default color * * @param color * the color/metric to be used * @return a list with a color for each box */ protected List<Color> getShapeColors(String color) { List<Color> result = new ArrayList<Color>(); if(Util.isValidColor(color)){ Color rgb = Util.parseColor(color); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>" try{ String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"}); Double min = Double.parseDouble(splitted[0]); Double max = Double.parseDouble(splitted[1]); String key = splitted[2]; result = getGrayScaleColors(min, max, key); } //Given input is not valid catch (IllegalArgumentException f){ Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } } return result; } /** * This method scales a list of metric values to a new list, with the lowest * value of the metric scaled to min, and the highest scaled to max. * * @param min * the minimum color value of the list with scaled colors * @param max * the maximum color value of the list with scaled colors * @param key * the key that represents the metric that should be scaled * @return a list with the scaled color values */ private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{ //TODO hoe<SUF> Map<String, Double> colors = measureFetcher.getMeasureValues(key); Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max); List<Color> result = new ArrayList<Color>(); try{ for (int i = 0; i < shapes.length; i++) { String name = shapes[i].getName(); int colorValue = scaledColors.get(name).intValue(); Color c = new Color(colorValue, colorValue, colorValue); result.add(c); } return result; } catch(Exception e){ throw new IllegalArgumentException(); } } /** * This method names all the shapes with the correct resource names. */ protected void nameShapes() { List<String> names = measureFetcher.getResourceNames(); int i = 0; for (String s : names) { shapes[i].setName(s); i++; } } }
False
1,859
150349_0
/* avondvierdaagse.java * * Pieter Eendebak * eendebak at math uu nl * */ import java.util.StringTokenizer; import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.lang.Math; class Mud { public long x, y; } class MudCompare implements Comparator{ public int compare(Object a, Object b) { Mud A = (Mud)a; Mud B = (Mud)b; return (A.x-B.x)<0?-1:1; } } class Main { public static StringTokenizer tok; public static String line; public static BufferedReader in; public static void write(String s) { System.out.print(s); } public static void writen(String s) { System.out.print(s+"\n"); } public static int readInt() throws Exception { tok(); return nextInt(); } public static void tok() throws Exception { tok = new StringTokenizer(in.readLine()); } public static String nextString() throws Exception { return (String)tok.nextToken(); } public static int nextInt() throws Exception { return Integer.parseInt((String)tok.nextToken()); } public static void main(String[] args) throws Exception { in = new BufferedReader( new InputStreamReader(System.in) ); int runs = readInt(); for( int run=0; run<runs; run++ ) doit(); } public static void doit() throws Exception { int n; long l; // read in data tok(); n = nextInt(); l = nextInt(); //writen("Doing run with "+n+" mudpools"); Mud [] mudpool = new Mud[n]; int i = 0, j; for(i=0;i<n;i++) { tok(); mudpool[i] = new Mud(); mudpool[i].x = nextInt(); mudpool[i].y = nextInt(); //writen("read " + mudpool[i].x + " " + mudpool[i].y); } // find optimal number of planks Arrays.sort( mudpool, new MudCompare()); long end=0; long pl=0; i=0; while(i<n) { //writen("i: " + i + " pl: " + pl + " end: " + end); if(mudpool[i].y>end) { // add new plank end = l + Math.max(end, mudpool[i].x); pl++; } else i++; } // print the results writen(""+pl); } }
WISVCH/chipcie-website
static/archive/2004/nkp/c/oplossing.java
782
/* avondvierdaagse.java * * Pieter Eendebak * eendebak at math uu nl * */
block_comment
nl
/* avondvierdaagse.java *<SUF>*/ import java.util.StringTokenizer; import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.lang.Math; class Mud { public long x, y; } class MudCompare implements Comparator{ public int compare(Object a, Object b) { Mud A = (Mud)a; Mud B = (Mud)b; return (A.x-B.x)<0?-1:1; } } class Main { public static StringTokenizer tok; public static String line; public static BufferedReader in; public static void write(String s) { System.out.print(s); } public static void writen(String s) { System.out.print(s+"\n"); } public static int readInt() throws Exception { tok(); return nextInt(); } public static void tok() throws Exception { tok = new StringTokenizer(in.readLine()); } public static String nextString() throws Exception { return (String)tok.nextToken(); } public static int nextInt() throws Exception { return Integer.parseInt((String)tok.nextToken()); } public static void main(String[] args) throws Exception { in = new BufferedReader( new InputStreamReader(System.in) ); int runs = readInt(); for( int run=0; run<runs; run++ ) doit(); } public static void doit() throws Exception { int n; long l; // read in data tok(); n = nextInt(); l = nextInt(); //writen("Doing run with "+n+" mudpools"); Mud [] mudpool = new Mud[n]; int i = 0, j; for(i=0;i<n;i++) { tok(); mudpool[i] = new Mud(); mudpool[i].x = nextInt(); mudpool[i].y = nextInt(); //writen("read " + mudpool[i].x + " " + mudpool[i].y); } // find optimal number of planks Arrays.sort( mudpool, new MudCompare()); long end=0; long pl=0; i=0; while(i<n) { //writen("i: " + i + " pl: " + pl + " end: " + end); if(mudpool[i].y>end) { // add new plank end = l + Math.max(end, mudpool[i].x); pl++; } else i++; } // print the results writen(""+pl); } }
False
2,133
202595_10
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] INTUITION, go along to diaonals and incrememnt but i-1, j+1 to do in reverse order, store all elements in arraylist and then reverse REGULAR DIAONGAL MATRIX class Solution { public int[] findDiagonalOrder(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; int index =0; int[] res = new int[m*n]; for(int k=0; k<=m-1; k++){ int i=k; // to print all the diagonals starting on left row int j=0; //starts on first col always while(i>=0){ //go until we reach the upper bord res[index++]=matrix[i][j]; i=i-1; j=j+1; } } for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice int i = m-1; //starts on last rol always int j= k; //to print all diagonals starting at bottom row while(j<=n-1){ //go until we reach the right border res[index++]=matrix[i][j]; i=i-1; j=j+1; } } return res; } } SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts, THEN add to result //TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix //SC: O(min(N,M)) to store elements in arraylist class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return new int[0]; int m = matrix.length; int n = matrix[0].length; int[] res = new int[m*n]; int resIndex = 0; ArrayList<Integer> temp = new ArrayList<>(); for(int k=0; k<m; k++){ temp.clear(); //clear out this temp array int i = k; int j =0; while(i>=0){ temp.add(matrix[i][j]); //copy this elemeent i= i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice temp.clear(); //clear out this temp array int i = m-1; int j = k; while(j< n){ temp.add((matrix[i][j])); i=i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } return res; } } // If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction. // if out of right border (col >= n) then col = n - 1; row += 2; change walk direction. // if out of top border (row < 0) then row = 0; change walk direction. // if out of left border (col < 0) then col = 0; change walk direction. // Otherwise, just go along with the current direction. BEST SOLUTION //O(M*N) //O(1) constant space solutioN!!!! public class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) return new int[0]; int m = matrix.length, n = matrix[0].length; int[] result = new int[m * n]; int row = 0, col = 0, d = 0; //first direction we go is upright int[][] dirs = {{-1, 1}, {1, -1}}; for (int i = 0; i < m * n; i++) { result[i] = matrix[row][col]; row += dirs[d][0]; col += dirs[d][1]; if (row >= m) { row = m - 1; col += 2; d = 1 - d;} if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col } return result; } }
armankhondker/best-leetcode-resources
leetcode-solutions/diagonalMatrixPrint.java
1,455
//copy this elemeent
line_comment
nl
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] INTUITION, go along to diaonals and incrememnt but i-1, j+1 to do in reverse order, store all elements in arraylist and then reverse REGULAR DIAONGAL MATRIX class Solution { public int[] findDiagonalOrder(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; int index =0; int[] res = new int[m*n]; for(int k=0; k<=m-1; k++){ int i=k; // to print all the diagonals starting on left row int j=0; //starts on first col always while(i>=0){ //go until we reach the upper bord res[index++]=matrix[i][j]; i=i-1; j=j+1; } } for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice int i = m-1; //starts on last rol always int j= k; //to print all diagonals starting at bottom row while(j<=n-1){ //go until we reach the right border res[index++]=matrix[i][j]; i=i-1; j=j+1; } } return res; } } SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts, THEN add to result //TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix //SC: O(min(N,M)) to store elements in arraylist class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return new int[0]; int m = matrix.length; int n = matrix[0].length; int[] res = new int[m*n]; int resIndex = 0; ArrayList<Integer> temp = new ArrayList<>(); for(int k=0; k<m; k++){ temp.clear(); //clear out this temp array int i = k; int j =0; while(i>=0){ temp.add(matrix[i][j]); //copy this<SUF> i= i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice temp.clear(); //clear out this temp array int i = m-1; int j = k; while(j< n){ temp.add((matrix[i][j])); i=i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } return res; } } // If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction. // if out of right border (col >= n) then col = n - 1; row += 2; change walk direction. // if out of top border (row < 0) then row = 0; change walk direction. // if out of left border (col < 0) then col = 0; change walk direction. // Otherwise, just go along with the current direction. BEST SOLUTION //O(M*N) //O(1) constant space solutioN!!!! public class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) return new int[0]; int m = matrix.length, n = matrix[0].length; int[] result = new int[m * n]; int row = 0, col = 0, d = 0; //first direction we go is upright int[][] dirs = {{-1, 1}, {1, -1}}; for (int i = 0; i < m * n; i++) { result[i] = matrix[row][col]; row += dirs[d][0]; col += dirs[d][1]; if (row >= m) { row = m - 1; col += 2; d = 1 - d;} if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col } return result; } }
False
2,501
75359_9
/** * Repraesentiert ein Auto. * */ abstract class Car implements Runnable{ //Repraesentiert einer der vier Himmelsrichtungen, in die das Auto zeigen kann. private Orientations orientation; private int x; private int y; private String name; protected int millisecondsToWait; protected Racetrack currentRacetrack; private Thread t; private int steps = 0; private int score = 0; /** * Initialisiere ein Auto. * * @param x - Startposition * @param y - Startposition * @param startOrientation - Anfangsorientierung * @param carName - Name des Autos */ public Car(int x, int y, Orientations startOrientation, String carName){ this.x = x; this.y = y; this.orientation = startOrientation; this.name = carName; this.millisecondsToWait = 0; } public Car(Orientations startOrientation, String carName){ this(0, 0, startOrientation, carName); } //VB: setOrientation darf nur ausgefuehrt werden, wenn vorher eine passende //Beweung stattgefunden hat. public void setOrientation(Orientations orientation){ this.orientation = orientation; } public Orientations getOrientation(){ return this.orientation; } public int getX(){ return this.x; } public int getY(){ return this.y; } //VB: x >= 0 public void setX(int x) { this.x = x; } //VB: y >= 0 public void setY(int y) { this.y = y; } //VB: rt != null //VB: Das Rennen auf diesem Track darf noch nicht begonnen haben public void setRacetrack(Racetrack rt) { this.currentRacetrack = rt; } //VB: Rennen hat begonnen //NB: Der Thread laeuft. public void startCar(){ this.t = new Thread(this); t.start(); } //Autos haben nur einen eingeschraenkten Aktionsradius, der hier ueberprueft wird. //Unterklassen liefern passenden boolean zurueck. protected boolean canDriveTo(Directions direction){ return false; } //Wird vom Thread aufgerufen. Implementierung in Unterklassen. protected abstract void drive() throws InterruptedException; public int getScore() { return score; } //Erhoeht den Score um eins. public void upScore() { score += 1; } // Verringert den Score um eins. public void downScore() { score -= 1; } public int getSteps() { return steps; } //Erhoeht die Schritte um eins. public void upSteps() { steps += 1; } // NB: Thread wurde angewiesen, abzubrechen. public void stop(){ if(t != null){ t.interrupt(); } } /** * Thread Methode, die unterbrochen werden kann. Ruft drive Methode auf. * Am Ende der Methode wird der Name und Score ausgegeben, da das * Rennen zu Ende ist. * */ @Override public void run() { while( !Thread.interrupted() ){ try { this.drive(); Thread.sleep(millisecondsToWait); }catch(InterruptedException e){ break; } } System.out.println("Auto \'"+name + "\' Punkte=" + score); } @Override public String toString() { return name; } // NB: Es laeuft fuer diese Instanz kein Thread mehr. public void join() throws InterruptedException { t.join(); } }
danurna/oop7
src/Car.java
1,086
//VB: Rennen hat begonnen
line_comment
nl
/** * Repraesentiert ein Auto. * */ abstract class Car implements Runnable{ //Repraesentiert einer der vier Himmelsrichtungen, in die das Auto zeigen kann. private Orientations orientation; private int x; private int y; private String name; protected int millisecondsToWait; protected Racetrack currentRacetrack; private Thread t; private int steps = 0; private int score = 0; /** * Initialisiere ein Auto. * * @param x - Startposition * @param y - Startposition * @param startOrientation - Anfangsorientierung * @param carName - Name des Autos */ public Car(int x, int y, Orientations startOrientation, String carName){ this.x = x; this.y = y; this.orientation = startOrientation; this.name = carName; this.millisecondsToWait = 0; } public Car(Orientations startOrientation, String carName){ this(0, 0, startOrientation, carName); } //VB: setOrientation darf nur ausgefuehrt werden, wenn vorher eine passende //Beweung stattgefunden hat. public void setOrientation(Orientations orientation){ this.orientation = orientation; } public Orientations getOrientation(){ return this.orientation; } public int getX(){ return this.x; } public int getY(){ return this.y; } //VB: x >= 0 public void setX(int x) { this.x = x; } //VB: y >= 0 public void setY(int y) { this.y = y; } //VB: rt != null //VB: Das Rennen auf diesem Track darf noch nicht begonnen haben public void setRacetrack(Racetrack rt) { this.currentRacetrack = rt; } //VB: Rennen<SUF> //NB: Der Thread laeuft. public void startCar(){ this.t = new Thread(this); t.start(); } //Autos haben nur einen eingeschraenkten Aktionsradius, der hier ueberprueft wird. //Unterklassen liefern passenden boolean zurueck. protected boolean canDriveTo(Directions direction){ return false; } //Wird vom Thread aufgerufen. Implementierung in Unterklassen. protected abstract void drive() throws InterruptedException; public int getScore() { return score; } //Erhoeht den Score um eins. public void upScore() { score += 1; } // Verringert den Score um eins. public void downScore() { score -= 1; } public int getSteps() { return steps; } //Erhoeht die Schritte um eins. public void upSteps() { steps += 1; } // NB: Thread wurde angewiesen, abzubrechen. public void stop(){ if(t != null){ t.interrupt(); } } /** * Thread Methode, die unterbrochen werden kann. Ruft drive Methode auf. * Am Ende der Methode wird der Name und Score ausgegeben, da das * Rennen zu Ende ist. * */ @Override public void run() { while( !Thread.interrupted() ){ try { this.drive(); Thread.sleep(millisecondsToWait); }catch(InterruptedException e){ break; } } System.out.println("Auto \'"+name + "\' Punkte=" + score); } @Override public String toString() { return name; } // NB: Es laeuft fuer diese Instanz kein Thread mehr. public void join() throws InterruptedException { t.join(); } }
False
808
152641_17
package intecbrussel.be.Vaccination;_x000D_ _x000D_ import java.util.*;_x000D_ import java.util.stream.Collectors;_x000D_ _x000D_ public class AnimalShelter {_x000D_ private List<Animal> animals;_x000D_ private int animalId;_x000D_ _x000D_ public AnimalShelter() {_x000D_ this.animals = new ArrayList<>();_x000D_ this.animalId = 1;_x000D_ }_x000D_ _x000D_ public List<Animal> getAnimals() {_x000D_ return animals;_x000D_ }_x000D_ _x000D_ public void setAnimals(List<Animal> animals) {_x000D_ this.animals = animals;_x000D_ }_x000D_ _x000D_ public int getAnimalId() {_x000D_ return animalId;_x000D_ }_x000D_ _x000D_ public void setAnimalId(int animalId) {_x000D_ this.animalId = animalId;_x000D_ }_x000D_ //1_x000D_ public void printAnimals(){_x000D_ for (Animal animal : animals){_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ // sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_ //2_x000D_ public void sortAnimals(){_x000D_ animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_ }_x000D_ //sorteert de dieren op naam_x000D_ //3_x000D_ public void sortAnimalsByName(){_x000D_ animals.sort(Comparator.comparing(Animal::getName));_x000D_ }_x000D_ // sorteert de dieren op leeftijd_x000D_ //4_x000D_ public void sortAnimalsByAge(){_x000D_ animals.sort(Comparator.comparing(Animal::getAge));_x000D_ }_x000D_ //print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_ //5_x000D_ public void printAnimalsNotVaccinated(Disease disease){_x000D_ List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_ for (Animal animal : notVaccinated){_x000D_ System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_ }_x000D_ }_x000D_ //zoek dier op dierennummer_x000D_ //6_x000D_ public Animal findAnimal(int animalNumber) {_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber() == animalNumber){_x000D_ return animal;_x000D_ }_x000D_ }_x000D_ return null;_x000D_ // return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_ }_x000D_ _x000D_ //zoek dier op dierennaam_x000D_ //7_x000D_ public Optional<Animal> findAnimal(String name){_x000D_ return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_ _x000D_ }_x000D_ // behandel opgegeven dier_x000D_ //8_x000D_ public void treatAnimal(int animalNumber){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber()==animalNumber){_x000D_ System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ //System.out.println("animal with number "+animalNumber+"not found");_x000D_ /* animals.stream()_x000D_ .sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_ .forEach(animal -> System.out.println(_x000D_ "Animal number: "+animal.getAnimalNumber()+_x000D_ "| name: "+animal.getName()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met number "+animalNumber+"not found");_x000D_ }*/_x000D_ }_x000D_ //behandel opgegeven dier_x000D_ //9_x000D_ public void treatAnimal(String name){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getName()==name){_x000D_ System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ /*animals.stream()_x000D_ .sorted(Comparator.comparing(Animal::getName))_x000D_ .forEach(animal -> System.out.println(_x000D_ "name: "+animal.getName()+_x000D_ "| animal number: "+animal.getAnimalNumber()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met name "+name+ "not found");_x000D_ }*/_x000D_ _x000D_ }_x000D_ //behandel alle dieren_x000D_ //10_x000D_ public void treatAllAnimals(){_x000D_ for (Animal animal : animals){_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ _x000D_ }_x000D_ //geef het oudste dier terug_x000D_ //11_x000D_ public Animal findOldestAnimal() throws NoSuchElementException {_x000D_ if (animals.isEmpty()) {_x000D_ throw new NoSuchElementException("No animal found in this list");_x000D_ }_x000D_ Animal oldestAnimal = animals.get(0);_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAge() > oldestAnimal.getAge()){_x000D_ oldestAnimal = animal;_x000D_ //System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ return oldestAnimal;_x000D_ _x000D_ }_x000D_ _x000D_ // geef het aantal dieren terug_x000D_ //12_x000D_ public int countAnimals(){_x000D_ if (animals != null){_x000D_ return animals.size();_x000D_ }else {_x000D_ return 0;_x000D_ }_x000D_ }_x000D_ _x000D_ //voeg een dier toe aan de lijst van animals_x000D_ //13_x000D_ public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_ if (animal != null){_x000D_ animal.setAnimalNumber(animalId);//toewijzen de nummer animal_x000D_ animals.add(animal);//add de animal to de list_x000D_ animalId++;//verhoog de animal id_x000D_ }else {_x000D_ throw new IllegalArgumentException("Can not add null animal to de list");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
JananJavdan/Vaccination
Vaccination/src/main/java/intecbrussel/be/Vaccination/AnimalShelter.java
2,073
//toewijzen de nummer animal_x000D_
line_comment
nl
package intecbrussel.be.Vaccination;_x000D_ _x000D_ import java.util.*;_x000D_ import java.util.stream.Collectors;_x000D_ _x000D_ public class AnimalShelter {_x000D_ private List<Animal> animals;_x000D_ private int animalId;_x000D_ _x000D_ public AnimalShelter() {_x000D_ this.animals = new ArrayList<>();_x000D_ this.animalId = 1;_x000D_ }_x000D_ _x000D_ public List<Animal> getAnimals() {_x000D_ return animals;_x000D_ }_x000D_ _x000D_ public void setAnimals(List<Animal> animals) {_x000D_ this.animals = animals;_x000D_ }_x000D_ _x000D_ public int getAnimalId() {_x000D_ return animalId;_x000D_ }_x000D_ _x000D_ public void setAnimalId(int animalId) {_x000D_ this.animalId = animalId;_x000D_ }_x000D_ //1_x000D_ public void printAnimals(){_x000D_ for (Animal animal : animals){_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ // sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_ //2_x000D_ public void sortAnimals(){_x000D_ animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_ }_x000D_ //sorteert de dieren op naam_x000D_ //3_x000D_ public void sortAnimalsByName(){_x000D_ animals.sort(Comparator.comparing(Animal::getName));_x000D_ }_x000D_ // sorteert de dieren op leeftijd_x000D_ //4_x000D_ public void sortAnimalsByAge(){_x000D_ animals.sort(Comparator.comparing(Animal::getAge));_x000D_ }_x000D_ //print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_ //5_x000D_ public void printAnimalsNotVaccinated(Disease disease){_x000D_ List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_ for (Animal animal : notVaccinated){_x000D_ System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_ }_x000D_ }_x000D_ //zoek dier op dierennummer_x000D_ //6_x000D_ public Animal findAnimal(int animalNumber) {_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber() == animalNumber){_x000D_ return animal;_x000D_ }_x000D_ }_x000D_ return null;_x000D_ // return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_ }_x000D_ _x000D_ //zoek dier op dierennaam_x000D_ //7_x000D_ public Optional<Animal> findAnimal(String name){_x000D_ return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_ _x000D_ }_x000D_ // behandel opgegeven dier_x000D_ //8_x000D_ public void treatAnimal(int animalNumber){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber()==animalNumber){_x000D_ System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ //System.out.println("animal with number "+animalNumber+"not found");_x000D_ /* animals.stream()_x000D_ .sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_ .forEach(animal -> System.out.println(_x000D_ "Animal number: "+animal.getAnimalNumber()+_x000D_ "| name: "+animal.getName()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met number "+animalNumber+"not found");_x000D_ }*/_x000D_ }_x000D_ //behandel opgegeven dier_x000D_ //9_x000D_ public void treatAnimal(String name){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getName()==name){_x000D_ System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ /*animals.stream()_x000D_ .sorted(Comparator.comparing(Animal::getName))_x000D_ .forEach(animal -> System.out.println(_x000D_ "name: "+animal.getName()+_x000D_ "| animal number: "+animal.getAnimalNumber()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met name "+name+ "not found");_x000D_ }*/_x000D_ _x000D_ }_x000D_ //behandel alle dieren_x000D_ //10_x000D_ public void treatAllAnimals(){_x000D_ for (Animal animal : animals){_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ _x000D_ }_x000D_ //geef het oudste dier terug_x000D_ //11_x000D_ public Animal findOldestAnimal() throws NoSuchElementException {_x000D_ if (animals.isEmpty()) {_x000D_ throw new NoSuchElementException("No animal found in this list");_x000D_ }_x000D_ Animal oldestAnimal = animals.get(0);_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAge() > oldestAnimal.getAge()){_x000D_ oldestAnimal = animal;_x000D_ //System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ return oldestAnimal;_x000D_ _x000D_ }_x000D_ _x000D_ // geef het aantal dieren terug_x000D_ //12_x000D_ public int countAnimals(){_x000D_ if (animals != null){_x000D_ return animals.size();_x000D_ }else {_x000D_ return 0;_x000D_ }_x000D_ }_x000D_ _x000D_ //voeg een dier toe aan de lijst van animals_x000D_ //13_x000D_ public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_ if (animal != null){_x000D_ animal.setAnimalNumber(animalId);//toewijzen de<SUF> animals.add(animal);//add de animal to de list_x000D_ animalId++;//verhoog de animal id_x000D_ }else {_x000D_ throw new IllegalArgumentException("Can not add null animal to de list");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
True
3,576
72814_22
package org.molgenis.animaldb.plugins.administration;_x000D_ _x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ import java.util.Locale;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.db.Query;_x000D_ import org.molgenis.framework.db.QueryRule;_x000D_ import org.molgenis.framework.db.QueryRule.Operator;_x000D_ import org.molgenis.pheno.ObservationTarget;_x000D_ import org.molgenis.pheno.ObservedValue;_x000D_ _x000D_ _x000D_ public class VWAReport5 extends AnimalDBReport {_x000D_ _x000D_ private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();_x000D_ private List<Integer> nrOfAnimalList = new ArrayList<Integer>();_x000D_ private String userName;_x000D_ _x000D_ public VWAReport5(Database db, String userName) {_x000D_ this.userName = userName;_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(db);_x000D_ nrCol = 17;_x000D_ warningsList = new ArrayList<String>();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void makeReport(int year, String type) {_x000D_ try {_x000D_ this.year = year;_x000D_ SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);_x000D_ SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);_x000D_ String startOfYearString = year + "-01-01 00:00:00";_x000D_ Date startOfYear = fullFormat.parse(startOfYearString);_x000D_ String endOfYearString = (year + 1) + "-01-01 00:00:00";_x000D_ Date endOfYear = fullFormat.parse(endOfYearString);_x000D_ _x000D_ List<String> investigationNames = ct.getOwnUserInvestigationNames(userName);_x000D_ List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames);_x000D_ for (ObservationTarget d : decappList) {_x000D_ String decName = d.getName();_x000D_ // Check if the DEC application was (partly) in this year_x000D_ Date startOfDec = null;_x000D_ String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate");_x000D_ if (startOfDecString != null && !startOfDecString.equals("")) {_x000D_ startOfDec = dbFormat.parse(startOfDecString);_x000D_ if (startOfDec.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ } else {_x000D_ continue;_x000D_ }_x000D_ Date endOfDec = null;_x000D_ String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate");_x000D_ if (endOfDecString != null && !endOfDecString.equals("")) {_x000D_ endOfDec = dbFormat.parse(endOfDecString);_x000D_ if (endOfDec.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ }_x000D_ // Get DEC number_x000D_ String decNr = ct.getMostRecentValueAsString(decName, "DecNr");_x000D_ // Find the experiments belonging to this DEC_x000D_ List<Integer> experimentIdList = new ArrayList<Integer>();_x000D_ Query<ObservedValue> q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication"));_x000D_ List<ObservedValue> valueList = q.find();_x000D_ // Make sure we have a list of unique experiments!_x000D_ for (ObservedValue v : valueList) {_x000D_ if (!experimentIdList.contains(v.getTarget_Id())) {_x000D_ experimentIdList.add(v.getTarget_Id());_x000D_ }_x000D_ }_x000D_ for (int expid : experimentIdList) {_x000D_ String expName = ct.getObservationTargetLabel(expid);_x000D_ // Get the experiment subcode_x000D_ String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr");_x000D_ // Doel vd proef (experiment's Goal)_x000D_ String goal = ct.getMostRecentValueAsString(expName, "Goal");_x000D_ // Belang van de proef (experiment's Concern)_x000D_ String concern = ct.getMostRecentValueAsString(expName, "Concern");_x000D_ // Wettelijke bepalingen (experiment's LawDef)_x000D_ String lawDef = ct.getMostRecentValueAsString(expName, "LawDef");_x000D_ // Toxicologisch / veiligheidsonderzoek (experiment's ToxRes)_x000D_ String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes");_x000D_ // Technieken byzondere (experiment's SpecialTechn)_x000D_ String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn");_x000D_ _x000D_ // Get the animals that were in the experiment this year_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ for (ObservedValue animalInExpValue : valueList) {_x000D_ // Get the corresponding protocol application_x000D_ int protocolApplicationId = animalInExpValue.getProtocolApplication_Id();_x000D_ // Get animal ID_x000D_ String animalName = animalInExpValue.getTarget_Name();_x000D_ // Get dates_x000D_ Date entryDate = animalInExpValue.getTime();_x000D_ Date exitDate = animalInExpValue.getEndtime();_x000D_ // Check dates_x000D_ if (entryDate.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ if (exitDate == null) { // should not be possible_x000D_ continue;_x000D_ } else if (exitDate.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ _x000D_ // Get the data about the animal in the experiment_x000D_ // Bijzonderheid dier (animal's AnimalType)_x000D_ String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType");_x000D_ // Diersoort (animal's Species -> VWASpecies and LatinSpecies)_x000D_ String vwaSpecies = "";_x000D_ String latinSpecies = "";_x000D_ String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species");_x000D_ // Get VWA species_x000D_ Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class);_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies"));_x000D_ List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find();_x000D_ if (vwaSpeciesValueList.size() == 1) {_x000D_ vwaSpecies = vwaSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ // Get scientific (Latin) species_x000D_ Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class);_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies"));_x000D_ List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find();_x000D_ if (latinSpeciesValueList.size() == 1) {_x000D_ latinSpecies = latinSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Herkomst en hergebruik (animal's SourceTypeSubproject, which includes reuse)_x000D_ String sourceType = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ sourceType = valueList.get(0).getValue();_x000D_ }_x000D_ // Aantal dieren (count later on!)_x000D_ _x000D_ // Anesthesie (animal's Anaesthesia)_x000D_ String anaesthesia = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ anaesthesia = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Pijnbestrijding, postoperatief (animal's PainManagement)_x000D_ String painManagement = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ painManagement = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ String actualDiscomfort = "";_x000D_ String actualAnimalEndStatus = ""; _x000D_ // Find protocol application ID for the removing of this animal from this DEC subproject_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment"));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id();_x000D_ _x000D_ // Ongerief (animal's ActualDiscomfort)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ actualDiscomfort = valueList.get(0).getValue();_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ // Toestand dier na beeindiging proef (animal's most recent ActualAnimalEndStatus)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus"));_x000D_ q.sortDESC(ObservedValue.TIME);_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // Check if most recent end status was in the PA we're now looking at_x000D_ if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = valueList.get(0).getValue();_x000D_ // If most recent end status was 'in leven gelaten' but animal died in given year,_x000D_ // change to 'dood ihkv de proef' because that's how the law wants it..._x000D_ if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) {_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // So animal did indeed die in the given year_x000D_ actualAnimalEndStatus = "B. Gedood na beeindiging van de proef";_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Find the end status value in the PA we're looking at_x000D_ for (ObservedValue endStatusValue : valueList) {_x000D_ if (endStatusValue.getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = endStatusValue.getValue();_x000D_ }_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'FromExperiment' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ ArrayList<String> newRow = new ArrayList<String>();_x000D_ newRow.add(decNr + expCode + " - " + d.getName());_x000D_ if (endOfDec != null) {_x000D_ newRow.add(dbFormat.format(endOfDec));_x000D_ } else {_x000D_ newRow.add("");_x000D_ }_x000D_ newRow.add(animalType);_x000D_ newRow.add(vwaSpecies);_x000D_ newRow.add(sourceType);_x000D_ newRow.add("");_x000D_ newRow.add(goal);_x000D_ newRow.add(concern);_x000D_ newRow.add(lawDef);_x000D_ newRow.add(toxRes);_x000D_ newRow.add(specialTechn);_x000D_ newRow.add(anaesthesia);_x000D_ newRow.add(painManagement);_x000D_ newRow.add(actualDiscomfort);_x000D_ newRow.add(actualAnimalEndStatus);_x000D_ newRow.add(decNr + expCode);_x000D_ newRow.add(latinSpecies);_x000D_ _x000D_ if (matrix.contains(newRow)) {_x000D_ // If the above values are exactly the same as an earlier row, aggregate them_x000D_ int rowIndex = matrix.indexOf(newRow);_x000D_ int tmpNr = nrOfAnimalList.get(rowIndex);_x000D_ nrOfAnimalList.set(rowIndex, tmpNr + 1);_x000D_ } else {_x000D_ // Else, make a new row_x000D_ matrix.add(newRow);_x000D_ nrOfAnimalList.add(1);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>";_x000D_ output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>";_x000D_ output += "<tr>";_x000D_ output += "<th></th>";_x000D_ output += "<th></th>";_x000D_ for (int col = 1; col < 15; col++) {_x000D_ output += ("<th>" + col + "</th>");_x000D_ }_x000D_ output += "<th></th>";_x000D_ output += "</tr>";_x000D_ output += "<tr>";_x000D_ output += "<td style='padding:5px'>DEC-nr.</td>";_x000D_ output += "<td style='padding:5px'>DEC verlopen op</td>";_x000D_ output += "<td style='padding:5px'>Bijzonderheid dier</td>";_x000D_ output += "<td style='padding:5px'>Diersoort</td>";_x000D_ output += "<td style='padding:5px'>Herkomst en hergebruik</td>";_x000D_ output += "<td style='padding:5px'>Aantal dieren</td>";_x000D_ output += "<td style='padding:5px'>Doel vd proef</td>";_x000D_ output += "<td style='padding:5px'>Belang van de proef</td>";_x000D_ output += "<td style='padding:5px'>Wettelijke bepalingen</td>";_x000D_ output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>";_x000D_ output += "<td style='padding:5px'>Bijzondere technieken</td>";_x000D_ output += "<td style='padding:5px'>Anesthesie</td>";_x000D_ output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>";_x000D_ output += "<td style='padding:5px'>Ongerief</td>";_x000D_ output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>";_x000D_ output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>";_x000D_ output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>";_x000D_ output += "</tr>";_x000D_ int counter = 0;_x000D_ for (ArrayList<String> currentRow : matrix) {_x000D_ output += "<tr>";_x000D_ for (int col = 0; col < nrCol; col++) {_x000D_ if (col == 5) {_x000D_ output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>");_x000D_ } else {_x000D_ output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>");_x000D_ }_x000D_ }_x000D_ output += "</tr>";_x000D_ counter++;_x000D_ }_x000D_ output += "</table></div>";_x000D_ _x000D_ // Warnings_x000D_ if (warningsList.size() > 0) {_x000D_ output += "<p><strong>Warnings</strong><br />";_x000D_ for (String warning : warningsList) {_x000D_ output += (warning + "<br />");_x000D_ }_x000D_ output += "</p>";_x000D_ }_x000D_ _x000D_ return output;_x000D_ }_x000D_ }_x000D_
martijnvermaat/molgenis_apps
apps/animaldb/org/molgenis/animaldb/plugins/administration/VWAReport5.java
5,368
// Pijnbestrijding, postoperatief (animal's PainManagement)_x000D_
line_comment
nl
package org.molgenis.animaldb.plugins.administration;_x000D_ _x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ import java.util.Locale;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.db.Query;_x000D_ import org.molgenis.framework.db.QueryRule;_x000D_ import org.molgenis.framework.db.QueryRule.Operator;_x000D_ import org.molgenis.pheno.ObservationTarget;_x000D_ import org.molgenis.pheno.ObservedValue;_x000D_ _x000D_ _x000D_ public class VWAReport5 extends AnimalDBReport {_x000D_ _x000D_ private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();_x000D_ private List<Integer> nrOfAnimalList = new ArrayList<Integer>();_x000D_ private String userName;_x000D_ _x000D_ public VWAReport5(Database db, String userName) {_x000D_ this.userName = userName;_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(db);_x000D_ nrCol = 17;_x000D_ warningsList = new ArrayList<String>();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void makeReport(int year, String type) {_x000D_ try {_x000D_ this.year = year;_x000D_ SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);_x000D_ SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);_x000D_ String startOfYearString = year + "-01-01 00:00:00";_x000D_ Date startOfYear = fullFormat.parse(startOfYearString);_x000D_ String endOfYearString = (year + 1) + "-01-01 00:00:00";_x000D_ Date endOfYear = fullFormat.parse(endOfYearString);_x000D_ _x000D_ List<String> investigationNames = ct.getOwnUserInvestigationNames(userName);_x000D_ List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames);_x000D_ for (ObservationTarget d : decappList) {_x000D_ String decName = d.getName();_x000D_ // Check if the DEC application was (partly) in this year_x000D_ Date startOfDec = null;_x000D_ String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate");_x000D_ if (startOfDecString != null && !startOfDecString.equals("")) {_x000D_ startOfDec = dbFormat.parse(startOfDecString);_x000D_ if (startOfDec.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ } else {_x000D_ continue;_x000D_ }_x000D_ Date endOfDec = null;_x000D_ String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate");_x000D_ if (endOfDecString != null && !endOfDecString.equals("")) {_x000D_ endOfDec = dbFormat.parse(endOfDecString);_x000D_ if (endOfDec.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ }_x000D_ // Get DEC number_x000D_ String decNr = ct.getMostRecentValueAsString(decName, "DecNr");_x000D_ // Find the experiments belonging to this DEC_x000D_ List<Integer> experimentIdList = new ArrayList<Integer>();_x000D_ Query<ObservedValue> q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication"));_x000D_ List<ObservedValue> valueList = q.find();_x000D_ // Make sure we have a list of unique experiments!_x000D_ for (ObservedValue v : valueList) {_x000D_ if (!experimentIdList.contains(v.getTarget_Id())) {_x000D_ experimentIdList.add(v.getTarget_Id());_x000D_ }_x000D_ }_x000D_ for (int expid : experimentIdList) {_x000D_ String expName = ct.getObservationTargetLabel(expid);_x000D_ // Get the experiment subcode_x000D_ String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr");_x000D_ // Doel vd proef (experiment's Goal)_x000D_ String goal = ct.getMostRecentValueAsString(expName, "Goal");_x000D_ // Belang van de proef (experiment's Concern)_x000D_ String concern = ct.getMostRecentValueAsString(expName, "Concern");_x000D_ // Wettelijke bepalingen (experiment's LawDef)_x000D_ String lawDef = ct.getMostRecentValueAsString(expName, "LawDef");_x000D_ // Toxicologisch / veiligheidsonderzoek (experiment's ToxRes)_x000D_ String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes");_x000D_ // Technieken byzondere (experiment's SpecialTechn)_x000D_ String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn");_x000D_ _x000D_ // Get the animals that were in the experiment this year_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ for (ObservedValue animalInExpValue : valueList) {_x000D_ // Get the corresponding protocol application_x000D_ int protocolApplicationId = animalInExpValue.getProtocolApplication_Id();_x000D_ // Get animal ID_x000D_ String animalName = animalInExpValue.getTarget_Name();_x000D_ // Get dates_x000D_ Date entryDate = animalInExpValue.getTime();_x000D_ Date exitDate = animalInExpValue.getEndtime();_x000D_ // Check dates_x000D_ if (entryDate.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ if (exitDate == null) { // should not be possible_x000D_ continue;_x000D_ } else if (exitDate.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ _x000D_ // Get the data about the animal in the experiment_x000D_ // Bijzonderheid dier (animal's AnimalType)_x000D_ String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType");_x000D_ // Diersoort (animal's Species -> VWASpecies and LatinSpecies)_x000D_ String vwaSpecies = "";_x000D_ String latinSpecies = "";_x000D_ String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species");_x000D_ // Get VWA species_x000D_ Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class);_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies"));_x000D_ List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find();_x000D_ if (vwaSpeciesValueList.size() == 1) {_x000D_ vwaSpecies = vwaSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ // Get scientific (Latin) species_x000D_ Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class);_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies"));_x000D_ List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find();_x000D_ if (latinSpeciesValueList.size() == 1) {_x000D_ latinSpecies = latinSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Herkomst en hergebruik (animal's SourceTypeSubproject, which includes reuse)_x000D_ String sourceType = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ sourceType = valueList.get(0).getValue();_x000D_ }_x000D_ // Aantal dieren (count later on!)_x000D_ _x000D_ // Anesthesie (animal's Anaesthesia)_x000D_ String anaesthesia = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ anaesthesia = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Pijnbestrijding, postoperatief<SUF> String painManagement = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ painManagement = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ String actualDiscomfort = "";_x000D_ String actualAnimalEndStatus = ""; _x000D_ // Find protocol application ID for the removing of this animal from this DEC subproject_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment"));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id();_x000D_ _x000D_ // Ongerief (animal's ActualDiscomfort)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ actualDiscomfort = valueList.get(0).getValue();_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ // Toestand dier na beeindiging proef (animal's most recent ActualAnimalEndStatus)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus"));_x000D_ q.sortDESC(ObservedValue.TIME);_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // Check if most recent end status was in the PA we're now looking at_x000D_ if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = valueList.get(0).getValue();_x000D_ // If most recent end status was 'in leven gelaten' but animal died in given year,_x000D_ // change to 'dood ihkv de proef' because that's how the law wants it..._x000D_ if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) {_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // So animal did indeed die in the given year_x000D_ actualAnimalEndStatus = "B. Gedood na beeindiging van de proef";_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Find the end status value in the PA we're looking at_x000D_ for (ObservedValue endStatusValue : valueList) {_x000D_ if (endStatusValue.getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = endStatusValue.getValue();_x000D_ }_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'FromExperiment' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ ArrayList<String> newRow = new ArrayList<String>();_x000D_ newRow.add(decNr + expCode + " - " + d.getName());_x000D_ if (endOfDec != null) {_x000D_ newRow.add(dbFormat.format(endOfDec));_x000D_ } else {_x000D_ newRow.add("");_x000D_ }_x000D_ newRow.add(animalType);_x000D_ newRow.add(vwaSpecies);_x000D_ newRow.add(sourceType);_x000D_ newRow.add("");_x000D_ newRow.add(goal);_x000D_ newRow.add(concern);_x000D_ newRow.add(lawDef);_x000D_ newRow.add(toxRes);_x000D_ newRow.add(specialTechn);_x000D_ newRow.add(anaesthesia);_x000D_ newRow.add(painManagement);_x000D_ newRow.add(actualDiscomfort);_x000D_ newRow.add(actualAnimalEndStatus);_x000D_ newRow.add(decNr + expCode);_x000D_ newRow.add(latinSpecies);_x000D_ _x000D_ if (matrix.contains(newRow)) {_x000D_ // If the above values are exactly the same as an earlier row, aggregate them_x000D_ int rowIndex = matrix.indexOf(newRow);_x000D_ int tmpNr = nrOfAnimalList.get(rowIndex);_x000D_ nrOfAnimalList.set(rowIndex, tmpNr + 1);_x000D_ } else {_x000D_ // Else, make a new row_x000D_ matrix.add(newRow);_x000D_ nrOfAnimalList.add(1);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>";_x000D_ output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>";_x000D_ output += "<tr>";_x000D_ output += "<th></th>";_x000D_ output += "<th></th>";_x000D_ for (int col = 1; col < 15; col++) {_x000D_ output += ("<th>" + col + "</th>");_x000D_ }_x000D_ output += "<th></th>";_x000D_ output += "</tr>";_x000D_ output += "<tr>";_x000D_ output += "<td style='padding:5px'>DEC-nr.</td>";_x000D_ output += "<td style='padding:5px'>DEC verlopen op</td>";_x000D_ output += "<td style='padding:5px'>Bijzonderheid dier</td>";_x000D_ output += "<td style='padding:5px'>Diersoort</td>";_x000D_ output += "<td style='padding:5px'>Herkomst en hergebruik</td>";_x000D_ output += "<td style='padding:5px'>Aantal dieren</td>";_x000D_ output += "<td style='padding:5px'>Doel vd proef</td>";_x000D_ output += "<td style='padding:5px'>Belang van de proef</td>";_x000D_ output += "<td style='padding:5px'>Wettelijke bepalingen</td>";_x000D_ output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>";_x000D_ output += "<td style='padding:5px'>Bijzondere technieken</td>";_x000D_ output += "<td style='padding:5px'>Anesthesie</td>";_x000D_ output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>";_x000D_ output += "<td style='padding:5px'>Ongerief</td>";_x000D_ output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>";_x000D_ output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>";_x000D_ output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>";_x000D_ output += "</tr>";_x000D_ int counter = 0;_x000D_ for (ArrayList<String> currentRow : matrix) {_x000D_ output += "<tr>";_x000D_ for (int col = 0; col < nrCol; col++) {_x000D_ if (col == 5) {_x000D_ output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>");_x000D_ } else {_x000D_ output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>");_x000D_ }_x000D_ }_x000D_ output += "</tr>";_x000D_ counter++;_x000D_ }_x000D_ output += "</table></div>";_x000D_ _x000D_ // Warnings_x000D_ if (warningsList.size() > 0) {_x000D_ output += "<p><strong>Warnings</strong><br />";_x000D_ for (String warning : warningsList) {_x000D_ output += (warning + "<br />");_x000D_ }_x000D_ output += "</p>";_x000D_ }_x000D_ _x000D_ return output;_x000D_ }_x000D_ }_x000D_
True
891
42237_0
package P2; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ReizigerDAOPsql implements ReizigerDAO { private Connection conn = Main.getConnection(); public ReizigerDAOPsql(Connection conn) throws SQLException { this.conn = conn; } @Override public boolean save(Reiziger reiziger) { // Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...? try { PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)"); preparedStatement.setInt(1, reiziger.getId()); preparedStatement.setString(2, reiziger.getVoorletters()); preparedStatement.setString(3, reiziger.getTussenvoegsel()); preparedStatement.setString(4, reiziger.getAchternaam()); preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Opslaan geen succes."); return false; } } @Override public boolean update(Reiziger reiziger) { try { PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?"); preparedStatement.setString(1, reiziger.getVoorletters()); preparedStatement.setString(2, reiziger.getTussenvoegsel()); preparedStatement.setString(3, reiziger.getAchternaam()); preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum()); preparedStatement.setInt(5, reiziger.getId()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Update kon niet voltooid worden door een onbekende reden"); return false; } } @Override public boolean delete(Reiziger reiziger) { try { PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?"); preparedStatement.setInt(1, reiziger.getId()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Delete is fout gegaan door een onbekende reden"); return false; } } @Override public Reiziger findById(int id) { try { PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?"); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); String voorletters = null; String tussenvoegsel = null; String achternaam = null; Date geboortedatum = null; Reiziger reiziger; while (resultSet.next()) { voorletters = resultSet.getString("voorletters"); tussenvoegsel = resultSet.getString("tussenvoegsel"); achternaam = resultSet.getString("achternaam"); geboortedatum = resultSet.getDate("geboortedatum"); } reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum); return reiziger; } catch (SQLException sqlException) { System.out.println("Geen reiziger gevonden met id: " + id); return null; } } @Override public List<Reiziger> findByGbDatum(String datum) { try { List<Reiziger> opDatum = new ArrayList<>(); PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?"); preparedStatement.setDate(1, Date.valueOf(datum)); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString("reiziger_id"); int reizigerId = Integer.parseInt(id); String voorletters = resultSet.getString("voorletters"); String tussenvoegsel = resultSet.getString("tussenvoegsel"); String achternaam = resultSet.getString("achternaam"); Date geboortedatum = resultSet.getDate("geboortedatum"); Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum); opDatum.add(reiziger); } return opDatum; } catch (SQLException sqlException) { System.out.println("Datum is niet gevonden of onjuist, controleer de input."); return null; } } @Override public List<Reiziger> findAll() { try { List<Reiziger> alleReizigers = new ArrayList<>(); PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString("reiziger_id"); int reizigerId = Integer.parseInt(id); String voorletters = resultSet.getString("voorletters"); String tussenvoegsel = resultSet.getString("tussenvoegsel"); String achternaam = resultSet.getString("achternaam"); Date geboortedatum = resultSet.getDate("geboortedatum"); Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum); alleReizigers.add(reiziger); } return alleReizigers; } catch (SQLException sqlException) { System.out.println("Er is een onbekende fout opgetreden in findAll()"); return null; } } }
JustMilan/DP
src/main/java/P2/ReizigerDAOPsql.java
1,642
// Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...?
line_comment
nl
package P2; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ReizigerDAOPsql implements ReizigerDAO { private Connection conn = Main.getConnection(); public ReizigerDAOPsql(Connection conn) throws SQLException { this.conn = conn; } @Override public boolean save(Reiziger reiziger) { // Waarom return<SUF> try { PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)"); preparedStatement.setInt(1, reiziger.getId()); preparedStatement.setString(2, reiziger.getVoorletters()); preparedStatement.setString(3, reiziger.getTussenvoegsel()); preparedStatement.setString(4, reiziger.getAchternaam()); preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Opslaan geen succes."); return false; } } @Override public boolean update(Reiziger reiziger) { try { PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?"); preparedStatement.setString(1, reiziger.getVoorletters()); preparedStatement.setString(2, reiziger.getTussenvoegsel()); preparedStatement.setString(3, reiziger.getAchternaam()); preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum()); preparedStatement.setInt(5, reiziger.getId()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Update kon niet voltooid worden door een onbekende reden"); return false; } } @Override public boolean delete(Reiziger reiziger) { try { PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?"); preparedStatement.setInt(1, reiziger.getId()); return preparedStatement.execute(); } catch (SQLException sqlException) { System.out.println("Delete is fout gegaan door een onbekende reden"); return false; } } @Override public Reiziger findById(int id) { try { PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?"); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); String voorletters = null; String tussenvoegsel = null; String achternaam = null; Date geboortedatum = null; Reiziger reiziger; while (resultSet.next()) { voorletters = resultSet.getString("voorletters"); tussenvoegsel = resultSet.getString("tussenvoegsel"); achternaam = resultSet.getString("achternaam"); geboortedatum = resultSet.getDate("geboortedatum"); } reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum); return reiziger; } catch (SQLException sqlException) { System.out.println("Geen reiziger gevonden met id: " + id); return null; } } @Override public List<Reiziger> findByGbDatum(String datum) { try { List<Reiziger> opDatum = new ArrayList<>(); PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?"); preparedStatement.setDate(1, Date.valueOf(datum)); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString("reiziger_id"); int reizigerId = Integer.parseInt(id); String voorletters = resultSet.getString("voorletters"); String tussenvoegsel = resultSet.getString("tussenvoegsel"); String achternaam = resultSet.getString("achternaam"); Date geboortedatum = resultSet.getDate("geboortedatum"); Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum); opDatum.add(reiziger); } return opDatum; } catch (SQLException sqlException) { System.out.println("Datum is niet gevonden of onjuist, controleer de input."); return null; } } @Override public List<Reiziger> findAll() { try { List<Reiziger> alleReizigers = new ArrayList<>(); PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString("reiziger_id"); int reizigerId = Integer.parseInt(id); String voorletters = resultSet.getString("voorletters"); String tussenvoegsel = resultSet.getString("tussenvoegsel"); String achternaam = resultSet.getString("achternaam"); Date geboortedatum = resultSet.getDate("geboortedatum"); Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum); alleReizigers.add(reiziger); } return alleReizigers; } catch (SQLException sqlException) { System.out.println("Er is een onbekende fout opgetreden in findAll()"); return null; } } }
False
1,721
202684_3
import java.util.Scanner; public class Main { public static void main(String[] args) { // Here you can try out the combined functionality of your classes TodoList list = new TodoList(); Scanner scanner = new Scanner(System.in); UserInterface ui = new UserInterface(list, scanner); ui.start(); // list.add("iets doen"); // list.add("nog iets doen"); // list.add("andermaal iets doen"); // list.add("een vierde taak"); // list.print(); // list.remove(3); // System.out.println(""); // list.print(); } }
Thibault-be/MOOC-Helsinki-Java-2
part08-Part08_05.TodoList/src/main/java/Main.java
174
// list.add("een vierde taak");
line_comment
nl
import java.util.Scanner; public class Main { public static void main(String[] args) { // Here you can try out the combined functionality of your classes TodoList list = new TodoList(); Scanner scanner = new Scanner(System.in); UserInterface ui = new UserInterface(list, scanner); ui.start(); // list.add("iets doen"); // list.add("nog iets doen"); // list.add("andermaal iets doen"); // list.add("een vierde<SUF> // list.print(); // list.remove(3); // System.out.println(""); // list.print(); } }
False
1,554
47470_4
// License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api; import java.util.Objects; import javax.json.Json; import javax.json.JsonObjectBuilder; import org.geotools.referencing.CRS; import org.geotools.referencing.operation.transform.IdentityTransform; import org.geotools.api.referencing.FactoryException; import org.geotools.api.referencing.crs.CoordinateReferenceSystem; import org.geotools.api.referencing.operation.MathTransform; import org.geotools.api.referencing.operation.TransformException; import org.openstreetmap.josm.data.coor.LatLon; import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG; import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties; /** * Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not * changed. */ public final class JsonNewReportEncoder { private static MathTransform transform; private JsonNewReportEncoder() { // Private constructor to avoid instantiation } public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) { LatLon reportLatLon = reportLatLon(report.getLatLon()); JsonObjectBuilder result = Json.createObjectBuilder(); Objects.requireNonNull(report); result.add("type", "FeatureCollection"); result.add("name", "TerugmeldingGeneriek"); result .add("crs", Json.createObjectBuilder() .add("type", "name") .add("properties", Json.createObjectBuilder() .add("name", "urn:ogc:def:crs:EPSG::28992"))); result.add( "features", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "Feature") .addAll(getReport(report)) .add("geometry", Json.createObjectBuilder() .add("type", "Point") .add("coordinates", Json.createArrayBuilder() .add(reportLatLon.getX()) .add(reportLatLon.getY()) ) ) ) ); return result; } private static JsonObjectBuilder getReport(ReportNewBAG report) { JsonObjectBuilder result = Json.createObjectBuilder(); JsonObjectBuilder properties = Json.createObjectBuilder(); properties.add("registratie", report.getBaseRegistration()); // Verplicht. Keuze uit BGT,BAG,BRT of KLIC // properties.add("product", ...); // Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of // TOP1000, anders veld weglaten. properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString()); // Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt. properties.add("omschrijving", report.getDescription()); // Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt // openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters. // properties.add("objectId", ""); // Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit // moment alleen bruikbaar bij registraties BAG en KLIC. // properties.add("objectType", ""); // Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment // alleen bruikbaar bij registraties BAG en KLIC. // properties.add("klicmeldnummer", ) // Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC, // anders veld weglaten. // properties.add("EigenVeld2", ""); // Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean // zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC. if (ReportProperties.USER_EMAIL.isSet()) { properties.add("email", ReportProperties.USER_EMAIL.get()); // Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen. // NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd." } if (!ReportProperties.USER_ORGANISATION.get().isEmpty()) { properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get()); // Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra // informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit // moment alleen bruikbaar bij registraties BAG en KLIC. // Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean // zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen. } // final JsonArrayBuilder bagChanges = Json.createArrayBuilder(); // for (File file : report.getFile) { // bagChanges.add(encodeBAGChanges(img)); // } result.add("properties", properties); return result; } /** * Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992. * * @param osmLatLon * the {@link LatLon} containing coordinate in EPSG:4326 * @return the encoded {@link LatLon} coordinate in EPSG:28992. */ public static LatLon reportLatLon(LatLon osmLatLon) { final double[] result = {osmLatLon.getX(), osmLatLon.getY()}; if (transform == null) { transform = IdentityTransform.create(2); try { CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326"); CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true); transform = CRS.findMathTransform(osmCrs, crsReport); } catch (FactoryException e) { throw new UnsupportedOperationException(e); } } try { transform.transform(result, 0, result, 0, 1); } catch (TransformException e) { throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e); } return new LatLon(result[1], result[0]); // swap coordinated??? } }
SanderH/josm-nl-report
src/main/java/org/openstreetmap/josm/plugins/nl_pdok_report/utils/api/JsonNewReportEncoder.java
1,967
// Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of
line_comment
nl
// License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api; import java.util.Objects; import javax.json.Json; import javax.json.JsonObjectBuilder; import org.geotools.referencing.CRS; import org.geotools.referencing.operation.transform.IdentityTransform; import org.geotools.api.referencing.FactoryException; import org.geotools.api.referencing.crs.CoordinateReferenceSystem; import org.geotools.api.referencing.operation.MathTransform; import org.geotools.api.referencing.operation.TransformException; import org.openstreetmap.josm.data.coor.LatLon; import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG; import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties; /** * Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not * changed. */ public final class JsonNewReportEncoder { private static MathTransform transform; private JsonNewReportEncoder() { // Private constructor to avoid instantiation } public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) { LatLon reportLatLon = reportLatLon(report.getLatLon()); JsonObjectBuilder result = Json.createObjectBuilder(); Objects.requireNonNull(report); result.add("type", "FeatureCollection"); result.add("name", "TerugmeldingGeneriek"); result .add("crs", Json.createObjectBuilder() .add("type", "name") .add("properties", Json.createObjectBuilder() .add("name", "urn:ogc:def:crs:EPSG::28992"))); result.add( "features", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "Feature") .addAll(getReport(report)) .add("geometry", Json.createObjectBuilder() .add("type", "Point") .add("coordinates", Json.createArrayBuilder() .add(reportLatLon.getX()) .add(reportLatLon.getY()) ) ) ) ); return result; } private static JsonObjectBuilder getReport(ReportNewBAG report) { JsonObjectBuilder result = Json.createObjectBuilder(); JsonObjectBuilder properties = Json.createObjectBuilder(); properties.add("registratie", report.getBaseRegistration()); // Verplicht. Keuze uit BGT,BAG,BRT of KLIC // properties.add("product", ...); // Optioneel. Let<SUF> // TOP1000, anders veld weglaten. properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString()); // Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt. properties.add("omschrijving", report.getDescription()); // Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt // openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters. // properties.add("objectId", ""); // Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit // moment alleen bruikbaar bij registraties BAG en KLIC. // properties.add("objectType", ""); // Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment // alleen bruikbaar bij registraties BAG en KLIC. // properties.add("klicmeldnummer", ) // Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC, // anders veld weglaten. // properties.add("EigenVeld2", ""); // Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean // zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC. if (ReportProperties.USER_EMAIL.isSet()) { properties.add("email", ReportProperties.USER_EMAIL.get()); // Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen. // NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd." } if (!ReportProperties.USER_ORGANISATION.get().isEmpty()) { properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get()); // Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra // informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit // moment alleen bruikbaar bij registraties BAG en KLIC. // Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean // zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen. } // final JsonArrayBuilder bagChanges = Json.createArrayBuilder(); // for (File file : report.getFile) { // bagChanges.add(encodeBAGChanges(img)); // } result.add("properties", properties); return result; } /** * Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992. * * @param osmLatLon * the {@link LatLon} containing coordinate in EPSG:4326 * @return the encoded {@link LatLon} coordinate in EPSG:28992. */ public static LatLon reportLatLon(LatLon osmLatLon) { final double[] result = {osmLatLon.getX(), osmLatLon.getY()}; if (transform == null) { transform = IdentityTransform.create(2); try { CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326"); CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true); transform = CRS.findMathTransform(osmCrs, crsReport); } catch (FactoryException e) { throw new UnsupportedOperationException(e); } } try { transform.transform(result, 0, result, 0, 1); } catch (TransformException e) { throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e); } return new LatLon(result[1], result[0]); // swap coordinated??? } }
False
3,239
99431_5
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.protocol.irc; /** * IRC color codes that can be specified in the color control code. * * @author Danny van Heumen */ public enum Color { /** * White. */ WHITE("White"), /** * Black. */ BLACK("Black"), /** * Navy. */ BLUE("Navy"), /** * Green. */ GREEN("Green"), /** * Red. */ RED("Red"), /** * Maroon. */ BROWN("Maroon"), /** * Purple. */ PURPLE("Purple"), /** * Orange. */ ORANGE("Orange"), /** * Yellow. */ YELLOW("Yellow"), /** * Lime. */ LIGHT_GREEN("Lime"), /** * Teal. */ TEAL("Teal"), /** * Cyan. */ LIGHT_CYAN("Cyan"), /** * RoyalBlue. */ LIGHT_BLUE("RoyalBlue"), /** * Fuchsia. */ PINK("Fuchsia"), /** * Grey. */ GREY("Grey"), /** * Silver. */ LIGHT_GREY("Silver"); /** * Instance containing the html representation of this color. */ private String html; /** * Constructor for enum entries. * * @param html HTML representation for color */ private Color(final String html) { this.html = html; } /** * Get the HTML representation of this color. * * @return returns html representation or null if none exist */ public String getHtml() { return this.html; } }
jitsi/jitsi
modules/impl/protocol-irc/src/main/java/net/java/sip/communicator/impl/protocol/irc/Color.java
690
/** * Green. */
block_comment
nl
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.protocol.irc; /** * IRC color codes that can be specified in the color control code. * * @author Danny van Heumen */ public enum Color { /** * White. */ WHITE("White"), /** * Black. */ BLACK("Black"), /** * Navy. */ BLUE("Navy"), /** * Green. <SUF>*/ GREEN("Green"), /** * Red. */ RED("Red"), /** * Maroon. */ BROWN("Maroon"), /** * Purple. */ PURPLE("Purple"), /** * Orange. */ ORANGE("Orange"), /** * Yellow. */ YELLOW("Yellow"), /** * Lime. */ LIGHT_GREEN("Lime"), /** * Teal. */ TEAL("Teal"), /** * Cyan. */ LIGHT_CYAN("Cyan"), /** * RoyalBlue. */ LIGHT_BLUE("RoyalBlue"), /** * Fuchsia. */ PINK("Fuchsia"), /** * Grey. */ GREY("Grey"), /** * Silver. */ LIGHT_GREY("Silver"); /** * Instance containing the html representation of this color. */ private String html; /** * Constructor for enum entries. * * @param html HTML representation for color */ private Color(final String html) { this.html = html; } /** * Get the HTML representation of this color. * * @return returns html representation or null if none exist */ public String getHtml() { return this.html; } }
False
3,819
27626_0
package semisplay; public interface SearchTree<E extends Comparable<E>> extends Iterable<E> { /** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit. * @return true als de sleutel effectief toegevoegd werd. */ boolean add(E e); /** Zoek de gegeven sleutel op in de boom. * @return true als de sleutel gevonden werd. */ boolean contains(E e); /** Verwijder de gegeven sleutel uit de boom. * @return true als de sleutel gevonden en verwijderd werd. */ boolean remove(E e); /** @return het aantal sleutels in de boom. */ int size(); /** @return de diepte van de boom. */ int depth(); }
nielsdos/Semisplay-tree
src/semisplay/SearchTree.java
203
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit. * @return true als de sleutel effectief toegevoegd werd. */
block_comment
nl
package semisplay; public interface SearchTree<E extends Comparable<E>> extends Iterable<E> { /** Voeg de gegeven<SUF>*/ boolean add(E e); /** Zoek de gegeven sleutel op in de boom. * @return true als de sleutel gevonden werd. */ boolean contains(E e); /** Verwijder de gegeven sleutel uit de boom. * @return true als de sleutel gevonden en verwijderd werd. */ boolean remove(E e); /** @return het aantal sleutels in de boom. */ int size(); /** @return de diepte van de boom. */ int depth(); }
True
646
172943_2
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList(); } /** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuilder buffer = new StringBuilder(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
HDauven/S32JSF3
JSF31_w04_KochFractalFX-startup/JSF31KochFractalFX - startup/src/timeutil/TimeStamp.java
1,267
/** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */
block_comment
nl
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList(); } /** * zet begintijdstip. gebruik<SUF>*/ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuilder buffer = new StringBuilder(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
True
517
106041_3
/** * Project Zelula * * Contextproject TI2800 * TU Delft - University of Technology * * Authors: * Felix Akkermans, Niels Doekemeijer, Thomas van Helden * Albert ten Napel, Jan Pieter Waagmeester * * https://github.com/FelixAkk/synthbio */ package synthbio.models; import org.json.JSONException; import org.json.JSONObject; /** * Point representation * @author jieter */ public class Position{ private double x; private double y; public Position(double x, double y){ this.x=x; this.y=y; } /** * Create a undefined position defaulting to 0,0 */ public Position(){ this(0, 0); } /** * getters */ public double getX(){ return this.x; } public double getY(){ return this.y; } /** * Calculate the distance between two positions * * @param that Position to calculate distance to. * @return The distance between this and that. */ public double distanceTo(Position that){ return Math.sqrt( Math.pow(this.getX()-that.getX(), 2) + Math.pow(this.getY()-that.getY(), 2) ); } public boolean equals(Object other){ if(!(other instanceof Position)){ return false; } Position that=(Position)other; return this.getX()==that.getX() && this.getY()==that.getY(); } /** * Return a simple String representation */ public String toString(){ return "("+this.getX()+","+this.getY()+")"; } /** * Deserialize JSON to a Position */ public static Position fromJSON(String json) throws JSONException{ return Position.fromJSON(new JSONObject(json)); } public static Position fromJSON(JSONObject json) throws JSONException{ return new Position(json.getDouble("x"), json.getDouble("y")); } }
FelixAkk/synthbio
program/WEB-INF/src/synthbio/models/Position.java
583
/** * getters */
block_comment
nl
/** * Project Zelula * * Contextproject TI2800 * TU Delft - University of Technology * * Authors: * Felix Akkermans, Niels Doekemeijer, Thomas van Helden * Albert ten Napel, Jan Pieter Waagmeester * * https://github.com/FelixAkk/synthbio */ package synthbio.models; import org.json.JSONException; import org.json.JSONObject; /** * Point representation * @author jieter */ public class Position{ private double x; private double y; public Position(double x, double y){ this.x=x; this.y=y; } /** * Create a undefined position defaulting to 0,0 */ public Position(){ this(0, 0); } /** * getters <SUF>*/ public double getX(){ return this.x; } public double getY(){ return this.y; } /** * Calculate the distance between two positions * * @param that Position to calculate distance to. * @return The distance between this and that. */ public double distanceTo(Position that){ return Math.sqrt( Math.pow(this.getX()-that.getX(), 2) + Math.pow(this.getY()-that.getY(), 2) ); } public boolean equals(Object other){ if(!(other instanceof Position)){ return false; } Position that=(Position)other; return this.getX()==that.getX() && this.getY()==that.getY(); } /** * Return a simple String representation */ public String toString(){ return "("+this.getX()+","+this.getY()+")"; } /** * Deserialize JSON to a Position */ public static Position fromJSON(String json) throws JSONException{ return Position.fromJSON(new JSONObject(json)); } public static Position fromJSON(JSONObject json) throws JSONException{ return new Position(json.getDouble("x"), json.getDouble("y")); } }
False
3,798
167369_5
/** * NetXMS - open source network management system * Copyright (C) 2003-2022 Victor Kirhenshtein * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.netxms.client.constants; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * OSPF neighbor state */ public enum OSPFNeighborState { UNKNOWN(0, ""), DOWN(1, "DOWN"), ATTEMPT(2, "ATTEMPT"), INIT(3, "INIT"), TWO_WAY(4, "TWO-WAY"), EXCHANGE_START(5, "EXCHANGE START"), EXCHANGE(6, "EXCHANGE"), LOADING(7, "LOADING"), FULL(8, "FULL"); private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class); private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>(); static { for(OSPFNeighborState element : OSPFNeighborState.values()) { lookupTable.put(element.value, element); } } private int value; private String text; /** * Internal constructor * * @param value integer value * @param text text value */ private OSPFNeighborState(int value, String text) { this.value = value; this.text = text; } /** * Get integer value * * @return integer value */ public int getValue() { return value; } /** * Get text value * * @return text value */ public String getText() { return text; } /** * Get enum element by integer value * * @param value integer value * @return enum element corresponding to given integer value or fall-back element for invalid value */ public static OSPFNeighborState getByValue(int value) { final OSPFNeighborState element = lookupTable.get(value); if (element == null) { logger.warn("Unknown element " + value); return UNKNOWN; // fall-back } return element; } }
netxms/netxms
src/client/java/netxms-client/src/main/java/org/netxms/client/constants/OSPFNeighborState.java
814
/** * Get enum element by integer value * * @param value integer value * @return enum element corresponding to given integer value or fall-back element for invalid value */
block_comment
nl
/** * NetXMS - open source network management system * Copyright (C) 2003-2022 Victor Kirhenshtein * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.netxms.client.constants; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * OSPF neighbor state */ public enum OSPFNeighborState { UNKNOWN(0, ""), DOWN(1, "DOWN"), ATTEMPT(2, "ATTEMPT"), INIT(3, "INIT"), TWO_WAY(4, "TWO-WAY"), EXCHANGE_START(5, "EXCHANGE START"), EXCHANGE(6, "EXCHANGE"), LOADING(7, "LOADING"), FULL(8, "FULL"); private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class); private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>(); static { for(OSPFNeighborState element : OSPFNeighborState.values()) { lookupTable.put(element.value, element); } } private int value; private String text; /** * Internal constructor * * @param value integer value * @param text text value */ private OSPFNeighborState(int value, String text) { this.value = value; this.text = text; } /** * Get integer value * * @return integer value */ public int getValue() { return value; } /** * Get text value * * @return text value */ public String getText() { return text; } /** * Get enum element<SUF>*/ public static OSPFNeighborState getByValue(int value) { final OSPFNeighborState element = lookupTable.get(value); if (element == null) { logger.warn("Unknown element " + value); return UNKNOWN; // fall-back } return element; } }
False
994
14145_0
public class Werknemer { public String voornaam; public String achternaam; public int werknemerNummer; protected float salaris; public static int aantalWerknemers; public void salarisVerhogen(int percentage) { float verhogingsfactor = (float)percentage/100; salaris += salaris*verhogingsfactor; } public float getSalaris() { return salaris; } public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) { this.voornaam = voornaam; //this.var => altijd dataleden this.achternaam = achternaam; werknemerNummer = wNummer; this.salaris = salaris; aantalWerknemers++; } }
LukaVerhoeven/Digital-Broadcast
Werknemer.java
220
//this.var => altijd dataleden
line_comment
nl
public class Werknemer { public String voornaam; public String achternaam; public int werknemerNummer; protected float salaris; public static int aantalWerknemers; public void salarisVerhogen(int percentage) { float verhogingsfactor = (float)percentage/100; salaris += salaris*verhogingsfactor; } public float getSalaris() { return salaris; } public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) { this.voornaam = voornaam; //this.var =><SUF> this.achternaam = achternaam; werknemerNummer = wNummer; this.salaris = salaris; aantalWerknemers++; } }
False
2,480
35814_3
import java.io.File; import java.lang.reflect.Array; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class MP1 { Random generator; String userName; String inputFileName; String delimiters = " \t,;.?!-:@[](){}_*/"; String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"}; void initialRandomGenerator(String seed) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(seed.toLowerCase().trim().getBytes()); byte[] seedMD5 = messageDigest.digest(); long longSeed = 0; for (int i = 0; i < seedMD5.length; i++) { longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i); } this.generator = new Random(longSeed); } Integer[] getIndexes() throws NoSuchAlgorithmException { Integer n = 10000; Integer number_of_lines = 50000; Integer[] ret = new Integer[n]; this.initialRandomGenerator(this.userName); for (int i = 0; i < n; i++) { ret[i] = generator.nextInt(number_of_lines); } return ret; } public MP1(String userName, String inputFileName) { this.userName = userName; this.inputFileName = inputFileName; } public String[] process() throws Exception { String[] ret = new String[20]; //TODO // read input file String line; try ( InputStream fis = new FileInputStream(this.inputFileName); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); ) { int i=0; /* begin Code B */ String regel=""; //debug regel="A._B._een_twee(drie)vier_(vijf)"; //debug /* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')' // resultaat zit nu in een Array van strings //print het aantal elementen in de array //debug System.out.println(result.length); //debug for (int x=0; x<result.length; x++) System.out.println(result[x]); /*eind code B */ // zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf /* begin code A*/ while ((line = br.readLine()) != null) { // Deal with the line // nog "nod code A verwerken voor de variable line" // dit nog vervangen if (i<20) { ret[i] = line; } i++; // dit nog vervangen } /* einde code A*/ } return ret; } public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("MP1 <User ID>"); } else { String userName = args[0]; String inputFileName = "./input.txt"; MP1 mp = new MP1(userName, inputFileName); String[] topItems = mp.process(); for (String item: topItems){ System.out.println(item); } } } }
cx1964/cx1964BladMuziek
Klassiek/Chopin_Frédéric/MP1.v002.java
1,466
// resultaat zit nu in een Array van strings
line_comment
nl
import java.io.File; import java.lang.reflect.Array; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class MP1 { Random generator; String userName; String inputFileName; String delimiters = " \t,;.?!-:@[](){}_*/"; String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"}; void initialRandomGenerator(String seed) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(seed.toLowerCase().trim().getBytes()); byte[] seedMD5 = messageDigest.digest(); long longSeed = 0; for (int i = 0; i < seedMD5.length; i++) { longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i); } this.generator = new Random(longSeed); } Integer[] getIndexes() throws NoSuchAlgorithmException { Integer n = 10000; Integer number_of_lines = 50000; Integer[] ret = new Integer[n]; this.initialRandomGenerator(this.userName); for (int i = 0; i < n; i++) { ret[i] = generator.nextInt(number_of_lines); } return ret; } public MP1(String userName, String inputFileName) { this.userName = userName; this.inputFileName = inputFileName; } public String[] process() throws Exception { String[] ret = new String[20]; //TODO // read input file String line; try ( InputStream fis = new FileInputStream(this.inputFileName); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); ) { int i=0; /* begin Code B */ String regel=""; //debug regel="A._B._een_twee(drie)vier_(vijf)"; //debug /* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')' // resultaat zit<SUF> //print het aantal elementen in de array //debug System.out.println(result.length); //debug for (int x=0; x<result.length; x++) System.out.println(result[x]); /*eind code B */ // zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf /* begin code A*/ while ((line = br.readLine()) != null) { // Deal with the line // nog "nod code A verwerken voor de variable line" // dit nog vervangen if (i<20) { ret[i] = line; } i++; // dit nog vervangen } /* einde code A*/ } return ret; } public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("MP1 <User ID>"); } else { String userName = args[0]; String inputFileName = "./input.txt"; MP1 mp = new MP1(userName, inputFileName); String[] topItems = mp.process(); for (String item: topItems){ System.out.println(item); } } } }
True
3,343
154850_15
/*_x000D_ * This code is subject to the HIEOS License, Version 1.0_x000D_ *_x000D_ * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved._x000D_ *_x000D_ * Unless required by applicable law or agreed to in writing, software_x000D_ * distributed under the License is distributed on an "AS IS" BASIS,_x000D_ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied._x000D_ *_x000D_ * See the License for the specific language governing permissions and_x000D_ * limitations under the License._x000D_ */_x000D_ _x000D_ /*_x000D_ * XConfig.java_x000D_ *_x000D_ * Created on January 14, 2009_x000D_ *_x000D_ */_x000D_ package com.vangent.hieos.xutil.xconfig;_x000D_ _x000D_ import com.vangent.hieos.xutil.exception.XMLParserException;_x000D_ import com.vangent.hieos.xutil.xml.XMLParser;_x000D_ import com.vangent.hieos.xutil.exception.XConfigException;_x000D_ import com.vangent.hieos.xutil.iosupport.Io;_x000D_ _x000D_ // Third-party._x000D_ import java.util.ArrayList;_x000D_ import java.util.Iterator;_x000D_ import java.util.HashMap;_x000D_ import org.apache.axiom.om.OMElement;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.util.List;_x000D_ import org.apache.log4j.Logger;_x000D_ _x000D_ /**_x000D_ * Maintains system configuration parameters for IHE XDS.b and XCA profiles. Acts as a Singleton._x000D_ *_x000D_ * @author Bernie Thuman_x000D_ *_x000D_ */_x000D_ public class XConfig {_x000D_ _x000D_ public enum ConfigItem {_x000D_ _x000D_ CONFIG_DIR, XCONFIG_FILE, SCHEMA_DIR, CODES_FILE, XDSBRIDGE_DIR, POLICY_DIR, EMPI_DIR_x000D_ };_x000D_ // HIEOS environment variables (would like to rename but remaining backward compatible)._x000D_ public final static String ENV_HIEOS_CONFIG_DIR = "HIEOSxConfigDir";_x000D_ public final static String ENV_HIEOS_XCONFIG_FILE = "HIEOSxConfigFile";_x000D_ public final static String ENV_HIEOS_SCHEMA_DIR = "HIEOSxSchemaDir";_x000D_ public final static String ENV_HIEOS_XDSBRIDGE_DIR = "HIEOSxXDSBridgeDir";_x000D_ public final static String ENV_HIEOS_POLICY_DIR = "HIEOSxPolicyDir";_x000D_ public final static String ENV_HIEOS_EMPI_DIR = "HIEOSxEMPIDir";_x000D_ public final static String ENV_HIEOS_CODES_FILE = "HIEOSxCodesFile";_x000D_ // HIEOS system properties (would like to rename but remaining backward compatible)._x000D_ public final static String SYSPROP_HIEOS_CONFIG_DIR = "com.vangent.hieos.configdir";_x000D_ public final static String SYSPROP_HIEOS_XCONFIG_FILE = "com.vangent.hieos.xconfig";_x000D_ public final static String SYSPROP_HIEOS_SCHEMA_DIR = "com.vangent.hieos.schemadir";_x000D_ public final static String SYSPROP_HIEOS_XDSBRIDGE_DIR = "com.vangent.hieos.xdsbridgedir";_x000D_ public final static String SYSPROP_HIEOS_POLICY_DIR = "com.vangent.hieos.policydir";_x000D_ public final static String SYSPROP_HIEOS_EMPI_DIR = "com.vangent.hieos.empidir";_x000D_ public final static String SYSPROP_HIEOS_CODES_FILE = "com.vangent.hieos.codesfile";_x000D_ private final static Logger logger = Logger.getLogger(XConfig.class);_x000D_ static private XConfig _instance = null; // Singleton instance._x000D_ static private String _configLocation = null; // Location of xconfig.xml file_x000D_ // Internal data structure starts here._x000D_ private List<XConfigObject> objects = new ArrayList<XConfigObject>();_x000D_ private HashMap<String, XConfigObject> objectByNameMap = new HashMap<String, XConfigObject>();_x000D_ private HashMap<String, XConfigObject> objectByIdMap = new HashMap<String, XConfigObject>();_x000D_ private List<XConfigObject> assigningAuthorities = new ArrayList<XConfigObject>();_x000D_ // Kept as strings versus enum to allow extension without XConfig code modification._x000D_ static final public String HOME_COMMUNITY_TYPE = "HomeCommunityType";_x000D_ static final public String XDSB_DOCUMENT_REGISTRY_TYPE = "DocumentRegistryType";_x000D_ static final public String XDSB_DOCUMENT_REPOSITORY_TYPE = "DocumentRepositoryType";_x000D_ static final public String XCA_INITIATING_GATEWAY_TYPE = "InitiatingGatewayType";_x000D_ static final public String XCA_RESPONDING_GATEWAY_TYPE = "RespondingGatewayType";_x000D_ static final public String XUA_PROPERTIES_TYPE = "XUAPropertiesType";_x000D_ static final public String ASSIGNING_AUTHORITY_TYPE = "AssigningAuthorityType";_x000D_ static final public String PDS_TYPE = "PDSType"; // Patient Demographics Service_x000D_ static final public String PolicyDecisionPoint_TYPE = "PolicyDecisionPointType";_x000D_ static final public String PolicyInformationPoint_TYPE = "PolicyInformationPointType";_x000D_ static final public String STS_TYPE = "SecureTokenServiceType";_x000D_ static final public String XDSBRIDGE_TYPE = "XDSBridgeType";_x000D_ static final public String PIX_MANAGER_TYPE = "PIXManagerType";_x000D_ static final public String XDR_DOCUMENT_RECIPIENT_TYPE = "DocumentRecipientType";_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param configItem_x000D_ * @return_x000D_ */_x000D_ static public String getConfigLocation(ConfigItem configItem) {_x000D_ String configLocation = null;_x000D_ switch (configItem) {_x000D_ case CONFIG_DIR:_x000D_ configLocation = getConfigDir();_x000D_ break;_x000D_ case XCONFIG_FILE:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XCONFIG_FILE, XConfig.ENV_HIEOS_XCONFIG_FILE);_x000D_ break;_x000D_ case SCHEMA_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_SCHEMA_DIR, XConfig.ENV_HIEOS_SCHEMA_DIR);_x000D_ break;_x000D_ case CODES_FILE:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_CODES_FILE, XConfig.ENV_HIEOS_CODES_FILE);_x000D_ break;_x000D_ case XDSBRIDGE_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XDSBRIDGE_DIR, XConfig.ENV_HIEOS_XDSBRIDGE_DIR);_x000D_ break;_x000D_ case POLICY_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_POLICY_DIR, XConfig.ENV_HIEOS_POLICY_DIR);_x000D_ break;_x000D_ case EMPI_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_EMPI_DIR, XConfig.ENV_HIEOS_EMPI_DIR);_x000D_ break;_x000D_ }_x000D_ return configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return_x000D_ */_x000D_ static public String getConfigDir() {_x000D_ // First look at system property._x000D_ String configDir = System.getProperty(XConfig.SYSPROP_HIEOS_CONFIG_DIR);_x000D_ if (configDir == null) {_x000D_ // Look in environment variable next._x000D_ configDir = System.getenv(XConfig.ENV_HIEOS_CONFIG_DIR);_x000D_ }_x000D_ return configDir;_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param sysPropName_x000D_ * @param envName_x000D_ * @return_x000D_ */_x000D_ static private String getConfigLocation(ConfigItem configItem, String sysPropName, String envName) {_x000D_ // First look at system property._x000D_ String configLocation = System.getProperty(sysPropName);_x000D_ if (configLocation == null) {_x000D_ // Look in environment variable next._x000D_ configLocation = System.getenv(envName);_x000D_ }_x000D_ if (configLocation == null) {_x000D_ String configDir = XConfig.getConfigDir();_x000D_ switch (configItem) {_x000D_ case XCONFIG_FILE:_x000D_ configLocation = configDir + "/xconfig.xml";_x000D_ break;_x000D_ case SCHEMA_DIR:_x000D_ configLocation = configDir + "/schema";_x000D_ break;_x000D_ case CODES_FILE:_x000D_ configLocation = configDir + "/codes/codes.xml";_x000D_ break;_x000D_ case XDSBRIDGE_DIR:_x000D_ configLocation = configDir + "/xdsbridge";_x000D_ break;_x000D_ case POLICY_DIR:_x000D_ configLocation = configDir + "/policy";_x000D_ break;_x000D_ case EMPI_DIR:_x000D_ configLocation = configDir + "/empi";_x000D_ break;_x000D_ }_x000D_ }_x000D_ return configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param configLocation_x000D_ */_x000D_ static public synchronized void setConfigLocation(String configLocation) {_x000D_ _configLocation = configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns Singleton instance of XConfig._x000D_ *_x000D_ * @return Singleton instance of XConfig_x000D_ * @throws XConfigException_x000D_ */_x000D_ static public synchronized XConfig getInstance() throws XConfigException {_x000D_ if (_instance == null) {_x000D_ _instance = new XConfig();_x000D_ }_x000D_ return _instance;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Private constructor responsible for loading configuration file into memory._x000D_ */_x000D_ private XConfig() throws XConfigException {_x000D_ loadConfiguration();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns the global configuration for the Home Community._x000D_ *_x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getHomeCommunityConfig() {_x000D_ String key = this.getKey("home", XConfig.HOME_COMMUNITY_TYPE);_x000D_ return this.objectByNameMap.get(key);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RespondingGatewayType) based on a homeCommunityId._x000D_ *_x000D_ * @param homeCommunityId_x000D_ * @return An instance of XConfigActor or null (if not found)._x000D_ */_x000D_ public XConfigActor getRespondingGatewayConfigForHomeCommunityId(String homeCommunityId) {_x000D_ return this.getXConfigActorById(homeCommunityId, XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return an XConfigActor (RespondingGatewayType) given a gateway name._x000D_ *_x000D_ * @param gatewayName Name of responding gateway._x000D_ * @return XConfigActor_x000D_ */_x000D_ protected XConfigActor getRespondingGatewayConfigByName(String gatewayName) {_x000D_ return this.getXConfigActorByName(gatewayName, XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return an XConfigActor (RepositoryType) given a repository id._x000D_ *_x000D_ * @param repositoryId_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRepositoryConfigById(String repositoryId) {_x000D_ return this.getXConfigActorById(repositoryId, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject for a given "name" and "type"._x000D_ *_x000D_ * @param name Name of the object._x000D_ * @param type Type of the object._x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getXConfigObjectByName(String name, String type) {_x000D_ XConfigObject configObject = null;_x000D_ String key = this.getKey(name, type);_x000D_ if (this.objectByNameMap.containsKey(key)) {_x000D_ configObject = this.objectByNameMap.get(key);_x000D_ }_x000D_ return configObject;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject for a given "id" and "type"._x000D_ * _x000D_ * @param id Identifier for the object._x000D_ * @param type Type of the object._x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getXConfigObjectById(String id, String type) {_x000D_ XConfigObject configObject = null;_x000D_ String key = this.getKey(id, type);_x000D_ if (this.objectByIdMap.containsKey(key)) {_x000D_ configObject = this.objectByIdMap.get(key);_x000D_ }_x000D_ return configObject;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns all XConfigObject instances of the specific type._x000D_ *_x000D_ * @param type The type of XConfigObject to locate._x000D_ * @return List<XConfigObject>_x000D_ */_x000D_ public List<XConfigObject> getXConfigObjectsOfType(String type) {_x000D_ List<XConfigObject> configObjects = new ArrayList<XConfigObject>();_x000D_ for (XConfigObject object : objects) {_x000D_ if (object.getType().equalsIgnoreCase(type)) {_x000D_ configObjects.add(object);_x000D_ }_x000D_ }_x000D_ return configObjects;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor for a give "name" and "type"._x000D_ *_x000D_ * @param name Name of the Actor._x000D_ * @param type Type of the Actor._x000D_ * @return XConfigActor._x000D_ */_x000D_ public XConfigActor getXConfigActorByName(String name, String type) {_x000D_ return (XConfigActor) this.getXConfigObjectByName(name, type);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor for a give "id" and "type"._x000D_ *_x000D_ * @param id Identifier of the Actor._x000D_ * @param type Type of the Actor._x000D_ * @return XConfigActor._x000D_ */_x000D_ public XConfigActor getXConfigActorById(String id, String type) {_x000D_ return (XConfigActor) this.getXConfigObjectById(id, type);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RepositoryType) for a given repository "name"._x000D_ *_x000D_ * @param repositoryName_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRepositoryConfigByName(String repositoryName) {_x000D_ return this.getXConfigActorByName(repositoryName, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RegistryType) for a given registry "name"._x000D_ *_x000D_ * @param registryName_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRegistryConfigByName(String registryName) {_x000D_ return this.getXConfigActorByName(registryName, XConfig.XDSB_DOCUMENT_REGISTRY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns list of available assigning authority configurations._x000D_ *_x000D_ * @return List<XConfigObject> List of assigning authority configurations._x000D_ */_x000D_ public List<XConfigObject> getAssigningAuthorityConfigs() {_x000D_ return this.assigningAuthorities;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject (AssigningAuthorityType) for a given "unique id"._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getAssigningAuthorityConfigById(String uniqueId) {_x000D_ return this.getXConfigObjectById(uniqueId, XConfig.ASSIGNING_AUTHORITY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns list of XConfigActors (of RespondingGatewayType) for a given assigning authority._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return List<XConfigActor>_x000D_ */_x000D_ public List<XConfigActor> getRespondingGatewayConfigsForAssigningAuthorityId(String uniqueId) {_x000D_ XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId);_x000D_ List<XConfigActor> gateways = new ArrayList<XConfigActor>();_x000D_ if (aa != null) {_x000D_ List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ for (XConfigObject configObject : configObjects) {_x000D_ gateways.add((XConfigActor) configObject);_x000D_ }_x000D_ }_x000D_ return gateways;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns XConfigActor (RegistryType) for a given assigning authority._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRegistryConfigForAssigningAuthorityId(String uniqueId) {_x000D_ XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId);_x000D_ XConfigActor registry = null;_x000D_ if (aa != null) {_x000D_ List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XDSB_DOCUMENT_REGISTRY_TYPE);_x000D_ if (configObjects.size() > 0) {_x000D_ registry = (XConfigActor) configObjects.get(0); // Should only have one._x000D_ }_x000D_ }_x000D_ return registry;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return String Property value._x000D_ */_x000D_ public String getHomeCommunityConfigProperty(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getProperty(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return boolean property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return String Property value._x000D_ */_x000D_ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getPropertyAsBoolean(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return boolean property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @param defaultValue Returned as value if "propKey" does not exist._x000D_ * @return String Property value._x000D_ */_x000D_ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey, boolean defaultValue) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getPropertyAsBoolean(propKey, defaultValue);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return "long" property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return long Property value._x000D_ */_x000D_ public long getHomeCommunityConfigPropertyAsLong(String propKey) {_x000D_ String longVal = this.getHomeCommunityConfigProperty(propKey);_x000D_ return (new Long(longVal)).longValue();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return true if property "key" exists in home community configuration._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return boolean True if exists. False, otherwise._x000D_ */_x000D_ public boolean containsHomeCommunityConfigProperty(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.containsProperty(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Retrieves XML configuration file, parses and places into an easily accessible data structure._x000D_ */_x000D_ private void loadConfiguration() throws XConfigException {_x000D_ String configLocation = _configLocation; // May be set._x000D_ if (configLocation == null) {_x000D_ configLocation = XConfig.getConfigLocation(ConfigItem.XCONFIG_FILE);_x000D_ }_x000D_ String configXML = null;_x000D_ if (configLocation != null) {_x000D_ try {_x000D_ logger.info("Loading XConfig from: " + configLocation);_x000D_ // Get the configuration file from the file system._x000D_ configXML = Io.getStringFromInputStream(new FileInputStream(new File(configLocation)));_x000D_ } catch (Exception e) {_x000D_ throw new XConfigException(_x000D_ "XConfig: Could not load configuration from " + configLocation + " " + e.getMessage());_x000D_ }_x000D_ } else {_x000D_ throw new XConfigException(_x000D_ "XConfig: Unable to get location of xconfig file");_x000D_ }_x000D_ _x000D_ // Parse the XML file._x000D_ OMElement configXMLRoot;_x000D_ try {_x000D_ configXMLRoot = XMLParser.stringToOM(configXML);_x000D_ } catch (XMLParserException ex) {_x000D_ throw new XConfigException(ex.getMessage());_x000D_ }_x000D_ if (configXMLRoot == null) {_x000D_ throw new XConfigException(_x000D_ "XConfig: Could not parse configuration from " + configLocation);_x000D_ }_x000D_ buildInternalStructure(configXMLRoot);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Builds internal data structures for quick access._x000D_ *_x000D_ * @param rootNode Holds root node of parsed configuration file._x000D_ */_x000D_ private void buildInternalStructure(OMElement rootNode) {_x000D_ parseObjects(rootNode);_x000D_ parseActors(rootNode);_x000D_ resolveObjectReferences();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Parses all "Object" XML nodes._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ */_x000D_ private void parseObjects(OMElement rootNode) {_x000D_ List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Object");_x000D_ for (OMElement currentNode : nodes) {_x000D_ XConfigObject configObject = new XConfigObject();_x000D_ configObject.parse(currentNode, this);_x000D_ this.addConfigObjectToMaps(configObject);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Parses all "Actor" XML nodes._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ */_x000D_ private void parseActors(OMElement rootNode) {_x000D_ List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Actor");_x000D_ for (OMElement currentNode : nodes) {_x000D_ XConfigActor configObject = new XConfigActor();_x000D_ configObject.parse(currentNode, this);_x000D_ this.addConfigObjectToMaps(configObject);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Add XConfigObject to internal data structures._x000D_ *_x000D_ * @param configObject XConfigObject_x000D_ */_x000D_ private void addConfigObjectToMaps(XConfigObject configObject) {_x000D_ if (configObject.getType().equals(XConfig.ASSIGNING_AUTHORITY_TYPE)) {_x000D_ this.assigningAuthorities.add(configObject);_x000D_ }_x000D_ this.objectByNameMap.put(this.getNameKey(configObject), configObject);_x000D_ if (configObject.getUniqueId() != null) {_x000D_ this.objectByIdMap.put(this.getIdKey(configObject), configObject);_x000D_ }_x000D_ this.objects.add(configObject);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a "name based" key to use for lookups._x000D_ *_x000D_ * @param configObject_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getNameKey(XConfigObject configObject) {_x000D_ return configObject.getName() + ":" + configObject.getType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a key to use for lookups._x000D_ *_x000D_ * @param name_x000D_ * @param key_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getKey(String name, String type) {_x000D_ return name + ":" + type;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a "name based" key to use for lookups._x000D_ *_x000D_ * @param configObjectRef_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getNameKey(XConfigObjectRef configObjectRef) {_x000D_ return configObjectRef.getRefName() + ":" + configObjectRef.getRefType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate an "id based" key to use for lookups._x000D_ *_x000D_ * @param configObject_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getIdKey(XConfigObject configObject) {_x000D_ return configObject.getUniqueId() + ":" + configObject.getType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Go through list of objects and resolve references to each other._x000D_ */_x000D_ private void resolveObjectReferences() {_x000D_ for (XConfigObject configObject : this.objects) {_x000D_ for (XConfigObjectRef objRef : configObject.getObjectRefs()) {_x000D_ // See if already resolved._x000D_ if (objRef.getXConfigObject() == null) {_x000D_ _x000D_ // Find reference (by refname)._x000D_ String refKey = this.getNameKey(objRef);_x000D_ if (this.objectByNameMap.containsKey(refKey) == true) {_x000D_ XConfigObject referencedObject = objectByNameMap.get(refKey);_x000D_ objRef.setXConfigObject(referencedObject);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Helper method to find all AXIOM nodes given a "root node" and "local name"._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ * @param localName Local name to find._x000D_ * @return List<OMElement>_x000D_ */_x000D_ public static List<OMElement> parseLevelOneNode(OMElement rootNode, String localName) {_x000D_ ArrayList<OMElement> al = new ArrayList<OMElement>();_x000D_ for (Iterator it = rootNode.getChildElements(); it.hasNext();) {_x000D_ OMElement child = (OMElement) it.next();_x000D_ if (child.getLocalName().equals(localName)) {_x000D_ al.add(child);_x000D_ }_x000D_ }_x000D_ return al;_x000D_ }_x000D_ /**_x000D_ * Just a test driver to exercise XConfig operations._x000D_ *_x000D_ * @param args the command line arguments_x000D_ */_x000D_ /*_x000D_ public static void main(String[] args) {_x000D_ try {_x000D_ XConfig xconf = XConfig.getInstance();_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Local Initiating Gateway = " + xconf.getHomeCommunity().getInitiatingGateway());_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Local Responding Gateway = " + xconf.getHomeCommunity().getRespondingGateway());_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Gateway = " + xconf.getGateway("urn:oid:1.19.6.24.109.42.1.3"));_x000D_ System.out.println("TXN = " + xconf.getGateway("urn:oid:1.19.6.24.109.42.1.3").getTransaction("CrossGatewayQuery"));_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Success!");_x000D_ } catch (Exception e) {_x000D_ System.out.println(e.toString());_x000D_ }_x000D_ }*/_x000D_ }_x000D_
kef/hieos
src/xutil/src/com/vangent/hieos/xutil/xconfig/XConfig.java
7,002
// Look in environment variable next._x000D_
line_comment
nl
/*_x000D_ * This code is subject to the HIEOS License, Version 1.0_x000D_ *_x000D_ * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved._x000D_ *_x000D_ * Unless required by applicable law or agreed to in writing, software_x000D_ * distributed under the License is distributed on an "AS IS" BASIS,_x000D_ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied._x000D_ *_x000D_ * See the License for the specific language governing permissions and_x000D_ * limitations under the License._x000D_ */_x000D_ _x000D_ /*_x000D_ * XConfig.java_x000D_ *_x000D_ * Created on January 14, 2009_x000D_ *_x000D_ */_x000D_ package com.vangent.hieos.xutil.xconfig;_x000D_ _x000D_ import com.vangent.hieos.xutil.exception.XMLParserException;_x000D_ import com.vangent.hieos.xutil.xml.XMLParser;_x000D_ import com.vangent.hieos.xutil.exception.XConfigException;_x000D_ import com.vangent.hieos.xutil.iosupport.Io;_x000D_ _x000D_ // Third-party._x000D_ import java.util.ArrayList;_x000D_ import java.util.Iterator;_x000D_ import java.util.HashMap;_x000D_ import org.apache.axiom.om.OMElement;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.util.List;_x000D_ import org.apache.log4j.Logger;_x000D_ _x000D_ /**_x000D_ * Maintains system configuration parameters for IHE XDS.b and XCA profiles. Acts as a Singleton._x000D_ *_x000D_ * @author Bernie Thuman_x000D_ *_x000D_ */_x000D_ public class XConfig {_x000D_ _x000D_ public enum ConfigItem {_x000D_ _x000D_ CONFIG_DIR, XCONFIG_FILE, SCHEMA_DIR, CODES_FILE, XDSBRIDGE_DIR, POLICY_DIR, EMPI_DIR_x000D_ };_x000D_ // HIEOS environment variables (would like to rename but remaining backward compatible)._x000D_ public final static String ENV_HIEOS_CONFIG_DIR = "HIEOSxConfigDir";_x000D_ public final static String ENV_HIEOS_XCONFIG_FILE = "HIEOSxConfigFile";_x000D_ public final static String ENV_HIEOS_SCHEMA_DIR = "HIEOSxSchemaDir";_x000D_ public final static String ENV_HIEOS_XDSBRIDGE_DIR = "HIEOSxXDSBridgeDir";_x000D_ public final static String ENV_HIEOS_POLICY_DIR = "HIEOSxPolicyDir";_x000D_ public final static String ENV_HIEOS_EMPI_DIR = "HIEOSxEMPIDir";_x000D_ public final static String ENV_HIEOS_CODES_FILE = "HIEOSxCodesFile";_x000D_ // HIEOS system properties (would like to rename but remaining backward compatible)._x000D_ public final static String SYSPROP_HIEOS_CONFIG_DIR = "com.vangent.hieos.configdir";_x000D_ public final static String SYSPROP_HIEOS_XCONFIG_FILE = "com.vangent.hieos.xconfig";_x000D_ public final static String SYSPROP_HIEOS_SCHEMA_DIR = "com.vangent.hieos.schemadir";_x000D_ public final static String SYSPROP_HIEOS_XDSBRIDGE_DIR = "com.vangent.hieos.xdsbridgedir";_x000D_ public final static String SYSPROP_HIEOS_POLICY_DIR = "com.vangent.hieos.policydir";_x000D_ public final static String SYSPROP_HIEOS_EMPI_DIR = "com.vangent.hieos.empidir";_x000D_ public final static String SYSPROP_HIEOS_CODES_FILE = "com.vangent.hieos.codesfile";_x000D_ private final static Logger logger = Logger.getLogger(XConfig.class);_x000D_ static private XConfig _instance = null; // Singleton instance._x000D_ static private String _configLocation = null; // Location of xconfig.xml file_x000D_ // Internal data structure starts here._x000D_ private List<XConfigObject> objects = new ArrayList<XConfigObject>();_x000D_ private HashMap<String, XConfigObject> objectByNameMap = new HashMap<String, XConfigObject>();_x000D_ private HashMap<String, XConfigObject> objectByIdMap = new HashMap<String, XConfigObject>();_x000D_ private List<XConfigObject> assigningAuthorities = new ArrayList<XConfigObject>();_x000D_ // Kept as strings versus enum to allow extension without XConfig code modification._x000D_ static final public String HOME_COMMUNITY_TYPE = "HomeCommunityType";_x000D_ static final public String XDSB_DOCUMENT_REGISTRY_TYPE = "DocumentRegistryType";_x000D_ static final public String XDSB_DOCUMENT_REPOSITORY_TYPE = "DocumentRepositoryType";_x000D_ static final public String XCA_INITIATING_GATEWAY_TYPE = "InitiatingGatewayType";_x000D_ static final public String XCA_RESPONDING_GATEWAY_TYPE = "RespondingGatewayType";_x000D_ static final public String XUA_PROPERTIES_TYPE = "XUAPropertiesType";_x000D_ static final public String ASSIGNING_AUTHORITY_TYPE = "AssigningAuthorityType";_x000D_ static final public String PDS_TYPE = "PDSType"; // Patient Demographics Service_x000D_ static final public String PolicyDecisionPoint_TYPE = "PolicyDecisionPointType";_x000D_ static final public String PolicyInformationPoint_TYPE = "PolicyInformationPointType";_x000D_ static final public String STS_TYPE = "SecureTokenServiceType";_x000D_ static final public String XDSBRIDGE_TYPE = "XDSBridgeType";_x000D_ static final public String PIX_MANAGER_TYPE = "PIXManagerType";_x000D_ static final public String XDR_DOCUMENT_RECIPIENT_TYPE = "DocumentRecipientType";_x000D_ _x000D_ /**_x000D_ *_x000D_ * @param configItem_x000D_ * @return_x000D_ */_x000D_ static public String getConfigLocation(ConfigItem configItem) {_x000D_ String configLocation = null;_x000D_ switch (configItem) {_x000D_ case CONFIG_DIR:_x000D_ configLocation = getConfigDir();_x000D_ break;_x000D_ case XCONFIG_FILE:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XCONFIG_FILE, XConfig.ENV_HIEOS_XCONFIG_FILE);_x000D_ break;_x000D_ case SCHEMA_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_SCHEMA_DIR, XConfig.ENV_HIEOS_SCHEMA_DIR);_x000D_ break;_x000D_ case CODES_FILE:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_CODES_FILE, XConfig.ENV_HIEOS_CODES_FILE);_x000D_ break;_x000D_ case XDSBRIDGE_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_XDSBRIDGE_DIR, XConfig.ENV_HIEOS_XDSBRIDGE_DIR);_x000D_ break;_x000D_ case POLICY_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_POLICY_DIR, XConfig.ENV_HIEOS_POLICY_DIR);_x000D_ break;_x000D_ case EMPI_DIR:_x000D_ configLocation = getConfigLocation(configItem, XConfig.SYSPROP_HIEOS_EMPI_DIR, XConfig.ENV_HIEOS_EMPI_DIR);_x000D_ break;_x000D_ }_x000D_ return configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ *_x000D_ * @return_x000D_ */_x000D_ static public String getConfigDir() {_x000D_ // First look at system property._x000D_ String configDir = System.getProperty(XConfig.SYSPROP_HIEOS_CONFIG_DIR);_x000D_ if (configDir == null) {_x000D_ // Look in environment variable next._x000D_ configDir = System.getenv(XConfig.ENV_HIEOS_CONFIG_DIR);_x000D_ }_x000D_ return configDir;_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param sysPropName_x000D_ * @param envName_x000D_ * @return_x000D_ */_x000D_ static private String getConfigLocation(ConfigItem configItem, String sysPropName, String envName) {_x000D_ // First look at system property._x000D_ String configLocation = System.getProperty(sysPropName);_x000D_ if (configLocation == null) {_x000D_ // Look in<SUF> configLocation = System.getenv(envName);_x000D_ }_x000D_ if (configLocation == null) {_x000D_ String configDir = XConfig.getConfigDir();_x000D_ switch (configItem) {_x000D_ case XCONFIG_FILE:_x000D_ configLocation = configDir + "/xconfig.xml";_x000D_ break;_x000D_ case SCHEMA_DIR:_x000D_ configLocation = configDir + "/schema";_x000D_ break;_x000D_ case CODES_FILE:_x000D_ configLocation = configDir + "/codes/codes.xml";_x000D_ break;_x000D_ case XDSBRIDGE_DIR:_x000D_ configLocation = configDir + "/xdsbridge";_x000D_ break;_x000D_ case POLICY_DIR:_x000D_ configLocation = configDir + "/policy";_x000D_ break;_x000D_ case EMPI_DIR:_x000D_ configLocation = configDir + "/empi";_x000D_ break;_x000D_ }_x000D_ }_x000D_ return configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ * _x000D_ * @param configLocation_x000D_ */_x000D_ static public synchronized void setConfigLocation(String configLocation) {_x000D_ _configLocation = configLocation;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns Singleton instance of XConfig._x000D_ *_x000D_ * @return Singleton instance of XConfig_x000D_ * @throws XConfigException_x000D_ */_x000D_ static public synchronized XConfig getInstance() throws XConfigException {_x000D_ if (_instance == null) {_x000D_ _instance = new XConfig();_x000D_ }_x000D_ return _instance;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Private constructor responsible for loading configuration file into memory._x000D_ */_x000D_ private XConfig() throws XConfigException {_x000D_ loadConfiguration();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns the global configuration for the Home Community._x000D_ *_x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getHomeCommunityConfig() {_x000D_ String key = this.getKey("home", XConfig.HOME_COMMUNITY_TYPE);_x000D_ return this.objectByNameMap.get(key);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RespondingGatewayType) based on a homeCommunityId._x000D_ *_x000D_ * @param homeCommunityId_x000D_ * @return An instance of XConfigActor or null (if not found)._x000D_ */_x000D_ public XConfigActor getRespondingGatewayConfigForHomeCommunityId(String homeCommunityId) {_x000D_ return this.getXConfigActorById(homeCommunityId, XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return an XConfigActor (RespondingGatewayType) given a gateway name._x000D_ *_x000D_ * @param gatewayName Name of responding gateway._x000D_ * @return XConfigActor_x000D_ */_x000D_ protected XConfigActor getRespondingGatewayConfigByName(String gatewayName) {_x000D_ return this.getXConfigActorByName(gatewayName, XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return an XConfigActor (RepositoryType) given a repository id._x000D_ *_x000D_ * @param repositoryId_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRepositoryConfigById(String repositoryId) {_x000D_ return this.getXConfigActorById(repositoryId, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject for a given "name" and "type"._x000D_ *_x000D_ * @param name Name of the object._x000D_ * @param type Type of the object._x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getXConfigObjectByName(String name, String type) {_x000D_ XConfigObject configObject = null;_x000D_ String key = this.getKey(name, type);_x000D_ if (this.objectByNameMap.containsKey(key)) {_x000D_ configObject = this.objectByNameMap.get(key);_x000D_ }_x000D_ return configObject;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject for a given "id" and "type"._x000D_ * _x000D_ * @param id Identifier for the object._x000D_ * @param type Type of the object._x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getXConfigObjectById(String id, String type) {_x000D_ XConfigObject configObject = null;_x000D_ String key = this.getKey(id, type);_x000D_ if (this.objectByIdMap.containsKey(key)) {_x000D_ configObject = this.objectByIdMap.get(key);_x000D_ }_x000D_ return configObject;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns all XConfigObject instances of the specific type._x000D_ *_x000D_ * @param type The type of XConfigObject to locate._x000D_ * @return List<XConfigObject>_x000D_ */_x000D_ public List<XConfigObject> getXConfigObjectsOfType(String type) {_x000D_ List<XConfigObject> configObjects = new ArrayList<XConfigObject>();_x000D_ for (XConfigObject object : objects) {_x000D_ if (object.getType().equalsIgnoreCase(type)) {_x000D_ configObjects.add(object);_x000D_ }_x000D_ }_x000D_ return configObjects;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor for a give "name" and "type"._x000D_ *_x000D_ * @param name Name of the Actor._x000D_ * @param type Type of the Actor._x000D_ * @return XConfigActor._x000D_ */_x000D_ public XConfigActor getXConfigActorByName(String name, String type) {_x000D_ return (XConfigActor) this.getXConfigObjectByName(name, type);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor for a give "id" and "type"._x000D_ *_x000D_ * @param id Identifier of the Actor._x000D_ * @param type Type of the Actor._x000D_ * @return XConfigActor._x000D_ */_x000D_ public XConfigActor getXConfigActorById(String id, String type) {_x000D_ return (XConfigActor) this.getXConfigObjectById(id, type);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RepositoryType) for a given repository "name"._x000D_ *_x000D_ * @param repositoryName_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRepositoryConfigByName(String repositoryName) {_x000D_ return this.getXConfigActorByName(repositoryName, XConfig.XDSB_DOCUMENT_REPOSITORY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigActor (RegistryType) for a given registry "name"._x000D_ *_x000D_ * @param registryName_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRegistryConfigByName(String registryName) {_x000D_ return this.getXConfigActorByName(registryName, XConfig.XDSB_DOCUMENT_REGISTRY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns list of available assigning authority configurations._x000D_ *_x000D_ * @return List<XConfigObject> List of assigning authority configurations._x000D_ */_x000D_ public List<XConfigObject> getAssigningAuthorityConfigs() {_x000D_ return this.assigningAuthorities;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an XConfigObject (AssigningAuthorityType) for a given "unique id"._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return XConfigObject_x000D_ */_x000D_ public XConfigObject getAssigningAuthorityConfigById(String uniqueId) {_x000D_ return this.getXConfigObjectById(uniqueId, XConfig.ASSIGNING_AUTHORITY_TYPE);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns list of XConfigActors (of RespondingGatewayType) for a given assigning authority._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return List<XConfigActor>_x000D_ */_x000D_ public List<XConfigActor> getRespondingGatewayConfigsForAssigningAuthorityId(String uniqueId) {_x000D_ XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId);_x000D_ List<XConfigActor> gateways = new ArrayList<XConfigActor>();_x000D_ if (aa != null) {_x000D_ List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XCA_RESPONDING_GATEWAY_TYPE);_x000D_ for (XConfigObject configObject : configObjects) {_x000D_ gateways.add((XConfigActor) configObject);_x000D_ }_x000D_ }_x000D_ return gateways;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns XConfigActor (RegistryType) for a given assigning authority._x000D_ *_x000D_ * @param uniqueId_x000D_ * @return XConfigActor_x000D_ */_x000D_ public XConfigActor getRegistryConfigForAssigningAuthorityId(String uniqueId) {_x000D_ XConfigObject aa = this.getAssigningAuthorityConfigById(uniqueId);_x000D_ XConfigActor registry = null;_x000D_ if (aa != null) {_x000D_ List<XConfigObject> configObjects = aa.getXConfigObjectsWithType(XConfig.XDSB_DOCUMENT_REGISTRY_TYPE);_x000D_ if (configObjects.size() > 0) {_x000D_ registry = (XConfigActor) configObjects.get(0); // Should only have one._x000D_ }_x000D_ }_x000D_ return registry;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return String Property value._x000D_ */_x000D_ public String getHomeCommunityConfigProperty(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getProperty(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return boolean property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return String Property value._x000D_ */_x000D_ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getPropertyAsBoolean(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return boolean property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @param defaultValue Returned as value if "propKey" does not exist._x000D_ * @return String Property value._x000D_ */_x000D_ public boolean getHomeCommunityConfigPropertyAsBoolean(String propKey, boolean defaultValue) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.getPropertyAsBoolean(propKey, defaultValue);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return "long" property value given a property key (scoped to home community)._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return long Property value._x000D_ */_x000D_ public long getHomeCommunityConfigPropertyAsLong(String propKey) {_x000D_ String longVal = this.getHomeCommunityConfigProperty(propKey);_x000D_ return (new Long(longVal)).longValue();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Return true if property "key" exists in home community configuration._x000D_ *_x000D_ * @param propKey Property key._x000D_ * @return boolean True if exists. False, otherwise._x000D_ */_x000D_ public boolean containsHomeCommunityConfigProperty(String propKey) {_x000D_ XConfigObject homeCommunityConfig = this.getHomeCommunityConfig();_x000D_ return homeCommunityConfig.containsProperty(propKey);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Retrieves XML configuration file, parses and places into an easily accessible data structure._x000D_ */_x000D_ private void loadConfiguration() throws XConfigException {_x000D_ String configLocation = _configLocation; // May be set._x000D_ if (configLocation == null) {_x000D_ configLocation = XConfig.getConfigLocation(ConfigItem.XCONFIG_FILE);_x000D_ }_x000D_ String configXML = null;_x000D_ if (configLocation != null) {_x000D_ try {_x000D_ logger.info("Loading XConfig from: " + configLocation);_x000D_ // Get the configuration file from the file system._x000D_ configXML = Io.getStringFromInputStream(new FileInputStream(new File(configLocation)));_x000D_ } catch (Exception e) {_x000D_ throw new XConfigException(_x000D_ "XConfig: Could not load configuration from " + configLocation + " " + e.getMessage());_x000D_ }_x000D_ } else {_x000D_ throw new XConfigException(_x000D_ "XConfig: Unable to get location of xconfig file");_x000D_ }_x000D_ _x000D_ // Parse the XML file._x000D_ OMElement configXMLRoot;_x000D_ try {_x000D_ configXMLRoot = XMLParser.stringToOM(configXML);_x000D_ } catch (XMLParserException ex) {_x000D_ throw new XConfigException(ex.getMessage());_x000D_ }_x000D_ if (configXMLRoot == null) {_x000D_ throw new XConfigException(_x000D_ "XConfig: Could not parse configuration from " + configLocation);_x000D_ }_x000D_ buildInternalStructure(configXMLRoot);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Builds internal data structures for quick access._x000D_ *_x000D_ * @param rootNode Holds root node of parsed configuration file._x000D_ */_x000D_ private void buildInternalStructure(OMElement rootNode) {_x000D_ parseObjects(rootNode);_x000D_ parseActors(rootNode);_x000D_ resolveObjectReferences();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Parses all "Object" XML nodes._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ */_x000D_ private void parseObjects(OMElement rootNode) {_x000D_ List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Object");_x000D_ for (OMElement currentNode : nodes) {_x000D_ XConfigObject configObject = new XConfigObject();_x000D_ configObject.parse(currentNode, this);_x000D_ this.addConfigObjectToMaps(configObject);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Parses all "Actor" XML nodes._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ */_x000D_ private void parseActors(OMElement rootNode) {_x000D_ List<OMElement> nodes = XConfig.parseLevelOneNode(rootNode, "Actor");_x000D_ for (OMElement currentNode : nodes) {_x000D_ XConfigActor configObject = new XConfigActor();_x000D_ configObject.parse(currentNode, this);_x000D_ this.addConfigObjectToMaps(configObject);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Add XConfigObject to internal data structures._x000D_ *_x000D_ * @param configObject XConfigObject_x000D_ */_x000D_ private void addConfigObjectToMaps(XConfigObject configObject) {_x000D_ if (configObject.getType().equals(XConfig.ASSIGNING_AUTHORITY_TYPE)) {_x000D_ this.assigningAuthorities.add(configObject);_x000D_ }_x000D_ this.objectByNameMap.put(this.getNameKey(configObject), configObject);_x000D_ if (configObject.getUniqueId() != null) {_x000D_ this.objectByIdMap.put(this.getIdKey(configObject), configObject);_x000D_ }_x000D_ this.objects.add(configObject);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a "name based" key to use for lookups._x000D_ *_x000D_ * @param configObject_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getNameKey(XConfigObject configObject) {_x000D_ return configObject.getName() + ":" + configObject.getType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a key to use for lookups._x000D_ *_x000D_ * @param name_x000D_ * @param key_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getKey(String name, String type) {_x000D_ return name + ":" + type;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate a "name based" key to use for lookups._x000D_ *_x000D_ * @param configObjectRef_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getNameKey(XConfigObjectRef configObjectRef) {_x000D_ return configObjectRef.getRefName() + ":" + configObjectRef.getRefType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Formulate an "id based" key to use for lookups._x000D_ *_x000D_ * @param configObject_x000D_ * @return String Formatted key._x000D_ */_x000D_ private String getIdKey(XConfigObject configObject) {_x000D_ return configObject.getUniqueId() + ":" + configObject.getType();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Go through list of objects and resolve references to each other._x000D_ */_x000D_ private void resolveObjectReferences() {_x000D_ for (XConfigObject configObject : this.objects) {_x000D_ for (XConfigObjectRef objRef : configObject.getObjectRefs()) {_x000D_ // See if already resolved._x000D_ if (objRef.getXConfigObject() == null) {_x000D_ _x000D_ // Find reference (by refname)._x000D_ String refKey = this.getNameKey(objRef);_x000D_ if (this.objectByNameMap.containsKey(refKey) == true) {_x000D_ XConfigObject referencedObject = objectByNameMap.get(refKey);_x000D_ objRef.setXConfigObject(referencedObject);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Helper method to find all AXIOM nodes given a "root node" and "local name"._x000D_ *_x000D_ * @param rootNode Starting point._x000D_ * @param localName Local name to find._x000D_ * @return List<OMElement>_x000D_ */_x000D_ public static List<OMElement> parseLevelOneNode(OMElement rootNode, String localName) {_x000D_ ArrayList<OMElement> al = new ArrayList<OMElement>();_x000D_ for (Iterator it = rootNode.getChildElements(); it.hasNext();) {_x000D_ OMElement child = (OMElement) it.next();_x000D_ if (child.getLocalName().equals(localName)) {_x000D_ al.add(child);_x000D_ }_x000D_ }_x000D_ return al;_x000D_ }_x000D_ /**_x000D_ * Just a test driver to exercise XConfig operations._x000D_ *_x000D_ * @param args the command line arguments_x000D_ */_x000D_ /*_x000D_ public static void main(String[] args) {_x000D_ try {_x000D_ XConfig xconf = XConfig.getInstance();_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Local Initiating Gateway = " + xconf.getHomeCommunity().getInitiatingGateway());_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Local Responding Gateway = " + xconf.getHomeCommunity().getRespondingGateway());_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Gateway = " + xconf.getGateway("urn:oid:1.19.6.24.109.42.1.3"));_x000D_ System.out.println("TXN = " + xconf.getGateway("urn:oid:1.19.6.24.109.42.1.3").getTransaction("CrossGatewayQuery"));_x000D_ System.out.println("------------------------");_x000D_ System.out.println("Success!");_x000D_ } catch (Exception e) {_x000D_ System.out.println(e.toString());_x000D_ }_x000D_ }*/_x000D_ }_x000D_
False
1,117
18183_3
import java.awt.Rectangle;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ImageObserver;_x000D_ import java.io.File;_x000D_ import javax.imageio.ImageIO;_x000D_ import java.io.IOException;_x000D_ _x000D_ _x000D_ /** De klasse voor een Bitmap item_x000D_ * <P>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ public class BitmapItem extends SlideItem {_x000D_ private BufferedImage bufferedImage;_x000D_ private String imageName;_x000D_ _x000D_ // level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_ public BitmapItem(int level, String name) {_x000D_ super(level);_x000D_ imageName = name;_x000D_ try {_x000D_ bufferedImage = ImageIO.read(new File(imageName));_x000D_ }_x000D_ catch (IOException e) {_x000D_ System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_ }_x000D_ }_x000D_ _x000D_ // Een leeg bitmap-item_x000D_ public BitmapItem() {_x000D_ this(0, null);_x000D_ }_x000D_ _x000D_ // geef de bestandsnaam van het plaatje_x000D_ public String getName() {_x000D_ return imageName;_x000D_ }_x000D_ _x000D_ // geef de bounding box van het plaatje_x000D_ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_ return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_ (int) (bufferedImage.getWidth(observer) * scale),_x000D_ ((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_ }_x000D_ _x000D_ // teken het plaatje_x000D_ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_ int width = x + (int) (myStyle.indent * scale);_x000D_ int height = y + (int) (myStyle.leading * scale);_x000D_ g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_ (int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_ }_x000D_ }_x000D_
MichielMertens/OU_JP_MM_EVB
src/BitmapItem.java
794
// geef de bestandsnaam van het plaatje_x000D_
line_comment
nl
import java.awt.Rectangle;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ImageObserver;_x000D_ import java.io.File;_x000D_ import javax.imageio.ImageIO;_x000D_ import java.io.IOException;_x000D_ _x000D_ _x000D_ /** De klasse voor een Bitmap item_x000D_ * <P>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ public class BitmapItem extends SlideItem {_x000D_ private BufferedImage bufferedImage;_x000D_ private String imageName;_x000D_ _x000D_ // level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_ public BitmapItem(int level, String name) {_x000D_ super(level);_x000D_ imageName = name;_x000D_ try {_x000D_ bufferedImage = ImageIO.read(new File(imageName));_x000D_ }_x000D_ catch (IOException e) {_x000D_ System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_ }_x000D_ }_x000D_ _x000D_ // Een leeg bitmap-item_x000D_ public BitmapItem() {_x000D_ this(0, null);_x000D_ }_x000D_ _x000D_ // geef de<SUF> public String getName() {_x000D_ return imageName;_x000D_ }_x000D_ _x000D_ // geef de bounding box van het plaatje_x000D_ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_ return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_ (int) (bufferedImage.getWidth(observer) * scale),_x000D_ ((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_ }_x000D_ _x000D_ // teken het plaatje_x000D_ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_ int width = x + (int) (myStyle.indent * scale);_x000D_ int height = y + (int) (myStyle.leading * scale);_x000D_ g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_ (int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_ }_x000D_ }_x000D_
True
839
57662_0
package servlets;_x000D_ _x000D_ import java.io.IOException;_x000D_ import java.sql.Connection;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.servlet.RequestDispatcher;_x000D_ import javax.servlet.ServletException;_x000D_ import javax.servlet.http.HttpServlet;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import javax.servlet.http.HttpServletResponse;_x000D_ _x000D_ import database.ConnectDBProduct;_x000D_ import domeinklassen.Product;_x000D_ _x000D_ public class ProductServlet extends HttpServlet{_x000D_ private static final long serialVersionUID = 1L;_x000D_ _x000D_ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_ _x000D_ Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_ String knop = req.getParameter("knop");_x000D_ _x000D_ ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_ ArrayList<Product> deVoorraad = conn.getProducten();_x000D_ RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij default naar voorraadoverzicht_x000D_ _x000D_ //forward voorraadlijst naar de overzicht-pagina._x000D_ if(knop.equals("overzicht")){_x000D_ if(deVoorraad.size() == 0){_x000D_ req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ } _x000D_ //forward lijst producten onder min voorraad_x000D_ else if (knop.equals("OnderVoorraad")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", ondermin);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ }_x000D_ //bestel producten onder min voorraad_x000D_ else if(knop.equals("WerkVoorraadBij")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_ req.setAttribute("stap1", "Done");_x000D_ req.setAttribute("teBestellenProducten", ondermin);_x000D_ }_x000D_ }_x000D_ //maak een nieuw product aan_x000D_ else if(knop.equals("nieuw")){_x000D_ String nm = req.getParameter("naam");_x000D_ String ma = req.getParameter("minaantal");_x000D_ String eh = req.getParameter("eenheid");_x000D_ String pps = req.getParameter("pps");_x000D_ ArrayList<String> velden = new ArrayList<String>();_x000D_ velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_ _x000D_ //check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_ boolean allesIngevuld = true;_x000D_ for(String s : velden){_x000D_ if(s.equals("")){_x000D_ allesIngevuld = false;_x000D_ req.setAttribute("error", "Vul alle velden in!");_x000D_ break;_x000D_ }_x000D_ }_x000D_ //als gegevens ingevuld_x000D_ if(allesIngevuld){ _x000D_ try{ //check voor geldige nummers_x000D_ //maak product aan in database en haal op_x000D_ Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_ //stuur toString() van nieuwe product terug_x000D_ String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_ req.setAttribute("msg", terug);_x000D_ }_x000D_ catch(Exception ex){_x000D_ System.out.println(ex);_x000D_ req.setAttribute("error", "Voer geldige nummers in!");_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ //zoek product op naam of artikelnummer_x000D_ else if(knop.equals("zoek")){_x000D_ String nm = req.getParameter("zoeknaam");_x000D_ String eh = req.getParameter("zoekeenheid");_x000D_ String anr = req.getParameter("zoeknummer"); _x000D_ ArrayList<Product> terug = new ArrayList<Product>();_x000D_ //check welke zoekterm er in is gevoerd_x000D_ if(!anr.equals("")){_x000D_ //check voor geldig artikelnummer (int)_x000D_ try{_x000D_ int nummer = Integer.parseInt(anr);_x000D_ terug.add(conn.zoekProduct(nummer));_x000D_ }catch(NumberFormatException e){_x000D_ req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_ }_x000D_ }_x000D_ if(!nm.equals("")){_x000D_ for(Product p : conn.zoekProductNaam(nm)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ if(!eh.equals("")){_x000D_ for(Product p : conn.zoekProductEenheid(eh)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ else{_x000D_ req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_ }_x000D_ if(terug.size() == 0){_x000D_ req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_ req.setAttribute("arraygevonden", terug); _x000D_ }_x000D_ }_x000D_ _x000D_ //wijzig gezochte product_x000D_ else if(knop.equals("wijzig")){_x000D_ String productnummer = req.getParameter("product");_x000D_ Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_ req.setAttribute("product", hetProduct);_x000D_ rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_ } _x000D_ else if(knop.equals("verwijder")){_x000D_ String p = req.getParameter("product");_x000D_ if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_ req.setAttribute("msg", "Product met succes verwijderd.");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("error", "Kon product niet verwijderen!");_x000D_ }_x000D_ deVoorraad = conn.getProducten();_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ } _x000D_ rd.forward(req, resp); _x000D_ }_x000D_ }
Jfeurich/Themaopdracht2
Themaopdracht/src/servlets/ProductServlet.java
1,844
//stuur bij default naar voorraadoverzicht_x000D_
line_comment
nl
package servlets;_x000D_ _x000D_ import java.io.IOException;_x000D_ import java.sql.Connection;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.servlet.RequestDispatcher;_x000D_ import javax.servlet.ServletException;_x000D_ import javax.servlet.http.HttpServlet;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import javax.servlet.http.HttpServletResponse;_x000D_ _x000D_ import database.ConnectDBProduct;_x000D_ import domeinklassen.Product;_x000D_ _x000D_ public class ProductServlet extends HttpServlet{_x000D_ private static final long serialVersionUID = 1L;_x000D_ _x000D_ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_ _x000D_ Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_ String knop = req.getParameter("knop");_x000D_ _x000D_ ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_ ArrayList<Product> deVoorraad = conn.getProducten();_x000D_ RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij<SUF> _x000D_ //forward voorraadlijst naar de overzicht-pagina._x000D_ if(knop.equals("overzicht")){_x000D_ if(deVoorraad.size() == 0){_x000D_ req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ } _x000D_ //forward lijst producten onder min voorraad_x000D_ else if (knop.equals("OnderVoorraad")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", ondermin);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ }_x000D_ //bestel producten onder min voorraad_x000D_ else if(knop.equals("WerkVoorraadBij")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_ req.setAttribute("stap1", "Done");_x000D_ req.setAttribute("teBestellenProducten", ondermin);_x000D_ }_x000D_ }_x000D_ //maak een nieuw product aan_x000D_ else if(knop.equals("nieuw")){_x000D_ String nm = req.getParameter("naam");_x000D_ String ma = req.getParameter("minaantal");_x000D_ String eh = req.getParameter("eenheid");_x000D_ String pps = req.getParameter("pps");_x000D_ ArrayList<String> velden = new ArrayList<String>();_x000D_ velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_ _x000D_ //check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_ boolean allesIngevuld = true;_x000D_ for(String s : velden){_x000D_ if(s.equals("")){_x000D_ allesIngevuld = false;_x000D_ req.setAttribute("error", "Vul alle velden in!");_x000D_ break;_x000D_ }_x000D_ }_x000D_ //als gegevens ingevuld_x000D_ if(allesIngevuld){ _x000D_ try{ //check voor geldige nummers_x000D_ //maak product aan in database en haal op_x000D_ Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_ //stuur toString() van nieuwe product terug_x000D_ String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_ req.setAttribute("msg", terug);_x000D_ }_x000D_ catch(Exception ex){_x000D_ System.out.println(ex);_x000D_ req.setAttribute("error", "Voer geldige nummers in!");_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ //zoek product op naam of artikelnummer_x000D_ else if(knop.equals("zoek")){_x000D_ String nm = req.getParameter("zoeknaam");_x000D_ String eh = req.getParameter("zoekeenheid");_x000D_ String anr = req.getParameter("zoeknummer"); _x000D_ ArrayList<Product> terug = new ArrayList<Product>();_x000D_ //check welke zoekterm er in is gevoerd_x000D_ if(!anr.equals("")){_x000D_ //check voor geldig artikelnummer (int)_x000D_ try{_x000D_ int nummer = Integer.parseInt(anr);_x000D_ terug.add(conn.zoekProduct(nummer));_x000D_ }catch(NumberFormatException e){_x000D_ req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_ }_x000D_ }_x000D_ if(!nm.equals("")){_x000D_ for(Product p : conn.zoekProductNaam(nm)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ if(!eh.equals("")){_x000D_ for(Product p : conn.zoekProductEenheid(eh)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ else{_x000D_ req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_ }_x000D_ if(terug.size() == 0){_x000D_ req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_ req.setAttribute("arraygevonden", terug); _x000D_ }_x000D_ }_x000D_ _x000D_ //wijzig gezochte product_x000D_ else if(knop.equals("wijzig")){_x000D_ String productnummer = req.getParameter("product");_x000D_ Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_ req.setAttribute("product", hetProduct);_x000D_ rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_ } _x000D_ else if(knop.equals("verwijder")){_x000D_ String p = req.getParameter("product");_x000D_ if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_ req.setAttribute("msg", "Product met succes verwijderd.");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("error", "Kon product niet verwijderen!");_x000D_ }_x000D_ deVoorraad = conn.getProducten();_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ } _x000D_ rd.forward(req, resp); _x000D_ }_x000D_ }
True
1,579
27781_12
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.Tagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-"); private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "schaps", "teits" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "afgods", "allemans", "arbeiders", "bedrijfs", "dorps", "eindejaars", "etens", "gevechts", "gezichts", "jongens", "levens", "lijdens", "meisjes", "onderhouds", "oorlogs", "overlijdens", "passagiers", "personeels", "varkens", "vrijwilligers" ); // exceptions to the list "alwaysNeedsS" private final Set<String> part1Exceptions = ImmutableSet.of( "belasting", "dating", "doping", "gaming", "grooming", "honing", "kleding", "kring", "matching", "outsourcing", "paling", "rekening", "spring", "styling", "tracking", "tweeling", "viking" ); private final Set<String> part2Exceptions = ImmutableSet.of( "ding", "lijk", "lopen", "mara", "ping", "raat", "reek", "reen", "stag", "sten", "tand", "ting", "voor" ); private final Set<String> acronymExceptions = ImmutableSet.of( "aids", "alv", "AMvB", "Anw", "apk", "arbo", "Awb", "bbl", "Bevi", "Bopz", "bso", "btw", "cao", "cd", "dvd", "ecg", "gft", "ggz", "gps", "gsm", "hbs", "hifi", "hiv", "hrm", "hsl", "hts", "Hvb", "Hvw", "iMac", "iOS", "iPad", "iPod", "ivf", "lbo", "lcd", "lts", "mbo", "mdf", "mkb", "Opw", "ozb", "pc", "pdf", "pgb", "sms", "soa", "tbs", "tv", "ufo", "vip", "vwo", "Wabo", "Waz", "Wazo", "Wbp", "wifi", "Wft", "Wlz", "WvS", "Wwft", "Wzd", "xtc", "Zvw", "zzp" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "aandeel", "aangifte", "aanname", "accessoire", "achtergrond", "adres", "afgifte", "afname", "aids", "akte", "algoritme", "allure", "ambulance", "analyse", "anekdote", "antenne", "attitude", "auto", "balustrade", "bediende", "behoefte", "belangen", "belofte", "bende", "beroerte", "bezoek", "bijdrage", "bijlage", "binnenste", "blessure", "boeren", "boete", "bolide", "breedte", "brigade", "café", "cantate", "cassette", "catastrofe", "collecte", "competitie", "contract", "controverse", "curve", "detective", "diagnose", "dienst", "diepte", "dikte", "douane", "droogte", "einde", "ellende", "energie", "episode", "estafette", "etappe", "expertise", "façade", "familie", "fanfare", "fase", "feest", "finale", "fluoride", "fractie", "gebergte", "geboorte", "gedaante", "gedachte", "gedeelte", "gehalte", "gemeente", "gemiddelde", "genade", "genocide", "gestalte", "gesteente", "gevaarte", "gewoonte", "gezegde", "gilde", "gravure", "groente", "grootte", "halte", "hectare", "holte", "hoofd", "hoogte", "horde", "hybride", "hypothese", "impasse", "informatie", "inname", "inzage", "kade", "karakter", "kazerne", "keuze", "kinder", "krapte", "kudde", "lade", "leegte", "legende", "lengte", "liefde", "literatuur", "lucht", "luchtvaart", "made", "mannen", "mascotte", "mechanisme", "mede", "menigte", "mensenrechten", "metamorfose", "methode", "meute", "module", "mythe", "novelle", "nuance", "oase", "offerte", "onderwijs", "oorkonde", "oplage", "opname", "orde", "organisatie", "organisme", "orgasme", "overname", "papier", "pauze", "pedicure", "periode", "piramide", "piste", "politie", "privé", "probleem", "productie", "prothese", "prototype", "psychose", "pyjama", "rente", "ritme", "ronde", "rotonde", "route", "ruimte", "ruimtevaart", "ruïne", "satire", "schaarste", "schade", "school", "seconde", "secretaresse", "sekte", "sterfte", "sterkte", "stilte", "straat", "studenten", "synagoge", "synode", "synthese", "telefoon", "televisie", "tenue", "terzijde", "theater", "toelage", "tombe", "trede", "tube", "type", "uiteinde", "uitgifte", "verloofde", "verte", "vete", "vip", "vitamine", "vlakte", "vogel", "volume", "voorbeeld", "voorbode", "voorhoede", "voorliefde", "voorronde", "vreugde", "vrouwen", "waarde", "warmte", "weduwe", "weergave", "weide", "wereld", "woning", "woord", "ziekte", "zijde", "zonde", "zwaarte", "zwakte", "zwanger" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private final Tagger tagger; CompoundAcceptor() { tagger = Languages.getLanguageForShortCode("nl").getTagger(); } public CompoundAcceptor(Tagger tagger) { this.tagger = tagger; } boolean acceptCompound(String word) throws IOException { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); // reject if it's in the exceptions list if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !noS.contains(part1)) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return acronymOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } boolean isNoun(String word) throws IOException { List<AnalyzedTokenReadings> part2Readings = tagger.tag(Arrays.asList(word)); return part2Readings.stream().anyMatch(k -> k.hasPosTagStartingWith("ZNW")) && !part2Exceptions.contains(word) ; } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean acronymOk(String nonCompound) { // for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten if ( acronymPattern.matcher(nonCompound).matches() ){ return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1))); } else if ( specialAcronymPattern.matcher(nonCompound).matches() ) { // special case acronyms that are accepted only with specific casing return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1)); } else { return false; } } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet -> split as kinder,enHet } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
Sharcoux/languagetool
languagetool-language-modules/nl/src/main/java/org/languagetool/rules/nl/CompoundAcceptor.java
4,537
// e.g. kinderenHet -> split as kinder,enHet
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.Tagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z]{2,4}-"); private static final Pattern specialAcronymPattern = Pattern.compile("[A-Za-z]{2,4}-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "schaps", "teits" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "afgods", "allemans", "arbeiders", "bedrijfs", "dorps", "eindejaars", "etens", "gevechts", "gezichts", "jongens", "levens", "lijdens", "meisjes", "onderhouds", "oorlogs", "overlijdens", "passagiers", "personeels", "varkens", "vrijwilligers" ); // exceptions to the list "alwaysNeedsS" private final Set<String> part1Exceptions = ImmutableSet.of( "belasting", "dating", "doping", "gaming", "grooming", "honing", "kleding", "kring", "matching", "outsourcing", "paling", "rekening", "spring", "styling", "tracking", "tweeling", "viking" ); private final Set<String> part2Exceptions = ImmutableSet.of( "ding", "lijk", "lopen", "mara", "ping", "raat", "reek", "reen", "stag", "sten", "tand", "ting", "voor" ); private final Set<String> acronymExceptions = ImmutableSet.of( "aids", "alv", "AMvB", "Anw", "apk", "arbo", "Awb", "bbl", "Bevi", "Bopz", "bso", "btw", "cao", "cd", "dvd", "ecg", "gft", "ggz", "gps", "gsm", "hbs", "hifi", "hiv", "hrm", "hsl", "hts", "Hvb", "Hvw", "iMac", "iOS", "iPad", "iPod", "ivf", "lbo", "lcd", "lts", "mbo", "mdf", "mkb", "Opw", "ozb", "pc", "pdf", "pgb", "sms", "soa", "tbs", "tv", "ufo", "vip", "vwo", "Wabo", "Waz", "Wazo", "Wbp", "wifi", "Wft", "Wlz", "WvS", "Wwft", "Wzd", "xtc", "Zvw", "zzp" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "aandeel", "aangifte", "aanname", "accessoire", "achtergrond", "adres", "afgifte", "afname", "aids", "akte", "algoritme", "allure", "ambulance", "analyse", "anekdote", "antenne", "attitude", "auto", "balustrade", "bediende", "behoefte", "belangen", "belofte", "bende", "beroerte", "bezoek", "bijdrage", "bijlage", "binnenste", "blessure", "boeren", "boete", "bolide", "breedte", "brigade", "café", "cantate", "cassette", "catastrofe", "collecte", "competitie", "contract", "controverse", "curve", "detective", "diagnose", "dienst", "diepte", "dikte", "douane", "droogte", "einde", "ellende", "energie", "episode", "estafette", "etappe", "expertise", "façade", "familie", "fanfare", "fase", "feest", "finale", "fluoride", "fractie", "gebergte", "geboorte", "gedaante", "gedachte", "gedeelte", "gehalte", "gemeente", "gemiddelde", "genade", "genocide", "gestalte", "gesteente", "gevaarte", "gewoonte", "gezegde", "gilde", "gravure", "groente", "grootte", "halte", "hectare", "holte", "hoofd", "hoogte", "horde", "hybride", "hypothese", "impasse", "informatie", "inname", "inzage", "kade", "karakter", "kazerne", "keuze", "kinder", "krapte", "kudde", "lade", "leegte", "legende", "lengte", "liefde", "literatuur", "lucht", "luchtvaart", "made", "mannen", "mascotte", "mechanisme", "mede", "menigte", "mensenrechten", "metamorfose", "methode", "meute", "module", "mythe", "novelle", "nuance", "oase", "offerte", "onderwijs", "oorkonde", "oplage", "opname", "orde", "organisatie", "organisme", "orgasme", "overname", "papier", "pauze", "pedicure", "periode", "piramide", "piste", "politie", "privé", "probleem", "productie", "prothese", "prototype", "psychose", "pyjama", "rente", "ritme", "ronde", "rotonde", "route", "ruimte", "ruimtevaart", "ruïne", "satire", "schaarste", "schade", "school", "seconde", "secretaresse", "sekte", "sterfte", "sterkte", "stilte", "straat", "studenten", "synagoge", "synode", "synthese", "telefoon", "televisie", "tenue", "terzijde", "theater", "toelage", "tombe", "trede", "tube", "type", "uiteinde", "uitgifte", "verloofde", "verte", "vete", "vip", "vitamine", "vlakte", "vogel", "volume", "voorbeeld", "voorbode", "voorhoede", "voorliefde", "voorronde", "vreugde", "vrouwen", "waarde", "warmte", "weduwe", "weergave", "weide", "wereld", "woning", "woord", "ziekte", "zijde", "zonde", "zwaarte", "zwakte", "zwanger" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private final Tagger tagger; CompoundAcceptor() { tagger = Languages.getLanguageForShortCode("nl").getTagger(); } public CompoundAcceptor(Tagger tagger) { this.tagger = tagger; } boolean acceptCompound(String word) throws IOException { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); // reject if it's in the exceptions list if (part1.endsWith("s") && !part1Exceptions.contains(part1.substring(0, part1.length() -1)) && !noS.contains(part1)) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return acronymOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return (noS.contains(part1lc) || part1Exceptions.contains(part1lc)) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } boolean isNoun(String word) throws IOException { List<AnalyzedTokenReadings> part2Readings = tagger.tag(Arrays.asList(word)); return part2Readings.stream().anyMatch(k -> k.hasPosTagStartingWith("ZNW")) && !part2Exceptions.contains(word) ; } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean acronymOk(String nonCompound) { // for compound words like IRA-akkoord, MIDI-bestanden, WK-finalisten if ( acronymPattern.matcher(nonCompound).matches() ){ return acronymExceptions.stream().noneMatch(exception -> exception.toUpperCase().equals(nonCompound.substring(0, nonCompound.length() -1))); } else if ( specialAcronymPattern.matcher(nonCompound).matches() ) { // special case acronyms that are accepted only with specific casing return acronymExceptions.contains(nonCompound.substring(0, nonCompound.length() -1)); } else { return false; } } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet<SUF> } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
False
3,635
204402_44
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * 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 * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.operation.buffer; import com.vividsolutions.jts.algorithm.Angle; import com.vividsolutions.jts.algorithm.CGAlgorithms; import com.vividsolutions.jts.algorithm.HCoordinate; import com.vividsolutions.jts.algorithm.LineIntersector; import com.vividsolutions.jts.algorithm.NotRepresentableException; import com.vividsolutions.jts.algorithm.RobustLineIntersector; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.LineSegment; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geomgraph.Position; import com.vividsolutions.jts.util.Debug; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = CGAlgorithms.computeOrientation(s0, s1, s2); boolean outsideTurn = (orientation == CGAlgorithms.CLOCKWISE && side == Position.LEFT) || (orientation == CGAlgorithms.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addFillet(s1, offset0.p1, offset1.p0, CGAlgorithms.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, CGAlgorithms.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { boolean isMitreWithinLimit = true; Coordinate intPt = null; /** * This computation is unstable if the offset segments are nearly collinear. * Howver, this situation should have been eliminated earlier by the check for * whether the offset segment endpoints are almost coincident */ try { intPt = HCoordinate.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio > bufParams.getMitreLimit()) isMitreWithinLimit = false; } catch (NotRepresentableException ex) { intPt = new Coordinate(0,0); isMitreWithinLimit = false; } if (isMitreWithinLimit) { segList.addPt(intPt); } else { addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); double ang1 = Angle.angle(basePt, seg1.p1); // oriented angle between segments double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == CGAlgorithms.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == CGAlgorithms.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! double initAngle, currAngleInc; // choose angle increment so that each segment has equal length initAngle = 0.0; currAngleInc = totalAngle / nSegs; double currAngle = initAngle; Coordinate pt = new Coordinate(); while (currAngle < totalAngle) { double angle = startAngle + directionFactor * currAngle; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); currAngle += currAngleInc; } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
metteo/jts
jts-core/src/main/java/com/vividsolutions/jts/operation/buffer/OffsetSegmentGenerator.java
7,784
// oriented angle between segments_x000D_
line_comment
nl
/*_x000D_ * The JTS Topology Suite is a collection of Java classes that_x000D_ * implement the fundamental operations required to validate a given_x000D_ * geo-spatial data set to a known topological specification._x000D_ *_x000D_ * Copyright (C) 2001 Vivid Solutions_x000D_ *_x000D_ * This library is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU Lesser General Public_x000D_ * License as published by the Free Software Foundation; either_x000D_ * version 2.1 of the License, or (at your option) any later version._x000D_ *_x000D_ * This library is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU_x000D_ * Lesser General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU Lesser General Public_x000D_ * License along with this library; if not, write to the Free Software_x000D_ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA_x000D_ *_x000D_ * For more information, contact:_x000D_ *_x000D_ * Vivid Solutions_x000D_ * Suite #1A_x000D_ * 2328 Government Street_x000D_ * Victoria BC V8T 5G5_x000D_ * Canada_x000D_ *_x000D_ * (250)385-6040_x000D_ * www.vividsolutions.com_x000D_ */_x000D_ package com.vividsolutions.jts.operation.buffer;_x000D_ _x000D_ import com.vividsolutions.jts.algorithm.Angle;_x000D_ import com.vividsolutions.jts.algorithm.CGAlgorithms;_x000D_ import com.vividsolutions.jts.algorithm.HCoordinate;_x000D_ import com.vividsolutions.jts.algorithm.LineIntersector;_x000D_ import com.vividsolutions.jts.algorithm.NotRepresentableException;_x000D_ import com.vividsolutions.jts.algorithm.RobustLineIntersector;_x000D_ import com.vividsolutions.jts.geom.Coordinate;_x000D_ import com.vividsolutions.jts.geom.LineSegment;_x000D_ import com.vividsolutions.jts.geom.PrecisionModel;_x000D_ import com.vividsolutions.jts.geomgraph.Position;_x000D_ import com.vividsolutions.jts.util.Debug;_x000D_ _x000D_ /**_x000D_ * Generates segments which form an offset curve._x000D_ * Supports all end cap and join options _x000D_ * provided for buffering._x000D_ * This algorithm implements various heuristics to _x000D_ * produce smoother, simpler curves which are_x000D_ * still within a reasonable tolerance of the _x000D_ * true curve._x000D_ * _x000D_ * @author Martin Davis_x000D_ *_x000D_ */_x000D_ class OffsetSegmentGenerator _x000D_ {_x000D_ _x000D_ /**_x000D_ * Factor which controls how close offset segments can be to_x000D_ * skip adding a filler or mitre._x000D_ */_x000D_ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3;_x000D_ _x000D_ /**_x000D_ * Factor which controls how close curve vertices on inside turns can be to be snapped _x000D_ */_x000D_ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3;_x000D_ _x000D_ /**_x000D_ * Factor which controls how close curve vertices can be to be snapped_x000D_ */_x000D_ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6;_x000D_ _x000D_ /**_x000D_ * Factor which determines how short closing segs can be for round buffers_x000D_ */_x000D_ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80;_x000D_ _x000D_ /**_x000D_ * the max error of approximation (distance) between a quad segment and the true fillet curve_x000D_ */_x000D_ private double maxCurveSegmentError = 0.0;_x000D_ _x000D_ /**_x000D_ * The angle quantum with which to approximate a fillet curve_x000D_ * (based on the input # of quadrant segments)_x000D_ */_x000D_ private double filletAngleQuantum;_x000D_ _x000D_ /**_x000D_ * The Closing Segment Length Factor controls how long_x000D_ * "closing segments" are. Closing segments are added_x000D_ * at the middle of inside corners to ensure a smoother_x000D_ * boundary for the buffer offset curve. _x000D_ * In some cases (particularly for round joins with default-or-better_x000D_ * quantization) the closing segments can be made quite short._x000D_ * This substantially improves performance (due to fewer intersections being created)._x000D_ * _x000D_ * A closingSegFactor of 0 results in lines to the corner vertex_x000D_ * A closingSegFactor of 1 results in lines halfway to the corner vertex_x000D_ * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex_x000D_ * (this option is reasonable for the very common default situation of round joins_x000D_ * and quadrantSegs >= 8)_x000D_ */_x000D_ private int closingSegLengthFactor = 1;_x000D_ _x000D_ private OffsetSegmentString segList;_x000D_ private double distance = 0.0;_x000D_ private PrecisionModel precisionModel;_x000D_ private BufferParameters bufParams;_x000D_ private LineIntersector li;_x000D_ _x000D_ private Coordinate s0, s1, s2;_x000D_ private LineSegment seg0 = new LineSegment();_x000D_ private LineSegment seg1 = new LineSegment();_x000D_ private LineSegment offset0 = new LineSegment();_x000D_ private LineSegment offset1 = new LineSegment();_x000D_ private int side = 0;_x000D_ private boolean hasNarrowConcaveAngle = false;_x000D_ _x000D_ public OffsetSegmentGenerator(PrecisionModel precisionModel,_x000D_ BufferParameters bufParams, double distance) {_x000D_ this.precisionModel = precisionModel;_x000D_ this.bufParams = bufParams;_x000D_ _x000D_ // compute intersections in full precision, to provide accuracy_x000D_ // the points are rounded as they are inserted into the curve line_x000D_ li = new RobustLineIntersector();_x000D_ filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments();_x000D_ _x000D_ /**_x000D_ * Non-round joins cause issues with short closing segments, so don't use_x000D_ * them. In any case, non-round joins only really make sense for relatively_x000D_ * small buffer distances._x000D_ */_x000D_ if (bufParams.getQuadrantSegments() >= 8_x000D_ && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND)_x000D_ closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR;_x000D_ init(distance);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Tests whether the input has a narrow concave angle_x000D_ * (relative to the offset distance)._x000D_ * In this case the generated offset curve will contain self-intersections_x000D_ * and heuristic closing segments._x000D_ * This is expected behaviour in the case of Buffer curves. _x000D_ * For pure Offset Curves,_x000D_ * the output needs to be further treated _x000D_ * before it can be used. _x000D_ * _x000D_ * @return true if the input has a narrow concave angle_x000D_ */_x000D_ public boolean hasNarrowConcaveAngle()_x000D_ {_x000D_ return hasNarrowConcaveAngle;_x000D_ }_x000D_ _x000D_ private void init(double distance)_x000D_ {_x000D_ this.distance = distance;_x000D_ maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0));_x000D_ segList = new OffsetSegmentString();_x000D_ segList.setPrecisionModel(precisionModel);_x000D_ /**_x000D_ * Choose the min vertex separation as a small fraction of the offset distance._x000D_ */_x000D_ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR);_x000D_ }_x000D_ _x000D_ _x000D_ public void initSideSegments(Coordinate s1, Coordinate s2, int side)_x000D_ {_x000D_ this.s1 = s1;_x000D_ this.s2 = s2;_x000D_ this.side = side;_x000D_ seg1.setCoordinates(s1, s2);_x000D_ computeOffsetSegment(seg1, side, distance, offset1);_x000D_ }_x000D_ _x000D_ public Coordinate[] getCoordinates()_x000D_ {_x000D_ Coordinate[] pts = segList.getCoordinates();_x000D_ return pts;_x000D_ }_x000D_ _x000D_ public void closeRing()_x000D_ {_x000D_ segList.closeRing();_x000D_ }_x000D_ _x000D_ public void addSegments(Coordinate[] pt, boolean isForward)_x000D_ {_x000D_ segList.addPts(pt, isForward);_x000D_ }_x000D_ _x000D_ public void addFirstSegment()_x000D_ {_x000D_ segList.addPt(offset1.p0);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Add last offset point_x000D_ */_x000D_ public void addLastSegment()_x000D_ {_x000D_ segList.addPt(offset1.p1);_x000D_ }_x000D_ _x000D_ //private static double MAX_CLOSING_SEG_LEN = 3.0;_x000D_ _x000D_ public void addNextSegment(Coordinate p, boolean addStartPoint)_x000D_ {_x000D_ // s0-s1-s2 are the coordinates of the previous segment and the current one_x000D_ s0 = s1;_x000D_ s1 = s2;_x000D_ s2 = p;_x000D_ seg0.setCoordinates(s0, s1);_x000D_ computeOffsetSegment(seg0, side, distance, offset0);_x000D_ seg1.setCoordinates(s1, s2);_x000D_ computeOffsetSegment(seg1, side, distance, offset1);_x000D_ _x000D_ // do nothing if points are equal_x000D_ if (s1.equals(s2)) return;_x000D_ _x000D_ int orientation = CGAlgorithms.computeOrientation(s0, s1, s2);_x000D_ boolean outsideTurn =_x000D_ (orientation == CGAlgorithms.CLOCKWISE && side == Position.LEFT)_x000D_ || (orientation == CGAlgorithms.COUNTERCLOCKWISE && side == Position.RIGHT);_x000D_ _x000D_ if (orientation == 0) { // lines are collinear_x000D_ addCollinear(addStartPoint);_x000D_ }_x000D_ else if (outsideTurn) _x000D_ {_x000D_ addOutsideTurn(orientation, addStartPoint);_x000D_ }_x000D_ else { // inside turn_x000D_ addInsideTurn(orientation, addStartPoint);_x000D_ }_x000D_ }_x000D_ _x000D_ private void addCollinear(boolean addStartPoint)_x000D_ {_x000D_ /**_x000D_ * This test could probably be done more efficiently,_x000D_ * but the situation of exact collinearity should be fairly rare._x000D_ */_x000D_ li.computeIntersection(s0, s1, s1, s2);_x000D_ int numInt = li.getIntersectionNum();_x000D_ /**_x000D_ * if numInt is < 2, the lines are parallel and in the same direction. In_x000D_ * this case the point can be ignored, since the offset lines will also be_x000D_ * parallel._x000D_ */_x000D_ if (numInt >= 2) {_x000D_ /**_x000D_ * segments are collinear but reversing. _x000D_ * Add an "end-cap" fillet_x000D_ * all the way around to other direction This case should ONLY happen_x000D_ * for LineStrings, so the orientation is always CW. (Polygons can never_x000D_ * have two consecutive segments which are parallel but reversed,_x000D_ * because that would be a self intersection._x000D_ * _x000D_ */_x000D_ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL _x000D_ || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {_x000D_ if (addStartPoint) segList.addPt(offset0.p1);_x000D_ segList.addPt(offset1.p0);_x000D_ }_x000D_ else {_x000D_ addFillet(s1, offset0.p1, offset1.p0, CGAlgorithms.CLOCKWISE, distance);_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Adds the offset points for an outside (convex) turn_x000D_ * _x000D_ * @param orientation_x000D_ * @param addStartPoint_x000D_ */_x000D_ private void addOutsideTurn(int orientation, boolean addStartPoint)_x000D_ {_x000D_ /**_x000D_ * Heuristic: If offset endpoints are very close together, _x000D_ * just use one of them as the corner vertex._x000D_ * This avoids problems with computing mitre corners in the case_x000D_ * where the two segments are almost parallel _x000D_ * (which is hard to compute a robust intersection for)._x000D_ */_x000D_ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) {_x000D_ segList.addPt(offset0.p1);_x000D_ return;_x000D_ }_x000D_ _x000D_ if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) {_x000D_ addMitreJoin(s1, offset0, offset1, distance);_x000D_ }_x000D_ else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){_x000D_ addBevelJoin(offset0, offset1);_x000D_ }_x000D_ else {_x000D_ // add a circular fillet connecting the endpoints of the offset segments_x000D_ if (addStartPoint) segList.addPt(offset0.p1);_x000D_ // TESTING - comment out to produce beveled joins_x000D_ addFillet(s1, offset0.p1, offset1.p0, orientation, distance);_x000D_ segList.addPt(offset1.p0);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Adds the offset points for an inside (concave) turn._x000D_ * _x000D_ * @param orientation_x000D_ * @param addStartPoint_x000D_ */_x000D_ private void addInsideTurn(int orientation, boolean addStartPoint) {_x000D_ /**_x000D_ * add intersection point of offset segments (if any)_x000D_ */_x000D_ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1);_x000D_ if (li.hasIntersection()) {_x000D_ segList.addPt(li.getIntersection(0));_x000D_ }_x000D_ else {_x000D_ /**_x000D_ * If no intersection is detected, _x000D_ * it means the angle is so small and/or the offset so_x000D_ * large that the offsets segments don't intersect. _x000D_ * In this case we must_x000D_ * add a "closing segment" to make sure the buffer curve is continuous,_x000D_ * fairly smooth (e.g. no sharp reversals in direction)_x000D_ * and tracks the buffer correctly around the corner. The curve connects_x000D_ * the endpoints of the segment offsets to points_x000D_ * which lie toward the centre point of the corner._x000D_ * The joining curve will not appear in the final buffer outline, since it_x000D_ * is completely internal to the buffer polygon._x000D_ * _x000D_ * In complex buffer cases the closing segment may cut across many other_x000D_ * segments in the generated offset curve. In order to improve the _x000D_ * performance of the noding, the closing segment should be kept as short as possible._x000D_ * (But not too short, since that would defeat its purpose)._x000D_ * This is the purpose of the closingSegFactor heuristic value._x000D_ */ _x000D_ _x000D_ /** _x000D_ * The intersection test above is vulnerable to robustness errors; i.e. it_x000D_ * may be that the offsets should intersect very close to their endpoints,_x000D_ * but aren't reported as such due to rounding. To handle this situation_x000D_ * appropriately, we use the following test: If the offset points are very_x000D_ * close, don't add closing segments but simply use one of the offset_x000D_ * points_x000D_ */_x000D_ hasNarrowConcaveAngle = true;_x000D_ //System.out.println("NARROW ANGLE - distance = " + distance);_x000D_ if (offset0.p1.distance(offset1.p0) < distance_x000D_ * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) {_x000D_ segList.addPt(offset0.p1);_x000D_ } else {_x000D_ // add endpoint of this segment offset_x000D_ segList.addPt(offset0.p1);_x000D_ _x000D_ /**_x000D_ * Add "closing segment" of required length._x000D_ */_x000D_ if (closingSegLengthFactor > 0) {_x000D_ Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), _x000D_ (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1));_x000D_ segList.addPt(mid0);_x000D_ Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), _x000D_ (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1));_x000D_ segList.addPt(mid1);_x000D_ }_x000D_ else {_x000D_ /**_x000D_ * This branch is not expected to be used except for testing purposes._x000D_ * It is equivalent to the JTS 1.9 logic for closing segments_x000D_ * (which results in very poor performance for large buffer distances)_x000D_ */_x000D_ segList.addPt(s1);_x000D_ }_x000D_ _x000D_ //*/ _x000D_ // add start point of next segment offset_x000D_ segList.addPt(offset1.p0);_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Compute an offset segment for an input segment on a given side and at a given distance._x000D_ * The offset points are computed in full double precision, for accuracy._x000D_ *_x000D_ * @param seg the segment to offset_x000D_ * @param side the side of the segment ({@link Position}) the offset lies on_x000D_ * @param distance the offset distance_x000D_ * @param offset the points computed for the offset segment_x000D_ */_x000D_ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset)_x000D_ {_x000D_ int sideSign = side == Position.LEFT ? 1 : -1;_x000D_ double dx = seg.p1.x - seg.p0.x;_x000D_ double dy = seg.p1.y - seg.p0.y;_x000D_ double len = Math.sqrt(dx * dx + dy * dy);_x000D_ // u is the vector that is the length of the offset, in the direction of the segment_x000D_ double ux = sideSign * distance * dx / len;_x000D_ double uy = sideSign * distance * dy / len;_x000D_ offset.p0.x = seg.p0.x - uy;_x000D_ offset.p0.y = seg.p0.y + ux;_x000D_ offset.p1.x = seg.p1.x - uy;_x000D_ offset.p1.y = seg.p1.y + ux;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Add an end cap around point p1, terminating a line segment coming from p0_x000D_ */_x000D_ public void addLineEndCap(Coordinate p0, Coordinate p1)_x000D_ {_x000D_ LineSegment seg = new LineSegment(p0, p1);_x000D_ _x000D_ LineSegment offsetL = new LineSegment();_x000D_ computeOffsetSegment(seg, Position.LEFT, distance, offsetL);_x000D_ LineSegment offsetR = new LineSegment();_x000D_ computeOffsetSegment(seg, Position.RIGHT, distance, offsetR);_x000D_ _x000D_ double dx = p1.x - p0.x;_x000D_ double dy = p1.y - p0.y;_x000D_ double angle = Math.atan2(dy, dx);_x000D_ _x000D_ switch (bufParams.getEndCapStyle()) {_x000D_ case BufferParameters.CAP_ROUND:_x000D_ // add offset seg points with a fillet between them_x000D_ segList.addPt(offsetL.p1);_x000D_ addFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, CGAlgorithms.CLOCKWISE, distance);_x000D_ segList.addPt(offsetR.p1);_x000D_ break;_x000D_ case BufferParameters.CAP_FLAT:_x000D_ // only offset segment points are added_x000D_ segList.addPt(offsetL.p1);_x000D_ segList.addPt(offsetR.p1);_x000D_ break;_x000D_ case BufferParameters.CAP_SQUARE:_x000D_ // add a square defined by extensions of the offset segment endpoints_x000D_ Coordinate squareCapSideOffset = new Coordinate();_x000D_ squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle);_x000D_ squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle);_x000D_ _x000D_ Coordinate squareCapLOffset = new Coordinate(_x000D_ offsetL.p1.x + squareCapSideOffset.x,_x000D_ offsetL.p1.y + squareCapSideOffset.y);_x000D_ Coordinate squareCapROffset = new Coordinate(_x000D_ offsetR.p1.x + squareCapSideOffset.x,_x000D_ offsetR.p1.y + squareCapSideOffset.y);_x000D_ segList.addPt(squareCapLOffset);_x000D_ segList.addPt(squareCapROffset);_x000D_ break;_x000D_ _x000D_ }_x000D_ }_x000D_ /**_x000D_ * Adds a mitre join connecting the two reflex offset segments._x000D_ * The mitre will be beveled if it exceeds the mitre ratio limit._x000D_ * _x000D_ * @param offset0 the first offset segment_x000D_ * @param offset1 the second offset segment_x000D_ * @param distance the offset distance_x000D_ */_x000D_ private void addMitreJoin(Coordinate p, _x000D_ LineSegment offset0, _x000D_ LineSegment offset1,_x000D_ double distance)_x000D_ {_x000D_ boolean isMitreWithinLimit = true;_x000D_ Coordinate intPt = null;_x000D_ _x000D_ /**_x000D_ * This computation is unstable if the offset segments are nearly collinear._x000D_ * Howver, this situation should have been eliminated earlier by the check for _x000D_ * whether the offset segment endpoints are almost coincident_x000D_ */_x000D_ try {_x000D_ intPt = HCoordinate.intersection(offset0.p0, _x000D_ offset0.p1, offset1.p0, offset1.p1);_x000D_ _x000D_ double mitreRatio = distance <= 0.0 ? 1.0_x000D_ : intPt.distance(p) / Math.abs(distance);_x000D_ _x000D_ if (mitreRatio > bufParams.getMitreLimit())_x000D_ isMitreWithinLimit = false;_x000D_ }_x000D_ catch (NotRepresentableException ex) {_x000D_ intPt = new Coordinate(0,0);_x000D_ isMitreWithinLimit = false;_x000D_ }_x000D_ _x000D_ if (isMitreWithinLimit) {_x000D_ segList.addPt(intPt);_x000D_ }_x000D_ else {_x000D_ addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit());_x000D_ // addBevelJoin(offset0, offset1);_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Adds a limited mitre join connecting the two reflex offset segments._x000D_ * A limited mitre is a mitre which is beveled at the distance_x000D_ * determined by the mitre ratio limit._x000D_ * _x000D_ * @param offset0 the first offset segment_x000D_ * @param offset1 the second offset segment_x000D_ * @param distance the offset distance_x000D_ * @param mitreLimit the mitre limit ratio_x000D_ */_x000D_ private void addLimitedMitreJoin( _x000D_ LineSegment offset0, _x000D_ LineSegment offset1,_x000D_ double distance,_x000D_ double mitreLimit)_x000D_ {_x000D_ Coordinate basePt = seg0.p1;_x000D_ _x000D_ double ang0 = Angle.angle(basePt, seg0.p0);_x000D_ double ang1 = Angle.angle(basePt, seg1.p1);_x000D_ _x000D_ // oriented angle<SUF> double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1);_x000D_ // half of the interior angle_x000D_ double angDiffHalf = angDiff / 2;_x000D_ _x000D_ // angle for bisector of the interior angle between the segments_x000D_ double midAng = Angle.normalize(ang0 + angDiffHalf);_x000D_ // rotating this by PI gives the bisector of the reflex angle_x000D_ double mitreMidAng = Angle.normalize(midAng + Math.PI);_x000D_ _x000D_ // the miterLimit determines the distance to the mitre bevel_x000D_ double mitreDist = mitreLimit * distance;_x000D_ // the bevel delta is the difference between the buffer distance_x000D_ // and half of the length of the bevel segment_x000D_ double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf));_x000D_ double bevelHalfLen = distance - bevelDelta;_x000D_ _x000D_ // compute the midpoint of the bevel segment_x000D_ double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng);_x000D_ double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng);_x000D_ Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY);_x000D_ _x000D_ // compute the mitre midline segment from the corner point to the bevel segment midpoint_x000D_ LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt);_x000D_ _x000D_ // finally the bevel segment endpoints are computed as offsets from _x000D_ // the mitre midline_x000D_ Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen);_x000D_ Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen);_x000D_ _x000D_ if (side == Position.LEFT) {_x000D_ segList.addPt(bevelEndLeft);_x000D_ segList.addPt(bevelEndRight);_x000D_ }_x000D_ else {_x000D_ segList.addPt(bevelEndRight);_x000D_ segList.addPt(bevelEndLeft); _x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Adds a bevel join connecting the two offset segments_x000D_ * around a reflex corner._x000D_ * _x000D_ * @param offset0 the first offset segment_x000D_ * @param offset1 the second offset segment_x000D_ */_x000D_ private void addBevelJoin( _x000D_ LineSegment offset0, _x000D_ LineSegment offset1)_x000D_ {_x000D_ segList.addPt(offset0.p1);_x000D_ segList.addPt(offset1.p0); _x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Add points for a circular fillet around a reflex corner._x000D_ * Adds the start and end points_x000D_ * _x000D_ * @param p base point of curve_x000D_ * @param p0 start point of fillet curve_x000D_ * @param p1 endpoint of fillet curve_x000D_ * @param direction the orientation of the fillet_x000D_ * @param radius the radius of the fillet_x000D_ */_x000D_ private void addFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius)_x000D_ {_x000D_ double dx0 = p0.x - p.x;_x000D_ double dy0 = p0.y - p.y;_x000D_ double startAngle = Math.atan2(dy0, dx0);_x000D_ double dx1 = p1.x - p.x;_x000D_ double dy1 = p1.y - p.y;_x000D_ double endAngle = Math.atan2(dy1, dx1);_x000D_ _x000D_ if (direction == CGAlgorithms.CLOCKWISE) {_x000D_ if (startAngle <= endAngle) startAngle += 2.0 * Math.PI;_x000D_ }_x000D_ else { // direction == COUNTERCLOCKWISE_x000D_ if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI;_x000D_ }_x000D_ segList.addPt(p0);_x000D_ addFillet(p, startAngle, endAngle, direction, radius);_x000D_ segList.addPt(p1);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Adds points for a circular fillet arc_x000D_ * between two specified angles. _x000D_ * The start and end point for the fillet are not added -_x000D_ * the caller must add them if required._x000D_ *_x000D_ * @param direction is -1 for a CW angle, 1 for a CCW angle_x000D_ * @param radius the radius of the fillet_x000D_ */_x000D_ private void addFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius)_x000D_ {_x000D_ int directionFactor = direction == CGAlgorithms.CLOCKWISE ? -1 : 1;_x000D_ _x000D_ double totalAngle = Math.abs(startAngle - endAngle);_x000D_ int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5);_x000D_ _x000D_ if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do!_x000D_ _x000D_ double initAngle, currAngleInc;_x000D_ _x000D_ // choose angle increment so that each segment has equal length_x000D_ initAngle = 0.0;_x000D_ currAngleInc = totalAngle / nSegs;_x000D_ _x000D_ double currAngle = initAngle;_x000D_ Coordinate pt = new Coordinate();_x000D_ while (currAngle < totalAngle) {_x000D_ double angle = startAngle + directionFactor * currAngle;_x000D_ pt.x = p.x + radius * Math.cos(angle);_x000D_ pt.y = p.y + radius * Math.sin(angle);_x000D_ segList.addPt(pt);_x000D_ currAngle += currAngleInc;_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Creates a CW circle around a point_x000D_ */_x000D_ public void createCircle(Coordinate p)_x000D_ {_x000D_ // add start point_x000D_ Coordinate pt = new Coordinate(p.x + distance, p.y);_x000D_ segList.addPt(pt);_x000D_ addFillet(p, 0.0, 2.0 * Math.PI, -1, distance);_x000D_ segList.closeRing();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Creates a CW square around a point_x000D_ */_x000D_ public void createSquare(Coordinate p)_x000D_ {_x000D_ segList.addPt(new Coordinate(p.x + distance, p.y + distance));_x000D_ segList.addPt(new Coordinate(p.x + distance, p.y - distance));_x000D_ segList.addPt(new Coordinate(p.x - distance, p.y - distance));_x000D_ segList.addPt(new Coordinate(p.x - distance, p.y + distance));_x000D_ segList.closeRing();_x000D_ }_x000D_ }_x000D_
False
3,516
88901_3
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * 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, see <http://www.gnu.org/licenses/>. * **/ package lucee.servlet.pic; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lucee.commons.io.IOUtil; import lucee.runtime.net.http.ReqRspUtil; /** * Die Klasse PicServlet wird verwendet um Bilder darzustellen, alle Bilder die innerhalb des * Deployer angezeigt werden, werden ueber diese Klasse aus der lucee.jar Datei geladen, das macht * die Applikation flexibler und verlangt nicht das die Bilder fuer die Applikation an einem * bestimmten Ort abgelegt sein muessen. */ public final class PicServlet extends HttpServlet { /** * Verzeichnis in welchem die bilder liegen */ public final static String PIC_SOURCE = "/resource/img/"; /** * Interpretiert den Script-Name und laedt das entsprechende Bild aus den internen Resourcen. * * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { // get out Stream // pic String[] arrPath = (req.getServletPath()).split("\\."); String pic = PIC_SOURCE + "404.gif"; if (arrPath.length >= 3) { pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", "")); // mime type String mime = "image/" + arrPath[arrPath.length - 2]; ReqRspUtil.setContentType(rsp, mime); } // write data from pic input to response output OutputStream os = null; InputStream is = null; try { os = rsp.getOutputStream(); is = getClass().getResourceAsStream(pic); if (is == null) { is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif"); } byte[] buf = new byte[4 * 1024]; int nread = 0; while ((nread = is.read(buf)) >= 0) { os.write(buf, 0, nread); } } catch (FileNotFoundException e) {} catch (IOException e) {} finally { IOUtil.close(is, os); } } }
lucee/Lucee
core/src/main/java/lucee/servlet/pic/PicServlet.java
936
/** * Interpretiert den Script-Name und laedt das entsprechende Bild aus den internen Resourcen. * * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */
block_comment
nl
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * 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, see <http://www.gnu.org/licenses/>. * **/ package lucee.servlet.pic; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lucee.commons.io.IOUtil; import lucee.runtime.net.http.ReqRspUtil; /** * Die Klasse PicServlet wird verwendet um Bilder darzustellen, alle Bilder die innerhalb des * Deployer angezeigt werden, werden ueber diese Klasse aus der lucee.jar Datei geladen, das macht * die Applikation flexibler und verlangt nicht das die Bilder fuer die Applikation an einem * bestimmten Ort abgelegt sein muessen. */ public final class PicServlet extends HttpServlet { /** * Verzeichnis in welchem die bilder liegen */ public final static String PIC_SOURCE = "/resource/img/"; /** * Interpretiert den Script-Name<SUF>*/ @Override protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { // get out Stream // pic String[] arrPath = (req.getServletPath()).split("\\."); String pic = PIC_SOURCE + "404.gif"; if (arrPath.length >= 3) { pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", "")); // mime type String mime = "image/" + arrPath[arrPath.length - 2]; ReqRspUtil.setContentType(rsp, mime); } // write data from pic input to response output OutputStream os = null; InputStream is = null; try { os = rsp.getOutputStream(); is = getClass().getResourceAsStream(pic); if (is == null) { is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif"); } byte[] buf = new byte[4 * 1024]; int nread = 0; while ((nread = is.read(buf)) >= 0) { os.write(buf, 0, nread); } } catch (FileNotFoundException e) {} catch (IOException e) {} finally { IOUtil.close(is, os); } } }
False
804
203327_6
package be.ucll.workloadplanner; import static android.content.ContentValues.TAG; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; // Hoofdscherm waarin de verschillende fragmenten geladen worden public class MainActivity extends AppCompatActivity { private NavController navController; private FirebaseAuth firebaseAuth; private FirebaseFirestore db; private String userRole; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseAuth = FirebaseAuth.getInstance(); db = FirebaseFirestore.getInstance(); setSupportActionBar(findViewById(R.id.toolbar)); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); navController = navHostFragment.getNavController(); logCurrentUserId(); } // Controle ingelogde user om te checken of de login gewerkt heeft private void logCurrentUserId() { FirebaseUser user = getCurrentUser(); if (user != null) { String phoneNumber = user.getPhoneNumber(); if (phoneNumber != null) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("users").whereEqualTo("userId", phoneNumber) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String userId = documentSnapshot.getString("userId"); Log.d("MainActivity", "User ID: " + userId); getUserRole(userId); // Call to get user role after user ID retrieval } else { Log.d("MainActivity", "User document does not exist"); } }) .addOnFailureListener(e -> { Log.e("MainActivity", "Error getting user document", e); }); } else { Log.d("MainActivity", "No phone number associated with the current user"); } } else { Log.d("MainActivity", "No user is currently authenticated"); } } // Huidige gebruiker ophalen private FirebaseUser getCurrentUser() { return firebaseAuth.getCurrentUser(); } // Voor het weergeven van het menu rechtsboven @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // Hide or show menu items based on user role MenuItem homeItem = menu.findItem(R.id.action_home); MenuItem addTicketItem = menu.findItem(R.id.action_addTicket); MenuItem logoutItem = menu.findItem(R.id.action_logout); if (userRole != null && userRole.equals("Project Manager")) { homeItem.setVisible(true); addTicketItem.setVisible(true); logoutItem.setVisible(true); } else if (userRole != null && userRole.equals("Member")) { homeItem.setVisible(true); addTicketItem.setVisible(false); logoutItem.setVisible(true); } else { addTicketItem.setVisible(false); logoutItem.setVisible(false); } return true; } // Instellen van de opties van het menu @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_home) { navController.navigate(R.id.action_any_fragment_to_tickets); return true; } NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); if (navHostFragment != null) { Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment(); // Now you have the current fragment Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName()); if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) { if (item.getItemId() == R.id.action_addTicket) { Log.d("MainActivity", "Adding ticket..."); navController.navigate(R.id.action_any_fragment_to_addTicket); return true; } } } if (item.getItemId() == R.id.action_logout) { firebaseAuth.signOut(); Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null)); Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class); startActivity(loginIntent); finish(); return true; } return super.onOptionsItemSelected(item); } // De rol van de gebruiker opzoeken, member of project manager private void getUserRole(String userId) { FirebaseFirestore.getInstance() .collection("users") .whereEqualTo("userId", userId) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String role = documentSnapshot.getString("role"); if (role != null) { Log.d(TAG, "User id found: " + userId); Log.d(TAG, "User role found: " + role); userRole = role; // Update user role variable invalidateOptionsMenu(); // Refresh menu to reflect changes } else { Log.d(TAG, "Role field not found in user document"); } } else { Log.d(TAG, "User document not found for userId: " + userId); } }) .addOnFailureListener(e -> { Log.e(TAG, "Error fetching user document", e); }); } }
JanVHanssen/WorkloadPlanner
app/src/main/java/be/ucll/workloadplanner/MainActivity.java
1,848
// Instellen van de opties van het menu
line_comment
nl
package be.ucll.workloadplanner; import static android.content.ContentValues.TAG; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; // Hoofdscherm waarin de verschillende fragmenten geladen worden public class MainActivity extends AppCompatActivity { private NavController navController; private FirebaseAuth firebaseAuth; private FirebaseFirestore db; private String userRole; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseAuth = FirebaseAuth.getInstance(); db = FirebaseFirestore.getInstance(); setSupportActionBar(findViewById(R.id.toolbar)); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); navController = navHostFragment.getNavController(); logCurrentUserId(); } // Controle ingelogde user om te checken of de login gewerkt heeft private void logCurrentUserId() { FirebaseUser user = getCurrentUser(); if (user != null) { String phoneNumber = user.getPhoneNumber(); if (phoneNumber != null) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("users").whereEqualTo("userId", phoneNumber) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String userId = documentSnapshot.getString("userId"); Log.d("MainActivity", "User ID: " + userId); getUserRole(userId); // Call to get user role after user ID retrieval } else { Log.d("MainActivity", "User document does not exist"); } }) .addOnFailureListener(e -> { Log.e("MainActivity", "Error getting user document", e); }); } else { Log.d("MainActivity", "No phone number associated with the current user"); } } else { Log.d("MainActivity", "No user is currently authenticated"); } } // Huidige gebruiker ophalen private FirebaseUser getCurrentUser() { return firebaseAuth.getCurrentUser(); } // Voor het weergeven van het menu rechtsboven @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // Hide or show menu items based on user role MenuItem homeItem = menu.findItem(R.id.action_home); MenuItem addTicketItem = menu.findItem(R.id.action_addTicket); MenuItem logoutItem = menu.findItem(R.id.action_logout); if (userRole != null && userRole.equals("Project Manager")) { homeItem.setVisible(true); addTicketItem.setVisible(true); logoutItem.setVisible(true); } else if (userRole != null && userRole.equals("Member")) { homeItem.setVisible(true); addTicketItem.setVisible(false); logoutItem.setVisible(true); } else { addTicketItem.setVisible(false); logoutItem.setVisible(false); } return true; } // Instellen van<SUF> @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_home) { navController.navigate(R.id.action_any_fragment_to_tickets); return true; } NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); if (navHostFragment != null) { Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment(); // Now you have the current fragment Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName()); if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) { if (item.getItemId() == R.id.action_addTicket) { Log.d("MainActivity", "Adding ticket..."); navController.navigate(R.id.action_any_fragment_to_addTicket); return true; } } } if (item.getItemId() == R.id.action_logout) { firebaseAuth.signOut(); Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null)); Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class); startActivity(loginIntent); finish(); return true; } return super.onOptionsItemSelected(item); } // De rol van de gebruiker opzoeken, member of project manager private void getUserRole(String userId) { FirebaseFirestore.getInstance() .collection("users") .whereEqualTo("userId", userId) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String role = documentSnapshot.getString("role"); if (role != null) { Log.d(TAG, "User id found: " + userId); Log.d(TAG, "User role found: " + role); userRole = role; // Update user role variable invalidateOptionsMenu(); // Refresh menu to reflect changes } else { Log.d(TAG, "Role field not found in user document"); } } else { Log.d(TAG, "User document not found for userId: " + userId); } }) .addOnFailureListener(e -> { Log.e(TAG, "Error fetching user document", e); }); } }
True
1,508
37934_2
package nl.sbdeveloper.leastslack; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LeastSlack { private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)"); public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Geef een bestandsnaam mee!"); System.exit(0); return; } URL resource = LeastSlack.class.getClassLoader().getResource(args[0]); if (resource == null) { System.out.println("De meegegeven bestandsnaam bestaat niet!"); System.exit(0); return; } Scanner fileScanner = new Scanner(resource.openStream()); JobShop shop = new JobShop(); int jobs = 0; int machines = 0; int lowestMachine = Integer.MAX_VALUE; boolean wasFirstLine; int currentJob = 0; Matcher matcher; while (fileScanner.hasNextLine()) { matcher = pattern.matcher(fileScanner.nextLine()); wasFirstLine = false; if (jobs != 0 && machines != 0) { Job job = new Job(currentJob); shop.getJobs().add(job); } while (matcher.find()) { if (jobs == 0 || machines == 0) { jobs = Integer.parseInt(matcher.group(1)); machines = Integer.parseInt(matcher.group(2)); wasFirstLine = true; break; } else { int id = Integer.parseInt(matcher.group(1)); int duration = Integer.parseInt(matcher.group(2)); if (id < lowestMachine) lowestMachine = id; Task task = new Task(id, duration); int finalCurrentJob = currentJob; Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst(); if (jobOpt.isEmpty()) break; jobOpt.get().getTasks().add(task); } } if (!wasFirstLine) currentJob++; } fileScanner.close(); ////////////////////////////////// shop.getJobs().forEach(Job::calculateEarliestStart); shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration)) .ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration()))); shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } //TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine //TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80. // int loop = 0; int time = 0; // while (loop < 40) { while (!shop.isAllJobsDone()) { // loop++; System.out.println("------START------"); List<Job> conflictedJobs = new ArrayList<>(); int smallestTaskDuration = Integer.MAX_VALUE; Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) { if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip! pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID())); conflictedJobs.add(pair.getKey()); continue; } System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + "."); pair.getValue().setDone(true); pair.getKey().setBeginTime(time); foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration()); if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration(); } for (Job job : conflictedJobs) { job.calculateEarliestStart(); } if (!conflictedJobs.isEmpty()) { shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } } if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden. time += smallestTaskDuration; for (Job j : shop.getJobs()) { if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time); } System.out.println("Time: " + time); } for (Job j : shop.getJobs()) { System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime()); } } }
SBDPlugins/LeastSlackTime-OSM
src/main/java/nl/sbdeveloper/leastslack/LeastSlack.java
1,705
// int loop = 0;
line_comment
nl
package nl.sbdeveloper.leastslack; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LeastSlack { private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)"); public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Geef een bestandsnaam mee!"); System.exit(0); return; } URL resource = LeastSlack.class.getClassLoader().getResource(args[0]); if (resource == null) { System.out.println("De meegegeven bestandsnaam bestaat niet!"); System.exit(0); return; } Scanner fileScanner = new Scanner(resource.openStream()); JobShop shop = new JobShop(); int jobs = 0; int machines = 0; int lowestMachine = Integer.MAX_VALUE; boolean wasFirstLine; int currentJob = 0; Matcher matcher; while (fileScanner.hasNextLine()) { matcher = pattern.matcher(fileScanner.nextLine()); wasFirstLine = false; if (jobs != 0 && machines != 0) { Job job = new Job(currentJob); shop.getJobs().add(job); } while (matcher.find()) { if (jobs == 0 || machines == 0) { jobs = Integer.parseInt(matcher.group(1)); machines = Integer.parseInt(matcher.group(2)); wasFirstLine = true; break; } else { int id = Integer.parseInt(matcher.group(1)); int duration = Integer.parseInt(matcher.group(2)); if (id < lowestMachine) lowestMachine = id; Task task = new Task(id, duration); int finalCurrentJob = currentJob; Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst(); if (jobOpt.isEmpty()) break; jobOpt.get().getTasks().add(task); } } if (!wasFirstLine) currentJob++; } fileScanner.close(); ////////////////////////////////// shop.getJobs().forEach(Job::calculateEarliestStart); shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration)) .ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration()))); shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } //TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine //TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80. // int loop<SUF> int time = 0; // while (loop < 40) { while (!shop.isAllJobsDone()) { // loop++; System.out.println("------START------"); List<Job> conflictedJobs = new ArrayList<>(); int smallestTaskDuration = Integer.MAX_VALUE; Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) { if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip! pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID())); conflictedJobs.add(pair.getKey()); continue; } System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + "."); pair.getValue().setDone(true); pair.getKey().setBeginTime(time); foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration()); if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration(); } for (Job job : conflictedJobs) { job.calculateEarliestStart(); } if (!conflictedJobs.isEmpty()) { shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } } if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden. time += smallestTaskDuration; for (Job j : shop.getJobs()) { if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time); } System.out.println("Time: " + time); } for (Job j : shop.getJobs()) { System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime()); } } }
True
1,356
4744_9
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-2dook
DemoWorld.java
3,194
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van<SUF> // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
True
2,193
55393_3
/* * SPDX-FileCopyrightText: 2021 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.zgw.drc.model; import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS; import java.net.URI; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.UUID; import javax.json.bind.annotation.JsonbDateFormat; import javax.json.bind.annotation.JsonbProperty; import javax.json.bind.annotation.JsonbTransient; import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding; import net.atos.client.zgw.shared.util.URIUtil; /** * */ public abstract class AbstractEnkelvoudigInformatieobject { public static final int IDENTIFICATIE_MAX_LENGTH = 40; public static final int TITEL_MAX_LENGTH = 200; public static final int BESTANDSNAAM_MAX_LENGTH = 255; public static final int FORMAAT_MAX_LENGTH = 255; public static final int AUTEUR_MAX_LENGTH = 200; public static final int BESCHRIJVING_MAX_LENGTH = 1000; /** * URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object. */ private URI url; /** * Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT. * maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH} */ private String identificatie; /** * Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen * en als eerste in een samenwerkingsketen heeft vastgelegd. */ private String bronorganisatie; /** * Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT */ private LocalDate creatiedatum; /** * De naam waaronder het INFORMATIEOBJECT formeel bekend is. * maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH} */ private String titel; /** * Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is */ private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding; /** * De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT * maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH} */ private String auteur; /** * Aanduiding van de stand van zaken van een INFORMATIEOBJECT. * De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien. * Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben */ private InformatieobjectStatus status; /** * Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand. * Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml * maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH} */ private String formaat; /** * Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd. * Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html * maxLength: 3 * minLength: 3 */ private String taal; /** * Het (automatische) versienummer van het INFORMATIEOBJECT. * Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt. */ private Integer versie; /** * Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd. */ @JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS) private ZonedDateTime beginRegistratie; /** * De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie. * maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH} */ private String bestandsnaam; /** * Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt. */ private Long bestandsomvang; /** * De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen */ private URI link; /** * Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT. * maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH} */ private String beschrijving; /** * De datum waarop het INFORMATIEOBJECT ontvangen is. * Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn. * Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn * waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt. */ @JsonbProperty(nillable = true) private LocalDate ontvangstdatum; /** * De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is. * Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen. * Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn. * Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn * waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt. */ @JsonbProperty(nillable = true) private LocalDate verzenddatum; /** * Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging. * Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is. * Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource. */ private Boolean indicatieGebruiksrecht; /** * Aanduiding van de rechtskracht van een informatieobject. * Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft. */ private Ondertekening ondertekening; /** * Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand. */ private Integriteit integriteit; /** * URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API). */ private URI informatieobjecttype; /** * Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden. */ private Boolean locked; public URI getUrl() { return url; } public void setUrl(final URI url) { this.url = url; } public String getIdentificatie() { return identificatie; } public void setIdentificatie(final String identificatie) { this.identificatie = identificatie; } public String getBronorganisatie() { return bronorganisatie; } public void setBronorganisatie(final String bronorganisatie) { this.bronorganisatie = bronorganisatie; } public LocalDate getCreatiedatum() { return creatiedatum; } public void setCreatiedatum(final LocalDate creatiedatum) { this.creatiedatum = creatiedatum; } public String getTitel() { return titel; } public void setTitel(final String titel) { this.titel = titel; } public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() { return vertrouwelijkheidaanduiding; } public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) { this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding; } public String getAuteur() { return auteur; } public void setAuteur(final String auteur) { this.auteur = auteur; } public InformatieobjectStatus getStatus() { return status; } public void setStatus(final InformatieobjectStatus status) { this.status = status; } public String getFormaat() { return formaat; } public void setFormaat(final String formaat) { this.formaat = formaat; } public String getTaal() { return taal; } public void setTaal(final String taal) { this.taal = taal; } public Integer getVersie() { return versie; } public void setVersie(final Integer versie) { this.versie = versie; } public ZonedDateTime getBeginRegistratie() { return beginRegistratie; } public void setBeginRegistratie(final ZonedDateTime beginRegistratie) { this.beginRegistratie = beginRegistratie; } public String getBestandsnaam() { return bestandsnaam; } public void setBestandsnaam(final String bestandsnaam) { this.bestandsnaam = bestandsnaam; } public Long getBestandsomvang() { return bestandsomvang; } public void setBestandsomvang(final Long bestandsomvang) { this.bestandsomvang = bestandsomvang; } public URI getLink() { return link; } public void setLink(final URI link) { this.link = link; } public String getBeschrijving() { return beschrijving; } public void setBeschrijving(final String beschrijving) { this.beschrijving = beschrijving; } public LocalDate getOntvangstdatum() { return ontvangstdatum; } public void setOntvangstdatum(final LocalDate ontvangstdatum) { this.ontvangstdatum = ontvangstdatum; } public LocalDate getVerzenddatum() { return verzenddatum; } public void setVerzenddatum(final LocalDate verzenddatum) { this.verzenddatum = verzenddatum; } public Boolean getIndicatieGebruiksrecht() { return indicatieGebruiksrecht; } public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) { this.indicatieGebruiksrecht = indicatieGebruiksrecht; } public Ondertekening getOndertekening() { if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) { return null; } return ondertekening; } public void setOndertekening(final Ondertekening ondertekening) { this.ondertekening = ondertekening; } public Integriteit getIntegriteit() { return integriteit; } public void setIntegriteit(final Integriteit integriteit) { this.integriteit = integriteit; } public URI getInformatieobjecttype() { return informatieobjecttype; } public void setInformatieobjecttype(final URI informatieobjecttype) { this.informatieobjecttype = informatieobjecttype; } public Boolean getLocked() { return locked; } public void setLocked(final Boolean locked) { this.locked = locked; } @JsonbTransient public UUID getUUID() { return URIUtil.parseUUIDFromResourceURI(url); } @JsonbTransient public UUID getInformatieobjectTypeUUID() { return URIUtil.parseUUIDFromResourceURI(informatieobjecttype); } }
bartlukens/zaakafhandelcomponent
src/main/java/net/atos/client/zgw/drc/model/AbstractEnkelvoudigInformatieobject.java
3,539
/** * Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen * en als eerste in een samenwerkingsketen heeft vastgelegd. */
block_comment
nl
/* * SPDX-FileCopyrightText: 2021 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.zgw.drc.model; import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS; import java.net.URI; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.UUID; import javax.json.bind.annotation.JsonbDateFormat; import javax.json.bind.annotation.JsonbProperty; import javax.json.bind.annotation.JsonbTransient; import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding; import net.atos.client.zgw.shared.util.URIUtil; /** * */ public abstract class AbstractEnkelvoudigInformatieobject { public static final int IDENTIFICATIE_MAX_LENGTH = 40; public static final int TITEL_MAX_LENGTH = 200; public static final int BESTANDSNAAM_MAX_LENGTH = 255; public static final int FORMAAT_MAX_LENGTH = 255; public static final int AUTEUR_MAX_LENGTH = 200; public static final int BESCHRIJVING_MAX_LENGTH = 1000; /** * URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object. */ private URI url; /** * Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT. * maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH} */ private String identificatie; /** * Het RSIN van<SUF>*/ private String bronorganisatie; /** * Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT */ private LocalDate creatiedatum; /** * De naam waaronder het INFORMATIEOBJECT formeel bekend is. * maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH} */ private String titel; /** * Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is */ private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding; /** * De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT * maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH} */ private String auteur; /** * Aanduiding van de stand van zaken van een INFORMATIEOBJECT. * De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien. * Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben */ private InformatieobjectStatus status; /** * Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand. * Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml * maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH} */ private String formaat; /** * Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd. * Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html * maxLength: 3 * minLength: 3 */ private String taal; /** * Het (automatische) versienummer van het INFORMATIEOBJECT. * Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt. */ private Integer versie; /** * Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd. */ @JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS) private ZonedDateTime beginRegistratie; /** * De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie. * maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH} */ private String bestandsnaam; /** * Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt. */ private Long bestandsomvang; /** * De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen */ private URI link; /** * Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT. * maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH} */ private String beschrijving; /** * De datum waarop het INFORMATIEOBJECT ontvangen is. * Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn. * Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn * waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt. */ @JsonbProperty(nillable = true) private LocalDate ontvangstdatum; /** * De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is. * Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen. * Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn. * Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn * waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt. */ @JsonbProperty(nillable = true) private LocalDate verzenddatum; /** * Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging. * Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is. * Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource. */ private Boolean indicatieGebruiksrecht; /** * Aanduiding van de rechtskracht van een informatieobject. * Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft. */ private Ondertekening ondertekening; /** * Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand. */ private Integriteit integriteit; /** * URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API). */ private URI informatieobjecttype; /** * Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden. */ private Boolean locked; public URI getUrl() { return url; } public void setUrl(final URI url) { this.url = url; } public String getIdentificatie() { return identificatie; } public void setIdentificatie(final String identificatie) { this.identificatie = identificatie; } public String getBronorganisatie() { return bronorganisatie; } public void setBronorganisatie(final String bronorganisatie) { this.bronorganisatie = bronorganisatie; } public LocalDate getCreatiedatum() { return creatiedatum; } public void setCreatiedatum(final LocalDate creatiedatum) { this.creatiedatum = creatiedatum; } public String getTitel() { return titel; } public void setTitel(final String titel) { this.titel = titel; } public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() { return vertrouwelijkheidaanduiding; } public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) { this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding; } public String getAuteur() { return auteur; } public void setAuteur(final String auteur) { this.auteur = auteur; } public InformatieobjectStatus getStatus() { return status; } public void setStatus(final InformatieobjectStatus status) { this.status = status; } public String getFormaat() { return formaat; } public void setFormaat(final String formaat) { this.formaat = formaat; } public String getTaal() { return taal; } public void setTaal(final String taal) { this.taal = taal; } public Integer getVersie() { return versie; } public void setVersie(final Integer versie) { this.versie = versie; } public ZonedDateTime getBeginRegistratie() { return beginRegistratie; } public void setBeginRegistratie(final ZonedDateTime beginRegistratie) { this.beginRegistratie = beginRegistratie; } public String getBestandsnaam() { return bestandsnaam; } public void setBestandsnaam(final String bestandsnaam) { this.bestandsnaam = bestandsnaam; } public Long getBestandsomvang() { return bestandsomvang; } public void setBestandsomvang(final Long bestandsomvang) { this.bestandsomvang = bestandsomvang; } public URI getLink() { return link; } public void setLink(final URI link) { this.link = link; } public String getBeschrijving() { return beschrijving; } public void setBeschrijving(final String beschrijving) { this.beschrijving = beschrijving; } public LocalDate getOntvangstdatum() { return ontvangstdatum; } public void setOntvangstdatum(final LocalDate ontvangstdatum) { this.ontvangstdatum = ontvangstdatum; } public LocalDate getVerzenddatum() { return verzenddatum; } public void setVerzenddatum(final LocalDate verzenddatum) { this.verzenddatum = verzenddatum; } public Boolean getIndicatieGebruiksrecht() { return indicatieGebruiksrecht; } public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) { this.indicatieGebruiksrecht = indicatieGebruiksrecht; } public Ondertekening getOndertekening() { if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) { return null; } return ondertekening; } public void setOndertekening(final Ondertekening ondertekening) { this.ondertekening = ondertekening; } public Integriteit getIntegriteit() { return integriteit; } public void setIntegriteit(final Integriteit integriteit) { this.integriteit = integriteit; } public URI getInformatieobjecttype() { return informatieobjecttype; } public void setInformatieobjecttype(final URI informatieobjecttype) { this.informatieobjecttype = informatieobjecttype; } public Boolean getLocked() { return locked; } public void setLocked(final Boolean locked) { this.locked = locked; } @JsonbTransient public UUID getUUID() { return URIUtil.parseUUIDFromResourceURI(url); } @JsonbTransient public UUID getInformatieobjectTypeUUID() { return URIUtil.parseUUIDFromResourceURI(informatieobjecttype); } }
True
4,728
84602_23
/* * Social World * Copyright (C) 2014 Mathias Sikos * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * or see http://www.gnu.org/licenses/gpl-2.0.html * */ package org.socialworld.actions; import org.socialworld.GlobalSwitches; import org.socialworld.attributes.Time; import org.socialworld.calculation.IObjectReceiver; import org.socialworld.calculation.IObjectSender; import org.socialworld.calculation.NoObject; import org.socialworld.calculation.ObjectRequester; import org.socialworld.calculation.SimulationCluster; import org.socialworld.calculation.Type; import org.socialworld.calculation.Value; import org.socialworld.collections.ValueArrayList; import org.socialworld.core.Event; import org.socialworld.core.IEventParam; import org.socialworld.core.Simulation; import org.socialworld.objects.SimulationObject; import org.socialworld.objects.access.HiddenSimulationObject; /** * @author Mathias Sikos (MatWorsoc) * * It's the base class for all simulation actions (actions done by simulation * objects). It collects all base action attributes. That are action type, * action mode, priority, earliest execution time, latest execution time, * duration, remained duration, intensity. * * * German: * AbstractAction ist die Basisklasse (abstrakte Klasse) für Aktionen der Simlationsobjekte. * Die Aktionsobjekte von abgeleiteten Klassen werden im ActionMaster verwaltet * und vom ActionHandler zur Ausführung gebracht. * * Die Ausführung besteht dabei aus 2 Schritten * a) Einleitung der Ausführung * b) Wirksamwerden der Aktion * * a) Einleitung der Ausführung: * Der ActionMaster führt die ActionHandler aller Simulationsobjekte * und weist den jeweiligen ActionHandler an, mit der Ausführung einer Aktion zu beginnen bzw. eine Aktion fortzusetzen. * Der ActionHandler sorgt dafür, * dass für das auszuführende Aktionsobjekt (Ableitung von AbstractAction) die Methode perform() aufgerufen wird. * Die Methode perform() ist abstract und muss in allen Ableitungen implementiert werden/sein. * Die Methode perform() führt Vorabprüfungen der Daten zur Aktion durch, * erzeugt das zugehörige Performer-Objekt (siehe Schritt b), * erzeugt die auszulösenden Ereignisse, * fügt den Ereignissen das Performerobjekt als Ereigniseigenschaft hinzu, * und trägt diese in die Ereignisverwaltung (EventMaster) ein (siehe Schritt b). * * b) Wirksamwerden der Aktion * Es gilt der Grundsatz, dass alle Aktionen durch ihre Ereignisverarbeitung wirksam werden. * Im Schritt a) wurden Ereignisse zu den Aktionen in die Ereignisverwaltung eingetragen. * Die Ereignisverwaltung arbeitet die Ereignisse nach ihren Regeln ab. * Für jedes Event wird die evaluate-Methode des dem Ereignis zugeordenten Performers (Ableitung der Klasse ActionPerformer) aufgerufen. * Diese wiederum ruft die Methode perform im Performerobjekt auf. * Diese Methode ermittelt die für die Ereignisverarbeitung benötigten Werte * aus dem Aktionsobjekt, dem ausführenden Objekt (also dem Akteur) und ggf. dem Zielobjekt. * Diese Werte werden standardisiert in einer Liste abgelegt * und können vom Ereignis über Standardmethoden ausgelesen werden. * Schließlich werden für die Ereignisse ihre Wirkung auf die Simulationsobjekte und ggf. Reaktionen ermittelt. * * Die Klasse AbstractAction ist die Basisklasse für die Aktionsobjekte des Schrittes a), * enthält also die Daten für die Einleitung der Ausführung (Erzeugung von Performer und Event). * */ public abstract class AbstractAction implements IObjectSender, IObjectReceiver { public static final int MAX_ACTION_PRIORITY = 256; protected SimulationObject actor; private HiddenSimulationObject hiddenWriteAccesToActor; protected ActionType type; protected ActionMode mode; protected Time minTime; protected Time maxTime; protected int priority; protected float intensity; protected long duration; protected long remainedDuration; protected boolean interruptable = false; protected boolean interrupted = false; protected boolean done = false; private Simulation simulation = Simulation.getInstance(); protected AbstractAction linkedAction; static private String[] standardPropertyNames = ActionType.getStandardPropertyNames(); protected final String[] furtherPropertyNames; protected ObjectRequester objectRequester = new ObjectRequester(); protected AbstractAction() { this.type = ActionType.ignore; this.furtherPropertyNames = this.type.getFurtherPropertyNames(); } public AbstractAction(AbstractAction original) { setBaseProperties(original); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(original); } protected AbstractAction(ValueArrayList actionProperties) { setBaseProperties(actionProperties); this.furtherPropertyNames = this.type.getFurtherPropertyNames(); setFurtherProperties(actionProperties); } public void setActor(SimulationObject actor, HiddenSimulationObject hiddenWriteAccess) { this.hiddenWriteAccesToActor = hiddenWriteAccess; this.actor = actor; } public final void removeWriteAccess() { this.hiddenWriteAccesToActor = null; } protected final HiddenSimulationObject getHiddenWriteAccessToActor(AbstractAction concreteAction) { if (this == concreteAction ) return hiddenWriteAccesToActor; else // dummy return new HiddenSimulationObject(); } public boolean isToBeIgnored() { return (type == ActionType.ignore); } private void setBaseProperties(ValueArrayList actionProperties) { ActionType type; ActionMode mode; float intensity; Time minTime, maxTime; int priority; long duration; Value v; Object o; v = actionProperties.getValue( standardPropertyNames[0]); o = v.getObject(Type.actionType); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > type: o (getObject(Type.actionType)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { type = (ActionType) o; } v = actionProperties.getValue( standardPropertyNames[1]); o = v.getObject(Type.actionMode); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > mode: o (getObject(Type.actionMode)) is NoObject " + ((NoObject)o).getReason().toString() ); } return; } else { mode = (ActionMode) o; } v = actionProperties.getValue( standardPropertyNames[2]); o = v.getObject(Type.floatingpoint); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > intensity: o (getObject(Type.floatingpoint)) is NoObject " + ((NoObject)o).getReason().toString() ); } intensity = 0; } else { intensity = (float) o; } v = actionProperties.getValue( standardPropertyNames[3]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > minTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } minTime = new Time(); } else { minTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[4]); o = v.getObject(Type.time); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > maxTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() ); } maxTime = new Time(); } else { maxTime = (Time) o; } v = actionProperties.getValue( standardPropertyNames[5]); o = v.getObject(Type.integer); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > priority: o (getObject(Type.integer)) is NoObject " + ((NoObject)o).getReason().toString() ); } priority = 0; } else { priority = (int) o; } v = actionProperties.getValue( standardPropertyNames[6]); o = v.getObject(Type.longinteger); if (o instanceof NoObject) { if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) { System.out.println("AbstractAction.setBaseProperties > duration: o (getObject(Type.longinteger)) is NoObject " + ((NoObject)o).getReason().toString() ); } duration = 0; } else { duration = (long) o; } this.setType(type); this.setMode(mode); this.setIntensity(intensity); this.setMinTime(minTime); this.setMaxTime(maxTime); this.setPriority(priority); this.setDuration(duration); this.setRemainedDuration(duration); this.linkedAction = null; if (duration > 0) interruptable = true; } protected abstract void setFurtherProperties(ValueArrayList actionProperties); protected void setBaseProperties(AbstractAction original) { this.type = original.type; this.mode = original.mode; this.intensity = original.intensity; this.minTime = original.minTime; this.maxTime = original.maxTime; this.priority = original.priority; this.duration = original.duration; } protected abstract void setFurtherProperties(AbstractAction original); public abstract void perform(); protected void addEvent(Event event) { simulation.getEventMaster().addEvent(event); } /** * The method sets the linked action. * * @param linked action */ public void setLinkedAction (AbstractAction linkedAction) { this.linkedAction = linkedAction; } /** * The method returns the linked action. * It is null if there is no linked action. * * @return linked action */ public AbstractAction getLinkedAction() { return linkedAction; } public SimulationObject getActor() { return actor; } public void setDone() { done = true; } public boolean isDone() { return done; } public boolean isInterruptable() { return interruptable; } public boolean isInterrupted() { return interrupted; } public void interrupt() { this.setDuration(remainedDuration); this.setRemainedDuration(0); this.interrupted = true; } public void continueAfterInterrupt() { this.setRemainedDuration(duration); this.interrupted = false; } public void requestPropertyList(IEventParam paramObject) { ValueArrayList propertiesAsValueList = new ValueArrayList(); propertiesAsValueList.add(new Value(Type.floatingpoint, Value.VALUE_BY_NAME_ACTION_INTENSITY, this.intensity)); paramObject.answerPropertiesRequest(propertiesAsValueList); } /** * The methods returns the action type. * * @return type */ public ActionType getType() { return this.type; } /** * @param type * the type to set */ public void setType(final ActionType type) { this.type = type; } /** * @return the time */ public Time getMinTime() { return this.minTime; } /** * @param time * the time to set */ public void setMinTime(final Time time) { this.minTime = time; } /** * @return the time */ public Time getMaxTime() { return this.maxTime; } /** * @param time * the time to set */ public void setMaxTime(final Time time) { this.maxTime = time; } /** * The methods returns the action's priority. * * @return priority */ public int getPriority() { return this.priority; } /** * @param priority * the priority to set */ public void setPriority(final int priority) { this.priority = priority; } /** * @return the mode */ public ActionMode getMode() { return this.mode; } /** * @param mode * the mode to set */ public void setMode(final ActionMode mode) { this.mode = mode; } /** * @return the intensity */ public float getIntensity() { return this.intensity; } /** * @param intensity * the intensity to set */ public void setIntensity(final float intensity) { this.intensity = intensity; } /** * @return the duration */ public long getDuration() { return this.duration; } /** * @param duration * the duration to set */ public void setDuration(final long duration) { this.duration = duration; } /** * The methods returns the action's remained duration. * * @return remainedDuration */ public long getRemainedDuration() { return this.remainedDuration; } /** * @param remainedDuration * the remainedDuration to set */ public void setRemainedDuration(final long remainedDuration) { this.remainedDuration = remainedDuration; } /** * The method decrements the attribute remainedDuration. That means, an * action needs less time to complete. * * @param decrement */ public void lowerRemainedDuration(final long decrement) { this.remainedDuration -= decrement; // System.out.println("AbstractAction.lowerRemainedDuration(): " + toString() + " " + actor.toString() + " noch offen: " + this.remainedDuration); if (this.remainedDuration <= 0) done = true; } /** * The method increments the attribute remainedDuration. That means, an * action needs more time to complete. * * @param increment */ public void raiseRemainedDuration(final long increment) { this.remainedDuration += increment; } @Override public String toString() { return "(" + this.type.toString() + ")"; //$NON-NLS-1$ } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectSender /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public int sendYourselfTo(IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public int sendYourselfTo(SimulationCluster cluster, IObjectReceiver receiver, int requestID) { return receiver.receiveObject(requestID, this); } public IObjectSender copy() { return this; } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////implementing IObjectReceiver /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// @Override public int receiveObject(int requestID, Object object) { objectRequester.receive(requestID, object); return 0; } }
worsoc/socialworld
src/main/java/org/socialworld/actions/AbstractAction.java
4,863
//////////////////////implementing IObjectSender ///////////////////////////////////////_x000D_
line_comment
nl
/*_x000D_ * Social World_x000D_ * Copyright (C) 2014 Mathias Sikos_x000D_ *_x000D_ * This program is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU General Public License_x000D_ * as published by the Free Software Foundation; either version 2_x000D_ * of the License, or (at your option) any later version._x000D_ *_x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with this program; if not, write to the Free Software_x000D_ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. _x000D_ *_x000D_ * or see http://www.gnu.org/licenses/gpl-2.0.html_x000D_ *_x000D_ */_x000D_ package org.socialworld.actions;_x000D_ _x000D_ _x000D_ import org.socialworld.GlobalSwitches;_x000D_ import org.socialworld.attributes.Time;_x000D_ import org.socialworld.calculation.IObjectReceiver;_x000D_ import org.socialworld.calculation.IObjectSender;_x000D_ import org.socialworld.calculation.NoObject;_x000D_ import org.socialworld.calculation.ObjectRequester;_x000D_ import org.socialworld.calculation.SimulationCluster;_x000D_ import org.socialworld.calculation.Type;_x000D_ import org.socialworld.calculation.Value;_x000D_ import org.socialworld.collections.ValueArrayList;_x000D_ import org.socialworld.core.Event;_x000D_ import org.socialworld.core.IEventParam;_x000D_ import org.socialworld.core.Simulation;_x000D_ import org.socialworld.objects.SimulationObject;_x000D_ import org.socialworld.objects.access.HiddenSimulationObject;_x000D_ _x000D_ /**_x000D_ * @author Mathias Sikos (MatWorsoc)_x000D_ * _x000D_ * It's the base class for all simulation actions (actions done by simulation_x000D_ * objects). It collects all base action attributes. That are action type,_x000D_ * action mode, priority, earliest execution time, latest execution time,_x000D_ * duration, remained duration, intensity._x000D_ * _x000D_ * _x000D_ * German:_x000D_ * AbstractAction ist die Basisklasse (abstrakte Klasse) für Aktionen der Simlationsobjekte._x000D_ * Die Aktionsobjekte von abgeleiteten Klassen werden im ActionMaster verwaltet _x000D_ * und vom ActionHandler zur Ausführung gebracht._x000D_ * _x000D_ * Die Ausführung besteht dabei aus 2 Schritten_x000D_ * a) Einleitung der Ausführung_x000D_ * b) Wirksamwerden der Aktion_x000D_ * _x000D_ * a) Einleitung der Ausführung:_x000D_ * Der ActionMaster führt die ActionHandler aller Simulationsobjekte_x000D_ * und weist den jeweiligen ActionHandler an, mit der Ausführung einer Aktion zu beginnen bzw. eine Aktion fortzusetzen._x000D_ * Der ActionHandler sorgt dafür, _x000D_ * dass für das auszuführende Aktionsobjekt (Ableitung von AbstractAction) die Methode perform() aufgerufen wird._x000D_ * Die Methode perform() ist abstract und muss in allen Ableitungen implementiert werden/sein._x000D_ * Die Methode perform() führt Vorabprüfungen der Daten zur Aktion durch, _x000D_ * erzeugt das zugehörige Performer-Objekt (siehe Schritt b),_x000D_ * erzeugt die auszulösenden Ereignisse, _x000D_ * fügt den Ereignissen das Performerobjekt als Ereigniseigenschaft hinzu,_x000D_ * und trägt diese in die Ereignisverwaltung (EventMaster) ein (siehe Schritt b)._x000D_ * _x000D_ * b) Wirksamwerden der Aktion_x000D_ * Es gilt der Grundsatz, dass alle Aktionen durch ihre Ereignisverarbeitung wirksam werden._x000D_ * Im Schritt a) wurden Ereignisse zu den Aktionen in die Ereignisverwaltung eingetragen._x000D_ * Die Ereignisverwaltung arbeitet die Ereignisse nach ihren Regeln ab._x000D_ * Für jedes Event wird die evaluate-Methode des dem Ereignis zugeordenten Performers (Ableitung der Klasse ActionPerformer) aufgerufen._x000D_ * Diese wiederum ruft die Methode perform im Performerobjekt auf._x000D_ * Diese Methode ermittelt die für die Ereignisverarbeitung benötigten Werte _x000D_ * aus dem Aktionsobjekt, dem ausführenden Objekt (also dem Akteur) und ggf. dem Zielobjekt. _x000D_ * Diese Werte werden standardisiert in einer Liste abgelegt _x000D_ * und können vom Ereignis über Standardmethoden ausgelesen werden._x000D_ * Schließlich werden für die Ereignisse ihre Wirkung auf die Simulationsobjekte und ggf. Reaktionen ermittelt._x000D_ * _x000D_ * Die Klasse AbstractAction ist die Basisklasse für die Aktionsobjekte des Schrittes a), _x000D_ * enthält also die Daten für die Einleitung der Ausführung (Erzeugung von Performer und Event)._x000D_ * _x000D_ */_x000D_ public abstract class AbstractAction implements IObjectSender, IObjectReceiver {_x000D_ public static final int MAX_ACTION_PRIORITY = 256;_x000D_ _x000D_ _x000D_ protected SimulationObject actor;_x000D_ private HiddenSimulationObject hiddenWriteAccesToActor;_x000D_ _x000D_ protected ActionType type;_x000D_ protected ActionMode mode;_x000D_ protected Time minTime;_x000D_ protected Time maxTime;_x000D_ protected int priority;_x000D_ protected float intensity;_x000D_ protected long duration;_x000D_ protected long remainedDuration;_x000D_ _x000D_ protected boolean interruptable = false;_x000D_ protected boolean interrupted = false;_x000D_ protected boolean done = false;_x000D_ _x000D_ private Simulation simulation = Simulation.getInstance();_x000D_ _x000D_ protected AbstractAction linkedAction;_x000D_ _x000D_ static private String[] standardPropertyNames = ActionType.getStandardPropertyNames();_x000D_ protected final String[] furtherPropertyNames;_x000D_ _x000D_ protected ObjectRequester objectRequester = new ObjectRequester();_x000D_ _x000D_ protected AbstractAction() {_x000D_ this.type = ActionType.ignore;_x000D_ this.furtherPropertyNames = this.type.getFurtherPropertyNames();_x000D_ }_x000D_ _x000D_ _x000D_ public AbstractAction(AbstractAction original) {_x000D_ setBaseProperties(original);_x000D_ this.furtherPropertyNames = this.type.getFurtherPropertyNames();_x000D_ setFurtherProperties(original);_x000D_ }_x000D_ _x000D_ protected AbstractAction(ValueArrayList actionProperties) {_x000D_ setBaseProperties(actionProperties);_x000D_ this.furtherPropertyNames = this.type.getFurtherPropertyNames();_x000D_ setFurtherProperties(actionProperties);_x000D_ }_x000D_ _x000D_ public void setActor(SimulationObject actor, HiddenSimulationObject hiddenWriteAccess) {_x000D_ this.hiddenWriteAccesToActor = hiddenWriteAccess;_x000D_ this.actor = actor;_x000D_ }_x000D_ _x000D_ public final void removeWriteAccess() {_x000D_ this.hiddenWriteAccesToActor = null;_x000D_ }_x000D_ _x000D_ protected final HiddenSimulationObject getHiddenWriteAccessToActor(AbstractAction concreteAction) {_x000D_ if (this == concreteAction )_x000D_ return hiddenWriteAccesToActor;_x000D_ else_x000D_ // dummy_x000D_ return new HiddenSimulationObject();_x000D_ }_x000D_ _x000D_ public boolean isToBeIgnored() {_x000D_ return (type == ActionType.ignore);_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ private void setBaseProperties(ValueArrayList actionProperties) {_x000D_ _x000D_ ActionType type;_x000D_ ActionMode mode;_x000D_ float intensity;_x000D_ Time minTime, maxTime;_x000D_ int priority;_x000D_ long duration;_x000D_ _x000D_ Value v;_x000D_ Object o;_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[0]);_x000D_ o = v.getObject(Type.actionType);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > type: o (getObject(Type.actionType)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ return;_x000D_ }_x000D_ else {_x000D_ type = (ActionType) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[1]);_x000D_ o = v.getObject(Type.actionMode);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > mode: o (getObject(Type.actionMode)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ return;_x000D_ }_x000D_ else {_x000D_ mode = (ActionMode) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[2]);_x000D_ o = v.getObject(Type.floatingpoint);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > intensity: o (getObject(Type.floatingpoint)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ intensity = 0;_x000D_ }_x000D_ else {_x000D_ intensity = (float) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[3]);_x000D_ o = v.getObject(Type.time);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > minTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ minTime = new Time();_x000D_ }_x000D_ else {_x000D_ minTime = (Time) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[4]);_x000D_ o = v.getObject(Type.time);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > maxTime: o (getObject(Type.time)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ maxTime = new Time();_x000D_ }_x000D_ else {_x000D_ maxTime = (Time) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[5]);_x000D_ o = v.getObject(Type.integer);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > priority: o (getObject(Type.integer)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ priority = 0;_x000D_ }_x000D_ else {_x000D_ priority = (int) o;_x000D_ }_x000D_ _x000D_ v = actionProperties.getValue( standardPropertyNames[6]);_x000D_ o = v.getObject(Type.longinteger);_x000D_ if (o instanceof NoObject) {_x000D_ if (GlobalSwitches.OUTPUT_DEBUG_GETOBJECT) {_x000D_ System.out.println("AbstractAction.setBaseProperties > duration: o (getObject(Type.longinteger)) is NoObject " + ((NoObject)o).getReason().toString() );_x000D_ }_x000D_ duration = 0;_x000D_ }_x000D_ else {_x000D_ duration = (long) o;_x000D_ }_x000D_ _x000D_ _x000D_ this.setType(type);_x000D_ this.setMode(mode);_x000D_ this.setIntensity(intensity);_x000D_ this.setMinTime(minTime);_x000D_ this.setMaxTime(maxTime);_x000D_ this.setPriority(priority);_x000D_ this.setDuration(duration);_x000D_ this.setRemainedDuration(duration);_x000D_ _x000D_ this.linkedAction = null;_x000D_ _x000D_ if (duration > 0) interruptable = true;_x000D_ _x000D_ }_x000D_ _x000D_ protected abstract void setFurtherProperties(ValueArrayList actionProperties);_x000D_ _x000D_ _x000D_ protected void setBaseProperties(AbstractAction original) {_x000D_ _x000D_ this.type = original.type;_x000D_ this.mode = original.mode;_x000D_ this.intensity = original.intensity;_x000D_ this.minTime = original.minTime;_x000D_ this.maxTime = original.maxTime;_x000D_ this.priority = original.priority;_x000D_ this.duration = original.duration;_x000D_ _x000D_ }_x000D_ _x000D_ protected abstract void setFurtherProperties(AbstractAction original);_x000D_ _x000D_ public abstract void perform();_x000D_ _x000D_ _x000D_ protected void addEvent(Event event) {_x000D_ simulation.getEventMaster().addEvent(event);_x000D_ }_x000D_ _x000D_ /**_x000D_ * The method sets the linked action._x000D_ * _x000D_ * @param linked action_x000D_ */_x000D_ public void setLinkedAction (AbstractAction linkedAction) {_x000D_ this.linkedAction = linkedAction;_x000D_ }_x000D_ _x000D_ /**_x000D_ * The method returns the linked action._x000D_ * It is null if there is no linked action._x000D_ * _x000D_ * @return linked action_x000D_ */_x000D_ public AbstractAction getLinkedAction() {_x000D_ return linkedAction;_x000D_ }_x000D_ _x000D_ public SimulationObject getActor() {_x000D_ return actor;_x000D_ }_x000D_ _x000D_ public void setDone() {_x000D_ done = true;_x000D_ }_x000D_ _x000D_ public boolean isDone() {_x000D_ return done;_x000D_ }_x000D_ _x000D_ public boolean isInterruptable() {_x000D_ return interruptable;_x000D_ }_x000D_ _x000D_ public boolean isInterrupted() {_x000D_ return interrupted;_x000D_ }_x000D_ _x000D_ public void interrupt() {_x000D_ _x000D_ this.setDuration(remainedDuration);_x000D_ this.setRemainedDuration(0);_x000D_ this.interrupted = true;_x000D_ _x000D_ _x000D_ }_x000D_ _x000D_ public void continueAfterInterrupt() {_x000D_ this.setRemainedDuration(duration);_x000D_ this.interrupted = false;_x000D_ }_x000D_ _x000D_ _x000D_ public void requestPropertyList(IEventParam paramObject) {_x000D_ ValueArrayList propertiesAsValueList = new ValueArrayList();_x000D_ _x000D_ propertiesAsValueList.add(new Value(Type.floatingpoint, Value.VALUE_BY_NAME_ACTION_INTENSITY, this.intensity));_x000D_ paramObject.answerPropertiesRequest(propertiesAsValueList);_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * The methods returns the action type._x000D_ * _x000D_ * @return type_x000D_ */_x000D_ public ActionType getType() {_x000D_ return this.type;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param type_x000D_ * the type to set_x000D_ */_x000D_ public void setType(final ActionType type) {_x000D_ this.type = type;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return the time_x000D_ */_x000D_ public Time getMinTime() {_x000D_ return this.minTime;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param time_x000D_ * the time to set_x000D_ */_x000D_ public void setMinTime(final Time time) {_x000D_ this.minTime = time;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return the time_x000D_ */_x000D_ public Time getMaxTime() {_x000D_ return this.maxTime;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param time_x000D_ * the time to set_x000D_ */_x000D_ public void setMaxTime(final Time time) {_x000D_ this.maxTime = time;_x000D_ }_x000D_ _x000D_ /**_x000D_ * The methods returns the action's priority._x000D_ * _x000D_ * @return priority_x000D_ */_x000D_ public int getPriority() {_x000D_ return this.priority;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param priority_x000D_ * the priority to set_x000D_ */_x000D_ public void setPriority(final int priority) {_x000D_ this.priority = priority;_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ /**_x000D_ * @return the mode_x000D_ */_x000D_ public ActionMode getMode() {_x000D_ return this.mode;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param mode_x000D_ * the mode to set_x000D_ */_x000D_ public void setMode(final ActionMode mode) {_x000D_ this.mode = mode;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return the intensity_x000D_ */_x000D_ public float getIntensity() {_x000D_ return this.intensity;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param intensity_x000D_ * the intensity to set_x000D_ */_x000D_ public void setIntensity(final float intensity) {_x000D_ this.intensity = intensity;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return the duration_x000D_ */_x000D_ public long getDuration() {_x000D_ return this.duration;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param duration_x000D_ * the duration to set_x000D_ */_x000D_ public void setDuration(final long duration) {_x000D_ this.duration = duration;_x000D_ }_x000D_ _x000D_ /**_x000D_ * The methods returns the action's remained duration._x000D_ * _x000D_ * @return remainedDuration_x000D_ */_x000D_ public long getRemainedDuration() {_x000D_ return this.remainedDuration;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param remainedDuration_x000D_ * the remainedDuration to set_x000D_ */_x000D_ public void setRemainedDuration(final long remainedDuration) {_x000D_ this.remainedDuration = remainedDuration;_x000D_ }_x000D_ _x000D_ /**_x000D_ * The method decrements the attribute remainedDuration. That means, an_x000D_ * action needs less time to complete._x000D_ * _x000D_ * @param decrement_x000D_ */_x000D_ public void lowerRemainedDuration(final long decrement) {_x000D_ this.remainedDuration -= decrement;_x000D_ _x000D_ // System.out.println("AbstractAction.lowerRemainedDuration(): " + toString() + " " + actor.toString() + " noch offen: " + this.remainedDuration);_x000D_ if (this.remainedDuration <= 0) done = true;_x000D_ }_x000D_ _x000D_ /**_x000D_ * The method increments the attribute remainedDuration. That means, an_x000D_ * action needs more time to complete._x000D_ * _x000D_ * @param increment_x000D_ */_x000D_ public void raiseRemainedDuration(final long increment) {_x000D_ this.remainedDuration += increment;_x000D_ }_x000D_ _x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ return "(" + this.type.toString() + ")"; //$NON-NLS-1$_x000D_ }_x000D_ _x000D_ ///////////////////////////////////////////////////////////////////////////////////////////_x000D_ //////////////////////implementing IObjectSender<SUF> ///////////////////////////////////////////////////////////////////////////////////////////_x000D_ _x000D_ public int sendYourselfTo(IObjectReceiver receiver, int requestID) {_x000D_ return receiver.receiveObject(requestID, this);_x000D_ }_x000D_ public int sendYourselfTo(SimulationCluster cluster, IObjectReceiver receiver, int requestID) {_x000D_ return receiver.receiveObject(requestID, this);_x000D_ }_x000D_ _x000D_ public IObjectSender copy() {_x000D_ return this;_x000D_ }_x000D_ _x000D_ ///////////////////////////////////////////////////////////////////////////////////////////_x000D_ //////////////////////implementing IObjectReceiver ///////////////////////////////////////_x000D_ ///////////////////////////////////////////////////////////////////////////////////////////_x000D_ _x000D_ @Override_x000D_ public int receiveObject(int requestID, Object object) {_x000D_ objectRequester.receive(requestID, object);_x000D_ return 0;_x000D_ }_x000D_ _x000D_ _x000D_ }
False
2,864
146069_11
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // This test uses reference distributions from commons-math3 to compute the expected // PMF. These distributions have a dual functionality to compute the PMF and perform // sampling. When no sampling is needed for the created distribution, it is advised // to pass null as the random generator via the appropriate constructors to avoid the // additional initialisation overhead. org.apache.commons.math3.random.RandomGenerator unusedRng = null; // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse method"). final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(unusedRng, dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(unusedRng, numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(unusedRng, muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(unusedRng, muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 2.345; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log-normal (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log-normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT_64)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MWC_256)), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(unusedRng, muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(unusedRng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(unusedRng, aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(unusedRng, alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
grimreaper/commons-rng
commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java
4,537
// Beta ("inverse method").
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.rng.sampling.distribution; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // This test uses reference distributions from commons-math3 to compute the expected // PMF. These distributions have a dual functionality to compute the PMF and perform // sampling. When no sampling is needed for the created distribution, it is advised // to pass null as the random generator via the appropriate constructors to avoid the // additional initialisation overhead. org.apache.commons.math3.random.RandomGenerator unusedRng = null; // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(unusedRng, meanNormal, sigmaNormal), new GaussianSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse<SUF> final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(unusedRng, betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(unusedRng, medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(unusedRng, dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(unusedRng, meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(unusedRng, numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(unusedRng, thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(unusedRng, muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(unusedRng, muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(unusedRng, muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 2.345; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log-normal (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log-normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT_64)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(unusedRng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MWC_256)), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(unusedRng, muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(unusedRng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(unusedRng, scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(unusedRng, dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(unusedRng, aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(unusedRng, loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(unusedRng, alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
False
2,045
7579_19
package org.saga.listeners.events; import java.util.PriorityQueue; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.inventory.ItemStack; import org.saga.Saga; import org.saga.attributes.DamageType; import org.saga.config.AttributeConfiguration; import org.saga.config.VanillaConfiguration; import org.saga.dependencies.SagaMobsDependency; import org.saga.factions.Faction; import org.saga.player.SagaLiving; import org.saga.player.SagaPlayer; import org.saga.settlements.BundleManager; import org.saga.settlements.SagaChunk; import org.saga.utility.TwoPointFunction; public class SagaDamageEvent { /** * Damage type. */ public DamageType type; /** * Projectile. */ public final Projectile projectile; /** * Tool material. */ public final Material tool; /** * Attacker creature, null if none. */ public final Creature creatureAttacker; /** * Defender creature, null if none */ public final Creature creatureDefender; /** * Attacker Saga entity, null if none. */ public final SagaLiving sagaAttacker; /** * Defender saga entity, null if none */ public final SagaLiving sagaDefender; /** * Attackers saga chunk, null if none. */ public final SagaChunk attackerChunk; /** * Defenders saga chunk, null if none. */ public final SagaChunk defenderChunk; /** * Minecraft event. */ private final EntityDamageEvent event; /** * Damage modifier. */ private double modifier = 0.0; /** * Damage multiplier. */ private double multiplier = 1.0; /** * Hit chance modifier. */ private double hitChance = 1.0; /** * Armour penetration modifier. */ private double penetration = 0.0; /** * Enchantment penetration modifier. */ private double disenchant = 0.0; /** * Block multiplier. */ private double blocking = VanillaConfiguration.getBlockingMultiplier(); /** * Penalty multiplier. * Prevents massive damage from weak attacks. */ private double penalty = 1.0; /** * Tool sloppiness multiplier. */ private double sloppiness = 1.0; /** * PvP override. */ private PriorityQueue<PvPOverride> pvpOverride = new PriorityQueue<SagaDamageEvent.PvPOverride>(); // Initiate: /** * Extracts saga entities and chunks. * * @param event event * @param defender defender entity */ public SagaDamageEvent(EntityDamageEvent event) { Entity attacker = null; LivingEntity defender = null; this.event = event; type = DamageType.getDamageType(event); if(event.getEntity() instanceof LivingEntity) defender = (LivingEntity) event.getEntity(); // Damage penalty: // Prevents massive damage from weak attacks. double tresh = AttributeConfiguration.config().getPenaltyValue(type); if(tresh > 0 && event.getDamage() < tresh) penalty = event.getDamage() / tresh; // Attacked by an entity: if(event instanceof EntityDamageByEntityEvent) attacker = ((EntityDamageByEntityEvent) event).getDamager(); // Attacked by a projectile: if(attacker instanceof Projectile){ projectile = (Projectile) attacker; attacker = projectile.getShooter(); }else{ projectile = null; } // Get attacker saga player: if(attacker instanceof Player){ sagaAttacker = Saga.plugin().getLoadedPlayer( ((Player) attacker).getName() ); creatureAttacker = null; // Tool: tool = ((Player) attacker).getItemInHand().getType(); } // Get attacker creature: else if(attacker instanceof Creature){ creatureAttacker = (Creature)attacker; sagaAttacker = SagaMobsDependency.findSagaCreature(creatureAttacker); tool = Material.AIR; }else{ creatureAttacker = null; sagaAttacker = null; tool = Material.AIR; } // Get defender saga player: if(defender instanceof Player){ creatureDefender = null; sagaDefender = Saga.plugin().getLoadedPlayer( ((Player) defender).getName() ); } // Get defender creature: else if(defender instanceof Creature){ creatureDefender = (Creature)defender; sagaDefender = SagaMobsDependency.findSagaCreature(creatureDefender); } else{ creatureDefender = null; sagaDefender = null; } // Get chunks: attackerChunk = (attacker != null) ? BundleManager.manager().getSagaChunk(attacker.getLocation()) : null; defenderChunk = (defender != null) ? BundleManager.manager().getSagaChunk(defender.getLocation()) : null; } // Modify: /** * Modifies damage. * * @param amount amount to modify */ public void modifyDamage(double amount) { modifier+= amount; } /** * Multiplies damage. * * @param amount amount to multiply by */ public void multiplyDamage(double amount) { multiplier+= amount; } /** * Divides damage. * * @param amount amount to divide by */ public void divideDamage(double amount) { multiplier/= amount; } /** * Modifies hit chance. * * @param amount amount to modify */ public void modifyHitChance(double amount) { hitChance+=amount; } /** * Modifies armour penetration. * * @param amount amount to modify */ public void modifyArmourPenetration(double amount) { penetration+=amount; } /** * Modifies enchantment penetration. * * @param amount amount to modify */ public void modifyEnchantPenetration(double amount) { disenchant+=amount; } /** * Modifies blocking. * * @param amount amount to modify */ public void modifyBlocking(double amount) { blocking-= amount; } /** * Modifies tool handling. * * @param amount amount to modify */ public void modifyToolHandling(double amount) { sloppiness-= amount; } /** * Gets the projectile. * * @return projectile, null if none */ public Projectile getProjectile() { return projectile; } // Conclude: /** * Applies the event. * */ public void apply() { // Ignore cancelled: if(isCancelled()) return; // Dodge: if(hitChance <= Saga.RANDOM.nextDouble()) { event.setCancelled(true); return; } // Modify damage: double damage = calcDamage(); event.setDamage(damage); // Apply damage to player: if(sagaDefender != null){ double harm = damage; // Armour: double armour = VanillaConfiguration.getArmourMultiplier(event, sagaDefender.getWrapped()) + penetration; if(armour < 0.0) armour = 0.0; if(armour > 1.0) armour = 1.0; harm*= armour; // Enchantments: double ench = VanillaConfiguration.getEPFMultiplier(event, sagaDefender.getWrapped()) + disenchant; if(ench < 0.0) ench = 0.0; if(ench > 1.0) ench = 1.0; harm*= ench; // Blocking: if(VanillaConfiguration.checkBlocking(event, sagaDefender.getWrapped())) harm*= blocking; // Apply Saga damage: sagaDefender.getWrapped().damage(harm); // Take control: event.setDamage(0.0); } // Reduce tool damage: final int undurability; if(sagaAttacker != null) undurability = sagaAttacker.getHandItem().getDurability(); else undurability = 0; // Reduce armour durability: if(sagaDefender != null && VanillaConfiguration.checkArmourDamage(event.getCause())) sagaDefender.damageArmour(); // Schedule for next tick: Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Saga.plugin(), new Runnable() { @SuppressWarnings("deprecation") @Override public void run() { // Tool damage reduction: if(sagaAttacker instanceof SagaPlayer){ Player player = ((SagaPlayer)sagaAttacker).getPlayer(); ItemStack item = player.getItemInHand(); int damage = item.getDurability() - undurability; damage = TwoPointFunction.randomRound(sloppiness * damage).shortValue(); int pundurability = item.getDurability(); item.setDurability((short) (undurability + damage)); if(item.getDurability() != pundurability) player.updateInventory(); } } }, 1); } /** * Cancels the event. * */ public void cancel() { event.setCancelled(true); } // Event information: /** * Calculates damage. * * @return damage */ public double calcDamage() { return (event.getDamage() + modifier) * multiplier * penalty; } /** * Checks if the defender player is blocking. * * @return true if blocking */ public boolean isBlocking() { if(sagaDefender == null) return false; return VanillaConfiguration.checkBlocking(event, sagaDefender.getWrapped()); } /** * Checks if player attacked a player. * * @return true if player versus player */ public boolean isPvP() { return sagaAttacker instanceof SagaPlayer && sagaDefender instanceof SagaPlayer; } /** * Checks if player attacked a creature. * * @return true if player versus player */ public boolean isPvC() { return sagaAttacker instanceof SagaPlayer && creatureDefender != null; } /** * Checks if creature attacked a creature. * * @return true if player versus player */ public boolean isCvC() { return creatureAttacker != null && creatureDefender != null; } /** * Checks if creature attacked a player. * * @return true if player versus player */ public boolean isCvP() { return creatureAttacker != null && sagaDefender instanceof SagaPlayer; } /** * Checks if the event is faction versus faction. * * @return true if faction versus faction. */ public boolean isFvF() { if(!(sagaAttacker instanceof SagaPlayer) || !(sagaDefender instanceof SagaPlayer)) return false; return ((SagaPlayer) sagaAttacker).getFaction() != null && ((SagaPlayer) sagaDefender).getFaction() != null; } /** * Gets the attacker. * * @return attacker, null if none */ public LivingEntity getAttacker() { if(sagaAttacker != null) return sagaAttacker.getWrapped(); return creatureAttacker; } /** * Gets the defender. * * @return defender, null if none */ public LivingEntity getDefender() { if(sagaDefender != null) return sagaDefender.getWrapped(); return creatureDefender; } /** * Gets attacker faction. * * @return attacker faction, null if none */ public Faction getAttackerFaction() { if(sagaAttacker instanceof SagaPlayer) return ((SagaPlayer) sagaAttacker).getFaction(); return null; } /** * Gets defender faction. * * @return defender faction, null if none */ public Faction getDefenderFaction() { if(sagaDefender instanceof SagaPlayer) return ((SagaPlayer) sagaDefender).getFaction(); return null; } /** * Gets base damage. * * @return base damage */ public double getBaseDamage() { return event.getDamage(); } /** * Checks if the event is cancelled. * * @return true if cancelled */ public boolean isCancelled() { return event.isCancelled(); } /** * Adds a pvp override. * * @param override pvp override */ public void addPvpOverride(PvPOverride override) { pvpOverride.add(override); } /** * Gets the top override. * * @return top override, NONE if none */ public PvPOverride getOverride() { if(pvpOverride.size() == 0) return PvPOverride.NONE; return pvpOverride.peek(); } /** * Pvp overrides. * * @author andf * */ public enum PvPOverride{ ADMIN_ALLOW(true), ADMIN_DENY(false), RESPAWN_DENY(false), SELF_ALLOW(true), ARENA_ALLOW(true), SAME_FACTION_DENY(false), SAFE_AREA_DENY(false), FACTION_ONLY_PVP_DENY(false), ALLY_DENY(false), NONE(true); /** * If true, then pvp will be allowed. */ private boolean allow; /** * Sets if pvp override enables PvP. * * @param true if allows pvp, false if denies pvp */ private PvPOverride(boolean allow) { this.allow = allow; } /** * If true, then pvp will be allowed. Denied if false. * * @return true if allowed, false if denied */ public boolean isAllow() { return allow; } } }
andfRa/Saga
src/org/saga/listeners/events/SagaDamageEvent.java
4,353
/** * Extracts saga entities and chunks. * * @param event event * @param defender defender entity */
block_comment
nl
package org.saga.listeners.events; import java.util.PriorityQueue; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.inventory.ItemStack; import org.saga.Saga; import org.saga.attributes.DamageType; import org.saga.config.AttributeConfiguration; import org.saga.config.VanillaConfiguration; import org.saga.dependencies.SagaMobsDependency; import org.saga.factions.Faction; import org.saga.player.SagaLiving; import org.saga.player.SagaPlayer; import org.saga.settlements.BundleManager; import org.saga.settlements.SagaChunk; import org.saga.utility.TwoPointFunction; public class SagaDamageEvent { /** * Damage type. */ public DamageType type; /** * Projectile. */ public final Projectile projectile; /** * Tool material. */ public final Material tool; /** * Attacker creature, null if none. */ public final Creature creatureAttacker; /** * Defender creature, null if none */ public final Creature creatureDefender; /** * Attacker Saga entity, null if none. */ public final SagaLiving sagaAttacker; /** * Defender saga entity, null if none */ public final SagaLiving sagaDefender; /** * Attackers saga chunk, null if none. */ public final SagaChunk attackerChunk; /** * Defenders saga chunk, null if none. */ public final SagaChunk defenderChunk; /** * Minecraft event. */ private final EntityDamageEvent event; /** * Damage modifier. */ private double modifier = 0.0; /** * Damage multiplier. */ private double multiplier = 1.0; /** * Hit chance modifier. */ private double hitChance = 1.0; /** * Armour penetration modifier. */ private double penetration = 0.0; /** * Enchantment penetration modifier. */ private double disenchant = 0.0; /** * Block multiplier. */ private double blocking = VanillaConfiguration.getBlockingMultiplier(); /** * Penalty multiplier. * Prevents massive damage from weak attacks. */ private double penalty = 1.0; /** * Tool sloppiness multiplier. */ private double sloppiness = 1.0; /** * PvP override. */ private PriorityQueue<PvPOverride> pvpOverride = new PriorityQueue<SagaDamageEvent.PvPOverride>(); // Initiate: /** * Extracts saga entities<SUF>*/ public SagaDamageEvent(EntityDamageEvent event) { Entity attacker = null; LivingEntity defender = null; this.event = event; type = DamageType.getDamageType(event); if(event.getEntity() instanceof LivingEntity) defender = (LivingEntity) event.getEntity(); // Damage penalty: // Prevents massive damage from weak attacks. double tresh = AttributeConfiguration.config().getPenaltyValue(type); if(tresh > 0 && event.getDamage() < tresh) penalty = event.getDamage() / tresh; // Attacked by an entity: if(event instanceof EntityDamageByEntityEvent) attacker = ((EntityDamageByEntityEvent) event).getDamager(); // Attacked by a projectile: if(attacker instanceof Projectile){ projectile = (Projectile) attacker; attacker = projectile.getShooter(); }else{ projectile = null; } // Get attacker saga player: if(attacker instanceof Player){ sagaAttacker = Saga.plugin().getLoadedPlayer( ((Player) attacker).getName() ); creatureAttacker = null; // Tool: tool = ((Player) attacker).getItemInHand().getType(); } // Get attacker creature: else if(attacker instanceof Creature){ creatureAttacker = (Creature)attacker; sagaAttacker = SagaMobsDependency.findSagaCreature(creatureAttacker); tool = Material.AIR; }else{ creatureAttacker = null; sagaAttacker = null; tool = Material.AIR; } // Get defender saga player: if(defender instanceof Player){ creatureDefender = null; sagaDefender = Saga.plugin().getLoadedPlayer( ((Player) defender).getName() ); } // Get defender creature: else if(defender instanceof Creature){ creatureDefender = (Creature)defender; sagaDefender = SagaMobsDependency.findSagaCreature(creatureDefender); } else{ creatureDefender = null; sagaDefender = null; } // Get chunks: attackerChunk = (attacker != null) ? BundleManager.manager().getSagaChunk(attacker.getLocation()) : null; defenderChunk = (defender != null) ? BundleManager.manager().getSagaChunk(defender.getLocation()) : null; } // Modify: /** * Modifies damage. * * @param amount amount to modify */ public void modifyDamage(double amount) { modifier+= amount; } /** * Multiplies damage. * * @param amount amount to multiply by */ public void multiplyDamage(double amount) { multiplier+= amount; } /** * Divides damage. * * @param amount amount to divide by */ public void divideDamage(double amount) { multiplier/= amount; } /** * Modifies hit chance. * * @param amount amount to modify */ public void modifyHitChance(double amount) { hitChance+=amount; } /** * Modifies armour penetration. * * @param amount amount to modify */ public void modifyArmourPenetration(double amount) { penetration+=amount; } /** * Modifies enchantment penetration. * * @param amount amount to modify */ public void modifyEnchantPenetration(double amount) { disenchant+=amount; } /** * Modifies blocking. * * @param amount amount to modify */ public void modifyBlocking(double amount) { blocking-= amount; } /** * Modifies tool handling. * * @param amount amount to modify */ public void modifyToolHandling(double amount) { sloppiness-= amount; } /** * Gets the projectile. * * @return projectile, null if none */ public Projectile getProjectile() { return projectile; } // Conclude: /** * Applies the event. * */ public void apply() { // Ignore cancelled: if(isCancelled()) return; // Dodge: if(hitChance <= Saga.RANDOM.nextDouble()) { event.setCancelled(true); return; } // Modify damage: double damage = calcDamage(); event.setDamage(damage); // Apply damage to player: if(sagaDefender != null){ double harm = damage; // Armour: double armour = VanillaConfiguration.getArmourMultiplier(event, sagaDefender.getWrapped()) + penetration; if(armour < 0.0) armour = 0.0; if(armour > 1.0) armour = 1.0; harm*= armour; // Enchantments: double ench = VanillaConfiguration.getEPFMultiplier(event, sagaDefender.getWrapped()) + disenchant; if(ench < 0.0) ench = 0.0; if(ench > 1.0) ench = 1.0; harm*= ench; // Blocking: if(VanillaConfiguration.checkBlocking(event, sagaDefender.getWrapped())) harm*= blocking; // Apply Saga damage: sagaDefender.getWrapped().damage(harm); // Take control: event.setDamage(0.0); } // Reduce tool damage: final int undurability; if(sagaAttacker != null) undurability = sagaAttacker.getHandItem().getDurability(); else undurability = 0; // Reduce armour durability: if(sagaDefender != null && VanillaConfiguration.checkArmourDamage(event.getCause())) sagaDefender.damageArmour(); // Schedule for next tick: Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Saga.plugin(), new Runnable() { @SuppressWarnings("deprecation") @Override public void run() { // Tool damage reduction: if(sagaAttacker instanceof SagaPlayer){ Player player = ((SagaPlayer)sagaAttacker).getPlayer(); ItemStack item = player.getItemInHand(); int damage = item.getDurability() - undurability; damage = TwoPointFunction.randomRound(sloppiness * damage).shortValue(); int pundurability = item.getDurability(); item.setDurability((short) (undurability + damage)); if(item.getDurability() != pundurability) player.updateInventory(); } } }, 1); } /** * Cancels the event. * */ public void cancel() { event.setCancelled(true); } // Event information: /** * Calculates damage. * * @return damage */ public double calcDamage() { return (event.getDamage() + modifier) * multiplier * penalty; } /** * Checks if the defender player is blocking. * * @return true if blocking */ public boolean isBlocking() { if(sagaDefender == null) return false; return VanillaConfiguration.checkBlocking(event, sagaDefender.getWrapped()); } /** * Checks if player attacked a player. * * @return true if player versus player */ public boolean isPvP() { return sagaAttacker instanceof SagaPlayer && sagaDefender instanceof SagaPlayer; } /** * Checks if player attacked a creature. * * @return true if player versus player */ public boolean isPvC() { return sagaAttacker instanceof SagaPlayer && creatureDefender != null; } /** * Checks if creature attacked a creature. * * @return true if player versus player */ public boolean isCvC() { return creatureAttacker != null && creatureDefender != null; } /** * Checks if creature attacked a player. * * @return true if player versus player */ public boolean isCvP() { return creatureAttacker != null && sagaDefender instanceof SagaPlayer; } /** * Checks if the event is faction versus faction. * * @return true if faction versus faction. */ public boolean isFvF() { if(!(sagaAttacker instanceof SagaPlayer) || !(sagaDefender instanceof SagaPlayer)) return false; return ((SagaPlayer) sagaAttacker).getFaction() != null && ((SagaPlayer) sagaDefender).getFaction() != null; } /** * Gets the attacker. * * @return attacker, null if none */ public LivingEntity getAttacker() { if(sagaAttacker != null) return sagaAttacker.getWrapped(); return creatureAttacker; } /** * Gets the defender. * * @return defender, null if none */ public LivingEntity getDefender() { if(sagaDefender != null) return sagaDefender.getWrapped(); return creatureDefender; } /** * Gets attacker faction. * * @return attacker faction, null if none */ public Faction getAttackerFaction() { if(sagaAttacker instanceof SagaPlayer) return ((SagaPlayer) sagaAttacker).getFaction(); return null; } /** * Gets defender faction. * * @return defender faction, null if none */ public Faction getDefenderFaction() { if(sagaDefender instanceof SagaPlayer) return ((SagaPlayer) sagaDefender).getFaction(); return null; } /** * Gets base damage. * * @return base damage */ public double getBaseDamage() { return event.getDamage(); } /** * Checks if the event is cancelled. * * @return true if cancelled */ public boolean isCancelled() { return event.isCancelled(); } /** * Adds a pvp override. * * @param override pvp override */ public void addPvpOverride(PvPOverride override) { pvpOverride.add(override); } /** * Gets the top override. * * @return top override, NONE if none */ public PvPOverride getOverride() { if(pvpOverride.size() == 0) return PvPOverride.NONE; return pvpOverride.peek(); } /** * Pvp overrides. * * @author andf * */ public enum PvPOverride{ ADMIN_ALLOW(true), ADMIN_DENY(false), RESPAWN_DENY(false), SELF_ALLOW(true), ARENA_ALLOW(true), SAME_FACTION_DENY(false), SAFE_AREA_DENY(false), FACTION_ONLY_PVP_DENY(false), ALLY_DENY(false), NONE(true); /** * If true, then pvp will be allowed. */ private boolean allow; /** * Sets if pvp override enables PvP. * * @param true if allows pvp, false if denies pvp */ private PvPOverride(boolean allow) { this.allow = allow; } /** * If true, then pvp will be allowed. Denied if false. * * @return true if allowed, false if denied */ public boolean isAllow() { return allow; } } }
False
3,248
107719_3
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; /* * This file is part of the RoomSports distribution * (https://github.com/jobeagle/roomsports/roomsports.git). * * Copyright (c) 2020 Bruno Schmidt (mail@roomsports.de). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * 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/>. ***************************************************************************** * Update.java ***************************************************************************** * * Diese Klasse beinhaltet den automatischen Update. * Um die eigenen Klassen (und EXE-Dateien problemlos überschreiben zu können * ist der Update in ein extra Jar-Archiv ausgelagert. * */ public class Update { private final static String zipFile = "rsupdate.zip"; private final static String downloadURL = "https://www.mtbsimulator.de/rs/download/"+zipFile; private static Thread worker; private final static String root = "update/"; private static boolean logDebug = true; // Debugstatus für das Logging ein/aus private static boolean updateComplete = false; private static Shell shell; private static Label lblInfo = null; private static String infoText = new String(""); private static String javaRT = System.getProperty("java.home") + "\\bin\\javaw.exe"; /** * Alle Aktionen werden hier in einem extra Thread durchgeführt. */ private static void download() { worker = new Thread( new Runnable(){ public void run() { try { Mlog.info("Update startet mit Download"); downloadFile(downloadURL); Mlog.debug("Unzip..."); unzip(); Mlog.debug("kopiere Dateien"); copyFiles(new File(root),new File("").getAbsolutePath()); infoText = "aufräumen"; Mlog.debug("aufraeumen"); cleanup(); infoText = "Update beendet"; Mlog.debug(infoText); startRs(); Mlog.info("RS gestartet"); updateComplete = true; } catch (Exception ex) { updateComplete = true; String fehler = "Beim Updatevorgang ist ein Fehler aufgetreten!"; Mlog.error(fehler); Mlog.ex(ex); startRs(); Mlog.info("RS gestartet (ex)"); } } }); worker.start(); } /** * RoomSports wieder starten. */ private static void startRs() { Mlog.debug("Starte RoomSports..."); String[] run = {javaRT,"-jar","rs.jar"}; try { Runtime.getRuntime().exec(run); } catch (Exception ex) { Mlog.ex(ex);; } } /** * ZIP-Datei und Updateverzeichnis werden gelöscht. */ private static void cleanup() { Mlog.debug("Cleanup wird durchgeführt..."); File f = new File(zipFile); f.delete(); remove(new File(root)); new File(root).delete(); } /** * löscht rekursiv Dateien bzw. Verzeichnisse * @param f */ private static void remove(File f) { File[]files = f.listFiles(); for(File ff:files) { if(ff.isDirectory()) { remove(ff); ff.delete(); } else { ff.delete(); } } } /** * Kopiert die entzippten Dateien vom Verzeichnis update in das Programmverzeichnis * von RoomSports. * @param f Pfad des Quellverzeichnisses (update) * @param dir Zielverzeichnisname (Programmverzeichnis) * @throws IOException */ private static void copyFiles(File f,String dir) throws IOException { File[]files = f.listFiles(); for(File ff:files) { if(ff.isDirectory()){ new File(dir+"/"+ff.getName()).mkdir(); copyFiles(ff,dir+"/"+ff.getName()); } else { copy(ff.getAbsolutePath(),dir+"/"+ff.getName()); } } } /** * Ein einfacher Dateikopierer. * @param srFile Quellverzeichnis * @param dtFile Zielverzeichnis * @throws FileNotFoundException * @throws IOException */ public static void copy(String srFile, String dtFile) throws FileNotFoundException, IOException{ File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); } /** * Das "zipfile" wird entzipped. * @throws IOException */ private static void unzip() throws IOException { int BUFFER = 2048; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(zipFile); Enumeration<? extends ZipEntry> e = zipfile.entries(); (new File(root)).mkdir(); while(e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); infoText = "Extrahiere: " +entry; Mlog.debug(infoText); if(entry.isDirectory()) (new File(root+entry.getName())).mkdir(); else{ (new File(root+entry.getName())).createNewFile(); is = new BufferedInputStream (zipfile.getInputStream(entry)); int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(root+entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); } } zipfile.close(); } /** * Lädt die Datei aus der übergebenen URL herunter. * @param link * @throws MalformedURLException * @throws IOException */ private static void downloadFile(String link) throws MalformedURLException, IOException { URL url = new URL(link); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); long max = conn.getContentLength(); infoText = "download " + max + " Bytes"; Mlog.debug("Download Datei ...Update Größe(komprimiert): " + max + " Bytes"); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile))); byte[] buffer = new byte[32 * 1024]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } fOut.flush(); fOut.close(); is.close(); Mlog.debug("Download abgeschlossen"); } /** * Anzeige des aktuellen Status im Label * @param info */ private static void showInfoText(String info) { lblInfo.setText(info); lblInfo.redraw(); } /** * Hauptprogramm des Updaters * @param args */ public static void main(String[] args) { FontData wertKlFont = new FontData("Arial",(int) (14),SWT.BOLD); Display display = new Display (); shell = new Shell(display); shell.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { Mlog.init(); Mlog.setDebugstatus(logDebug); download(); } }); shell.setSize(310, 113); shell.setBounds(120, 10, 310, 80); shell.setText("Update"); lblInfo = new Label(shell, SWT.NONE); lblInfo.setBounds(10, 10, 290, 20); lblInfo.setFont(new Font(display, wertKlFont)); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { showInfoText(infoText); display.sleep(); if (updateComplete) { try { Thread.sleep(2000); } catch (InterruptedException e) { Mlog.ex(e); } shell.dispose(); } } } display.dispose(); } }
jobeagle/roomsports
updater/src/Update.java
2,877
/** * RoomSports wieder starten. */
block_comment
nl
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; /* * This file is part of the RoomSports distribution * (https://github.com/jobeagle/roomsports/roomsports.git). * * Copyright (c) 2020 Bruno Schmidt (mail@roomsports.de). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * 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/>. ***************************************************************************** * Update.java ***************************************************************************** * * Diese Klasse beinhaltet den automatischen Update. * Um die eigenen Klassen (und EXE-Dateien problemlos überschreiben zu können * ist der Update in ein extra Jar-Archiv ausgelagert. * */ public class Update { private final static String zipFile = "rsupdate.zip"; private final static String downloadURL = "https://www.mtbsimulator.de/rs/download/"+zipFile; private static Thread worker; private final static String root = "update/"; private static boolean logDebug = true; // Debugstatus für das Logging ein/aus private static boolean updateComplete = false; private static Shell shell; private static Label lblInfo = null; private static String infoText = new String(""); private static String javaRT = System.getProperty("java.home") + "\\bin\\javaw.exe"; /** * Alle Aktionen werden hier in einem extra Thread durchgeführt. */ private static void download() { worker = new Thread( new Runnable(){ public void run() { try { Mlog.info("Update startet mit Download"); downloadFile(downloadURL); Mlog.debug("Unzip..."); unzip(); Mlog.debug("kopiere Dateien"); copyFiles(new File(root),new File("").getAbsolutePath()); infoText = "aufräumen"; Mlog.debug("aufraeumen"); cleanup(); infoText = "Update beendet"; Mlog.debug(infoText); startRs(); Mlog.info("RS gestartet"); updateComplete = true; } catch (Exception ex) { updateComplete = true; String fehler = "Beim Updatevorgang ist ein Fehler aufgetreten!"; Mlog.error(fehler); Mlog.ex(ex); startRs(); Mlog.info("RS gestartet (ex)"); } } }); worker.start(); } /** * RoomSports wieder starten.<SUF>*/ private static void startRs() { Mlog.debug("Starte RoomSports..."); String[] run = {javaRT,"-jar","rs.jar"}; try { Runtime.getRuntime().exec(run); } catch (Exception ex) { Mlog.ex(ex);; } } /** * ZIP-Datei und Updateverzeichnis werden gelöscht. */ private static void cleanup() { Mlog.debug("Cleanup wird durchgeführt..."); File f = new File(zipFile); f.delete(); remove(new File(root)); new File(root).delete(); } /** * löscht rekursiv Dateien bzw. Verzeichnisse * @param f */ private static void remove(File f) { File[]files = f.listFiles(); for(File ff:files) { if(ff.isDirectory()) { remove(ff); ff.delete(); } else { ff.delete(); } } } /** * Kopiert die entzippten Dateien vom Verzeichnis update in das Programmverzeichnis * von RoomSports. * @param f Pfad des Quellverzeichnisses (update) * @param dir Zielverzeichnisname (Programmverzeichnis) * @throws IOException */ private static void copyFiles(File f,String dir) throws IOException { File[]files = f.listFiles(); for(File ff:files) { if(ff.isDirectory()){ new File(dir+"/"+ff.getName()).mkdir(); copyFiles(ff,dir+"/"+ff.getName()); } else { copy(ff.getAbsolutePath(),dir+"/"+ff.getName()); } } } /** * Ein einfacher Dateikopierer. * @param srFile Quellverzeichnis * @param dtFile Zielverzeichnis * @throws FileNotFoundException * @throws IOException */ public static void copy(String srFile, String dtFile) throws FileNotFoundException, IOException{ File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); } /** * Das "zipfile" wird entzipped. * @throws IOException */ private static void unzip() throws IOException { int BUFFER = 2048; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(zipFile); Enumeration<? extends ZipEntry> e = zipfile.entries(); (new File(root)).mkdir(); while(e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); infoText = "Extrahiere: " +entry; Mlog.debug(infoText); if(entry.isDirectory()) (new File(root+entry.getName())).mkdir(); else{ (new File(root+entry.getName())).createNewFile(); is = new BufferedInputStream (zipfile.getInputStream(entry)); int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(root+entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); } } zipfile.close(); } /** * Lädt die Datei aus der übergebenen URL herunter. * @param link * @throws MalformedURLException * @throws IOException */ private static void downloadFile(String link) throws MalformedURLException, IOException { URL url = new URL(link); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); long max = conn.getContentLength(); infoText = "download " + max + " Bytes"; Mlog.debug("Download Datei ...Update Größe(komprimiert): " + max + " Bytes"); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile))); byte[] buffer = new byte[32 * 1024]; int bytesRead = 0; while ((bytesRead = is.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } fOut.flush(); fOut.close(); is.close(); Mlog.debug("Download abgeschlossen"); } /** * Anzeige des aktuellen Status im Label * @param info */ private static void showInfoText(String info) { lblInfo.setText(info); lblInfo.redraw(); } /** * Hauptprogramm des Updaters * @param args */ public static void main(String[] args) { FontData wertKlFont = new FontData("Arial",(int) (14),SWT.BOLD); Display display = new Display (); shell = new Shell(display); shell.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { Mlog.init(); Mlog.setDebugstatus(logDebug); download(); } }); shell.setSize(310, 113); shell.setBounds(120, 10, 310, 80); shell.setText("Update"); lblInfo = new Label(shell, SWT.NONE); lblInfo.setBounds(10, 10, 290, 20); lblInfo.setFont(new Font(display, wertKlFont)); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { showInfoText(infoText); display.sleep(); if (updateComplete) { try { Thread.sleep(2000); } catch (InterruptedException e) { Mlog.ex(e); } shell.dispose(); } } } display.dispose(); } }
False
644
44589_2
package nl.han.ica.oopd.waterworld; import nl.han.ica.oopg.collision.ICollidableWithGameObjects; import nl.han.ica.oopg.objects.GameObject; import nl.han.ica.oopg.sound.Sound; import processing.core.PGraphics; import java.util.List; /** * @author Ralph Niels * Bel-klasse */ public class Bubble extends GameObject implements ICollidableWithGameObjects { private final Sound popSound; private WaterWorld world; private int bubbleSize; /** * Constructor * * @param bubbleSize Afmeting van de bel * @param world Referentie naar de wereld * @param popSound Geluid dat moet klinken als de bel knapt */ public Bubble(int bubbleSize, WaterWorld world, Sound popSound) { this.bubbleSize = bubbleSize; this.popSound = popSound; this.world = world; setySpeed(-bubbleSize / 10f); /* De volgende regels zijn in een zelfgekend object nodig om collisiondetectie mogelijk te maken. */ setHeight(bubbleSize); setWidth(bubbleSize); } @Override public void update() { if (getY() <= 100) { world.deleteGameObject(this); } } @Override public void draw(PGraphics g) { g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie g.stroke(0, 50, 200, 100); g.fill(0, 50, 200, 50); g.ellipse(getX(), getY(), bubbleSize, bubbleSize); } @Override public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) { for (GameObject g : collidedGameObjects) { if (g instanceof Swordfish) { popSound.rewind(); popSound.play(); world.deleteGameObject(this); world.increaseBubblesPopped(); } } } }
HANICA/waterworld
src/main/java/nl/han/ica/oopd/waterworld/Bubble.java
586
/* De volgende regels zijn in een zelfgekend object nodig om collisiondetectie mogelijk te maken. */
block_comment
nl
package nl.han.ica.oopd.waterworld; import nl.han.ica.oopg.collision.ICollidableWithGameObjects; import nl.han.ica.oopg.objects.GameObject; import nl.han.ica.oopg.sound.Sound; import processing.core.PGraphics; import java.util.List; /** * @author Ralph Niels * Bel-klasse */ public class Bubble extends GameObject implements ICollidableWithGameObjects { private final Sound popSound; private WaterWorld world; private int bubbleSize; /** * Constructor * * @param bubbleSize Afmeting van de bel * @param world Referentie naar de wereld * @param popSound Geluid dat moet klinken als de bel knapt */ public Bubble(int bubbleSize, WaterWorld world, Sound popSound) { this.bubbleSize = bubbleSize; this.popSound = popSound; this.world = world; setySpeed(-bubbleSize / 10f); /* De volgende regels<SUF>*/ setHeight(bubbleSize); setWidth(bubbleSize); } @Override public void update() { if (getY() <= 100) { world.deleteGameObject(this); } } @Override public void draw(PGraphics g) { g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie g.stroke(0, 50, 200, 100); g.fill(0, 50, 200, 50); g.ellipse(getX(), getY(), bubbleSize, bubbleSize); } @Override public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) { for (GameObject g : collidedGameObjects) { if (g instanceof Swordfish) { popSound.rewind(); popSound.play(); world.deleteGameObject(this); world.increaseBubblesPopped(); } } } }
True
3,983
204960_25
null
philburk/jsyn
src/main/java/com/jsyn/engine/MultiTable.java
2,361
/* Interpolate between adjacent samples. */
block_comment
nl
/* * Copyright 2009 Phil Burk, Mobileer 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.jsyn.engine; /* * Multiple tables of sawtooth data. * organized by octaves below the Nyquist Rate. * used to generate band-limited Sawtooth, Impulse, Pulse, Square and Triangle BL waveforms * <pre> Analysis of octave requirements for tables. OctavesIndex Frequency Partials 0 N/2 11025 1 1 N/4 5512 2 2 N/8 2756 4 3 N/16 1378 8 4 N/32 689 16 5 N/64 344 32 6 N/128 172 64 7 N/256 86 128 </pre> * * @author Phil Burk (C) 2009 Mobileer Inc */ public class MultiTable { public final static int NUM_TABLES = 8; public final static int CYCLE_SIZE = (1 << 10); private static MultiTable instance = new MultiTable(NUM_TABLES, CYCLE_SIZE); private double phaseScalar; private float[][] tables; // array of array of tables /************************************************************************** * Initialize sawtooth wavetables. Table[0] should contain a pure sine wave. Succeeding tables * should have increasing numbers of partials. */ public MultiTable(int numTables, int cycleSize) { int tableSize = cycleSize + 1; // Allocate array of arrays. tables = new float[numTables][tableSize]; float[] sineTable = tables[0]; phaseScalar = (float) (cycleSize * 0.5); /* Fill initial sine table with values for -PI to PI. */ for (int j = 0; j < tableSize; j++) { sineTable[j] = (float) Math.sin(((((double) j) / (double) cycleSize) * Math.PI * 2.0) - Math.PI); } /* * Build each table from scratch and scale partials by raised cosine* to eliminate Gibbs * effect. */ for (int i = 1; i < numTables; i++) { int numPartials; double kGibbs; float[] table = tables[i]; /* Add together partials for this table. */ numPartials = 1 << i; kGibbs = Math.PI / (2 * numPartials); for (int k = 0; k < numPartials; k++) { double ampl, cGibbs; int sineIndex = 0; int partial = k + 1; cGibbs = Math.cos(k * kGibbs); /* Calculate amplitude for Nth partial */ ampl = cGibbs * cGibbs / partial; for (int j = 0; j < tableSize; j++) { table[j] += (float) ampl * sineTable[sineIndex]; sineIndex += partial; /* Wrap index at end of table.. */ if (sineIndex >= cycleSize) { sineIndex -= cycleSize; } } } } /* Normalize after */ for (int i = 1; i < numTables; i++) { normalizeArray(tables[i]); } } /**************************************************************************/ public static float normalizeArray(float[] fdata) { float max, val, gain; int i; // determine maximum value. max = 0.0f; for (i = 0; i < fdata.length; i++) { val = Math.abs(fdata[i]); if (val > max) max = val; } if (max < 0.0000001f) max = 0.0000001f; // scale array gain = 1.0f / max; for (i = 0; i < fdata.length; i++) fdata[i] *= gain; return gain; } /***************************************************************************** * When the phaseInc maps to the highest level table, then we start interpolating between the * highest table and the raw sawtooth value (phase). When phaseInc points to highest table: * flevel = NUM_TABLES - 1 = -1 - log2(pInc); log2(pInc) = - NUM_TABLES pInc = 2**(-NUM_TABLES) */ private final static double LOWEST_PHASE_INC_INV = (1 << NUM_TABLES); /**************************************************************************/ /* Phase ranges from -1.0 to +1.0 */ public double calculateSawtooth(double currentPhase, double positivePhaseIncrement, double flevel) { float[] tableBase; double val; double hiSam; /* Use when verticalFraction is 1.0 */ double loSam; /* Use when verticalFraction is 0.0 */ double sam1, sam2; /* Use Phase to determine sampleIndex into table. */ double findex = ((phaseScalar * currentPhase) + phaseScalar); // findex is > 0 so we do not need to call floor(). int sampleIndex = (int) findex; double horizontalFraction = findex - sampleIndex; int tableIndex = (int) flevel; if (tableIndex > (NUM_TABLES - 2)) { /* * Just use top table and mix with arithmetic sawtooth if below lowest frequency. * Generate new fraction for interpolating between 0.0 and lowest table frequency. */ double fraction = positivePhaseIncrement * LOWEST_PHASE_INC_INV; tableBase = tables[(NUM_TABLES - 1)]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Use arithmetic version for low frequencies. */ /* fraction is 0.0 at 0 Hz */ val = currentPhase + (fraction * (loSam - currentPhase)); } else { double verticalFraction = flevel - tableIndex; if (tableIndex < 0) { if (tableIndex < -1) // above Nyquist! { val = 0.0; } else { /* * At top of supported range, interpolate between 0.0 and first partial. */ tableBase = tables[0]; /* Sine wave table. */ /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent<SUF>*/ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* loSam = 0.0 */ // verticalFraction is 0.0 at Nyquist val = verticalFraction * hiSam; } } else { /* * Interpolate between adjacent levels to prevent harmonics from popping. */ tableBase = tables[tableIndex + 1]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Get adjacent samples. Assume guard point present. */ tableBase = tables[tableIndex]; sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); val = loSam + (verticalFraction * (hiSam - loSam)); } } return val; } public double convertPhaseIncrementToLevel(double positivePhaseIncrement) { if (positivePhaseIncrement < 1.0e-30) { positivePhaseIncrement = 1.0e-30; } return -1.0 - (Math.log(positivePhaseIncrement) / Math.log(2.0)); } public static MultiTable getInstance() { return instance; } }
False
2,822
106576_25
package org.myrobotlab.service; import java.io.IOException; import org.myrobotlab.framework.Peers; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.LeapMotion2.Hand; import org.myrobotlab.service.LeapMotion2.LeapData; import org.myrobotlab.service.interfaces.LeapDataListener; import org.slf4j.Logger; public class InMoovHand extends Service implements LeapDataListener { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(InMoovHand.class); /** * peer services */ transient public LeapMotion2 leap; transient public Servo thumb; transient public Servo index; transient public Servo majeure; transient public Servo ringFinger; transient public Servo pinky; transient public Servo wrist; transient public Arduino arduino; private String side; // static in Java are not overloaded but overwritten - there is no // polymorphism for statics public static Peers getPeers(String name) { Peers peers = new Peers(name); peers.put("thumb", "Servo", "Thumb servo"); peers.put("index", "Servo", "Index servo"); peers.put("majeure", "Servo", "Majeure servo"); peers.put("ringFinger", "Servo", "RingFinger servo"); peers.put("pinky", "Servo", "Pinky servo"); peers.put("wrist", "Servo", "Wrist servo"); peers.put("arduino", "Arduino", "Arduino controller for this arm"); peers.put("leap", "LeapMotion2", "Leap Motion Service"); // peers.put("keyboard", "Keyboard", "Keyboard control"); // peers.put("xmpp", "XMPP", "XMPP control"); return peers; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { InMoovHand rightHand = new InMoovHand("r01"); Runtime.createAndStart("gui", "GUIService"); rightHand.connect("COM12"); rightHand.startService(); Runtime.createAndStart("webgui", "WebGUI"); // rightHand.connect("COM12"); TEST RECOVERY !!! rightHand.close(); rightHand.open(); rightHand.openPinch(); rightHand.closePinch(); rightHand.rest(); /* * GUIService gui = new GUIService("gui"); gui.startService(); */ } catch (Exception e) { Logging.logError(e); } } // FIXME make // .isValidToStart() !!! < check all user data !!! public InMoovHand(String n) { super(n); thumb = (Servo) createPeer("thumb"); index = (Servo) createPeer("index"); majeure = (Servo) createPeer("majeure"); ringFinger = (Servo) createPeer("ringFinger"); pinky = (Servo) createPeer("pinky"); wrist = (Servo) createPeer("wrist"); arduino = (Arduino) createPeer("arduino"); thumb.setRest(2); index.setRest(2); majeure.setRest(2); ringFinger.setRest(2); pinky.setRest(2); wrist.setRest(90); // connection details thumb.setPin(2); index.setPin(3); majeure.setPin(4); ringFinger.setPin(5); pinky.setPin(6); wrist.setPin(7); thumb.setController(arduino); index.setController(arduino); majeure.setController(arduino); ringFinger.setController(arduino); pinky.setController(arduino); wrist.setController(arduino); } /** * attach all the servos - this must be re-entrant and accomplish the * re-attachment when servos are detached * * @return */ public boolean attach() { sleep(InMoov.attachPauseMs); thumb.attach(); sleep(InMoov.attachPauseMs); index.attach(); sleep(InMoov.attachPauseMs); majeure.attach(); sleep(InMoov.attachPauseMs); ringFinger.attach(); sleep(InMoov.attachPauseMs); pinky.attach(); sleep(InMoov.attachPauseMs); wrist.attach(); return true; } public void bird() { moveTo(150, 180, 0, 180, 180, 90); } @Override public void broadcastState() { // notify the gui thumb.broadcastState(); index.broadcastState(); majeure.broadcastState(); ringFinger.broadcastState(); pinky.broadcastState(); wrist.broadcastState(); } public void close() { moveTo(130, 180, 180, 180, 180); } public void closePinch() { moveTo(130, 140, 180, 180, 180); } // FIXME FIXME - this method must be called // user data needed /** * connect - user data needed * * @param port * @return * @throws IOException */ public boolean connect(String port) throws IOException { if (arduino == null) { error("arduino is invalid"); return false; } arduino.connect(port); if (!arduino.isConnected()) { error("arduino %s not connected", arduino.getName()); return false; } attach(); setSpeed(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f); rest(); sleep(2000); setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); broadcastState(); return true; } public void count() { one(); sleep(1); two(); sleep(1); three(); sleep(1); four(); sleep(1); five(); } public void detach() { thumb.detach(); sleep(InMoov.attachPauseMs); index.detach(); sleep(InMoov.attachPauseMs); majeure.detach(); sleep(InMoov.attachPauseMs); ringFinger.detach(); sleep(InMoov.attachPauseMs); pinky.detach(); sleep(InMoov.attachPauseMs); wrist.detach(); } public void devilHorns() { moveTo(150, 0, 180, 180, 0, 90); } public void five() { open(); } public void four() { moveTo(150, 0, 0, 0, 0, 90); } @Override public String[] getCategories() { return new String[] { "robot" }; } @Override public String getDescription() { return "hand service for inmoov"; } public long getLastActivityTime() { long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime()); return lastActivityTime; } public String getScript(String inMoovServiceName) { return String.format("%s.moveHand(\"%s\",%d,%d,%d,%d,%d,%d)\n", inMoovServiceName, side, thumb.getPos(), index.getPos(), majeure.getPos(), ringFinger.getPos(), pinky.getPos(), wrist.getPos()); } public String getSide() { return side; } public void hangTen() { moveTo(0, 180, 180, 180, 0, 90); } public boolean isAttached() { boolean attached = false; attached |= thumb.isAttached(); attached |= index.isAttached(); attached |= majeure.isAttached(); attached |= ringFinger.isAttached(); attached |= pinky.isAttached(); attached |= wrist.isAttached(); return attached; } public void map(int minX, int maxX, int minY, int maxY) { thumb.map(minX, maxX, minY, maxY); index.map(minX, maxX, minY, maxY); majeure.map(minX, maxX, minY, maxY); ringFinger.map(minX, maxX, minY, maxY); pinky.map(minX, maxX, minY, maxY); } // TODO - waving thread fun public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky) { moveTo(thumb, index, majeure, ringFinger, pinky, null); } public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { if (log.isDebugEnabled()) { log.debug(String.format("%s.moveTo %d %d %d %d %d %d", getName(), thumb, index, majeure, ringFinger, pinky, wrist)); } this.thumb.moveTo(thumb); this.index.moveTo(index); this.majeure.moveTo(majeure); this.ringFinger.moveTo(ringFinger); this.pinky.moveTo(pinky); if (wrist != null) this.wrist.moveTo(wrist); } public void ok() { moveTo(150, 180, 0, 0, 0, 90); } public void one() { moveTo(150, 0, 180, 180, 180, 90); } @Override public LeapData onLeapData(LeapData data) { if (!data.frame.isValid()) { // TODO: we could return void here? not sure // who wants the return value form this method. log.info("Leap data frame not valid."); return data; } Hand h; if ("right".equalsIgnoreCase(side)) { if (data.frame.hands().rightmost().isValid()) { h = data.rightHand; } else { log.info("Right hand frame not valid."); // return this hand isn't valid return data; } } else if ("left".equalsIgnoreCase(side)) { if (data.frame.hands().leftmost().isValid()) { h = data.leftHand; } else { log.info("Left hand frame not valid."); // return this frame isn't valid. return data; } } else { // side could be null? log.info("Unknown Side or side not set on hand (Side = {})", side); // we can default to the right side? // TODO: come up with a better default or at least document this // behavior. if (data.frame.hands().rightmost().isValid()) { h = data.rightHand; } else { log.info("Right(unknown) hand frame not valid."); // return this hand isn't valid return data; } } // If the hand data came from a valid frame, update the finger postions. // move all fingers if (index != null && index.isAttached()) { index.moveTo(h.index); } else { log.debug("Index finger isn't attached or is null."); } if (thumb != null && thumb.isAttached()) { thumb.moveTo(h.thumb); } else { log.debug("Thumb isn't attached or is null."); } if (pinky != null && pinky.isAttached()) { pinky.moveTo(h.pinky); } else { log.debug("Pinky finger isn't attached or is null."); } if (ringFinger != null && ringFinger.isAttached()) { ringFinger.moveTo(h.ring); } else { log.debug("Ring finger isn't attached or is null."); } if (majeure != null && majeure.isAttached()) { majeure.moveTo(h.middle); } else { log.debug("Middle(Majeure) finger isn't attached or is null."); } return data; } public void open() { rest(); } public void openPinch() { moveTo(0, 0, 180, 180, 180); } // ----- initialization end -------- // ----- movements begin ----------- public void release() { detach(); thumb.releaseService(); index.releaseService(); majeure.releaseService(); ringFinger.releaseService(); pinky.releaseService(); wrist.releaseService(); } public void rest() { // initial positions setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); thumb.rest(); index.rest(); majeure.rest(); ringFinger.rest(); pinky.rest(); wrist.rest(); } @Override public boolean save() { super.save(); thumb.save(); index.save(); majeure.save(); ringFinger.save(); pinky.save(); wrist.save(); return true; } public void setPins(int thumb, int index, int majeure, int ringFinger, int pinky, int wrist) { log.info(String.format("setPins %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setPin(thumb); this.index.setPin(index); this.majeure.setPin(majeure); this.ringFinger.setPin(ringFinger); this.pinky.setPin(pinky); this.wrist.setPin(wrist); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky) { setRest(thumb, index, majeure, ringFinger, pinky, null); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky, Integer wrist) { log.info(String.format("setRest %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setRest(thumb); this.index.setRest(index); this.majeure.setRest(majeure); this.ringFinger.setRest(ringFinger); this.pinky.setRest(pinky); if (wrist != null) { this.wrist.setRest(wrist); } } public void setSide(String side) { this.side = side; } public void setSpeed(Float thumb, Float index, Float majeure, Float ringFinger, Float pinky, Float wrist) { this.thumb.setSpeed(thumb); this.index.setSpeed(index); this.majeure.setSpeed(majeure); this.ringFinger.setSpeed(ringFinger); this.pinky.setSpeed(pinky); this.wrist.setSpeed(wrist); } public void startLeapTracking() throws Exception { if (leap == null) { leap = (LeapMotion2) startPeer("leap"); } this.index.map(90, 0, this.index.getMin(), this.index.getMax()); this.thumb.map(90, 50, this.thumb.getMin(), this.thumb.getMax()); this.majeure.map(90, 0, this.majeure.getMin(), this.majeure.getMax()); this.ringFinger.map(90, 0, this.ringFinger.getMin(), this.ringFinger.getMax()); this.pinky.map(90, 0, this.pinky.getMin(), this.pinky.getMax()); leap.addLeapDataListener(this); leap.startTracking(); return; } @Override public void startService() { super.startService(); thumb.startService(); index.startService(); majeure.startService(); ringFinger.startService(); pinky.startService(); wrist.startService(); arduino.startService(); } public void stopLeapTracking() { leap.stopTracking(); this.index.map(this.index.getMin(), this.index.getMax(), this.index.getMin(), this.index.getMax()); this.thumb.map(this.thumb.getMin(), this.thumb.getMax(), this.thumb.getMin(), this.thumb.getMax()); this.majeure.map(this.majeure.getMin(), this.majeure.getMax(), this.majeure.getMin(), this.majeure.getMax()); this.ringFinger.map(this.ringFinger.getMin(), this.ringFinger.getMax(), this.ringFinger.getMin(), this.ringFinger.getMax()); this.pinky.map(this.pinky.getMin(), this.pinky.getMax(), this.pinky.getMin(), this.pinky.getMax()); this.rest(); return; } @Override public Status test() { Status status = Status.info("starting %s %s test", getName(), getType()); try { if (arduino == null) { // gson encoding prevents this throw new Exception("arduino is null"); } if (!arduino.isConnected()) { throw new Exception("arduino not connected"); } thumb.moveTo(thumb.getPos() + 2); index.moveTo(index.getPos() + 2); majeure.moveTo(majeure.getPos() + 2); ringFinger.moveTo(ringFinger.getPos() + 2); pinky.moveTo(pinky.getPos() + 2); wrist.moveTo(wrist.getPos() + 2); } catch (Exception e) { status.addError(e); } status.addInfo("test completed"); return status; } public void three() { moveTo(150, 0, 0, 0, 180, 90); } public void thumbsUp() { moveTo(0, 180, 180, 180, 180, 90); } public void two() { victory(); } public void victory() { moveTo(150, 0, 0, 180, 180, 90); } }
glaudiston/project-bianca
arduino/code/myrobotlab-1.0.119/src/org/myrobotlab/service/InMoovHand.java
5,429
// ----- movements begin -----------
line_comment
nl
package org.myrobotlab.service; import java.io.IOException; import org.myrobotlab.framework.Peers; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.LeapMotion2.Hand; import org.myrobotlab.service.LeapMotion2.LeapData; import org.myrobotlab.service.interfaces.LeapDataListener; import org.slf4j.Logger; public class InMoovHand extends Service implements LeapDataListener { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(InMoovHand.class); /** * peer services */ transient public LeapMotion2 leap; transient public Servo thumb; transient public Servo index; transient public Servo majeure; transient public Servo ringFinger; transient public Servo pinky; transient public Servo wrist; transient public Arduino arduino; private String side; // static in Java are not overloaded but overwritten - there is no // polymorphism for statics public static Peers getPeers(String name) { Peers peers = new Peers(name); peers.put("thumb", "Servo", "Thumb servo"); peers.put("index", "Servo", "Index servo"); peers.put("majeure", "Servo", "Majeure servo"); peers.put("ringFinger", "Servo", "RingFinger servo"); peers.put("pinky", "Servo", "Pinky servo"); peers.put("wrist", "Servo", "Wrist servo"); peers.put("arduino", "Arduino", "Arduino controller for this arm"); peers.put("leap", "LeapMotion2", "Leap Motion Service"); // peers.put("keyboard", "Keyboard", "Keyboard control"); // peers.put("xmpp", "XMPP", "XMPP control"); return peers; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { InMoovHand rightHand = new InMoovHand("r01"); Runtime.createAndStart("gui", "GUIService"); rightHand.connect("COM12"); rightHand.startService(); Runtime.createAndStart("webgui", "WebGUI"); // rightHand.connect("COM12"); TEST RECOVERY !!! rightHand.close(); rightHand.open(); rightHand.openPinch(); rightHand.closePinch(); rightHand.rest(); /* * GUIService gui = new GUIService("gui"); gui.startService(); */ } catch (Exception e) { Logging.logError(e); } } // FIXME make // .isValidToStart() !!! < check all user data !!! public InMoovHand(String n) { super(n); thumb = (Servo) createPeer("thumb"); index = (Servo) createPeer("index"); majeure = (Servo) createPeer("majeure"); ringFinger = (Servo) createPeer("ringFinger"); pinky = (Servo) createPeer("pinky"); wrist = (Servo) createPeer("wrist"); arduino = (Arduino) createPeer("arduino"); thumb.setRest(2); index.setRest(2); majeure.setRest(2); ringFinger.setRest(2); pinky.setRest(2); wrist.setRest(90); // connection details thumb.setPin(2); index.setPin(3); majeure.setPin(4); ringFinger.setPin(5); pinky.setPin(6); wrist.setPin(7); thumb.setController(arduino); index.setController(arduino); majeure.setController(arduino); ringFinger.setController(arduino); pinky.setController(arduino); wrist.setController(arduino); } /** * attach all the servos - this must be re-entrant and accomplish the * re-attachment when servos are detached * * @return */ public boolean attach() { sleep(InMoov.attachPauseMs); thumb.attach(); sleep(InMoov.attachPauseMs); index.attach(); sleep(InMoov.attachPauseMs); majeure.attach(); sleep(InMoov.attachPauseMs); ringFinger.attach(); sleep(InMoov.attachPauseMs); pinky.attach(); sleep(InMoov.attachPauseMs); wrist.attach(); return true; } public void bird() { moveTo(150, 180, 0, 180, 180, 90); } @Override public void broadcastState() { // notify the gui thumb.broadcastState(); index.broadcastState(); majeure.broadcastState(); ringFinger.broadcastState(); pinky.broadcastState(); wrist.broadcastState(); } public void close() { moveTo(130, 180, 180, 180, 180); } public void closePinch() { moveTo(130, 140, 180, 180, 180); } // FIXME FIXME - this method must be called // user data needed /** * connect - user data needed * * @param port * @return * @throws IOException */ public boolean connect(String port) throws IOException { if (arduino == null) { error("arduino is invalid"); return false; } arduino.connect(port); if (!arduino.isConnected()) { error("arduino %s not connected", arduino.getName()); return false; } attach(); setSpeed(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f); rest(); sleep(2000); setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); broadcastState(); return true; } public void count() { one(); sleep(1); two(); sleep(1); three(); sleep(1); four(); sleep(1); five(); } public void detach() { thumb.detach(); sleep(InMoov.attachPauseMs); index.detach(); sleep(InMoov.attachPauseMs); majeure.detach(); sleep(InMoov.attachPauseMs); ringFinger.detach(); sleep(InMoov.attachPauseMs); pinky.detach(); sleep(InMoov.attachPauseMs); wrist.detach(); } public void devilHorns() { moveTo(150, 0, 180, 180, 0, 90); } public void five() { open(); } public void four() { moveTo(150, 0, 0, 0, 0, 90); } @Override public String[] getCategories() { return new String[] { "robot" }; } @Override public String getDescription() { return "hand service for inmoov"; } public long getLastActivityTime() { long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime()); return lastActivityTime; } public String getScript(String inMoovServiceName) { return String.format("%s.moveHand(\"%s\",%d,%d,%d,%d,%d,%d)\n", inMoovServiceName, side, thumb.getPos(), index.getPos(), majeure.getPos(), ringFinger.getPos(), pinky.getPos(), wrist.getPos()); } public String getSide() { return side; } public void hangTen() { moveTo(0, 180, 180, 180, 0, 90); } public boolean isAttached() { boolean attached = false; attached |= thumb.isAttached(); attached |= index.isAttached(); attached |= majeure.isAttached(); attached |= ringFinger.isAttached(); attached |= pinky.isAttached(); attached |= wrist.isAttached(); return attached; } public void map(int minX, int maxX, int minY, int maxY) { thumb.map(minX, maxX, minY, maxY); index.map(minX, maxX, minY, maxY); majeure.map(minX, maxX, minY, maxY); ringFinger.map(minX, maxX, minY, maxY); pinky.map(minX, maxX, minY, maxY); } // TODO - waving thread fun public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky) { moveTo(thumb, index, majeure, ringFinger, pinky, null); } public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { if (log.isDebugEnabled()) { log.debug(String.format("%s.moveTo %d %d %d %d %d %d", getName(), thumb, index, majeure, ringFinger, pinky, wrist)); } this.thumb.moveTo(thumb); this.index.moveTo(index); this.majeure.moveTo(majeure); this.ringFinger.moveTo(ringFinger); this.pinky.moveTo(pinky); if (wrist != null) this.wrist.moveTo(wrist); } public void ok() { moveTo(150, 180, 0, 0, 0, 90); } public void one() { moveTo(150, 0, 180, 180, 180, 90); } @Override public LeapData onLeapData(LeapData data) { if (!data.frame.isValid()) { // TODO: we could return void here? not sure // who wants the return value form this method. log.info("Leap data frame not valid."); return data; } Hand h; if ("right".equalsIgnoreCase(side)) { if (data.frame.hands().rightmost().isValid()) { h = data.rightHand; } else { log.info("Right hand frame not valid."); // return this hand isn't valid return data; } } else if ("left".equalsIgnoreCase(side)) { if (data.frame.hands().leftmost().isValid()) { h = data.leftHand; } else { log.info("Left hand frame not valid."); // return this frame isn't valid. return data; } } else { // side could be null? log.info("Unknown Side or side not set on hand (Side = {})", side); // we can default to the right side? // TODO: come up with a better default or at least document this // behavior. if (data.frame.hands().rightmost().isValid()) { h = data.rightHand; } else { log.info("Right(unknown) hand frame not valid."); // return this hand isn't valid return data; } } // If the hand data came from a valid frame, update the finger postions. // move all fingers if (index != null && index.isAttached()) { index.moveTo(h.index); } else { log.debug("Index finger isn't attached or is null."); } if (thumb != null && thumb.isAttached()) { thumb.moveTo(h.thumb); } else { log.debug("Thumb isn't attached or is null."); } if (pinky != null && pinky.isAttached()) { pinky.moveTo(h.pinky); } else { log.debug("Pinky finger isn't attached or is null."); } if (ringFinger != null && ringFinger.isAttached()) { ringFinger.moveTo(h.ring); } else { log.debug("Ring finger isn't attached or is null."); } if (majeure != null && majeure.isAttached()) { majeure.moveTo(h.middle); } else { log.debug("Middle(Majeure) finger isn't attached or is null."); } return data; } public void open() { rest(); } public void openPinch() { moveTo(0, 0, 180, 180, 180); } // ----- initialization end -------- // ----- movements<SUF> public void release() { detach(); thumb.releaseService(); index.releaseService(); majeure.releaseService(); ringFinger.releaseService(); pinky.releaseService(); wrist.releaseService(); } public void rest() { // initial positions setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); thumb.rest(); index.rest(); majeure.rest(); ringFinger.rest(); pinky.rest(); wrist.rest(); } @Override public boolean save() { super.save(); thumb.save(); index.save(); majeure.save(); ringFinger.save(); pinky.save(); wrist.save(); return true; } public void setPins(int thumb, int index, int majeure, int ringFinger, int pinky, int wrist) { log.info(String.format("setPins %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setPin(thumb); this.index.setPin(index); this.majeure.setPin(majeure); this.ringFinger.setPin(ringFinger); this.pinky.setPin(pinky); this.wrist.setPin(wrist); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky) { setRest(thumb, index, majeure, ringFinger, pinky, null); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky, Integer wrist) { log.info(String.format("setRest %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setRest(thumb); this.index.setRest(index); this.majeure.setRest(majeure); this.ringFinger.setRest(ringFinger); this.pinky.setRest(pinky); if (wrist != null) { this.wrist.setRest(wrist); } } public void setSide(String side) { this.side = side; } public void setSpeed(Float thumb, Float index, Float majeure, Float ringFinger, Float pinky, Float wrist) { this.thumb.setSpeed(thumb); this.index.setSpeed(index); this.majeure.setSpeed(majeure); this.ringFinger.setSpeed(ringFinger); this.pinky.setSpeed(pinky); this.wrist.setSpeed(wrist); } public void startLeapTracking() throws Exception { if (leap == null) { leap = (LeapMotion2) startPeer("leap"); } this.index.map(90, 0, this.index.getMin(), this.index.getMax()); this.thumb.map(90, 50, this.thumb.getMin(), this.thumb.getMax()); this.majeure.map(90, 0, this.majeure.getMin(), this.majeure.getMax()); this.ringFinger.map(90, 0, this.ringFinger.getMin(), this.ringFinger.getMax()); this.pinky.map(90, 0, this.pinky.getMin(), this.pinky.getMax()); leap.addLeapDataListener(this); leap.startTracking(); return; } @Override public void startService() { super.startService(); thumb.startService(); index.startService(); majeure.startService(); ringFinger.startService(); pinky.startService(); wrist.startService(); arduino.startService(); } public void stopLeapTracking() { leap.stopTracking(); this.index.map(this.index.getMin(), this.index.getMax(), this.index.getMin(), this.index.getMax()); this.thumb.map(this.thumb.getMin(), this.thumb.getMax(), this.thumb.getMin(), this.thumb.getMax()); this.majeure.map(this.majeure.getMin(), this.majeure.getMax(), this.majeure.getMin(), this.majeure.getMax()); this.ringFinger.map(this.ringFinger.getMin(), this.ringFinger.getMax(), this.ringFinger.getMin(), this.ringFinger.getMax()); this.pinky.map(this.pinky.getMin(), this.pinky.getMax(), this.pinky.getMin(), this.pinky.getMax()); this.rest(); return; } @Override public Status test() { Status status = Status.info("starting %s %s test", getName(), getType()); try { if (arduino == null) { // gson encoding prevents this throw new Exception("arduino is null"); } if (!arduino.isConnected()) { throw new Exception("arduino not connected"); } thumb.moveTo(thumb.getPos() + 2); index.moveTo(index.getPos() + 2); majeure.moveTo(majeure.getPos() + 2); ringFinger.moveTo(ringFinger.getPos() + 2); pinky.moveTo(pinky.getPos() + 2); wrist.moveTo(wrist.getPos() + 2); } catch (Exception e) { status.addError(e); } status.addInfo("test completed"); return status; } public void three() { moveTo(150, 0, 0, 0, 180, 90); } public void thumbsUp() { moveTo(0, 180, 180, 180, 180, 90); } public void two() { victory(); } public void victory() { moveTo(150, 0, 0, 180, 180, 90); } }
False
1,810
143257_32
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * A class to hold all init parameters specific to the JSP engine. * * @author Anil K. Vijendran * @author Hans Bergsten * @author Pierre Delisle */ public final class EmbeddedServletOptions implements Options { // Logger private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); private Properties settings = new Properties(); /** * Is Jasper being used in development mode? */ private boolean development = true; /** * Should Ant fork its java compiles of JSP pages. */ public boolean fork = true; /** * Do you want to keep the generated Java files around? */ private boolean keepGenerated = true; /** * Should white spaces between directives or actions be trimmed? */ private boolean trimSpaces = false; /** * Determines whether tag handler pooling is enabled. */ private boolean isPoolingEnabled = true; /** * Do you want support for "mapped" files? This will generate * servlet that has a print statement per line of the JSP file. * This seems like a really nice feature to have for debugging. */ private boolean mappedFile = true; /** * Do we want to include debugging information in the class file? */ private boolean classDebugInfo = true; /** * Background compile thread check interval in seconds. */ private int checkInterval = 0; /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ private boolean isSmapSuppressed = false; /** * Should SMAP info for JSR45 debugging be dumped to a file? */ private boolean isSmapDumped = false; /** * Are Text strings to be generated as char arrays? */ private boolean genStringAsCharArray = false; private boolean errorOnUseBeanInvalidClassAttribute = true; /** * I want to see my generated servlets. Which directory are they * in? */ private File scratchDir; /** * Need to have this as is for versions 4 and 5 of IE. Can be set from * the initParams so if it changes in the future all that is needed is * to have a jsp initParam of type ieClassId="<value>" */ private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; /** * What classpath should I use while compiling generated servlets? */ private String classpath = null; /** * Compiler to use. */ private String compiler = null; /** * Compiler target VM. */ private String compilerTargetVM = "1.8"; /** * The compiler source VM. */ private String compilerSourceVM = "1.8"; /** * The compiler class name. */ private String compilerClassName = null; /** * Cache for the TLD URIs, resource paths and parsed files. */ private TldCache tldCache = null; /** * Jsp config information */ private JspConfig jspConfig = null; /** * TagPluginManager */ private TagPluginManager tagPluginManager = null; /** * Java platform encoding to generate the JSP * page servlet. */ private String javaEncoding = "UTF8"; /** * Modification test interval. */ private int modificationTestInterval = 4; /** * Is re-compilation attempted immediately after a failure? */ private boolean recompileOnFail = false; /** * Is generation of X-Powered-By response header enabled/disabled? */ private boolean xpoweredBy; /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ private boolean displaySourceFragment = true; /** * The maximum number of loaded jsps per web-application. If there are more * jsps loaded, they will be unloaded. */ private int maxLoadedJsps = -1; /** * The idle time in seconds after which a JSP is unloaded. * If unset or less or equal than 0, no jsps are unloaded. */ private int jspIdleTimeout = -1; /** * Should JSP.1.6 be applied strictly to attributes defined using scriptlet * expressions? */ private boolean strictQuoteEscaping = true; /** * When EL is used in JSP attribute values, should the rules for quoting of * attributes described in JSP.1.6 be applied to the expression? */ private boolean quoteAttributeEL = true; public String getProperty(String name ) { return settings.getProperty( name ); } public void setProperty(String name, String value ) { if (name != null && value != null){ settings.setProperty( name, value ); } } public void setQuoteAttributeEL(boolean b) { this.quoteAttributeEL = b; } @Override public boolean getQuoteAttributeEL() { return quoteAttributeEL; } /** * Are we keeping generated code around? */ @Override public boolean getKeepGenerated() { return keepGenerated; } /** * Should white spaces between directives or actions be trimmed? */ @Override public boolean getTrimSpaces() { return trimSpaces; } @Override public boolean isPoolingEnabled() { return isPoolingEnabled; } /** * Are we supporting HTML mapped servlets? */ @Override public boolean getMappedFile() { return mappedFile; } /** * Should class files be compiled with debug information? */ @Override public boolean getClassDebugInfo() { return classDebugInfo; } /** * Background JSP compile thread check interval */ @Override public int getCheckInterval() { return checkInterval; } /** * Modification test interval. */ @Override public int getModificationTestInterval() { return modificationTestInterval; } /** * Re-compile on failure. */ @Override public boolean getRecompileOnFail() { return recompileOnFail; } /** * Is Jasper being used in development mode? */ @Override public boolean getDevelopment() { return development; } /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ @Override public boolean isSmapSuppressed() { return isSmapSuppressed; } /** * Should SMAP info for JSR45 debugging be dumped to a file? */ @Override public boolean isSmapDumped() { return isSmapDumped; } /** * Are Text strings to be generated as char arrays? */ @Override public boolean genStringAsCharArray() { return this.genStringAsCharArray; } /** * Class ID for use in the plugin tag when the browser is IE. */ @Override public String getIeClassId() { return ieClassId; } /** * What is my scratch dir? */ @Override public File getScratchDir() { return scratchDir; } /** * What classpath should I use while compiling the servlets * generated from JSP files? */ @Override public String getClassPath() { return classpath; } /** * Is generation of X-Powered-By response header enabled/disabled? */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Compiler to use. */ @Override public String getCompiler() { return compiler; } /** * @see Options#getCompilerTargetVM */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * @see Options#getCompilerSourceVM */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Java compiler class to use. */ @Override public String getCompilerClassName() { return compilerClassName; } @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } @Override public TldCache getTldCache() { return tldCache; } public void setTldCache(TldCache tldCache) { this.tldCache = tldCache; } @Override public String getJavaEncoding() { return javaEncoding; } @Override public boolean getFork() { return fork; } @Override public JspConfig getJspConfig() { return jspConfig; } @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } @Override public boolean isCaching() { return false; } @Override public Map<String, TagLibraryInfo> getCache() { return null; } /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ @Override public boolean getDisplaySourceFragment() { return displaySourceFragment; } /** * Should jsps be unloaded if to many are loaded? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getMaxLoadedJsps() { return maxLoadedJsps; } /** * Should any jsps be unloaded when being idle for this time in seconds? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getJspIdleTimeout() { return jspIdleTimeout; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } /** * Create an EmbeddedServletOptions object using data available from * ServletConfig and ServletContext. */ public EmbeddedServletOptions(ServletConfig config, ServletContext context) { Enumeration<String> enumeration=config.getInitParameterNames(); while( enumeration.hasMoreElements() ) { String k=enumeration.nextElement(); String v=config.getInitParameter( k ); setProperty( k, v); } String keepgen = config.getInitParameter("keepgenerated"); if (keepgen != null) { if (keepgen.equalsIgnoreCase("true")) { this.keepGenerated = true; } else if (keepgen.equalsIgnoreCase("false")) { this.keepGenerated = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.keepgen")); } } } String trimsp = config.getInitParameter("trimSpaces"); if (trimsp != null) { if (trimsp.equalsIgnoreCase("true")) { trimSpaces = true; } else if (trimsp.equalsIgnoreCase("false")) { trimSpaces = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.trimspaces")); } } } this.isPoolingEnabled = true; String poolingEnabledParam = config.getInitParameter("enablePooling"); if (poolingEnabledParam != null && !poolingEnabledParam.equalsIgnoreCase("true")) { if (poolingEnabledParam.equalsIgnoreCase("false")) { this.isPoolingEnabled = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.enablePooling")); } } } String mapFile = config.getInitParameter("mappedfile"); if (mapFile != null) { if (mapFile.equalsIgnoreCase("true")) { this.mappedFile = true; } else if (mapFile.equalsIgnoreCase("false")) { this.mappedFile = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.mappedFile")); } } } String debugInfo = config.getInitParameter("classdebuginfo"); if (debugInfo != null) { if (debugInfo.equalsIgnoreCase("true")) { this.classDebugInfo = true; } else if (debugInfo.equalsIgnoreCase("false")) { this.classDebugInfo = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.classDebugInfo")); } } } String checkInterval = config.getInitParameter("checkInterval"); if (checkInterval != null) { try { this.checkInterval = Integer.parseInt(checkInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } } } String modificationTestInterval = config.getInitParameter("modificationTestInterval"); if (modificationTestInterval != null) { try { this.modificationTestInterval = Integer.parseInt(modificationTestInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } } } String recompileOnFail = config.getInitParameter("recompileOnFail"); if (recompileOnFail != null) { if (recompileOnFail.equalsIgnoreCase("true")) { this.recompileOnFail = true; } else if (recompileOnFail.equalsIgnoreCase("false")) { this.recompileOnFail = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.recompileOnFail")); } } } String development = config.getInitParameter("development"); if (development != null) { if (development.equalsIgnoreCase("true")) { this.development = true; } else if (development.equalsIgnoreCase("false")) { this.development = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.development")); } } } String suppressSmap = config.getInitParameter("suppressSmap"); if (suppressSmap != null) { if (suppressSmap.equalsIgnoreCase("true")) { isSmapSuppressed = true; } else if (suppressSmap.equalsIgnoreCase("false")) { isSmapSuppressed = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.suppressSmap")); } } } String dumpSmap = config.getInitParameter("dumpSmap"); if (dumpSmap != null) { if (dumpSmap.equalsIgnoreCase("true")) { isSmapDumped = true; } else if (dumpSmap.equalsIgnoreCase("false")) { isSmapDumped = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.dumpSmap")); } } } String genCharArray = config.getInitParameter("genStringAsCharArray"); if (genCharArray != null) { if (genCharArray.equalsIgnoreCase("true")) { genStringAsCharArray = true; } else if (genCharArray.equalsIgnoreCase("false")) { genStringAsCharArray = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.genchararray")); } } } String errBeanClass = config.getInitParameter("errorOnUseBeanInvalidClassAttribute"); if (errBeanClass != null) { if (errBeanClass.equalsIgnoreCase("true")) { errorOnUseBeanInvalidClassAttribute = true; } else if (errBeanClass.equalsIgnoreCase("false")) { errorOnUseBeanInvalidClassAttribute = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.errBean")); } } } String ieClassId = config.getInitParameter("ieClassId"); if (ieClassId != null) this.ieClassId = ieClassId; String classpath = config.getInitParameter("classpath"); if (classpath != null) this.classpath = classpath; /* * scratchdir */ String dir = config.getInitParameter("scratchdir"); if (dir != null) { scratchDir = new File(dir); } else { // First try the Servlet 2.2 javax.servlet.context.tempdir property scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR); if (scratchDir == null) { // Not running in a Servlet 2.2 container. // Try to get the JDK 1.2 java.io.tmpdir property dir = System.getProperty("java.io.tmpdir"); if (dir != null) scratchDir = new File(dir); } } if (this.scratchDir == null) { log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir")); return; } if (!(scratchDir.exists() && scratchDir.canRead() && scratchDir.canWrite() && scratchDir.isDirectory())) log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir", scratchDir.getAbsolutePath())); this.compiler = config.getInitParameter("compiler"); String compilerTargetVM = config.getInitParameter("compilerTargetVM"); if(compilerTargetVM != null) { this.compilerTargetVM = compilerTargetVM; } String compilerSourceVM = config.getInitParameter("compilerSourceVM"); if(compilerSourceVM != null) { this.compilerSourceVM = compilerSourceVM; } String javaEncoding = config.getInitParameter("javaEncoding"); if (javaEncoding != null) { this.javaEncoding = javaEncoding; } String compilerClassName = config.getInitParameter("compilerClassName"); if (compilerClassName != null) { this.compilerClassName = compilerClassName; } String fork = config.getInitParameter("fork"); if (fork != null) { if (fork.equalsIgnoreCase("true")) { this.fork = true; } else if (fork.equalsIgnoreCase("false")) { this.fork = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.fork")); } } } String xpoweredBy = config.getInitParameter("xpoweredBy"); if (xpoweredBy != null) { if (xpoweredBy.equalsIgnoreCase("true")) { this.xpoweredBy = true; } else if (xpoweredBy.equalsIgnoreCase("false")) { this.xpoweredBy = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.xpoweredBy")); } } } String displaySourceFragment = config.getInitParameter("displaySourceFragment"); if (displaySourceFragment != null) { if (displaySourceFragment.equalsIgnoreCase("true")) { this.displaySourceFragment = true; } else if (displaySourceFragment.equalsIgnoreCase("false")) { this.displaySourceFragment = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment")); } } } String maxLoadedJsps = config.getInitParameter("maxLoadedJsps"); if (maxLoadedJsps != null) { try { this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } } } String jspIdleTimeout = config.getInitParameter("jspIdleTimeout"); if (jspIdleTimeout != null) { try { this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } } } String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping"); if (strictQuoteEscaping != null) { if (strictQuoteEscaping.equalsIgnoreCase("true")) { this.strictQuoteEscaping = true; } else if (strictQuoteEscaping.equalsIgnoreCase("false")) { this.strictQuoteEscaping = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping")); } } } String quoteAttributeEL = config.getInitParameter("quoteAttributeEL"); if (quoteAttributeEL != null) { if (quoteAttributeEL.equalsIgnoreCase("true")) { this.quoteAttributeEL = true; } else if (quoteAttributeEL.equalsIgnoreCase("false")) { this.quoteAttributeEL = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL")); } } } // Setup the global Tag Libraries location cache for this // web-application. tldCache = TldCache.getInstance(context); // Setup the jsp config info for this web app. jspConfig = new JspConfig(context); // Create a Tag plugin instance tagPluginManager = new TagPluginManager(context); } }
UnimibSoftEngCourse1516/lab4-es1-f.giannini3
java/org/apache/jasper/EmbeddedServletOptions.java
6,476
/** * Are we keeping generated code around? */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * A class to hold all init parameters specific to the JSP engine. * * @author Anil K. Vijendran * @author Hans Bergsten * @author Pierre Delisle */ public final class EmbeddedServletOptions implements Options { // Logger private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); private Properties settings = new Properties(); /** * Is Jasper being used in development mode? */ private boolean development = true; /** * Should Ant fork its java compiles of JSP pages. */ public boolean fork = true; /** * Do you want to keep the generated Java files around? */ private boolean keepGenerated = true; /** * Should white spaces between directives or actions be trimmed? */ private boolean trimSpaces = false; /** * Determines whether tag handler pooling is enabled. */ private boolean isPoolingEnabled = true; /** * Do you want support for "mapped" files? This will generate * servlet that has a print statement per line of the JSP file. * This seems like a really nice feature to have for debugging. */ private boolean mappedFile = true; /** * Do we want to include debugging information in the class file? */ private boolean classDebugInfo = true; /** * Background compile thread check interval in seconds. */ private int checkInterval = 0; /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ private boolean isSmapSuppressed = false; /** * Should SMAP info for JSR45 debugging be dumped to a file? */ private boolean isSmapDumped = false; /** * Are Text strings to be generated as char arrays? */ private boolean genStringAsCharArray = false; private boolean errorOnUseBeanInvalidClassAttribute = true; /** * I want to see my generated servlets. Which directory are they * in? */ private File scratchDir; /** * Need to have this as is for versions 4 and 5 of IE. Can be set from * the initParams so if it changes in the future all that is needed is * to have a jsp initParam of type ieClassId="<value>" */ private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; /** * What classpath should I use while compiling generated servlets? */ private String classpath = null; /** * Compiler to use. */ private String compiler = null; /** * Compiler target VM. */ private String compilerTargetVM = "1.8"; /** * The compiler source VM. */ private String compilerSourceVM = "1.8"; /** * The compiler class name. */ private String compilerClassName = null; /** * Cache for the TLD URIs, resource paths and parsed files. */ private TldCache tldCache = null; /** * Jsp config information */ private JspConfig jspConfig = null; /** * TagPluginManager */ private TagPluginManager tagPluginManager = null; /** * Java platform encoding to generate the JSP * page servlet. */ private String javaEncoding = "UTF8"; /** * Modification test interval. */ private int modificationTestInterval = 4; /** * Is re-compilation attempted immediately after a failure? */ private boolean recompileOnFail = false; /** * Is generation of X-Powered-By response header enabled/disabled? */ private boolean xpoweredBy; /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ private boolean displaySourceFragment = true; /** * The maximum number of loaded jsps per web-application. If there are more * jsps loaded, they will be unloaded. */ private int maxLoadedJsps = -1; /** * The idle time in seconds after which a JSP is unloaded. * If unset or less or equal than 0, no jsps are unloaded. */ private int jspIdleTimeout = -1; /** * Should JSP.1.6 be applied strictly to attributes defined using scriptlet * expressions? */ private boolean strictQuoteEscaping = true; /** * When EL is used in JSP attribute values, should the rules for quoting of * attributes described in JSP.1.6 be applied to the expression? */ private boolean quoteAttributeEL = true; public String getProperty(String name ) { return settings.getProperty( name ); } public void setProperty(String name, String value ) { if (name != null && value != null){ settings.setProperty( name, value ); } } public void setQuoteAttributeEL(boolean b) { this.quoteAttributeEL = b; } @Override public boolean getQuoteAttributeEL() { return quoteAttributeEL; } /** * Are we keeping<SUF>*/ @Override public boolean getKeepGenerated() { return keepGenerated; } /** * Should white spaces between directives or actions be trimmed? */ @Override public boolean getTrimSpaces() { return trimSpaces; } @Override public boolean isPoolingEnabled() { return isPoolingEnabled; } /** * Are we supporting HTML mapped servlets? */ @Override public boolean getMappedFile() { return mappedFile; } /** * Should class files be compiled with debug information? */ @Override public boolean getClassDebugInfo() { return classDebugInfo; } /** * Background JSP compile thread check interval */ @Override public int getCheckInterval() { return checkInterval; } /** * Modification test interval. */ @Override public int getModificationTestInterval() { return modificationTestInterval; } /** * Re-compile on failure. */ @Override public boolean getRecompileOnFail() { return recompileOnFail; } /** * Is Jasper being used in development mode? */ @Override public boolean getDevelopment() { return development; } /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ @Override public boolean isSmapSuppressed() { return isSmapSuppressed; } /** * Should SMAP info for JSR45 debugging be dumped to a file? */ @Override public boolean isSmapDumped() { return isSmapDumped; } /** * Are Text strings to be generated as char arrays? */ @Override public boolean genStringAsCharArray() { return this.genStringAsCharArray; } /** * Class ID for use in the plugin tag when the browser is IE. */ @Override public String getIeClassId() { return ieClassId; } /** * What is my scratch dir? */ @Override public File getScratchDir() { return scratchDir; } /** * What classpath should I use while compiling the servlets * generated from JSP files? */ @Override public String getClassPath() { return classpath; } /** * Is generation of X-Powered-By response header enabled/disabled? */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Compiler to use. */ @Override public String getCompiler() { return compiler; } /** * @see Options#getCompilerTargetVM */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * @see Options#getCompilerSourceVM */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Java compiler class to use. */ @Override public String getCompilerClassName() { return compilerClassName; } @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } @Override public TldCache getTldCache() { return tldCache; } public void setTldCache(TldCache tldCache) { this.tldCache = tldCache; } @Override public String getJavaEncoding() { return javaEncoding; } @Override public boolean getFork() { return fork; } @Override public JspConfig getJspConfig() { return jspConfig; } @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } @Override public boolean isCaching() { return false; } @Override public Map<String, TagLibraryInfo> getCache() { return null; } /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ @Override public boolean getDisplaySourceFragment() { return displaySourceFragment; } /** * Should jsps be unloaded if to many are loaded? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getMaxLoadedJsps() { return maxLoadedJsps; } /** * Should any jsps be unloaded when being idle for this time in seconds? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getJspIdleTimeout() { return jspIdleTimeout; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } /** * Create an EmbeddedServletOptions object using data available from * ServletConfig and ServletContext. */ public EmbeddedServletOptions(ServletConfig config, ServletContext context) { Enumeration<String> enumeration=config.getInitParameterNames(); while( enumeration.hasMoreElements() ) { String k=enumeration.nextElement(); String v=config.getInitParameter( k ); setProperty( k, v); } String keepgen = config.getInitParameter("keepgenerated"); if (keepgen != null) { if (keepgen.equalsIgnoreCase("true")) { this.keepGenerated = true; } else if (keepgen.equalsIgnoreCase("false")) { this.keepGenerated = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.keepgen")); } } } String trimsp = config.getInitParameter("trimSpaces"); if (trimsp != null) { if (trimsp.equalsIgnoreCase("true")) { trimSpaces = true; } else if (trimsp.equalsIgnoreCase("false")) { trimSpaces = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.trimspaces")); } } } this.isPoolingEnabled = true; String poolingEnabledParam = config.getInitParameter("enablePooling"); if (poolingEnabledParam != null && !poolingEnabledParam.equalsIgnoreCase("true")) { if (poolingEnabledParam.equalsIgnoreCase("false")) { this.isPoolingEnabled = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.enablePooling")); } } } String mapFile = config.getInitParameter("mappedfile"); if (mapFile != null) { if (mapFile.equalsIgnoreCase("true")) { this.mappedFile = true; } else if (mapFile.equalsIgnoreCase("false")) { this.mappedFile = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.mappedFile")); } } } String debugInfo = config.getInitParameter("classdebuginfo"); if (debugInfo != null) { if (debugInfo.equalsIgnoreCase("true")) { this.classDebugInfo = true; } else if (debugInfo.equalsIgnoreCase("false")) { this.classDebugInfo = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.classDebugInfo")); } } } String checkInterval = config.getInitParameter("checkInterval"); if (checkInterval != null) { try { this.checkInterval = Integer.parseInt(checkInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } } } String modificationTestInterval = config.getInitParameter("modificationTestInterval"); if (modificationTestInterval != null) { try { this.modificationTestInterval = Integer.parseInt(modificationTestInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } } } String recompileOnFail = config.getInitParameter("recompileOnFail"); if (recompileOnFail != null) { if (recompileOnFail.equalsIgnoreCase("true")) { this.recompileOnFail = true; } else if (recompileOnFail.equalsIgnoreCase("false")) { this.recompileOnFail = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.recompileOnFail")); } } } String development = config.getInitParameter("development"); if (development != null) { if (development.equalsIgnoreCase("true")) { this.development = true; } else if (development.equalsIgnoreCase("false")) { this.development = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.development")); } } } String suppressSmap = config.getInitParameter("suppressSmap"); if (suppressSmap != null) { if (suppressSmap.equalsIgnoreCase("true")) { isSmapSuppressed = true; } else if (suppressSmap.equalsIgnoreCase("false")) { isSmapSuppressed = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.suppressSmap")); } } } String dumpSmap = config.getInitParameter("dumpSmap"); if (dumpSmap != null) { if (dumpSmap.equalsIgnoreCase("true")) { isSmapDumped = true; } else if (dumpSmap.equalsIgnoreCase("false")) { isSmapDumped = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.dumpSmap")); } } } String genCharArray = config.getInitParameter("genStringAsCharArray"); if (genCharArray != null) { if (genCharArray.equalsIgnoreCase("true")) { genStringAsCharArray = true; } else if (genCharArray.equalsIgnoreCase("false")) { genStringAsCharArray = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.genchararray")); } } } String errBeanClass = config.getInitParameter("errorOnUseBeanInvalidClassAttribute"); if (errBeanClass != null) { if (errBeanClass.equalsIgnoreCase("true")) { errorOnUseBeanInvalidClassAttribute = true; } else if (errBeanClass.equalsIgnoreCase("false")) { errorOnUseBeanInvalidClassAttribute = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.errBean")); } } } String ieClassId = config.getInitParameter("ieClassId"); if (ieClassId != null) this.ieClassId = ieClassId; String classpath = config.getInitParameter("classpath"); if (classpath != null) this.classpath = classpath; /* * scratchdir */ String dir = config.getInitParameter("scratchdir"); if (dir != null) { scratchDir = new File(dir); } else { // First try the Servlet 2.2 javax.servlet.context.tempdir property scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR); if (scratchDir == null) { // Not running in a Servlet 2.2 container. // Try to get the JDK 1.2 java.io.tmpdir property dir = System.getProperty("java.io.tmpdir"); if (dir != null) scratchDir = new File(dir); } } if (this.scratchDir == null) { log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir")); return; } if (!(scratchDir.exists() && scratchDir.canRead() && scratchDir.canWrite() && scratchDir.isDirectory())) log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir", scratchDir.getAbsolutePath())); this.compiler = config.getInitParameter("compiler"); String compilerTargetVM = config.getInitParameter("compilerTargetVM"); if(compilerTargetVM != null) { this.compilerTargetVM = compilerTargetVM; } String compilerSourceVM = config.getInitParameter("compilerSourceVM"); if(compilerSourceVM != null) { this.compilerSourceVM = compilerSourceVM; } String javaEncoding = config.getInitParameter("javaEncoding"); if (javaEncoding != null) { this.javaEncoding = javaEncoding; } String compilerClassName = config.getInitParameter("compilerClassName"); if (compilerClassName != null) { this.compilerClassName = compilerClassName; } String fork = config.getInitParameter("fork"); if (fork != null) { if (fork.equalsIgnoreCase("true")) { this.fork = true; } else if (fork.equalsIgnoreCase("false")) { this.fork = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.fork")); } } } String xpoweredBy = config.getInitParameter("xpoweredBy"); if (xpoweredBy != null) { if (xpoweredBy.equalsIgnoreCase("true")) { this.xpoweredBy = true; } else if (xpoweredBy.equalsIgnoreCase("false")) { this.xpoweredBy = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.xpoweredBy")); } } } String displaySourceFragment = config.getInitParameter("displaySourceFragment"); if (displaySourceFragment != null) { if (displaySourceFragment.equalsIgnoreCase("true")) { this.displaySourceFragment = true; } else if (displaySourceFragment.equalsIgnoreCase("false")) { this.displaySourceFragment = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment")); } } } String maxLoadedJsps = config.getInitParameter("maxLoadedJsps"); if (maxLoadedJsps != null) { try { this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } } } String jspIdleTimeout = config.getInitParameter("jspIdleTimeout"); if (jspIdleTimeout != null) { try { this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } } } String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping"); if (strictQuoteEscaping != null) { if (strictQuoteEscaping.equalsIgnoreCase("true")) { this.strictQuoteEscaping = true; } else if (strictQuoteEscaping.equalsIgnoreCase("false")) { this.strictQuoteEscaping = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping")); } } } String quoteAttributeEL = config.getInitParameter("quoteAttributeEL"); if (quoteAttributeEL != null) { if (quoteAttributeEL.equalsIgnoreCase("true")) { this.quoteAttributeEL = true; } else if (quoteAttributeEL.equalsIgnoreCase("false")) { this.quoteAttributeEL = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL")); } } } // Setup the global Tag Libraries location cache for this // web-application. tldCache = TldCache.getInstance(context); // Setup the jsp config info for this web app. jspConfig = new JspConfig(context); // Create a Tag plugin instance tagPluginManager = new TagPluginManager(context); } }
False
1,577
55900_5
package nl.shadowlink.tools.shadowlib.model.model; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import nl.shadowlink.tools.io.Vector4D; import java.util.ArrayList; /** * @author Shadow-Link */ public class Strip { private ArrayList<Polygon> poly = new ArrayList(); private ArrayList<Vertex> vert = new ArrayList(); private int polyCount; private int materialIndex; // shader index public Vertex max = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vertex min = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vertex center = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vector4D sphere = new Vector4D(0.0f, 0.0f, 0.0f, 0.0f); /** * Creates a new strip with the given amount of polys and materialindex * * @param polyCount number of polys * @param materialIndex index of the material */ public Strip(int polyCount, int materialIndex) { this.polyCount = polyCount; this.materialIndex = materialIndex; } /** * Adds a poly to this strip * * @param polygon to add */ public void addPoly(Polygon polygon) { poly.add(polygon); } /** * Add vertex to this strip and checks if it's not already in the strip * * @param vertex to add * @return index where the vertex has been added */ public int addVertex(Vertex vertex) { int ret = -1; if (!vert.contains(vertex)) { ret = vert.size(); vert.add(vertex); // //Message.displayMsgLow("Added vertex at " + ret); } else { ret = vert.indexOf(vertex); // //Message.displayMsgLow("Vertex bestond al in deze strip " + ret); } return ret; } /** * Adds vertex to the strip without checking if it already exists * * @param vertex the vertex to add */ public void addVertexToStrip(Vertex vertex) { vert.add(vertex); checkBounds(vertex); } public Polygon getPoly(int id) { return poly.get(id); } public int getPolyCount() { return poly.size(); } public int getShaderNumber() { return materialIndex; } public int getVertexCount() { return vert.size(); } public Vertex getVertex(int i) { return vert.get(i); } /** * Render this strip * * @param gl used to render this strip */ public void render(GL2 gl) { gl.glBegin(GL.GL_TRIANGLES); //begin triangle object for (int i = 0; i < poly.size(); i++) { //zolang we polygons hebben Polygon pol = poly.get(i); Vertex verta = vert.get(pol.a); Vertex vertb = vert.get(pol.b); Vertex vertc = vert.get(pol.c); gl.glTexCoord2f(verta.u, verta.v); gl.glVertex3f(verta.x, verta.y, verta.z); //eerste vertex van polygon gl.glTexCoord2f(vertb.u, vertb.v); gl.glVertex3f(vertb.x, vertb.y, vertb.z); // tweede vertex van polygon gl.glTexCoord2f(vertc.u, vertc.v); gl.glVertex3f(vertc.x, vertc.y, vertc.z); // derde vertex van polygon } gl.glEnd(); } /** * Check if the vertex is out of the current bounds if so it will set the bounds of this element to the current * vertex * * @param vertex Vertex to check this with */ public void checkBounds(Vertex vertex) { if (vertex.getVertexX() > max.getVertexX()) max.setVertexX(vertex.getVertexX()); if (vertex.getVertexY() > max.getVertexY()) max.setVertexY(vertex.getVertexY()); if (vertex.getVertexZ() > max.getVertexZ()) max.setVertexZ(vertex.getVertexZ()); if (vertex.getVertexX() < min.getVertexX()) min.setVertexX(vertex.getVertexX()); if (vertex.getVertexY() < min.getVertexY()) min.setVertexY(vertex.getVertexY()); if (vertex.getVertexZ() < min.getVertexZ()) min.setVertexZ(vertex.getVertexZ()); center.setVertexX((max.getVertexX() + min.getVertexX()) / 2); center.setVertexY((max.getVertexY() + min.getVertexY()) / 2); center.setVertexZ((max.getVertexZ() + min.getVertexZ()) / 2); sphere.x = center.x; sphere.y = center.y; sphere.z = center.z; sphere.w = getMax(); } private float getMax() { float value = max.x; if (value < max.y) value = max.y; if (value < max.z) value = max.z; if (value < 0 - min.x) value = 0 - min.x; if (value < 0 - min.y) value = 0 - min.y; if (value < 0 - min.z) value = 0 - min.z; // System.out.println("Max is: " + value); return value; } }
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/model/model/Strip.java
1,590
// //Message.displayMsgLow("Vertex bestond al in deze strip " + ret);
line_comment
nl
package nl.shadowlink.tools.shadowlib.model.model; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import nl.shadowlink.tools.io.Vector4D; import java.util.ArrayList; /** * @author Shadow-Link */ public class Strip { private ArrayList<Polygon> poly = new ArrayList(); private ArrayList<Vertex> vert = new ArrayList(); private int polyCount; private int materialIndex; // shader index public Vertex max = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vertex min = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vertex center = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f); public Vector4D sphere = new Vector4D(0.0f, 0.0f, 0.0f, 0.0f); /** * Creates a new strip with the given amount of polys and materialindex * * @param polyCount number of polys * @param materialIndex index of the material */ public Strip(int polyCount, int materialIndex) { this.polyCount = polyCount; this.materialIndex = materialIndex; } /** * Adds a poly to this strip * * @param polygon to add */ public void addPoly(Polygon polygon) { poly.add(polygon); } /** * Add vertex to this strip and checks if it's not already in the strip * * @param vertex to add * @return index where the vertex has been added */ public int addVertex(Vertex vertex) { int ret = -1; if (!vert.contains(vertex)) { ret = vert.size(); vert.add(vertex); // //Message.displayMsgLow("Added vertex at " + ret); } else { ret = vert.indexOf(vertex); // //Message.displayMsgLow("Vertex bestond<SUF> } return ret; } /** * Adds vertex to the strip without checking if it already exists * * @param vertex the vertex to add */ public void addVertexToStrip(Vertex vertex) { vert.add(vertex); checkBounds(vertex); } public Polygon getPoly(int id) { return poly.get(id); } public int getPolyCount() { return poly.size(); } public int getShaderNumber() { return materialIndex; } public int getVertexCount() { return vert.size(); } public Vertex getVertex(int i) { return vert.get(i); } /** * Render this strip * * @param gl used to render this strip */ public void render(GL2 gl) { gl.glBegin(GL.GL_TRIANGLES); //begin triangle object for (int i = 0; i < poly.size(); i++) { //zolang we polygons hebben Polygon pol = poly.get(i); Vertex verta = vert.get(pol.a); Vertex vertb = vert.get(pol.b); Vertex vertc = vert.get(pol.c); gl.glTexCoord2f(verta.u, verta.v); gl.glVertex3f(verta.x, verta.y, verta.z); //eerste vertex van polygon gl.glTexCoord2f(vertb.u, vertb.v); gl.glVertex3f(vertb.x, vertb.y, vertb.z); // tweede vertex van polygon gl.glTexCoord2f(vertc.u, vertc.v); gl.glVertex3f(vertc.x, vertc.y, vertc.z); // derde vertex van polygon } gl.glEnd(); } /** * Check if the vertex is out of the current bounds if so it will set the bounds of this element to the current * vertex * * @param vertex Vertex to check this with */ public void checkBounds(Vertex vertex) { if (vertex.getVertexX() > max.getVertexX()) max.setVertexX(vertex.getVertexX()); if (vertex.getVertexY() > max.getVertexY()) max.setVertexY(vertex.getVertexY()); if (vertex.getVertexZ() > max.getVertexZ()) max.setVertexZ(vertex.getVertexZ()); if (vertex.getVertexX() < min.getVertexX()) min.setVertexX(vertex.getVertexX()); if (vertex.getVertexY() < min.getVertexY()) min.setVertexY(vertex.getVertexY()); if (vertex.getVertexZ() < min.getVertexZ()) min.setVertexZ(vertex.getVertexZ()); center.setVertexX((max.getVertexX() + min.getVertexX()) / 2); center.setVertexY((max.getVertexY() + min.getVertexY()) / 2); center.setVertexZ((max.getVertexZ() + min.getVertexZ()) / 2); sphere.x = center.x; sphere.y = center.y; sphere.z = center.z; sphere.w = getMax(); } private float getMax() { float value = max.x; if (value < max.y) value = max.y; if (value < max.z) value = max.z; if (value < 0 - min.x) value = 0 - min.x; if (value < 0 - min.y) value = 0 - min.y; if (value < 0 - min.z) value = 0 - min.z; // System.out.println("Max is: " + value); return value; } }
False
1,020
209269_11
package be.ehb.koalaexpress; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.TextHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Date; import java.util.List; import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB; import be.ehb.koalaexpress.models.WinkelMandje; import cz.msebera.android.httpclient.Header; public class CheckoutActivity extends AppCompatActivity { TextView orderID_label; TextView payerID_label; TextView paymentAmount_label; Button confirm_btn; Button annuleren_btn; ProgressBar progressbar; public String orderID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hiding ActionBar if (getSupportActionBar() != null) { getSupportActionBar().hide(); } setContentView(R.layout.activity_checkout); //get the orderID from the query parameter Uri redirectUri = getIntent().getData(); List<String> segmentsInUrl = redirectUri.getPathSegments(); //hier kan je succes of failure halen uit de segmenstInURL orderID = redirectUri.getQueryParameter("token"); String payerID = redirectUri.getQueryParameter("PayerID"); progressbar = findViewById(R.id.progressbar); progressbar.setVisibility(View.INVISIBLE); //set the orderID string to the UI orderID_label = (TextView) findViewById(R.id.orderID); orderID_label.setText("Checkout ID: " +orderID); payerID_label = (TextView) findViewById(R.id.payerid); payerID_label.setText("Je Betaler Id is: " +payerID); paymentAmount_label = (TextView) findViewById(R.id.amt); paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice)); //add an onClick listener to the confirm button confirm_btn = findViewById(R.id.confirm_btn); confirm_btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { captureOrder(orderID); //function to finalize the payment } }); annuleren_btn= findViewById(R.id.annuleren_btn); annuleren_btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { returnToOrderZonderConfirm(); } }); } void captureOrder(String orderID){ //get the accessToken from MainActivity progressbar.setVisibility(View.VISIBLE); String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken; AsyncHttpClient client = new AsyncHttpClient(); client.addHeader("Accept", "application/json"); client.addHeader("Content-type", "application/json"); client.addHeader("Authorization", "Bearer " + accessToken); client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) { Log.i("RESPONSE", response); } @Override public void onSuccess(int statusCode, Header[] headers, String response) { // eerst het resultaat van call verwerken om paymentid op te halen String paymentId = ""; try { JSONObject jsonResponse = new JSONObject(response); String orderId = jsonResponse.getString("id"); // This is the order ID JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units"); if (purchaseUnits.length() > 0) { JSONObject purchaseUnit = purchaseUnits.getJSONObject(0); JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures"); if (payments.length() > 0) { JSONObject payment = payments.getJSONObject(0); paymentId = payment.getString("id"); // dit is de payment id } } } catch (JSONException e) { e.printStackTrace(); } KoalaDataRepository repo = KoalaDataRepository.getInstance(); WinkelMandje mandje = repo.mWinkelMandje.getValue(); mandje.mPayPalPaymentId = paymentId; Date currentDate = new Date(); mandje.mPayedOnDate = new Timestamp(currentDate.getTime()); repo.mWinkelMandje.setValue(mandje); // order opslaan in db Task_SendOrderToDB taak = new Task_SendOrderToDB(); taak.execute(mandje); // 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //redirect back to home page of app Intent intent = new Intent(CheckoutActivity.this, MainActivity.class); intent.putExtra("JumpToFragment","WinkelMandjeSucces"); intent.putExtra("AfgeslotenOrderId",orderID); intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId); progressbar.setVisibility(View.INVISIBLE); startActivity(intent); } }, 3000); // 3000ms delay } }); } public void returnToOrderZonderConfirm() { Intent intent = new Intent(CheckoutActivity.this, MainActivity.class); intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren"); startActivity(intent); } }
MRoeland/KoalaExpress
app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java
1,762
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
line_comment
nl
package be.ehb.koalaexpress; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.TextHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Date; import java.util.List; import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB; import be.ehb.koalaexpress.models.WinkelMandje; import cz.msebera.android.httpclient.Header; public class CheckoutActivity extends AppCompatActivity { TextView orderID_label; TextView payerID_label; TextView paymentAmount_label; Button confirm_btn; Button annuleren_btn; ProgressBar progressbar; public String orderID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hiding ActionBar if (getSupportActionBar() != null) { getSupportActionBar().hide(); } setContentView(R.layout.activity_checkout); //get the orderID from the query parameter Uri redirectUri = getIntent().getData(); List<String> segmentsInUrl = redirectUri.getPathSegments(); //hier kan je succes of failure halen uit de segmenstInURL orderID = redirectUri.getQueryParameter("token"); String payerID = redirectUri.getQueryParameter("PayerID"); progressbar = findViewById(R.id.progressbar); progressbar.setVisibility(View.INVISIBLE); //set the orderID string to the UI orderID_label = (TextView) findViewById(R.id.orderID); orderID_label.setText("Checkout ID: " +orderID); payerID_label = (TextView) findViewById(R.id.payerid); payerID_label.setText("Je Betaler Id is: " +payerID); paymentAmount_label = (TextView) findViewById(R.id.amt); paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice)); //add an onClick listener to the confirm button confirm_btn = findViewById(R.id.confirm_btn); confirm_btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { captureOrder(orderID); //function to finalize the payment } }); annuleren_btn= findViewById(R.id.annuleren_btn); annuleren_btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { returnToOrderZonderConfirm(); } }); } void captureOrder(String orderID){ //get the accessToken from MainActivity progressbar.setVisibility(View.VISIBLE); String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken; AsyncHttpClient client = new AsyncHttpClient(); client.addHeader("Accept", "application/json"); client.addHeader("Content-type", "application/json"); client.addHeader("Authorization", "Bearer " + accessToken); client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) { Log.i("RESPONSE", response); } @Override public void onSuccess(int statusCode, Header[] headers, String response) { // eerst het resultaat van call verwerken om paymentid op te halen String paymentId = ""; try { JSONObject jsonResponse = new JSONObject(response); String orderId = jsonResponse.getString("id"); // This is the order ID JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units"); if (purchaseUnits.length() > 0) { JSONObject purchaseUnit = purchaseUnits.getJSONObject(0); JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures"); if (payments.length() > 0) { JSONObject payment = payments.getJSONObject(0); paymentId = payment.getString("id"); // dit is de payment id } } } catch (JSONException e) { e.printStackTrace(); } KoalaDataRepository repo = KoalaDataRepository.getInstance(); WinkelMandje mandje = repo.mWinkelMandje.getValue(); mandje.mPayPalPaymentId = paymentId; Date currentDate = new Date(); mandje.mPayedOnDate = new Timestamp(currentDate.getTime()); repo.mWinkelMandje.setValue(mandje); // order opslaan in db Task_SendOrderToDB taak = new Task_SendOrderToDB(); taak.execute(mandje); // 3 seconden<SUF> Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //redirect back to home page of app Intent intent = new Intent(CheckoutActivity.this, MainActivity.class); intent.putExtra("JumpToFragment","WinkelMandjeSucces"); intent.putExtra("AfgeslotenOrderId",orderID); intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId); progressbar.setVisibility(View.INVISIBLE); startActivity(intent); } }, 3000); // 3000ms delay } }); } public void returnToOrderZonderConfirm() { Intent intent = new Intent(CheckoutActivity.this, MainActivity.class); intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren"); startActivity(intent); } }
True
4,078
69850_5
package com.dudu0118.superrefreshlib.view; import android.content.Context; import android.content.res.TypedArray; import android.support.v4.view.ViewCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Scroller; import android.widget.Toast; import com.dudu0118.superrefreshlib.R; import com.dudu0118.superrefreshlib.holder.BaseHolder; import com.dudu0118.superrefreshlib.holder.LoadMoreHolder; import com.dudu0118.superrefreshlib.utils.Util; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ValueAnimator; /** * author: qiulie * created on: 2016/9/2 18:34 * description: 支持listview与Recyclerview下拉刷新控件 */ public class SuperRefreshLayout extends RelativeLayout { public static final String Tag = SuperRefreshLayout.class.getSimpleName(); public static final int STATE_PULL_REFRESH = 0;// 下拉刷新 public static final int STATE_RELEASE_REFRESH = 1;// 松开刷新 public static final int STATE_REFRESHING = 2;// 正在刷新 public static final int STATE_LOADMOREING = 3;// 正在加载更多 // 初始化参数 private boolean isPullEndless; // 下拉无尽模式 private boolean isOverlay; // 覆盖模式 private int showType; // 显示类型 0:文字模式 1:官方模式 // 运行中参数 private int mCurrrentState = STATE_PULL_REFRESH;// 当前状态 private Context context; private View mChildView; private DefaultHeadView mHeadView; private int mHeadViewHeight; private BaseHolder mFootView; private int mFootViewHeight; private float mTouchY; private float mLastY; private boolean isInControl = false; private boolean isLoadMore = true; // 是否有加载更多 private boolean isLoadMoreing = false; //加载更多中 private Scroller mScroller; private RefreshListener mRefreshListener; public SuperRefreshLayout(Context context) { this(context, null); } public SuperRefreshLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SuperRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { this.context = context; TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.SuperRefreshLayout, defStyleAttr, 0); isPullEndless = t.getBoolean(R.styleable.SuperRefreshLayout_pull_endless, false); isOverlay = t.getBoolean(R.styleable.SuperRefreshLayout_overlay, false); showType = t.getInt(R.styleable.SuperRefreshLayout_show_type, 0); t.recycle(); mScroller = new Scroller(context); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); // Log.i(Tag, "onAttachedToWindow"); Context context = getContext(); mChildView = getChildAt(0); switch (showType) { case 0: mHeadView = new TextHeadView(context); break; case 1: mHeadView = new MaterialHeaderView(context); break; case 2: mHeadView = new GooHeadView(context); break; } if (mChildView instanceof ListView) { ((ListView) mChildView).setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_FLING) { if (((ListView) mChildView).getLastVisiblePosition() == ((ListView) mChildView).getCount() - 1) {// 滑动到最后 // Log.e(Tag, "滑动到底部了..."); if(isLoadMore) toggleFootView(true); } else { } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } if(mChildView instanceof RecyclerView){ ((RecyclerView)mChildView).addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { int type; int lastVisiblePosition = 0; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if(manager instanceof LinearLayoutManager){ lastVisiblePosition = ((LinearLayoutManager)manager).findLastVisibleItemPosition(); }else if(manager instanceof GridLayoutManager){ lastVisiblePosition = ((GridLayoutManager)manager).findLastVisibleItemPosition(); }else if(manager instanceof StaggeredGridLayoutManager){ int[] positions = ((StaggeredGridLayoutManager) manager).findLastVisibleItemPositions(null); for (int a : positions) { lastVisiblePosition = Math.max(a,lastVisiblePosition); } } if (newState == RecyclerView.SCROLL_STATE_IDLE) { if(lastVisiblePosition >= manager.getItemCount() - 1){// 滑动到最后 // Log.e(Tag, "滑动到底部了..."); if(isLoadMore) toggleFootView(true); } else { } } } }); } mHeadView.measure(0, 0); mHeadViewHeight = mHeadView.getMeasuredHeight(); if (showType == 1) { mHeadViewHeight += Util.dip2px(context, 10); } mFootView = new LoadMoreHolder(context); mFootView.getRootView().measure(0, 0); mFootViewHeight = mFootView.getRootView().getMeasuredHeight(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, mFootViewHeight); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lp.setMargins(0, -mFootViewHeight, 0, -mFootViewHeight); mFootView.getRootView().setLayoutParams(lp); // Log.e(Tag, "mHeadViewHeight=" + mHeadView.getMeasuredHeight()); // Log.e(Tag, "mFootViewHeight=" + mFootView.getMeasuredHeight()); // mHeadViewHeight = Util.dip2px(context, 48); mHeadView.setVisibility(View.GONE); mFootView.getRootView().setVisibility(View.VISIBLE); addView(mHeadView, LayoutParams.MATCH_PARENT, mHeadViewHeight); addView(mFootView.getRootView()); if (mChildView == null) { return; } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int action = ev.getAction(); float y = ev.getY(); switch (action) { case MotionEvent.ACTION_DOWN: // Log.e(Tag, "dispatchTouchEvent === ACTION_DOWN"); mLastY = y; break; case MotionEvent.ACTION_MOVE: // Log.e(Tag, "dispatchTouchEvent === ACTION_MOVE"); float dy = y - mLastY; if (!isInControl && mCurrrentState != STATE_REFRESHING && ((!canPullDown() && dy > 0) || (getScrollY() != 0) || (isLoadMore && !canPullUp() && dy < 0))) { // Log.e(Tag, "事件分发处理..."); isInControl = true; ev.setAction(MotionEvent.ACTION_CANCEL); MotionEvent ev2 = MotionEvent.obtain(ev); dispatchTouchEvent(ev); ev2.setAction(MotionEvent.ACTION_DOWN); return dispatchTouchEvent(ev2); } break; } return super.dispatchTouchEvent(ev); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mCurrrentState == STATE_REFRESHING) return true; switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // Log.e(Tag, "onInterceptTouchEvent === ACTION_DOWN"); mTouchY = ev.getY(); break; case MotionEvent.ACTION_MOVE: // Log.e(Tag, "onInterceptTouchEvent === ACTION_MOVE"); float curY = ev.getY(); float dy = curY - mTouchY; if (getScrollY() != 0) { return true; } if (mCurrrentState != STATE_REFRESHING && dy > 0 && !canPullDown()) { return true; } if (isLoadMore && mCurrrentState != STATE_REFRESHING && dy < 0 && !canPullUp()) { return true; } isInControl = false; break; } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { if (mCurrrentState == STATE_REFRESHING) return super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_MOVE: // Log.e(Tag, "TouchEvent === ACTION_MOVE"); float curY = event.getY(); float dy = curY - mTouchY; int scrollY = getScrollY(); //加载更多有显示的情况 if (scrollY != 0) { scrollY = Math.max(0, scrollY - (int) dy); if (scrollY > mFootViewHeight) scrollY = mFootViewHeight; scrollTo(0, scrollY); mTouchY = curY; //让listview去处理事件 if (scrollY == 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; } return true; } if (!canPullDown()) dealHeadView(event, dy); else if (!canPullUp() && isLoadMore) dealFootView(event, dy); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (mCurrrentState == STATE_RELEASE_REFRESH) { startAnimator(mChildView, mHeadViewHeight, mHeadView); } else if (mCurrrentState == STATE_PULL_REFRESH) { startAnimator(mChildView, 0, mHeadView); } //判断是否加载更多 int y = getScrollY(); if(y != 0 && isLoadMore) { if (y == mFootViewHeight) { toggleFootView(true); } else { if(mCurrrentState == STATE_LOADMOREING) toggleFootView(true); else toggleFootView(false); } } break; } return true; } private void dealFootView(MotionEvent event, float dy) { //让listview去处理事件 if (dy > 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; dy = 0; } dy = Math.abs(dy); if (dy > mFootViewHeight) dy = mFootViewHeight; scrollTo(0, (int) dy); // mFootView.setVisibility(View.VISIBLE); } private void dealHeadView(MotionEvent event, float dy) { if (dy < 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; dy = 0; } if (dy / 2 > mHeadViewHeight) { if (!isPullEndless) dy = mHeadViewHeight * 2; else dy = (((dy / 2 - mHeadViewHeight) / 2) + mHeadViewHeight) * 2; if (mCurrrentState != STATE_RELEASE_REFRESH) { mCurrrentState = STATE_RELEASE_REFRESH; refreshState(); } } else { if (mCurrrentState != STATE_PULL_REFRESH) { mCurrrentState = STATE_PULL_REFRESH; refreshState(); } } // Log.e(Tag, "dy=" + dy); mHeadView.setVisibility(View.VISIBLE); mHeadView.getLayoutParams().height = (int) (dy / 2); mHeadView.requestLayout(); mHeadView.updatePullOffset(dy / 2 / mHeadViewHeight); if (!isOverlay) { LayoutParams layoutParams = (LayoutParams) mChildView.getLayoutParams(); layoutParams.setMargins(0, (int) (dy / 2), 0, 0); mChildView.setLayoutParams(layoutParams); } } private void toggleFootView(boolean isOpen) { int scrollY = getScrollY(); mScroller.abortAnimation(); if(isOpen) { // Log.e(Tag,"isOpen..."); int dy = mFootViewHeight - scrollY; mScroller.startScroll(0, scrollY, 0, dy, 250); if(mCurrrentState == STATE_LOADMOREING) return; mCurrrentState = STATE_LOADMOREING; refreshState(); } else { // Log.e(Tag,"isClose..."); if(scrollY == 0) return; mScroller.startScroll(0, scrollY, 0, -scrollY, 250); mCurrrentState = STATE_PULL_REFRESH; refreshState(); } invalidate(); // scrollTo(0, mFootViewHeight); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); }else{ // Log.e(Tag,"computeScroll="+getScrollY()); } } private void refreshState() { switch (mCurrrentState) { case STATE_PULL_REFRESH: mHeadView.setPullState(STATE_PULL_REFRESH); break; case STATE_RELEASE_REFRESH: mHeadView.setPullState(STATE_RELEASE_REFRESH); break; case STATE_REFRESHING: mHeadView.setPullState(STATE_REFRESHING); if (mRefreshListener != null) mRefreshListener.onRefresh(this); break; case STATE_LOADMOREING: if(mRefreshListener != null) mRefreshListener.onRefreshLoadMore(this); break; default: break; } } private boolean canPullDown() { if (mChildView == null) return false; return ViewCompat.canScrollVertically(mChildView, -1); } private boolean canPullUp() { if (mChildView == null) return false; return ViewCompat.canScrollVertically(mChildView, 1); } public void finishRefresh() { this.post(new Runnable() { @Override public void run() { if (mHeadView != null) mHeadView.overRefresh(); startAnimator(mChildView, 0, mHeadView); } }); } public void finishLoadMore() { this.post(new Runnable() { @Override public void run() { if (mFootView != null) toggleFootView(false); } }); } public void autoRefresh() { this.postDelayed(new Runnable() { @Override public void run() { if (mCurrrentState != STATE_REFRESHING) { if (mHeadView != null) { startAnimator(mChildView, mHeadViewHeight, mHeadView); } } } }, 50); } private void startAnimator(final View v, final int endH, final FrameLayout fl) { final RelativeLayout.LayoutParams childParams = (LayoutParams) mChildView.getLayoutParams(); int startH = childParams.topMargin; if (isOverlay) startH = fl.getLayoutParams().height; ValueAnimator valueAnimator = ValueAnimator.ofInt(startH, endH); valueAnimator.setDuration(250); valueAnimator.start(); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int height = (int) valueAnimator.getAnimatedValue(); if (fl.getVisibility() != View.VISIBLE) fl.setVisibility(View.VISIBLE); fl.getLayoutParams().height = height; fl.requestLayout(); mHeadView.setVisibility(View.VISIBLE); if (!isOverlay) { childParams.setMargins(0, height, 0, 0); mChildView.setLayoutParams(childParams); } } }); valueAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { if (endH == 0) { mCurrrentState = STATE_PULL_REFRESH; refreshState(); } else { mCurrrentState = STATE_REFRESHING; refreshState(); } } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); } public <T extends DefaultHeadView> void setHeadView(T v) { if (mHeadView != null) removeView(mHeadView); mHeadView = v; v.measure(0, 0); mHeadViewHeight = v.getMeasuredHeight(); addView(mHeadView, LayoutParams.MATCH_PARENT, mHeadViewHeight); } /** * 监听回调接口 */ public interface RefreshListener { public void onRefresh(SuperRefreshLayout superRefreshLayout); public void onRefreshLoadMore(SuperRefreshLayout superRefreshLayout); } public void setRefreshListener(RefreshListener refreshListener) { this.mRefreshListener = refreshListener; } public boolean isLoadMore() { return isLoadMore; } public void setLoadMore(boolean loadMore) { isLoadMore = loadMore; } public boolean isOverlay() { return isOverlay; } public void setOverlay(boolean overlay) { isOverlay = overlay; } public boolean isPullEndless() { return isPullEndless; } public void setPullEndless(boolean pullEndless) { isPullEndless = pullEndless; } }
ql0101/SuperRefreshLayout-Android
library/src/main/java/com/dudu0118/superrefreshlib/view/SuperRefreshLayout.java
5,538
// Log.e(Tag, "dispatchTouchEvent === ACTION_DOWN");
line_comment
nl
package com.dudu0118.superrefreshlib.view; import android.content.Context; import android.content.res.TypedArray; import android.support.v4.view.ViewCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Scroller; import android.widget.Toast; import com.dudu0118.superrefreshlib.R; import com.dudu0118.superrefreshlib.holder.BaseHolder; import com.dudu0118.superrefreshlib.holder.LoadMoreHolder; import com.dudu0118.superrefreshlib.utils.Util; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ValueAnimator; /** * author: qiulie * created on: 2016/9/2 18:34 * description: 支持listview与Recyclerview下拉刷新控件 */ public class SuperRefreshLayout extends RelativeLayout { public static final String Tag = SuperRefreshLayout.class.getSimpleName(); public static final int STATE_PULL_REFRESH = 0;// 下拉刷新 public static final int STATE_RELEASE_REFRESH = 1;// 松开刷新 public static final int STATE_REFRESHING = 2;// 正在刷新 public static final int STATE_LOADMOREING = 3;// 正在加载更多 // 初始化参数 private boolean isPullEndless; // 下拉无尽模式 private boolean isOverlay; // 覆盖模式 private int showType; // 显示类型 0:文字模式 1:官方模式 // 运行中参数 private int mCurrrentState = STATE_PULL_REFRESH;// 当前状态 private Context context; private View mChildView; private DefaultHeadView mHeadView; private int mHeadViewHeight; private BaseHolder mFootView; private int mFootViewHeight; private float mTouchY; private float mLastY; private boolean isInControl = false; private boolean isLoadMore = true; // 是否有加载更多 private boolean isLoadMoreing = false; //加载更多中 private Scroller mScroller; private RefreshListener mRefreshListener; public SuperRefreshLayout(Context context) { this(context, null); } public SuperRefreshLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SuperRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { this.context = context; TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.SuperRefreshLayout, defStyleAttr, 0); isPullEndless = t.getBoolean(R.styleable.SuperRefreshLayout_pull_endless, false); isOverlay = t.getBoolean(R.styleable.SuperRefreshLayout_overlay, false); showType = t.getInt(R.styleable.SuperRefreshLayout_show_type, 0); t.recycle(); mScroller = new Scroller(context); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); // Log.i(Tag, "onAttachedToWindow"); Context context = getContext(); mChildView = getChildAt(0); switch (showType) { case 0: mHeadView = new TextHeadView(context); break; case 1: mHeadView = new MaterialHeaderView(context); break; case 2: mHeadView = new GooHeadView(context); break; } if (mChildView instanceof ListView) { ((ListView) mChildView).setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_FLING) { if (((ListView) mChildView).getLastVisiblePosition() == ((ListView) mChildView).getCount() - 1) {// 滑动到最后 // Log.e(Tag, "滑动到底部了..."); if(isLoadMore) toggleFootView(true); } else { } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } if(mChildView instanceof RecyclerView){ ((RecyclerView)mChildView).addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { int type; int lastVisiblePosition = 0; RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if(manager instanceof LinearLayoutManager){ lastVisiblePosition = ((LinearLayoutManager)manager).findLastVisibleItemPosition(); }else if(manager instanceof GridLayoutManager){ lastVisiblePosition = ((GridLayoutManager)manager).findLastVisibleItemPosition(); }else if(manager instanceof StaggeredGridLayoutManager){ int[] positions = ((StaggeredGridLayoutManager) manager).findLastVisibleItemPositions(null); for (int a : positions) { lastVisiblePosition = Math.max(a,lastVisiblePosition); } } if (newState == RecyclerView.SCROLL_STATE_IDLE) { if(lastVisiblePosition >= manager.getItemCount() - 1){// 滑动到最后 // Log.e(Tag, "滑动到底部了..."); if(isLoadMore) toggleFootView(true); } else { } } } }); } mHeadView.measure(0, 0); mHeadViewHeight = mHeadView.getMeasuredHeight(); if (showType == 1) { mHeadViewHeight += Util.dip2px(context, 10); } mFootView = new LoadMoreHolder(context); mFootView.getRootView().measure(0, 0); mFootViewHeight = mFootView.getRootView().getMeasuredHeight(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, mFootViewHeight); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lp.setMargins(0, -mFootViewHeight, 0, -mFootViewHeight); mFootView.getRootView().setLayoutParams(lp); // Log.e(Tag, "mHeadViewHeight=" + mHeadView.getMeasuredHeight()); // Log.e(Tag, "mFootViewHeight=" + mFootView.getMeasuredHeight()); // mHeadViewHeight = Util.dip2px(context, 48); mHeadView.setVisibility(View.GONE); mFootView.getRootView().setVisibility(View.VISIBLE); addView(mHeadView, LayoutParams.MATCH_PARENT, mHeadViewHeight); addView(mFootView.getRootView()); if (mChildView == null) { return; } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int action = ev.getAction(); float y = ev.getY(); switch (action) { case MotionEvent.ACTION_DOWN: // Log.e(Tag, "dispatchTouchEvent<SUF> mLastY = y; break; case MotionEvent.ACTION_MOVE: // Log.e(Tag, "dispatchTouchEvent === ACTION_MOVE"); float dy = y - mLastY; if (!isInControl && mCurrrentState != STATE_REFRESHING && ((!canPullDown() && dy > 0) || (getScrollY() != 0) || (isLoadMore && !canPullUp() && dy < 0))) { // Log.e(Tag, "事件分发处理..."); isInControl = true; ev.setAction(MotionEvent.ACTION_CANCEL); MotionEvent ev2 = MotionEvent.obtain(ev); dispatchTouchEvent(ev); ev2.setAction(MotionEvent.ACTION_DOWN); return dispatchTouchEvent(ev2); } break; } return super.dispatchTouchEvent(ev); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mCurrrentState == STATE_REFRESHING) return true; switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // Log.e(Tag, "onInterceptTouchEvent === ACTION_DOWN"); mTouchY = ev.getY(); break; case MotionEvent.ACTION_MOVE: // Log.e(Tag, "onInterceptTouchEvent === ACTION_MOVE"); float curY = ev.getY(); float dy = curY - mTouchY; if (getScrollY() != 0) { return true; } if (mCurrrentState != STATE_REFRESHING && dy > 0 && !canPullDown()) { return true; } if (isLoadMore && mCurrrentState != STATE_REFRESHING && dy < 0 && !canPullUp()) { return true; } isInControl = false; break; } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { if (mCurrrentState == STATE_REFRESHING) return super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_MOVE: // Log.e(Tag, "TouchEvent === ACTION_MOVE"); float curY = event.getY(); float dy = curY - mTouchY; int scrollY = getScrollY(); //加载更多有显示的情况 if (scrollY != 0) { scrollY = Math.max(0, scrollY - (int) dy); if (scrollY > mFootViewHeight) scrollY = mFootViewHeight; scrollTo(0, scrollY); mTouchY = curY; //让listview去处理事件 if (scrollY == 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; } return true; } if (!canPullDown()) dealHeadView(event, dy); else if (!canPullUp() && isLoadMore) dealFootView(event, dy); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (mCurrrentState == STATE_RELEASE_REFRESH) { startAnimator(mChildView, mHeadViewHeight, mHeadView); } else if (mCurrrentState == STATE_PULL_REFRESH) { startAnimator(mChildView, 0, mHeadView); } //判断是否加载更多 int y = getScrollY(); if(y != 0 && isLoadMore) { if (y == mFootViewHeight) { toggleFootView(true); } else { if(mCurrrentState == STATE_LOADMOREING) toggleFootView(true); else toggleFootView(false); } } break; } return true; } private void dealFootView(MotionEvent event, float dy) { //让listview去处理事件 if (dy > 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; dy = 0; } dy = Math.abs(dy); if (dy > mFootViewHeight) dy = mFootViewHeight; scrollTo(0, (int) dy); // mFootView.setVisibility(View.VISIBLE); } private void dealHeadView(MotionEvent event, float dy) { if (dy < 0) { event.setAction(MotionEvent.ACTION_DOWN); dispatchTouchEvent(event); isInControl = false; dy = 0; } if (dy / 2 > mHeadViewHeight) { if (!isPullEndless) dy = mHeadViewHeight * 2; else dy = (((dy / 2 - mHeadViewHeight) / 2) + mHeadViewHeight) * 2; if (mCurrrentState != STATE_RELEASE_REFRESH) { mCurrrentState = STATE_RELEASE_REFRESH; refreshState(); } } else { if (mCurrrentState != STATE_PULL_REFRESH) { mCurrrentState = STATE_PULL_REFRESH; refreshState(); } } // Log.e(Tag, "dy=" + dy); mHeadView.setVisibility(View.VISIBLE); mHeadView.getLayoutParams().height = (int) (dy / 2); mHeadView.requestLayout(); mHeadView.updatePullOffset(dy / 2 / mHeadViewHeight); if (!isOverlay) { LayoutParams layoutParams = (LayoutParams) mChildView.getLayoutParams(); layoutParams.setMargins(0, (int) (dy / 2), 0, 0); mChildView.setLayoutParams(layoutParams); } } private void toggleFootView(boolean isOpen) { int scrollY = getScrollY(); mScroller.abortAnimation(); if(isOpen) { // Log.e(Tag,"isOpen..."); int dy = mFootViewHeight - scrollY; mScroller.startScroll(0, scrollY, 0, dy, 250); if(mCurrrentState == STATE_LOADMOREING) return; mCurrrentState = STATE_LOADMOREING; refreshState(); } else { // Log.e(Tag,"isClose..."); if(scrollY == 0) return; mScroller.startScroll(0, scrollY, 0, -scrollY, 250); mCurrrentState = STATE_PULL_REFRESH; refreshState(); } invalidate(); // scrollTo(0, mFootViewHeight); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); }else{ // Log.e(Tag,"computeScroll="+getScrollY()); } } private void refreshState() { switch (mCurrrentState) { case STATE_PULL_REFRESH: mHeadView.setPullState(STATE_PULL_REFRESH); break; case STATE_RELEASE_REFRESH: mHeadView.setPullState(STATE_RELEASE_REFRESH); break; case STATE_REFRESHING: mHeadView.setPullState(STATE_REFRESHING); if (mRefreshListener != null) mRefreshListener.onRefresh(this); break; case STATE_LOADMOREING: if(mRefreshListener != null) mRefreshListener.onRefreshLoadMore(this); break; default: break; } } private boolean canPullDown() { if (mChildView == null) return false; return ViewCompat.canScrollVertically(mChildView, -1); } private boolean canPullUp() { if (mChildView == null) return false; return ViewCompat.canScrollVertically(mChildView, 1); } public void finishRefresh() { this.post(new Runnable() { @Override public void run() { if (mHeadView != null) mHeadView.overRefresh(); startAnimator(mChildView, 0, mHeadView); } }); } public void finishLoadMore() { this.post(new Runnable() { @Override public void run() { if (mFootView != null) toggleFootView(false); } }); } public void autoRefresh() { this.postDelayed(new Runnable() { @Override public void run() { if (mCurrrentState != STATE_REFRESHING) { if (mHeadView != null) { startAnimator(mChildView, mHeadViewHeight, mHeadView); } } } }, 50); } private void startAnimator(final View v, final int endH, final FrameLayout fl) { final RelativeLayout.LayoutParams childParams = (LayoutParams) mChildView.getLayoutParams(); int startH = childParams.topMargin; if (isOverlay) startH = fl.getLayoutParams().height; ValueAnimator valueAnimator = ValueAnimator.ofInt(startH, endH); valueAnimator.setDuration(250); valueAnimator.start(); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int height = (int) valueAnimator.getAnimatedValue(); if (fl.getVisibility() != View.VISIBLE) fl.setVisibility(View.VISIBLE); fl.getLayoutParams().height = height; fl.requestLayout(); mHeadView.setVisibility(View.VISIBLE); if (!isOverlay) { childParams.setMargins(0, height, 0, 0); mChildView.setLayoutParams(childParams); } } }); valueAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { if (endH == 0) { mCurrrentState = STATE_PULL_REFRESH; refreshState(); } else { mCurrrentState = STATE_REFRESHING; refreshState(); } } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); } public <T extends DefaultHeadView> void setHeadView(T v) { if (mHeadView != null) removeView(mHeadView); mHeadView = v; v.measure(0, 0); mHeadViewHeight = v.getMeasuredHeight(); addView(mHeadView, LayoutParams.MATCH_PARENT, mHeadViewHeight); } /** * 监听回调接口 */ public interface RefreshListener { public void onRefresh(SuperRefreshLayout superRefreshLayout); public void onRefreshLoadMore(SuperRefreshLayout superRefreshLayout); } public void setRefreshListener(RefreshListener refreshListener) { this.mRefreshListener = refreshListener; } public boolean isLoadMore() { return isLoadMore; } public void setLoadMore(boolean loadMore) { isLoadMore = loadMore; } public boolean isOverlay() { return isOverlay; } public void setOverlay(boolean overlay) { isOverlay = overlay; } public boolean isPullEndless() { return isPullEndless; } public void setPullEndless(boolean pullEndless) { isPullEndless = pullEndless; } }
False
2,444
183422_24
package joining.join.wcoj; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import buffer.BufferManager; import config.CheckConfig; import data.ColumnData; import data.IntData; import joining.join.DynamicMWJoin; import preprocessing.Context; import query.ColumnRef; import query.QueryInfo; import statistics.JoinStats; /** * Implements variant of the Leapfrog Trie Join * (see paper "Leapfrog Triejoin: a worst-case * optimal join algorithm" by T. Veldhuizen). * This version allows to dynamically change * the attribute order for each time slice. * * @author immanueltrummer * */ public class LFTjoin extends DynamicMWJoin { /** * Maps alias IDs to corresponding iterator. */ final Map<String, LFTJiter> aliasToIter; /** * Contains at i-th position iterator over * i-th element in query from clause. */ final LFTJiter[] idToIter; /** * Order of variables (i.e., equivalence classes * of join attributes connected via equality * predicates). */ final List<Set<ColumnRef>> varOrder; /** * Contains at i-th position the iterators * involved in obtaining keys for i-th * variable (consistent with global * variable order). */ final List<List<LFTJiter>> itersByVar; /** * Number of variables in input query (i.e., * number of equivalence classes of join columns * connected via equality predicates). */ final int nrVars; /** * Whether entire result was generated. */ boolean finished = false; /** * Initialize join for given query. * * @param query join query to process via LFTJ * @param preSummary summarizes effects of pre-processing * @throws Exception */ public LFTjoin(QueryInfo query, Context preSummary) throws Exception { super(query, preSummary); // Choose variable order arbitrarily varOrder = new ArrayList<>(); varOrder.addAll(query.equiJoinClasses); nrVars = query.equiJoinClasses.size(); Collections.shuffle(varOrder); System.out.println("Variable Order: " + varOrder); // Initialize iterators aliasToIter = new HashMap<>(); idToIter = new LFTJiter[nrJoined]; for (int aliasCtr=0; aliasCtr<nrJoined; ++aliasCtr) { String alias = query.aliases[aliasCtr]; LFTJiter iter = new LFTJiter(query, preSummary, aliasCtr, varOrder); aliasToIter.put(alias, iter); idToIter[aliasCtr] = iter; } // Group iterators by variable itersByVar = new ArrayList<>(); for (Set<ColumnRef> var : varOrder) { List<LFTJiter> curVarIters = new ArrayList<>(); for (ColumnRef colRef : var) { String alias = colRef.aliasName; LFTJiter iter = aliasToIter.get(alias); curVarIters.add(iter); } itersByVar.add(curVarIters); } } /** * Initializes iterators and checks for * quick termination. * * @param iters iterators for current attribute * @return true if join continues * @throws Exception */ boolean leapfrogInit(List<LFTJiter> iters) throws Exception { // Advance to next trie level (iterators are // initially positioned before first trie level). for (LFTJiter iter : iters) { iter.open(); } // Check for early termination for (LFTJiter iter : iters) { if (iter.atEnd()) { return false; } } // Sort iterators by their keys Collections.sort(iters, new Comparator<LFTJiter>() { @Override public int compare(LFTJiter o1, LFTJiter o2) { return Integer.compare(o1.key(), o2.key()); } }); // Must continue with join return true; } /** * Add join result tuple based on current * iterator positions. */ void addResultTuple() throws Exception { //System.out.println("addResultTuple"); // Generate result tuple int[] resultTuple = new int[nrJoined]; // Iterate over all joined tables for (int aliasCtr=0; aliasCtr<nrJoined; ++aliasCtr) { LFTJiter iter = idToIter[aliasCtr]; resultTuple[aliasCtr] = iter.rid(); } // Add new result tuple result.add(resultTuple); // Verify result tuple if activated if (CheckConfig.CHECK_LFTJ_RESULTS) { if (!testResult(resultTuple)) { System.out.println( "Error - inconsistent result tuple: " + Arrays.toString(resultTuple)); } } } /** * Returns true iff given result tuples satisfies * all binary join equality predicates. * * @param resultTuple check this result tuple * @return true iff tuple passes checks * @throws Exception */ boolean testResult(int[] resultTuple) throws Exception { // Iterate over equality join conditions for (Set<ColumnRef> equiPair : query.equiJoinPairs) { Set<Integer> keyVals = new HashSet<>(); // Iterate over columns in equality condition for (ColumnRef colRef : equiPair) { // Retrieve tuple index String alias = colRef.aliasName; int aliasIdx = query.aliasToIndex.get(alias); int tupleIdx = resultTuple[aliasIdx]; // Retrieve corresponding data String table = preSummary.aliasToFiltered.get(alias); String column = colRef.columnName; ColumnRef baseRef = new ColumnRef(table, column); ColumnData data = BufferManager.getData(baseRef); IntData intData = (IntData)data; int key = intData.data[tupleIdx]; keyVals.add(key); } // Check whether key values collapse if (keyVals.size()>1) { System.out.println( "Equality not satisfied: " + equiPair.toString()); return false; } /* else { System.out.println( "Equality satisfied: " + equiPair.toString()); } */ } // No inconsistencies were found - passed check return true; } long roundCtr = 0; class JoinFrame { int curVariableID = -1; List<LFTJiter> curIters = null; int nrCurIters = -1; int p = -1; int maxIterPos = -1; int maxKey = -1; } Stack<JoinFrame> joinStack = new Stack<>(); void recInvoke() { JoinFrame oldFrame = joinStack.peek(); JoinFrame newFrame = new JoinFrame(); newFrame.curVariableID = oldFrame.curVariableID+1; joinStack.push(newFrame); } void recReturn() { joinStack.pop(); returning = true; } boolean returning = false; void executeLFTJ() throws Exception { while (true) { if (joinStack.empty()) { break; } JoinFrame joinFrame = joinStack.peek(); if (returning) { returning = false; LFTJiter minIter = joinFrame.curIters.get(joinFrame.p); minIter.seek(joinFrame.maxKey+1); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); continue; } joinFrame.maxKey = minIter.key(); joinFrame.p = (joinFrame.p + 1) % joinFrame.nrCurIters; } else { // Check for timeout if (System.currentTimeMillis() - startMillis > 60000) { recReturn(); break; } // Have we completed a result tuple? if (joinFrame.curVariableID >= nrVars) { addResultTuple(); recReturn(); continue; } // Collect relevant iterators joinFrame.curIters = itersByVar.get(joinFrame.curVariableID); joinFrame.nrCurIters = joinFrame.curIters.size(); // Order iterators and check for early termination if(!leapfrogInit(joinFrame.curIters)) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); continue; } // Execute search procedure joinFrame.p = 0; joinFrame.maxIterPos = (joinFrame.nrCurIters+joinFrame.p-1) % joinFrame.nrCurIters; joinFrame.maxKey = joinFrame.curIters.get(joinFrame.maxIterPos).key(); } while (true) { // Update statistics JoinStats.nrIterations++; // Get current key LFTJiter minIter = joinFrame.curIters.get(joinFrame.p); int minKey = minIter.key(); // Generate debugging output ++roundCtr; if (roundCtr < 10) { System.out.println("--- Current variable ID: " + joinFrame.curVariableID); System.out.println("p: " + joinFrame.p); System.out.println("minKey: " + minKey); System.out.println("maxKey: " + joinFrame.maxKey); for (LFTJiter iter : joinFrame.curIters) { System.out.println(iter.rid() + ":" + iter.key()); } } // Did we find a match between iterators? if (minKey == joinFrame.maxKey) { recInvoke(); break; } else { minIter.seek(joinFrame.maxKey); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); break; } else { // Min-iter to max-iter joinFrame.maxKey = minIter.key(); joinFrame.p = (joinFrame.p + 1) % joinFrame.nrCurIters; } } } } } /** * Execute leapfrog trie join for given variable. * * @param curVariableID variable index in global variable order * @throws Exception */ /* void executeLFTJ(int curVariableID) throws Exception { // Check for timeout if (System.currentTimeMillis() - startMillis > 60000) { return; } // Have we completed a result tuple? if (curVariableID >= nrVars) { addResultTuple(); return; } // Collect relevant iterators List<LFTJiter> curIters = itersByVar.get(curVariableID); int nrCurIters = curIters.size(); // Order iterators and check for early termination if(!leapfrogInit(curIters)) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } // Execute search procedure int p = 0; int maxIterPos = (nrCurIters+p-1) % nrCurIters; int maxKey = curIters.get(maxIterPos).key(); while (true) { // Update statistics JoinStats.nrIterations++; // Get current key LFTJiter minIter = curIters.get(p); int minKey = minIter.key(); // Generate debugging output ++roundCtr; if (roundCtr < 10) { System.out.println("--- Current variable ID: " + curVariableID); System.out.println("p: " + p); System.out.println("minKey: " + minKey); System.out.println("maxKey: " + maxKey); for (LFTJiter iter : curIters) { System.out.println(iter.rid() + ":" + iter.key()); } } // Did we find a match between iterators? if (minKey == maxKey) { executeLFTJ(curVariableID+1); minIter.seek(maxKey+1); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } maxKey = minIter.key(); p = (p + 1) % nrCurIters; } else { minIter.seek(maxKey); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } else { // Min-iter to max-iter maxKey = minIter.key(); p = (p + 1) % nrCurIters; } } } } */ long startMillis = -1; @Override public double execute(int[] order) throws Exception { // Retrieve result via WCOJ startMillis = System.currentTimeMillis(); // Start LFTJ algorithm JoinFrame joinFrame = new JoinFrame(); joinFrame.curVariableID = 0; joinStack.push(joinFrame); executeLFTJ(); // Set termination flag finished = true; // Return dummy reward return 1; } @Override public boolean isFinished() { return finished; } }
cornelldbgroup/skinnerdb
src/joining/join/wcoj/LFTjoin.java
3,947
// Retrieve tuple index
line_comment
nl
package joining.join.wcoj; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import buffer.BufferManager; import config.CheckConfig; import data.ColumnData; import data.IntData; import joining.join.DynamicMWJoin; import preprocessing.Context; import query.ColumnRef; import query.QueryInfo; import statistics.JoinStats; /** * Implements variant of the Leapfrog Trie Join * (see paper "Leapfrog Triejoin: a worst-case * optimal join algorithm" by T. Veldhuizen). * This version allows to dynamically change * the attribute order for each time slice. * * @author immanueltrummer * */ public class LFTjoin extends DynamicMWJoin { /** * Maps alias IDs to corresponding iterator. */ final Map<String, LFTJiter> aliasToIter; /** * Contains at i-th position iterator over * i-th element in query from clause. */ final LFTJiter[] idToIter; /** * Order of variables (i.e., equivalence classes * of join attributes connected via equality * predicates). */ final List<Set<ColumnRef>> varOrder; /** * Contains at i-th position the iterators * involved in obtaining keys for i-th * variable (consistent with global * variable order). */ final List<List<LFTJiter>> itersByVar; /** * Number of variables in input query (i.e., * number of equivalence classes of join columns * connected via equality predicates). */ final int nrVars; /** * Whether entire result was generated. */ boolean finished = false; /** * Initialize join for given query. * * @param query join query to process via LFTJ * @param preSummary summarizes effects of pre-processing * @throws Exception */ public LFTjoin(QueryInfo query, Context preSummary) throws Exception { super(query, preSummary); // Choose variable order arbitrarily varOrder = new ArrayList<>(); varOrder.addAll(query.equiJoinClasses); nrVars = query.equiJoinClasses.size(); Collections.shuffle(varOrder); System.out.println("Variable Order: " + varOrder); // Initialize iterators aliasToIter = new HashMap<>(); idToIter = new LFTJiter[nrJoined]; for (int aliasCtr=0; aliasCtr<nrJoined; ++aliasCtr) { String alias = query.aliases[aliasCtr]; LFTJiter iter = new LFTJiter(query, preSummary, aliasCtr, varOrder); aliasToIter.put(alias, iter); idToIter[aliasCtr] = iter; } // Group iterators by variable itersByVar = new ArrayList<>(); for (Set<ColumnRef> var : varOrder) { List<LFTJiter> curVarIters = new ArrayList<>(); for (ColumnRef colRef : var) { String alias = colRef.aliasName; LFTJiter iter = aliasToIter.get(alias); curVarIters.add(iter); } itersByVar.add(curVarIters); } } /** * Initializes iterators and checks for * quick termination. * * @param iters iterators for current attribute * @return true if join continues * @throws Exception */ boolean leapfrogInit(List<LFTJiter> iters) throws Exception { // Advance to next trie level (iterators are // initially positioned before first trie level). for (LFTJiter iter : iters) { iter.open(); } // Check for early termination for (LFTJiter iter : iters) { if (iter.atEnd()) { return false; } } // Sort iterators by their keys Collections.sort(iters, new Comparator<LFTJiter>() { @Override public int compare(LFTJiter o1, LFTJiter o2) { return Integer.compare(o1.key(), o2.key()); } }); // Must continue with join return true; } /** * Add join result tuple based on current * iterator positions. */ void addResultTuple() throws Exception { //System.out.println("addResultTuple"); // Generate result tuple int[] resultTuple = new int[nrJoined]; // Iterate over all joined tables for (int aliasCtr=0; aliasCtr<nrJoined; ++aliasCtr) { LFTJiter iter = idToIter[aliasCtr]; resultTuple[aliasCtr] = iter.rid(); } // Add new result tuple result.add(resultTuple); // Verify result tuple if activated if (CheckConfig.CHECK_LFTJ_RESULTS) { if (!testResult(resultTuple)) { System.out.println( "Error - inconsistent result tuple: " + Arrays.toString(resultTuple)); } } } /** * Returns true iff given result tuples satisfies * all binary join equality predicates. * * @param resultTuple check this result tuple * @return true iff tuple passes checks * @throws Exception */ boolean testResult(int[] resultTuple) throws Exception { // Iterate over equality join conditions for (Set<ColumnRef> equiPair : query.equiJoinPairs) { Set<Integer> keyVals = new HashSet<>(); // Iterate over columns in equality condition for (ColumnRef colRef : equiPair) { // Retrieve tuple<SUF> String alias = colRef.aliasName; int aliasIdx = query.aliasToIndex.get(alias); int tupleIdx = resultTuple[aliasIdx]; // Retrieve corresponding data String table = preSummary.aliasToFiltered.get(alias); String column = colRef.columnName; ColumnRef baseRef = new ColumnRef(table, column); ColumnData data = BufferManager.getData(baseRef); IntData intData = (IntData)data; int key = intData.data[tupleIdx]; keyVals.add(key); } // Check whether key values collapse if (keyVals.size()>1) { System.out.println( "Equality not satisfied: " + equiPair.toString()); return false; } /* else { System.out.println( "Equality satisfied: " + equiPair.toString()); } */ } // No inconsistencies were found - passed check return true; } long roundCtr = 0; class JoinFrame { int curVariableID = -1; List<LFTJiter> curIters = null; int nrCurIters = -1; int p = -1; int maxIterPos = -1; int maxKey = -1; } Stack<JoinFrame> joinStack = new Stack<>(); void recInvoke() { JoinFrame oldFrame = joinStack.peek(); JoinFrame newFrame = new JoinFrame(); newFrame.curVariableID = oldFrame.curVariableID+1; joinStack.push(newFrame); } void recReturn() { joinStack.pop(); returning = true; } boolean returning = false; void executeLFTJ() throws Exception { while (true) { if (joinStack.empty()) { break; } JoinFrame joinFrame = joinStack.peek(); if (returning) { returning = false; LFTJiter minIter = joinFrame.curIters.get(joinFrame.p); minIter.seek(joinFrame.maxKey+1); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); continue; } joinFrame.maxKey = minIter.key(); joinFrame.p = (joinFrame.p + 1) % joinFrame.nrCurIters; } else { // Check for timeout if (System.currentTimeMillis() - startMillis > 60000) { recReturn(); break; } // Have we completed a result tuple? if (joinFrame.curVariableID >= nrVars) { addResultTuple(); recReturn(); continue; } // Collect relevant iterators joinFrame.curIters = itersByVar.get(joinFrame.curVariableID); joinFrame.nrCurIters = joinFrame.curIters.size(); // Order iterators and check for early termination if(!leapfrogInit(joinFrame.curIters)) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); continue; } // Execute search procedure joinFrame.p = 0; joinFrame.maxIterPos = (joinFrame.nrCurIters+joinFrame.p-1) % joinFrame.nrCurIters; joinFrame.maxKey = joinFrame.curIters.get(joinFrame.maxIterPos).key(); } while (true) { // Update statistics JoinStats.nrIterations++; // Get current key LFTJiter minIter = joinFrame.curIters.get(joinFrame.p); int minKey = minIter.key(); // Generate debugging output ++roundCtr; if (roundCtr < 10) { System.out.println("--- Current variable ID: " + joinFrame.curVariableID); System.out.println("p: " + joinFrame.p); System.out.println("minKey: " + minKey); System.out.println("maxKey: " + joinFrame.maxKey); for (LFTJiter iter : joinFrame.curIters) { System.out.println(iter.rid() + ":" + iter.key()); } } // Did we find a match between iterators? if (minKey == joinFrame.maxKey) { recInvoke(); break; } else { minIter.seek(joinFrame.maxKey); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : joinFrame.curIters) { iter.up(); } recReturn(); break; } else { // Min-iter to max-iter joinFrame.maxKey = minIter.key(); joinFrame.p = (joinFrame.p + 1) % joinFrame.nrCurIters; } } } } } /** * Execute leapfrog trie join for given variable. * * @param curVariableID variable index in global variable order * @throws Exception */ /* void executeLFTJ(int curVariableID) throws Exception { // Check for timeout if (System.currentTimeMillis() - startMillis > 60000) { return; } // Have we completed a result tuple? if (curVariableID >= nrVars) { addResultTuple(); return; } // Collect relevant iterators List<LFTJiter> curIters = itersByVar.get(curVariableID); int nrCurIters = curIters.size(); // Order iterators and check for early termination if(!leapfrogInit(curIters)) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } // Execute search procedure int p = 0; int maxIterPos = (nrCurIters+p-1) % nrCurIters; int maxKey = curIters.get(maxIterPos).key(); while (true) { // Update statistics JoinStats.nrIterations++; // Get current key LFTJiter minIter = curIters.get(p); int minKey = minIter.key(); // Generate debugging output ++roundCtr; if (roundCtr < 10) { System.out.println("--- Current variable ID: " + curVariableID); System.out.println("p: " + p); System.out.println("minKey: " + minKey); System.out.println("maxKey: " + maxKey); for (LFTJiter iter : curIters) { System.out.println(iter.rid() + ":" + iter.key()); } } // Did we find a match between iterators? if (minKey == maxKey) { executeLFTJ(curVariableID+1); minIter.seek(maxKey+1); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } maxKey = minIter.key(); p = (p + 1) % nrCurIters; } else { minIter.seek(maxKey); if (minIter.atEnd()) { // Go one level up in each trie for (LFTJiter iter : curIters) { iter.up(); } return; } else { // Min-iter to max-iter maxKey = minIter.key(); p = (p + 1) % nrCurIters; } } } } */ long startMillis = -1; @Override public double execute(int[] order) throws Exception { // Retrieve result via WCOJ startMillis = System.currentTimeMillis(); // Start LFTJ algorithm JoinFrame joinFrame = new JoinFrame(); joinFrame.curVariableID = 0; joinStack.push(joinFrame); executeLFTJ(); // Set termination flag finished = true; // Return dummy reward return 1; } @Override public boolean isFinished() { return finished; } }
False
3,379
703_31
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; import core.Tuple; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes interencounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone); if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. * @see #SECONDS_IN_UNIT_S */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for(Connection con : getHost()) { // for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
knightcode/the-one-pitt
routing/ProphetRouterWithEstimation.java
5,142
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
line_comment
nl
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing;_x000D_ _x000D_ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; import core.Tuple; _x000D_ /**_x000D_ * Implementation of PRoPHET router as described in _x000D_ * <I>Probabilistic routing in intermittently connected networks</I> by_x000D_ * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * _x000D_ */_x000D_ public class ProphetRouterWithEstimation extends ActiveRouter {_x000D_ /** delivery predictability initialization constant*/_x000D_ public static final double P_INIT = 0.75;_x000D_ /** delivery predictability transitivity scaling constant default value */_x000D_ public static final double DEFAULT_BETA = 0.25;_x000D_ /** delivery predictability aging constant */_x000D_ public static final double GAMMA = 0.98;_x000D_ /** default P target */ public static final double DEFAULT_PTARGET = .2; _x000D_ /** Prophet router's setting namespace ({@value})*/ _x000D_ public static final String PROPHET_NS = "ProphetRouterWithEstimation";_x000D_ /**_x000D_ * Number of seconds in time scale.*/_x000D_ public static final String TIME_SCALE_S ="timeScale";_x000D_ /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; _x000D_ /**_x000D_ * Transitivity scaling constant (beta) -setting id ({@value})._x000D_ * Default value for setting is {@link #DEFAULT_BETA}._x000D_ */_x000D_ public static final String BETA_S = "beta";_x000D_ _x000D_ /** values of parameter settings */_x000D_ private double beta;_x000D_ private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; _x000D_ /** delivery predictabilities */_x000D_ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; _x000D_ /** last delivery predictability update (sim)time */_x000D_ private double lastAgeUpdate;_x000D_ _x000D_ /**_x000D_ * Constructor. Creates a new message router based on the settings in_x000D_ * the given Settings object._x000D_ * @param s The settings object_x000D_ */_x000D_ public ProphetRouterWithEstimation(Settings s) {_x000D_ super(s);_x000D_ Settings prophetSettings = new Settings(PROPHET_NS);_x000D_ timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; }_x000D_ if (prophetSettings.contains(BETA_S)) {_x000D_ beta = prophetSettings.getDouble(BETA_S);_x000D_ } else {_x000D_ beta = DEFAULT_BETA;_x000D_ } gamma = GAMMA; pinit = P_INIT;_x000D_ _x000D_ initPreds(); initMeetings();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Copyconstructor._x000D_ * @param r The router prototype where setting values are copied from_x000D_ */_x000D_ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) {_x000D_ super(r);_x000D_ this.timescale = r.timescale; this.ptavg = r.ptavg;_x000D_ this.beta = r.beta;_x000D_ initPreds(); initMeetings();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Initializes predictability hash_x000D_ */_x000D_ private void initPreds() {_x000D_ this.preds = new HashMap<DTNHost, Double>();_x000D_ } /** * Initializes interencounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; }_x000D_ _x000D_ @Override_x000D_ public void changedConnection(Connection con) {_x000D_ if (con.isUp()) {_x000D_ DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } _x000D_ updateDeliveryPredFor(otherHost);_x000D_ updateTransitivePreds(otherHost);_x000D_ }_x000D_ }_x000D_ /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t<SUF> if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } _x000D_ /**_x000D_ * Updates delivery predictions for a host._x000D_ * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE>_x000D_ * @param host The host we just met_x000D_ */_x000D_ private void updateDeliveryPredFor(DTNHost host) {_x000D_ double oldValue = getPredFor(host);_x000D_ double newValue = oldValue + (1 - oldValue) * pinit;_x000D_ preds.put(host, newValue);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns the current prediction (P) value for a host or 0 if entry for_x000D_ * the host doesn't exist._x000D_ * @param host The host to look the P for_x000D_ * @return the current P value_x000D_ */_x000D_ public double getPredFor(DTNHost host) {_x000D_ ageDeliveryPreds(); // make sure preds are updated before getting_x000D_ if (preds.containsKey(host)) {_x000D_ return preds.get(host);_x000D_ }_x000D_ else {_x000D_ return 0;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Updates transitive (A->B->C) delivery predictions._x000D_ * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA_x000D_ * </CODE>_x000D_ * @param host The B host who we just met_x000D_ */_x000D_ private void updateTransitivePreds(DTNHost host) {_x000D_ MessageRouter otherRouter = host.getRouter();_x000D_ assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + _x000D_ " with other routers of same type";_x000D_ _x000D_ double pForHost = getPredFor(host); // P(a,b)_x000D_ Map<DTNHost, Double> othersPreds = _x000D_ ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds();_x000D_ _x000D_ for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) {_x000D_ if (e.getKey() == getHost()) {_x000D_ continue; // don't add yourself_x000D_ }_x000D_ _x000D_ double pOld = getPredFor(e.getKey()); // P(a,c)_old_x000D_ double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta;_x000D_ preds.put(e.getKey(), pNew);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Ages all entries in the delivery predictions._x000D_ * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of_x000D_ * time units that have elapsed since the last time the metric was aged._x000D_ * @see #SECONDS_IN_UNIT_S_x000D_ */_x000D_ private void ageDeliveryPreds() {_x000D_ double timeDiff = (SimClock.getTime() - this.lastAgeUpdate);_x000D_ _x000D_ if (timeDiff == 0) {_x000D_ return;_x000D_ }_x000D_ _x000D_ double mult = Math.pow(gamma, timeDiff);_x000D_ for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {_x000D_ e.setValue(e.getValue()*mult);_x000D_ }_x000D_ _x000D_ this.lastAgeUpdate = SimClock.getTime();_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns a map of this router's delivery predictions_x000D_ * @return a map of this router's delivery predictions_x000D_ */_x000D_ private Map<DTNHost, Double> getDeliveryPreds() {_x000D_ ageDeliveryPreds(); // make sure the aging is done_x000D_ return this.preds;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void update() {_x000D_ super.update();_x000D_ if (!canStartTransfer() ||isTransferring()) {_x000D_ return; // nothing to transfer or is currently transferring _x000D_ }_x000D_ _x000D_ // try messages that could be delivered to final recipient_x000D_ if (exchangeDeliverableMessages() != null) {_x000D_ return;_x000D_ }_x000D_ _x000D_ tryOtherMessages(); _x000D_ }_x000D_ _x000D_ /**_x000D_ * Tries to send all other messages to all connected hosts ordered by_x000D_ * their delivery probability_x000D_ * @return The return value of {@link #tryMessagesForConnected(List)}_x000D_ */_x000D_ private Tuple<Message, Connection> tryOtherMessages() {_x000D_ List<Tuple<Message, Connection>> messages = _x000D_ new ArrayList<Tuple<Message, Connection>>(); _x000D_ _x000D_ Collection<Message> msgCollection = getMessageCollection();_x000D_ _x000D_ /* for all connected hosts collect all messages that have a higher_x000D_ probability of delivery by the other host */ for(Connection con : getHost()) {_x000D_ // for (Connection con : getConnections()) {_x000D_ DTNHost other = con.getOtherNode(getHost());_x000D_ ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter();_x000D_ _x000D_ if (othRouter.isTransferring()) {_x000D_ continue; // skip hosts that are transferring_x000D_ }_x000D_ _x000D_ for (Message m : msgCollection) {_x000D_ if (othRouter.hasMessage(m.getId())) {_x000D_ continue; // skip messages that the other one has_x000D_ }_x000D_ if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) {_x000D_ // the other node has higher probability of delivery_x000D_ messages.add(new Tuple<Message, Connection>(m,con));_x000D_ }_x000D_ } _x000D_ }_x000D_ _x000D_ if (messages.size() == 0) {_x000D_ return null;_x000D_ }_x000D_ _x000D_ // sort the message-connection tuples_x000D_ Collections.sort(messages, new TupleComparator());_x000D_ return tryMessagesForConnected(messages); // try to send messages_x000D_ }_x000D_ _x000D_ /**_x000D_ * Comparator for Message-Connection-Tuples that orders the tuples by_x000D_ * their delivery probability by the host on the other side of the _x000D_ * connection (GRTRMax)_x000D_ */_x000D_ private class TupleComparator implements Comparator _x000D_ <Tuple<Message, Connection>> {_x000D_ _x000D_ public int compare(Tuple<Message, Connection> tuple1,_x000D_ Tuple<Message, Connection> tuple2) {_x000D_ // delivery probability of tuple1's message with tuple1's connection_x000D_ double p1 = ((ProphetRouterWithEstimation)tuple1.getValue()._x000D_ getOtherNode(getHost()).getRouter()).getPredFor(_x000D_ tuple1.getKey().getTo());_x000D_ // -"- tuple2..._x000D_ double p2 = ((ProphetRouterWithEstimation)tuple2.getValue()._x000D_ getOtherNode(getHost()).getRouter()).getPredFor(_x000D_ tuple2.getKey().getTo());_x000D_ _x000D_ // bigger probability should come first_x000D_ if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */_x000D_ return compareByQueueMode(tuple1.getKey(), tuple2.getKey());_x000D_ }_x000D_ else if (p2-p1 < 0) {_x000D_ return -1;_x000D_ }_x000D_ else {_x000D_ return 1;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ public RoutingInfo getRoutingInfo() {_x000D_ ageDeliveryPreds();_x000D_ RoutingInfo top = super.getRoutingInfo();_x000D_ RoutingInfo ri = new RoutingInfo(preds.size() + _x000D_ " delivery prediction(s)");_x000D_ _x000D_ for (Map.Entry<DTNHost, Double> e : preds.entrySet()) {_x000D_ DTNHost host = e.getKey();_x000D_ Double value = e.getValue();_x000D_ _x000D_ ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", _x000D_ host, value)));_x000D_ }_x000D_ ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); _x000D_ top.addMoreInfo(ri);_x000D_ return top;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public MessageRouter replicate() {_x000D_ ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this);_x000D_ return r;_x000D_ }_x000D_ _x000D_ }_x000D_
False
4,675
20602_2
import java.util.*; import java.util.stream.*; import java.lang.Math; import java.lang.Exception; public class PrefixTreeApp { // returns up to n candidates start with given prefix public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t, String key, int n) { if (t == null) return Collections.emptyList(); String prefix = ""; boolean match; do { match = false; for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) { String k = entry.getKey(); PrefixTree.Node<T> tr = entry.getValue(); if (k.startsWith(key)) { // key is prefix of k return expand(prefix + k, tr, n); } if (key.startsWith(k)) { match = true; key = key.substring(k.length()); t = tr; prefix = prefix + k; break; } } } while (match); return Collections.emptyList(); } static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) { List<Map.Entry<String, T>> res = new ArrayList<>(); Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>(); q.offer(entryOf(prefix, t)); while(res.size() < n && !q.isEmpty()) { Map.Entry<String, PrefixTree.Node<T>> entry = q.poll(); String s = entry.getKey(); PrefixTree.Node<T> tr = entry.getValue(); if (tr.value.isPresent()) { res.add(entryOf(s, tr.value.get())); } for (Map.Entry<String, PrefixTree.Node<T>> e : new TreeMap<>(tr.subTrees).entrySet()) { q.offer(entryOf(s + e.getKey(), e.getValue())); } } return res; } static <K, V> Map.Entry<K, V> entryOf(K key, V val) { return new AbstractMap.SimpleImmutableEntry<K, V>(key, val); } // T9 map static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{ put('1', ",."); put('2', "abc"); put('3', "def"); put('4', "ghi"); put('5', "jkl"); put('6', "mno"); put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz"); }}; // T9 reverse map static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{ for (Character d : MAP_T9.keySet()) { String cs = MAP_T9.get(d); for (int i = 0; i < cs.length(); ++i) put(cs.charAt(i), d); } }}; /* * The T9 reverse map can be built with stream, but it's hard to read * * static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream() * .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i) * .map(c -> entryOf(c, e.getKey()))) * .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); */ public static String digits(String w) { StringBuilder d = new StringBuilder(); for(int i = 0; i < w.length(); ++i) d.append(RMAP_T9.get(w.charAt(i))); return d.toString(); } static class Tuple<T> { String prefix; String key; PrefixTree.Node<T> tree; Tuple(String p, String k, PrefixTree.Node<T> t) { prefix = p; key = k; tree = t; } public static <T> Tuple<T> of(String prefix, String key, PrefixTree.Node<T> tree) { return new Tuple<T>(prefix, key, tree); } } static String limit(int n, String s) { return s.substring(0, Math.min(n, s.length())); } public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) { List<String> res = new ArrayList<>(); if (t == null || key.isEmpty()) return res; Queue<Tuple<T>> q = new LinkedList<>(); q.offer(Tuple.of("", key, t)); while (!q.isEmpty()) { Tuple<T> elem = q.poll(); for (Map.Entry<String, PrefixTree.Node<T>> e : elem.tree.subTrees.entrySet()) { String k = e.getKey(); String ds = digits(k); if (ds.startsWith(elem.key)) { res.add(limit(key.length(), elem.prefix + k)); } else if (elem.key.startsWith(ds)) { q.offer(Tuple.of(elem.prefix + k, elem.key.substring(k.length()), e.getValue())); } } } return res; } public static class Test { final static String[] testKeys = new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"}; final static String[] testVals = new String[]{"the first letter of English", "used instead of 'a' when the following word begins witha vowel sound", "one more person or thing or an extra amount", "to leave a place, thing or person forever", "on the subject of; connected with", "a character in the Bible who was the first man made by God", "a male child or, more generally, a male of any age", "the whole physical structure that forms a person or animal", "an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"}; static void testEdict() { PrefixTree.Node<String> t = null; Map<String, String> m = new HashMap<>(); int n = Math.min(testKeys.length, testVals.length); for (int i = 0; i < n; ++i) { t = PrefixTree.insert(t, testKeys[i], testVals[i]); m.put(testKeys[i], testVals[i]); } verifyLookup(m, t, "a", 5); verifyLookup(m, t, "a", 6); verifyLookup(m, t, "a", 7); verifyLookup(m, t, "ab", 2); verifyLookup(m, t, "ab", 5); verifyLookup(m, t, "b", 2); verifyLookup(m, t, "bo", 5); verifyLookup(m, t, "z", 3); } static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) { System.out.format("lookup %s with limit: %d\n", key, n); SortedMap<String, String> m1 = new TreeMap<>(); for (Map.Entry<String, String> e : lookup(t, key, n)) { m1.put(e.getKey(), e.getValue()); } SortedMap<String, String> m2 = take(n, toSortedMap(m.entrySet().stream() .filter(e -> e.getKey().startsWith(key)))); if (!m2.equals(m1)) throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString()); System.out.println("result:\n" + m1.toString()); } static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) { return toSortedMap(m.entrySet().stream().limit(n)); } static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) { return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue()))); } public static void testT9() { //System.out.println("T9 map: " + MAP_T9); //System.out.println("reverse T9 map: " + RMAP_T9); final String txt = "home good gone hood a another an"; final String[] words = txt.split("\\W+"); PrefixTree.Node<Integer> t = PrefixTree.fromString(txt); for (String testDigits : new String[]{"4663", "22", "2668437"}) { for (int i = 1; i <= testDigits.length(); ++i) { String ds = limit(i, testDigits); SortedSet<String> as = new TreeSet<>(lookupT9(t, ds)); SortedSet<String> bs = new TreeSet<>(); for (String w : words) { String candidate = limit(i, w); if (digits(candidate).equals(ds)) bs.add(candidate); } //System.out.println("T9 look up: " + as); //System.out.println("Brute force:" + bs); if (!as.equals(bs)) throw new RuntimeException("T9 look up " + as + "\n!=\n" + "Brute force" + bs + "\n"); } } System.out.println("T9 verified"); } public static void test() { testEdict(); testT9(); } } }
warmchang/AlgoXY-algorithms
datastruct/tree/trie/src/PrefixTreeApp.java
2,711
// T9 reverse map
line_comment
nl
import java.util.*; import java.util.stream.*; import java.lang.Math; import java.lang.Exception; public class PrefixTreeApp { // returns up to n candidates start with given prefix public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t, String key, int n) { if (t == null) return Collections.emptyList(); String prefix = ""; boolean match; do { match = false; for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) { String k = entry.getKey(); PrefixTree.Node<T> tr = entry.getValue(); if (k.startsWith(key)) { // key is prefix of k return expand(prefix + k, tr, n); } if (key.startsWith(k)) { match = true; key = key.substring(k.length()); t = tr; prefix = prefix + k; break; } } } while (match); return Collections.emptyList(); } static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) { List<Map.Entry<String, T>> res = new ArrayList<>(); Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>(); q.offer(entryOf(prefix, t)); while(res.size() < n && !q.isEmpty()) { Map.Entry<String, PrefixTree.Node<T>> entry = q.poll(); String s = entry.getKey(); PrefixTree.Node<T> tr = entry.getValue(); if (tr.value.isPresent()) { res.add(entryOf(s, tr.value.get())); } for (Map.Entry<String, PrefixTree.Node<T>> e : new TreeMap<>(tr.subTrees).entrySet()) { q.offer(entryOf(s + e.getKey(), e.getValue())); } } return res; } static <K, V> Map.Entry<K, V> entryOf(K key, V val) { return new AbstractMap.SimpleImmutableEntry<K, V>(key, val); } // T9 map static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{ put('1', ",."); put('2', "abc"); put('3', "def"); put('4', "ghi"); put('5', "jkl"); put('6', "mno"); put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz"); }}; // T9 reverse<SUF> static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{ for (Character d : MAP_T9.keySet()) { String cs = MAP_T9.get(d); for (int i = 0; i < cs.length(); ++i) put(cs.charAt(i), d); } }}; /* * The T9 reverse map can be built with stream, but it's hard to read * * static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream() * .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i) * .map(c -> entryOf(c, e.getKey()))) * .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); */ public static String digits(String w) { StringBuilder d = new StringBuilder(); for(int i = 0; i < w.length(); ++i) d.append(RMAP_T9.get(w.charAt(i))); return d.toString(); } static class Tuple<T> { String prefix; String key; PrefixTree.Node<T> tree; Tuple(String p, String k, PrefixTree.Node<T> t) { prefix = p; key = k; tree = t; } public static <T> Tuple<T> of(String prefix, String key, PrefixTree.Node<T> tree) { return new Tuple<T>(prefix, key, tree); } } static String limit(int n, String s) { return s.substring(0, Math.min(n, s.length())); } public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) { List<String> res = new ArrayList<>(); if (t == null || key.isEmpty()) return res; Queue<Tuple<T>> q = new LinkedList<>(); q.offer(Tuple.of("", key, t)); while (!q.isEmpty()) { Tuple<T> elem = q.poll(); for (Map.Entry<String, PrefixTree.Node<T>> e : elem.tree.subTrees.entrySet()) { String k = e.getKey(); String ds = digits(k); if (ds.startsWith(elem.key)) { res.add(limit(key.length(), elem.prefix + k)); } else if (elem.key.startsWith(ds)) { q.offer(Tuple.of(elem.prefix + k, elem.key.substring(k.length()), e.getValue())); } } } return res; } public static class Test { final static String[] testKeys = new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"}; final static String[] testVals = new String[]{"the first letter of English", "used instead of 'a' when the following word begins witha vowel sound", "one more person or thing or an extra amount", "to leave a place, thing or person forever", "on the subject of; connected with", "a character in the Bible who was the first man made by God", "a male child or, more generally, a male of any age", "the whole physical structure that forms a person or animal", "an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"}; static void testEdict() { PrefixTree.Node<String> t = null; Map<String, String> m = new HashMap<>(); int n = Math.min(testKeys.length, testVals.length); for (int i = 0; i < n; ++i) { t = PrefixTree.insert(t, testKeys[i], testVals[i]); m.put(testKeys[i], testVals[i]); } verifyLookup(m, t, "a", 5); verifyLookup(m, t, "a", 6); verifyLookup(m, t, "a", 7); verifyLookup(m, t, "ab", 2); verifyLookup(m, t, "ab", 5); verifyLookup(m, t, "b", 2); verifyLookup(m, t, "bo", 5); verifyLookup(m, t, "z", 3); } static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) { System.out.format("lookup %s with limit: %d\n", key, n); SortedMap<String, String> m1 = new TreeMap<>(); for (Map.Entry<String, String> e : lookup(t, key, n)) { m1.put(e.getKey(), e.getValue()); } SortedMap<String, String> m2 = take(n, toSortedMap(m.entrySet().stream() .filter(e -> e.getKey().startsWith(key)))); if (!m2.equals(m1)) throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString()); System.out.println("result:\n" + m1.toString()); } static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) { return toSortedMap(m.entrySet().stream().limit(n)); } static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) { return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue()))); } public static void testT9() { //System.out.println("T9 map: " + MAP_T9); //System.out.println("reverse T9 map: " + RMAP_T9); final String txt = "home good gone hood a another an"; final String[] words = txt.split("\\W+"); PrefixTree.Node<Integer> t = PrefixTree.fromString(txt); for (String testDigits : new String[]{"4663", "22", "2668437"}) { for (int i = 1; i <= testDigits.length(); ++i) { String ds = limit(i, testDigits); SortedSet<String> as = new TreeSet<>(lookupT9(t, ds)); SortedSet<String> bs = new TreeSet<>(); for (String w : words) { String candidate = limit(i, w); if (digits(candidate).equals(ds)) bs.add(candidate); } //System.out.println("T9 look up: " + as); //System.out.println("Brute force:" + bs); if (!as.equals(bs)) throw new RuntimeException("T9 look up " + as + "\n!=\n" + "Brute force" + bs + "\n"); } } System.out.println("T9 verified"); } public static void test() { testEdict(); testT9(); } } }
False
4,291
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 ===="); } }
True
349
143258_32
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import jakarta.servlet.WriteListener; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Harish Prabandham * @author Hans Bergsten [hans@gefionsoftware.com] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); private static final Log log = LogFactory.getLog(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); private Supplier<Map<String,String>> trailerFieldsSupplier = null; /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean committed = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; Charset charset = null; // Retain the original name used to set the charset so exactly that name is // used in the ContentType header. Some (arguably non-specification // compliant) user agents are very particular String characterEncoding = null; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General information private long contentWritten = 0; private long commitTimeNanos = -1; /** * Holds response writing error exception. */ private Exception errorException = null; /** * With the introduction of async processing and the possibility of * non-container threads calling sendError() tracking the current error * state and ensuring that the correct error page is called becomes more * complicated. This state attribute helps by tracking the current error * state and informing callers that attempt to change state if the change * was successful or if another thread got there first. * * <pre> * The state machine is very simple: * * 0 - NONE * 1 - NOT_REPORTED * 2 - REPORTED * * * -->---->-- >NONE * | | | * | | | setError() * ^ ^ | * | | \|/ * | |-<-NOT_REPORTED * | | * ^ | report() * | | * | \|/ * |----<----REPORTED * </pre> */ private final AtomicInteger errorState = new AtomicInteger(0); Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return committed; } public void setCommitted(boolean v) { if (v && !this.committed) { this.commitTimeNanos = System.nanoTime(); } this.committed = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return System.currentTimeMillis() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - commitTimeNanos); } /** * Return the time the response was committed (based on System.nanoTime). * * @return the time the response was committed */ public long getCommitTimeNanos() { return commitTimeNanos; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during the writing of the response * processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during the writing of the response. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return errorException != null; } /** * Set the error flag. * * @return <code>false</code> if the error flag was already set */ public boolean setError() { return errorState.compareAndSet(0, 1); } /** * Error flag accessor. * * @return <code>true</code> if the response has encountered an error */ public boolean isError() { return errorState.get() > 0; } public boolean isErrorReportRequired() { return errorState.get() == 1; } public boolean setErrorReported() { return errorState.compareAndSet(1, 2); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (committed) { throw new IllegalStateException(); } recycle(); } // -------------------- Headers -------------------- /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } public void setTrailerFields(Supplier<Map<String, String>> supplier) { AtomicBoolean trailerFieldsSupported = new AtomicBoolean(false); action(ActionCode.IS_TRAILER_FIELDS_SUPPORTED, trailerFieldsSupported); if (!trailerFieldsSupported.get()) { throw new IllegalStateException(sm.getString("response.noTrailers.notSupported")); } this.trailerFieldsSupplier = supplier; } public Supplier<Map<String, String>> getTrailerFields() { return trailerFieldsSupplier; } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what they're doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { this.locale = null; this.contentLanguage = null; return; } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /** * Overrides the character encoding used in the body of the response. This * method must be called prior to writing output using getWriter(). * * @param characterEncoding The name of character encoding. * * @throws UnsupportedEncodingException If the specified name is not * recognised */ public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException { if (isCommitted()) { return; } if (characterEncoding == null) { this.charset = null; this.characterEncoding = null; return; } this.characterEncoding = characterEncoding; this.charset = B2CConverter.getCharset(characterEncoding); } public Charset getCharset() { return charset; } /** * @return The name of the current encoding */ public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue == null) { // No charset and we know value is valid as parser was successful // Pass-through user provided value in case user-agent is buggy and // requires specific format this.contentType = type; } else { // There is a charset so have to rebuild content-type without it this.contentType = m.toStringNoCharset(); charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { try { charset = B2CConverter.getCharset(charsetValue); } catch (UnsupportedEncodingException e) { log.warn(sm.getString("response.encoding.invalid", charsetValue), e); } } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && charset != null) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The ByteBuffer to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteBuffer chunk) throws IOException { int len = chunk.remaining(); outputBuffer.doWrite(chunk); contentWritten += len - chunk.remaining(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; charset = null; characterEncoding = null; contentLength = -1; status = 200; message = null; committed = false; commitTimeNanos = -1; errorException = null; errorState.set(0); headers.clear(); trailerFieldsSupplier = null; // Servlet 3.1 non-blocking write listener listener = null; synchronized (nonBlockingStateLock) { fireListener = false; registeredForWrite = false; } // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; // Ensures listener is only fired after a call is isReady() private boolean fireListener = false; // Tracks write registration to prevent duplicate registrations private boolean registeredForWrite = false; // Lock used to manage concurrent access to above flags private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!req.isRequestThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { return true; } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
Cosium/tomcat
java/org/apache/coyote/Response.java
5,768
// -------------------- Headers --------------------
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import jakarta.servlet.WriteListener; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Harish Prabandham * @author Hans Bergsten [hans@gefionsoftware.com] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); private static final Log log = LogFactory.getLog(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); private Supplier<Map<String,String>> trailerFieldsSupplier = null; /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean committed = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; Charset charset = null; // Retain the original name used to set the charset so exactly that name is // used in the ContentType header. Some (arguably non-specification // compliant) user agents are very particular String characterEncoding = null; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General information private long contentWritten = 0; private long commitTimeNanos = -1; /** * Holds response writing error exception. */ private Exception errorException = null; /** * With the introduction of async processing and the possibility of * non-container threads calling sendError() tracking the current error * state and ensuring that the correct error page is called becomes more * complicated. This state attribute helps by tracking the current error * state and informing callers that attempt to change state if the change * was successful or if another thread got there first. * * <pre> * The state machine is very simple: * * 0 - NONE * 1 - NOT_REPORTED * 2 - REPORTED * * * -->---->-- >NONE * | | | * | | | setError() * ^ ^ | * | | \|/ * | |-<-NOT_REPORTED * | | * ^ | report() * | | * | \|/ * |----<----REPORTED * </pre> */ private final AtomicInteger errorState = new AtomicInteger(0); Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return committed; } public void setCommitted(boolean v) { if (v && !this.committed) { this.commitTimeNanos = System.nanoTime(); } this.committed = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return System.currentTimeMillis() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - commitTimeNanos); } /** * Return the time the response was committed (based on System.nanoTime). * * @return the time the response was committed */ public long getCommitTimeNanos() { return commitTimeNanos; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during the writing of the response * processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during the writing of the response. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return errorException != null; } /** * Set the error flag. * * @return <code>false</code> if the error flag was already set */ public boolean setError() { return errorState.compareAndSet(0, 1); } /** * Error flag accessor. * * @return <code>true</code> if the response has encountered an error */ public boolean isError() { return errorState.get() > 0; } public boolean isErrorReportRequired() { return errorState.get() == 1; } public boolean setErrorReported() { return errorState.compareAndSet(1, 2); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (committed) { throw new IllegalStateException(); } recycle(); } // -------------------- Headers<SUF> /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } public void setTrailerFields(Supplier<Map<String, String>> supplier) { AtomicBoolean trailerFieldsSupported = new AtomicBoolean(false); action(ActionCode.IS_TRAILER_FIELDS_SUPPORTED, trailerFieldsSupported); if (!trailerFieldsSupported.get()) { throw new IllegalStateException(sm.getString("response.noTrailers.notSupported")); } this.trailerFieldsSupplier = supplier; } public Supplier<Map<String, String>> getTrailerFields() { return trailerFieldsSupplier; } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what they're doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { this.locale = null; this.contentLanguage = null; return; } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /** * Overrides the character encoding used in the body of the response. This * method must be called prior to writing output using getWriter(). * * @param characterEncoding The name of character encoding. * * @throws UnsupportedEncodingException If the specified name is not * recognised */ public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException { if (isCommitted()) { return; } if (characterEncoding == null) { this.charset = null; this.characterEncoding = null; return; } this.characterEncoding = characterEncoding; this.charset = B2CConverter.getCharset(characterEncoding); } public Charset getCharset() { return charset; } /** * @return The name of the current encoding */ public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue == null) { // No charset and we know value is valid as parser was successful // Pass-through user provided value in case user-agent is buggy and // requires specific format this.contentType = type; } else { // There is a charset so have to rebuild content-type without it this.contentType = m.toStringNoCharset(); charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { try { charset = B2CConverter.getCharset(charsetValue); } catch (UnsupportedEncodingException e) { log.warn(sm.getString("response.encoding.invalid", charsetValue), e); } } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && charset != null) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The ByteBuffer to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteBuffer chunk) throws IOException { int len = chunk.remaining(); outputBuffer.doWrite(chunk); contentWritten += len - chunk.remaining(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; charset = null; characterEncoding = null; contentLength = -1; status = 200; message = null; committed = false; commitTimeNanos = -1; errorException = null; errorState.set(0); headers.clear(); trailerFieldsSupplier = null; // Servlet 3.1 non-blocking write listener listener = null; synchronized (nonBlockingStateLock) { fireListener = false; registeredForWrite = false; } // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; // Ensures listener is only fired after a call is isReady() private boolean fireListener = false; // Tracks write registration to prevent duplicate registrations private boolean registeredForWrite = false; // Lock used to manage concurrent access to above flags private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!req.isRequestThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { return true; } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
False
1,448
172434_16
package com.jess.arms.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Message; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.SpannedString; import android.text.style.AbsoluteSizeSpan; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import com.jess.arms.base.BaseApplication; import org.simple.eventbus.EventBus; import java.security.MessageDigest; import static com.jess.arms.base.AppManager.APPMANAGER_MESSAGE; import static com.jess.arms.base.AppManager.APP_EXIT; import static com.jess.arms.base.AppManager.KILL_ALL; import static com.jess.arms.base.AppManager.SHOW_SNACKBAR; import static com.jess.arms.base.AppManager.START_ACTIVITY; /** * Created by jess on 2015/11/23. */ public class UiUtils { static public Toast mToast; /** * 设置hint大小 * * @param size * @param v * @param res */ public static void setViewHintSize(int size, TextView v, int res) { SpannableString ss = new SpannableString(getResources().getString( res)); // 新建一个属性对象,设置文字的大小 AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true); // 附加属性到文本 ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置hint v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失 } /** * dip转pix * * @param dpValue * @return */ public static int dip2px(float dpValue) { final float scale = BaseApplication.getContext().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 获得资源 */ public static Resources getResources() { return BaseApplication.getContext().getResources(); } /** * 得到字符数组 */ public static String[] getStringArray(int id) { return getResources().getStringArray(id); } /** * pix转dip */ public static int pix2dip(int pix) { final float densityDpi = getResources().getDisplayMetrics().density; return (int) (pix / densityDpi + 0.5f); } /** * 获得上下文 * * @return */ public static Context getContext() { return BaseApplication.getContext(); } /** * 从dimens中获得尺寸 * * @param homePicHeight * @return */ public static int getDimens(int homePicHeight) { return (int) getResources().getDimension(homePicHeight); } /** * 从dimens中获得尺寸 * * @param * @return */ public static float getDimens(String dimenNmae) { return getResources().getDimension(getResources().getIdentifier(dimenNmae, "dimen", getContext().getPackageName())); } /** * 从String 中获得字符 * * @return */ public static String getString(int stringID) { return getResources().getString(stringID); } /** * 从String 中获得字符 * * @return */ public static String getString(String strName) { return getString(getResources().getIdentifier(strName, "string", getContext().getPackageName())); } /** * findview * * @param view * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(View view, String viewName) { int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName()); T v = (T) view.findViewById(id); return v; } /** * findview * * @param activity * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(Activity activity, String viewName) { int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName()); T v = (T) activity.findViewById(id); return v; } /** * 根据lauout名字获得id * * @param layoutName * @return */ public static int findLayout(String layoutName) { int id = getResources().getIdentifier(layoutName, "layout", getContext().getPackageName()); return id; } /** * 填充view * * @param detailScreen * @return */ public static View inflate(int detailScreen) { return View.inflate(getContext(), detailScreen, null); } /** * 单列toast * * @param string */ public static void makeText(String string) { if (mToast == null) { mToast = Toast.makeText(getContext(), string, Toast.LENGTH_SHORT); } mToast.setText(string); mToast.show(); } /** * 用snackbar显示 * * @param text */ public static void SnackbarText(String text) { Message message = new Message(); message.what = SHOW_SNACKBAR; message.obj = text; message.arg1 = 0; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 用snackbar长时间显示 * * @param text */ public static void SnackbarTextWithLong(String text) { Message message = new Message(); message.what = SHOW_SNACKBAR; message.obj = text; message.arg1 = 1; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 通过资源id获得drawable * * @param rID * @return */ public static Drawable getDrawablebyResource(int rID) { return getResources().getDrawable(rID); } /** * 跳转界面 * * @param activity * @param homeActivityClass */ public static void startActivity(Activity activity, Class homeActivityClass) { Intent intent = new Intent(getContext(), homeActivityClass); activity.startActivity(intent); } /** * 跳转界面3 * * @param * @param homeActivityClass */ public static void startActivity(Class homeActivityClass) { Message message = new Message(); message.what = START_ACTIVITY; message.obj = homeActivityClass; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 跳转界面3 * * @param */ public static void startActivity(Intent content) { Message message = new Message(); message.what = START_ACTIVITY; message.obj = content; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 跳转界面4 * * @param */ public static void startActivity(Activity activity, Intent intent) { activity.startActivity(intent); } public static int getLayoutId(String layoutName) { return getResources().getIdentifier(layoutName, "layout", getContext().getPackageName()); } /** * 获得屏幕的宽度 * * @return */ public static int getScreenWidth() { return getResources().getDisplayMetrics().widthPixels; } /** * 获得屏幕的高度 * * @return */ public static int getScreenHeidth() { return getResources().getDisplayMetrics().heightPixels; } /** * 获得颜色 */ public static int getColor(int rid) { return getResources().getColor(rid); } /** * 获得颜色 */ public static int getColor(String colorName) { return getColor(getResources().getIdentifier(colorName, "color", getContext().getPackageName())); } /** * 移除孩子 * * @param view */ public static void removeChild(View view) { ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { ViewGroup group = (ViewGroup) parent; group.removeView(view); } } public static boolean isEmpty(Object obj) { if (obj == null) { return true; } return false; } /** * MD5 * * @param string * @return * @throws Exception */ public static String MD5encode(String string) { byte[] hash = new byte[0]; try { hash = MessageDigest.getInstance("MD5").digest( string.getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) { hex.append("0"); } hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } /** * 全屏,并且沉侵式状态栏 * * @param activity */ public static void statuInScreen(Activity activity) { WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; activity.getWindow().setAttributes(attrs); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } /** * 配置recycleview * * @param recyclerView * @param layoutManager */ public static void configRecycleView(final RecyclerView recyclerView , RecyclerView.LayoutManager layoutManager) { recyclerView.setLayoutManager(layoutManager); //如果可以确定每个item的高度是固定的,设置这个选项可以提高性能 recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); } public static void killAll(){ Message message = new Message(); message.what = KILL_ALL; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } public static void exitApp(){ Message message = new Message(); message.what = APP_EXIT; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } }
ReepicheepRed/PhotoMark-official
arms/src/main/java/com/jess/arms/utils/UiUtils.java
3,086
/** * 填充view * * @param detailScreen * @return */
block_comment
nl
package com.jess.arms.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Message; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.SpannedString; import android.text.style.AbsoluteSizeSpan; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import com.jess.arms.base.BaseApplication; import org.simple.eventbus.EventBus; import java.security.MessageDigest; import static com.jess.arms.base.AppManager.APPMANAGER_MESSAGE; import static com.jess.arms.base.AppManager.APP_EXIT; import static com.jess.arms.base.AppManager.KILL_ALL; import static com.jess.arms.base.AppManager.SHOW_SNACKBAR; import static com.jess.arms.base.AppManager.START_ACTIVITY; /** * Created by jess on 2015/11/23. */ public class UiUtils { static public Toast mToast; /** * 设置hint大小 * * @param size * @param v * @param res */ public static void setViewHintSize(int size, TextView v, int res) { SpannableString ss = new SpannableString(getResources().getString( res)); // 新建一个属性对象,设置文字的大小 AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true); // 附加属性到文本 ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置hint v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失 } /** * dip转pix * * @param dpValue * @return */ public static int dip2px(float dpValue) { final float scale = BaseApplication.getContext().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 获得资源 */ public static Resources getResources() { return BaseApplication.getContext().getResources(); } /** * 得到字符数组 */ public static String[] getStringArray(int id) { return getResources().getStringArray(id); } /** * pix转dip */ public static int pix2dip(int pix) { final float densityDpi = getResources().getDisplayMetrics().density; return (int) (pix / densityDpi + 0.5f); } /** * 获得上下文 * * @return */ public static Context getContext() { return BaseApplication.getContext(); } /** * 从dimens中获得尺寸 * * @param homePicHeight * @return */ public static int getDimens(int homePicHeight) { return (int) getResources().getDimension(homePicHeight); } /** * 从dimens中获得尺寸 * * @param * @return */ public static float getDimens(String dimenNmae) { return getResources().getDimension(getResources().getIdentifier(dimenNmae, "dimen", getContext().getPackageName())); } /** * 从String 中获得字符 * * @return */ public static String getString(int stringID) { return getResources().getString(stringID); } /** * 从String 中获得字符 * * @return */ public static String getString(String strName) { return getString(getResources().getIdentifier(strName, "string", getContext().getPackageName())); } /** * findview * * @param view * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(View view, String viewName) { int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName()); T v = (T) view.findViewById(id); return v; } /** * findview * * @param activity * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(Activity activity, String viewName) { int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName()); T v = (T) activity.findViewById(id); return v; } /** * 根据lauout名字获得id * * @param layoutName * @return */ public static int findLayout(String layoutName) { int id = getResources().getIdentifier(layoutName, "layout", getContext().getPackageName()); return id; } /** * 填充view <SUF>*/ public static View inflate(int detailScreen) { return View.inflate(getContext(), detailScreen, null); } /** * 单列toast * * @param string */ public static void makeText(String string) { if (mToast == null) { mToast = Toast.makeText(getContext(), string, Toast.LENGTH_SHORT); } mToast.setText(string); mToast.show(); } /** * 用snackbar显示 * * @param text */ public static void SnackbarText(String text) { Message message = new Message(); message.what = SHOW_SNACKBAR; message.obj = text; message.arg1 = 0; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 用snackbar长时间显示 * * @param text */ public static void SnackbarTextWithLong(String text) { Message message = new Message(); message.what = SHOW_SNACKBAR; message.obj = text; message.arg1 = 1; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 通过资源id获得drawable * * @param rID * @return */ public static Drawable getDrawablebyResource(int rID) { return getResources().getDrawable(rID); } /** * 跳转界面 * * @param activity * @param homeActivityClass */ public static void startActivity(Activity activity, Class homeActivityClass) { Intent intent = new Intent(getContext(), homeActivityClass); activity.startActivity(intent); } /** * 跳转界面3 * * @param * @param homeActivityClass */ public static void startActivity(Class homeActivityClass) { Message message = new Message(); message.what = START_ACTIVITY; message.obj = homeActivityClass; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 跳转界面3 * * @param */ public static void startActivity(Intent content) { Message message = new Message(); message.what = START_ACTIVITY; message.obj = content; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } /** * 跳转界面4 * * @param */ public static void startActivity(Activity activity, Intent intent) { activity.startActivity(intent); } public static int getLayoutId(String layoutName) { return getResources().getIdentifier(layoutName, "layout", getContext().getPackageName()); } /** * 获得屏幕的宽度 * * @return */ public static int getScreenWidth() { return getResources().getDisplayMetrics().widthPixels; } /** * 获得屏幕的高度 * * @return */ public static int getScreenHeidth() { return getResources().getDisplayMetrics().heightPixels; } /** * 获得颜色 */ public static int getColor(int rid) { return getResources().getColor(rid); } /** * 获得颜色 */ public static int getColor(String colorName) { return getColor(getResources().getIdentifier(colorName, "color", getContext().getPackageName())); } /** * 移除孩子 * * @param view */ public static void removeChild(View view) { ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { ViewGroup group = (ViewGroup) parent; group.removeView(view); } } public static boolean isEmpty(Object obj) { if (obj == null) { return true; } return false; } /** * MD5 * * @param string * @return * @throws Exception */ public static String MD5encode(String string) { byte[] hash = new byte[0]; try { hash = MessageDigest.getInstance("MD5").digest( string.getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) { hex.append("0"); } hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } /** * 全屏,并且沉侵式状态栏 * * @param activity */ public static void statuInScreen(Activity activity) { WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; activity.getWindow().setAttributes(attrs); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } /** * 配置recycleview * * @param recyclerView * @param layoutManager */ public static void configRecycleView(final RecyclerView recyclerView , RecyclerView.LayoutManager layoutManager) { recyclerView.setLayoutManager(layoutManager); //如果可以确定每个item的高度是固定的,设置这个选项可以提高性能 recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); } public static void killAll(){ Message message = new Message(); message.what = KILL_ALL; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } public static void exitApp(){ Message message = new Message(); message.what = APP_EXIT; EventBus.getDefault().post(message, APPMANAGER_MESSAGE); } }
False
3,993
19056_6
package bozels.gui.panels; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import bozels.gui.actions.BooleanValueSelectAction; import bozels.gui.basicComponents.AutoJLabel; import bozels.gui.basicComponents.ColorButton; import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField; import bozels.gui.resourceModel.ResourceTracker; import bozels.gui.resourceModel.guiColorModel.GUIColorModel; import bozels.gui.resourceModel.localeConstant.LocaleConstant; import bozels.physicsModel.material.Material; import bozels.superModel.SuperModel; import bozels.valueWrappers.Value; import bozels.visualisatie.gameColorModel.GameColorModel; /** * Bozels * * Door: * Pieter Vander Vennet * 1ste Bachelor Informatica * Universiteit Gent * */ public class OneMaterialEditorPanel extends JPanel { private static final long serialVersionUID = 1L; private final GUIColorModel colorSettings; public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) { final ResourceTracker tracker = supM.getResourceModel(); colorSettings = supM.getResourceModel().getGuiColorModel(); // \\//\\//\\//\\ LABELS //\\//\\//\\//\\ JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY); JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION); JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION); JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR); JLabel empty = new JLabel(); JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD); JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH); JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR); // \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\ GameColorModel cm = supM.getGameColorModel(); LocaleConstant name = mat.getMaterialName(); int key = mat.getColorKey(); JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key)); JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key)); // \\//\\//\\//\\ FIELDS //\\//\\//\\//\\ JTextField dens = createField(mat.getDensitValue()); JTextField rest = createField(mat.getRestitutionValue()); JTextField frict = createField(mat.getFrictionValue()); JTextField powThr = createField(mat.getPowerThresholdValue()); JTextField str = createField(mat.getStrengthValue()); // \\//\\//\\//\\ Checkbox //\\//\\//\\//\\ BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(), LocaleConstant.BREAKABLE, tracker); sw.getSwitchesWith().add(powThr); sw.getSwitchesWith().add(str); sw.revalidate(); JCheckBox breakable = new JCheckBox(sw); // \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\ GroupLayout l = new GroupLayout(this); this.setLayout(l); /* * VERANTWOORDING: * * Hier een if-else voor de layout is inderdaad lelijk. * Ik heb echter gekozen om deze hier te gebruiken, * omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken. * * Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar * klassenstructuur toe. * */ if(showBreakable){ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(createPar(l, Alignment.TRAILING, empty, powerThrs, strength, sleepingColor)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, breakable, powThr, str, sleepingColorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker) ) .addContainerGap() ); }else{ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker)) .addContainerGap()); } } private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){ ParallelGroup group = l.createParallelGroup(al); for (JComponent jComponent : components) { group.addComponent(jComponent); } return group; } private DoubleValueTextField createField(Value<Double> val){ return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000); } }
pietervdvn/Bozels
src/bozels/gui/panels/OneMaterialEditorPanel.java
1,960
/* * VERANTWOORDING: * * Hier een if-else voor de layout is inderdaad lelijk. * Ik heb echter gekozen om deze hier te gebruiken, * omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken. * * Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar * klassenstructuur toe. * */
block_comment
nl
package bozels.gui.panels; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import bozels.gui.actions.BooleanValueSelectAction; import bozels.gui.basicComponents.AutoJLabel; import bozels.gui.basicComponents.ColorButton; import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField; import bozels.gui.resourceModel.ResourceTracker; import bozels.gui.resourceModel.guiColorModel.GUIColorModel; import bozels.gui.resourceModel.localeConstant.LocaleConstant; import bozels.physicsModel.material.Material; import bozels.superModel.SuperModel; import bozels.valueWrappers.Value; import bozels.visualisatie.gameColorModel.GameColorModel; /** * Bozels * * Door: * Pieter Vander Vennet * 1ste Bachelor Informatica * Universiteit Gent * */ public class OneMaterialEditorPanel extends JPanel { private static final long serialVersionUID = 1L; private final GUIColorModel colorSettings; public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) { final ResourceTracker tracker = supM.getResourceModel(); colorSettings = supM.getResourceModel().getGuiColorModel(); // \\//\\//\\//\\ LABELS //\\//\\//\\//\\ JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY); JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION); JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION); JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR); JLabel empty = new JLabel(); JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD); JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH); JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR); // \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\ GameColorModel cm = supM.getGameColorModel(); LocaleConstant name = mat.getMaterialName(); int key = mat.getColorKey(); JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key)); JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key)); // \\//\\//\\//\\ FIELDS //\\//\\//\\//\\ JTextField dens = createField(mat.getDensitValue()); JTextField rest = createField(mat.getRestitutionValue()); JTextField frict = createField(mat.getFrictionValue()); JTextField powThr = createField(mat.getPowerThresholdValue()); JTextField str = createField(mat.getStrengthValue()); // \\//\\//\\//\\ Checkbox //\\//\\//\\//\\ BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(), LocaleConstant.BREAKABLE, tracker); sw.getSwitchesWith().add(powThr); sw.getSwitchesWith().add(str); sw.revalidate(); JCheckBox breakable = new JCheckBox(sw); // \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\ GroupLayout l = new GroupLayout(this); this.setLayout(l); /* * VERANTWOORDING: <SUF>*/ if(showBreakable){ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(createPar(l, Alignment.TRAILING, empty, powerThrs, strength, sleepingColor)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, breakable, powThr, str, sleepingColorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker) ) .addContainerGap() ); }else{ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker)) .addContainerGap()); } } private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){ ParallelGroup group = l.createParallelGroup(al); for (JComponent jComponent : components) { group.addComponent(jComponent); } return group; } private DoubleValueTextField createField(Value<Double> val){ return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000); } }
True
3,892
138253_15
/* * Copyright (C) 2021 B3Partners B.V. */ package nl.b3p.brmo.loader.xml; import nl.b3p.brmo.loader.BrmoFramework; import nl.b3p.brmo.loader.StagingProxy; import nl.b3p.brmo.loader.entity.Bericht; import nl.b3p.brmo.loader.entity.WozBericht; import nl.b3p.brmo.loader.util.RsgbTransformer; import org.apache.commons.io.input.TeeInputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; 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 java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Map; public class WozXMLReader extends BrmoXMLReader { public static final String PREFIX_PRS = "WOZ.NPS."; public static final String PREFIX_NNP = "WOZ.NNP."; public static final String PREFIX_WOZ = "WOZ.WOZ."; public static final String PREFIX_VES = "WOZ.VES."; private static final Log LOG = LogFactory.getLog(WozXMLReader.class); private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl"; private final StagingProxy staging; private final XPathFactory xPathfactory = XPathFactory.newInstance(); private InputStream in; private Templates template; private NodeList objectNodes = null; private int index; private String brOrigXML = null; public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception { this.in = in; this.staging = staging; setBestandsDatum(d); init(); } @Override public void init() throws Exception { soort = BrmoFramework.BR_WOZ; ByteArrayOutputStream bos = new ByteArrayOutputStream(); in = new TeeInputStream(in, bos, true); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(in); brOrigXML = bos.toString(StandardCharsets.UTF_8); LOG.trace("Originele WOZ xml is: \n" + brOrigXML); TransformerFactory tf = TransformerFactory.newInstance(); tf.setURIResolver((href, base) -> { LOG.debug("looking for: " + href + " base: " + base); return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href)); }); Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl)); this.template = tf.newTemplates(xsl); XPath xpath = xPathfactory.newXPath(); if (this.getBestandsDatum() == null) { // probeer datum nog uit doc te halen.. LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht."); XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']"); Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE); setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS"); LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum()); } // woz:object nodes XPathExpression objectNode = xpath.compile("//*[local-name()='object']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); // mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01) if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente NPS omhangbericht"); } } if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente NNP omhangbericht"); } } if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente VES omhangbericht"); } } index = 0; } @Override public boolean hasNext() throws Exception { return index < objectNodes.getLength(); } @Override public WozBericht next() throws Exception { Node n = objectNodes.item(index); index++; String object_ref = getObjectRef(n); StringWriter sw = new StringWriter(); // kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone. Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder()); Transformer t; if (old != null) { LOG.debug("gebruik preprocessor xsl"); t = this.template.newTransformer(); } else { LOG.debug("gebruik extractie xsl"); t = TransformerFactory.newInstance().newTransformer(); } t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.INDENT, "no"); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.transform(new DOMSource(n), new StreamResult(sw)); Map<String, String> bsns = extractBSN(n); String el = getXML(bsns); String origXML = sw.toString(); String brXML = "<root>" + origXML; brXML += el + "</root>"; WozBericht b = new WozBericht(brXML); b.setDatum(getBestandsDatum()); if (index == 1) { // alleen op 1e brmo bericht van mogelijk meer uit originele bericht b.setBrOrgineelXml(brOrigXML); } // TODO volgorde nummer: // bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere // object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS" // bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref // van een NPS, maar met een hoger volgordenummer... // vooralsnog halen we niet de geneste entiteiten uit het bericht b.setVolgordeNummer(index); if (index > 1) { // om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken b.setDatum(new Date(getBestandsDatum().getTime() + 10)); } b.setObjectRef(object_ref); if (StringUtils.isEmpty(b.getObjectRef())) { // geen object_ref kunnen vaststellen; dan ook niet transformeren b.setStatus(Bericht.STATUS.STAGING_NOK); b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht."); } LOG.trace("bericht: " + b); return b; } private String getObjectRef(Node wozObjectNode) throws XPathExpressionException { // WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']"); NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0) { return PREFIX_WOZ + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']"); obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0) { return PREFIX_PRS + getHash(obRefs.item(0).getTextContent()); } // WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']"); obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_NNP + obRefs.item(0).getTextContent(); } // er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld... // WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']"); obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id."); return PREFIX_NNP + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer XPathExpression wrd = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']"); obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_WOZ + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']"); obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_VES + obRefs.item(0).getTextContent(); } return null; } /** * maakt een map met bsn,bsnhash. * * @param n document node met bsn-nummer * @return hashmap met bsn,bsnhash * @throws XPathExpressionException if any */ public Map<String, String> extractBSN(Node n) throws XPathExpressionException { Map<String, String> hashes = new HashMap<>(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']"); NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET); for (int i = 0; i < nodelist.getLength(); i++) { Node bsn = nodelist.item(i); String bsnString = bsn.getTextContent(); String hash = getHash(bsnString); hashes.put(bsnString, hash); } return hashes; } public String getXML(Map<String, String> map) throws ParserConfigurationException { if (map.isEmpty()) { // als in bericht geen personen zitten return ""; } String root = "<bsnhashes>"; for (Map.Entry<String, String> entry : map.entrySet()) { if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) { String hash = entry.getValue(); String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">"; root += el; } } root += "</bsnhashes>"; return root; } }
opengeogroep/brmo
brmo-loader/src/main/java/nl/b3p/brmo/loader/xml/WozXMLReader.java
4,086
/*[local-name()='inn.nnpId']"); obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_NNP + obRefs.item(0).getTextContent(); } // er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld... // WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']"); obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id."); return PREFIX_NNP + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer XPathExpression wrd = xPathfactory.newXPath().compile("./*/
block_comment
nl
/* * Copyright (C) 2021 B3Partners B.V. */ package nl.b3p.brmo.loader.xml; import nl.b3p.brmo.loader.BrmoFramework; import nl.b3p.brmo.loader.StagingProxy; import nl.b3p.brmo.loader.entity.Bericht; import nl.b3p.brmo.loader.entity.WozBericht; import nl.b3p.brmo.loader.util.RsgbTransformer; import org.apache.commons.io.input.TeeInputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; 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 java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Map; public class WozXMLReader extends BrmoXMLReader { public static final String PREFIX_PRS = "WOZ.NPS."; public static final String PREFIX_NNP = "WOZ.NNP."; public static final String PREFIX_WOZ = "WOZ.WOZ."; public static final String PREFIX_VES = "WOZ.VES."; private static final Log LOG = LogFactory.getLog(WozXMLReader.class); private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl"; private final StagingProxy staging; private final XPathFactory xPathfactory = XPathFactory.newInstance(); private InputStream in; private Templates template; private NodeList objectNodes = null; private int index; private String brOrigXML = null; public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception { this.in = in; this.staging = staging; setBestandsDatum(d); init(); } @Override public void init() throws Exception { soort = BrmoFramework.BR_WOZ; ByteArrayOutputStream bos = new ByteArrayOutputStream(); in = new TeeInputStream(in, bos, true); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(in); brOrigXML = bos.toString(StandardCharsets.UTF_8); LOG.trace("Originele WOZ xml is: \n" + brOrigXML); TransformerFactory tf = TransformerFactory.newInstance(); tf.setURIResolver((href, base) -> { LOG.debug("looking for: " + href + " base: " + base); return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href)); }); Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl)); this.template = tf.newTemplates(xsl); XPath xpath = xPathfactory.newXPath(); if (this.getBestandsDatum() == null) { // probeer datum nog uit doc te halen.. LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht."); XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']"); Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE); setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS"); LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum()); } // woz:object nodes XPathExpression objectNode = xpath.compile("//*[local-name()='object']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); // mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01) if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente NPS omhangbericht"); } } if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente NNP omhangbericht"); } } if (objectNodes.getLength() < 1) { objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']"); objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET); if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) { LOG.debug("nieuweGemeente VES omhangbericht"); } } index = 0; } @Override public boolean hasNext() throws Exception { return index < objectNodes.getLength(); } @Override public WozBericht next() throws Exception { Node n = objectNodes.item(index); index++; String object_ref = getObjectRef(n); StringWriter sw = new StringWriter(); // kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone. Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder()); Transformer t; if (old != null) { LOG.debug("gebruik preprocessor xsl"); t = this.template.newTransformer(); } else { LOG.debug("gebruik extractie xsl"); t = TransformerFactory.newInstance().newTransformer(); } t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.INDENT, "no"); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.transform(new DOMSource(n), new StreamResult(sw)); Map<String, String> bsns = extractBSN(n); String el = getXML(bsns); String origXML = sw.toString(); String brXML = "<root>" + origXML; brXML += el + "</root>"; WozBericht b = new WozBericht(brXML); b.setDatum(getBestandsDatum()); if (index == 1) { // alleen op 1e brmo bericht van mogelijk meer uit originele bericht b.setBrOrgineelXml(brOrigXML); } // TODO volgorde nummer: // bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere // object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS" // bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref // van een NPS, maar met een hoger volgordenummer... // vooralsnog halen we niet de geneste entiteiten uit het bericht b.setVolgordeNummer(index); if (index > 1) { // om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken b.setDatum(new Date(getBestandsDatum().getTime() + 10)); } b.setObjectRef(object_ref); if (StringUtils.isEmpty(b.getObjectRef())) { // geen object_ref kunnen vaststellen; dan ook niet transformeren b.setStatus(Bericht.STATUS.STAGING_NOK); b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht."); } LOG.trace("bericht: " + b); return b; } private String getObjectRef(Node wozObjectNode) throws XPathExpressionException { // WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']"); NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0) { return PREFIX_WOZ + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']"); obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0) { return PREFIX_PRS + getHash(obRefs.item(0).getTextContent()); } // WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']"); <SUF>*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']"); obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_WOZ + obRefs.item(0).getTextContent(); } // WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']"); obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET); if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) { return PREFIX_VES + obRefs.item(0).getTextContent(); } return null; } /** * maakt een map met bsn,bsnhash. * * @param n document node met bsn-nummer * @return hashmap met bsn,bsnhash * @throws XPathExpressionException if any */ public Map<String, String> extractBSN(Node n) throws XPathExpressionException { Map<String, String> hashes = new HashMap<>(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']"); NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET); for (int i = 0; i < nodelist.getLength(); i++) { Node bsn = nodelist.item(i); String bsnString = bsn.getTextContent(); String hash = getHash(bsnString); hashes.put(bsnString, hash); } return hashes; } public String getXML(Map<String, String> map) throws ParserConfigurationException { if (map.isEmpty()) { // als in bericht geen personen zitten return ""; } String root = "<bsnhashes>"; for (Map.Entry<String, String> entry : map.entrySet()) { if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) { String hash = entry.getValue(); String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">"; root += el; } } root += "</bsnhashes>"; return root; } }
False
3,242
109250_5
/** * Created by alexandru on 7/8/16. */ package jlg.jade.asterix.cat048; import jlg.jade.asterix.VariableLengthAsterixData; import java.util.BitSet; /** * Cat048Item170 - Track Status * Status of monoradar track (PSR and/or SSR updated). */ public class Cat048Item170 extends VariableLengthAsterixData { private int sensorMaintainingTrackType; // RAD private int confirmedTrack; // CNF private int trackConfidenceLevel; // DOU private int manoeuvreDetectionInHorizontalSense; // MAH private int climbingDescendingMode; // CDM private int signalEndOfTrack; // TRE private int ghostVsTrueTarget; // GHO private int maintainedWithNeighbourSupport; // SUP private int coordinatePlotType; // TCC @Override protected void decodeFromByteArray(byte[] input, int offset) { // decode first part BitSet firstPartBits = BitSet.valueOf(new byte[]{input[offset]}); // decode CNF - bit position 7 final int CNF_BIT_INDEX = 7; if (firstPartBits.get(CNF_BIT_INDEX)) { this.confirmedTrack = 1; } else { this.confirmedTrack = 0; } appendItemDebugMsg("CNF", this.confirmedTrack); // decode RAD - bits 6-5 decodeRAD(firstPartBits); // decode DOU - bit 4 final int DOU_BIT_INDEX = 4; if (firstPartBits.get(DOU_BIT_INDEX)) { this.trackConfidenceLevel = 1; } else { this.trackConfidenceLevel = 0; } appendItemDebugMsg("DOU", this.trackConfidenceLevel); // decode MAH - bit 3 final int MAH_BIT_INDEX = 3; if (firstPartBits.get(MAH_BIT_INDEX)) { this.manoeuvreDetectionInHorizontalSense = 1; } else { this.manoeuvreDetectionInHorizontalSense = 0; } appendItemDebugMsg("MAH", this.manoeuvreDetectionInHorizontalSense); // decode CMD - bits 2-1 decodeCDM(firstPartBits); // decode first extent if present if (this.getSizeInBytes() > 1) { BitSet firstExtentBits = BitSet.valueOf(new byte[]{input[offset+1]}); // decode TRE - bit position 7 final int TRE_BIT_INDEX = 7; if(firstExtentBits.get(TRE_BIT_INDEX)){ this.signalEndOfTrack = 1; } else { this.signalEndOfTrack = 0; } appendItemDebugMsg("TRE", this.signalEndOfTrack); // decode GHO final int GHO_BIT_INDEX = 6; if(firstExtentBits.get(GHO_BIT_INDEX)){ this.ghostVsTrueTarget = 1; } else { this.ghostVsTrueTarget = 0; } appendItemDebugMsg("GHO", this.ghostVsTrueTarget); // decode SUP final int SUP_BIT_INDEX = 5; if(firstExtentBits.get(SUP_BIT_INDEX)){ this.maintainedWithNeighbourSupport = 1; } else { this.maintainedWithNeighbourSupport = 0; } appendItemDebugMsg("SUP", this.maintainedWithNeighbourSupport); // decode TCC final int TCC_BIT_INDEX = 4; if(firstExtentBits.get(TCC_BIT_INDEX)){ this.coordinatePlotType = 1; } else { this.coordinatePlotType = 0; } appendItemDebugMsg("TCC", this.coordinatePlotType); } } @Override protected String setDisplayName() { return "Cat048Item170 - Track Status"; } /** * @return type of Sensor(s) maintaining Track - RAD */ public int getSensorMaintainingTrackType() { return sensorMaintainingTrackType; } public int getConfirmedTrack() { return confirmedTrack; } public int getTrackConfidenceLevel() { return trackConfidenceLevel; } public int getManoeuvreDetectionInHorizontalSense() { return manoeuvreDetectionInHorizontalSense; } public int getClimbingDescendingMode() { return climbingDescendingMode; } public int getSignalEndOfTrack() { return signalEndOfTrack; } public int getGhostVsTrueTarget() { return ghostVsTrueTarget; } public int getMaintainedWithNeighbourSupport() { return maintainedWithNeighbourSupport; } public int getCoordinatePlotType() { return coordinatePlotType; } private void decodeRAD(BitSet firstPartBits) { final int RAD_BIT0_INDEX = 5; final int RAD_BIT1_INDEX = 6; int RADBit0Value = 0; int RADBit1Value = 0; if (firstPartBits.get(RAD_BIT0_INDEX)) { RADBit0Value = 1; } if (firstPartBits.get(RAD_BIT1_INDEX)) { RADBit1Value = 1; } this.sensorMaintainingTrackType = RADBit1Value * 2 + RADBit0Value; appendItemDebugMsg("RAD", this.sensorMaintainingTrackType); } private void decodeCDM(BitSet firstPartBits) { final int CDM_BIT0_INDEX = 1; final int CMD_BIT1_INDEX = 2; int CDMBit0Value = 0; int CDMBit1Value = 0; if (firstPartBits.get(CDM_BIT0_INDEX)) { CDMBit0Value = 1; } if (firstPartBits.get(CMD_BIT1_INDEX)) { CDMBit1Value = 1; } this.climbingDescendingMode = CDMBit1Value * 2 + CDMBit0Value; appendItemDebugMsg("CDM", this.climbingDescendingMode); } }
jlgconsulting/JADE-JavaAsterixDecoderEncoder
src/main/java/jlg/jade/asterix/cat048/Cat048Item170.java
1,795
// decode DOU - bit 4
line_comment
nl
/** * Created by alexandru on 7/8/16. */ package jlg.jade.asterix.cat048; import jlg.jade.asterix.VariableLengthAsterixData; import java.util.BitSet; /** * Cat048Item170 - Track Status * Status of monoradar track (PSR and/or SSR updated). */ public class Cat048Item170 extends VariableLengthAsterixData { private int sensorMaintainingTrackType; // RAD private int confirmedTrack; // CNF private int trackConfidenceLevel; // DOU private int manoeuvreDetectionInHorizontalSense; // MAH private int climbingDescendingMode; // CDM private int signalEndOfTrack; // TRE private int ghostVsTrueTarget; // GHO private int maintainedWithNeighbourSupport; // SUP private int coordinatePlotType; // TCC @Override protected void decodeFromByteArray(byte[] input, int offset) { // decode first part BitSet firstPartBits = BitSet.valueOf(new byte[]{input[offset]}); // decode CNF - bit position 7 final int CNF_BIT_INDEX = 7; if (firstPartBits.get(CNF_BIT_INDEX)) { this.confirmedTrack = 1; } else { this.confirmedTrack = 0; } appendItemDebugMsg("CNF", this.confirmedTrack); // decode RAD - bits 6-5 decodeRAD(firstPartBits); // decode DOU<SUF> final int DOU_BIT_INDEX = 4; if (firstPartBits.get(DOU_BIT_INDEX)) { this.trackConfidenceLevel = 1; } else { this.trackConfidenceLevel = 0; } appendItemDebugMsg("DOU", this.trackConfidenceLevel); // decode MAH - bit 3 final int MAH_BIT_INDEX = 3; if (firstPartBits.get(MAH_BIT_INDEX)) { this.manoeuvreDetectionInHorizontalSense = 1; } else { this.manoeuvreDetectionInHorizontalSense = 0; } appendItemDebugMsg("MAH", this.manoeuvreDetectionInHorizontalSense); // decode CMD - bits 2-1 decodeCDM(firstPartBits); // decode first extent if present if (this.getSizeInBytes() > 1) { BitSet firstExtentBits = BitSet.valueOf(new byte[]{input[offset+1]}); // decode TRE - bit position 7 final int TRE_BIT_INDEX = 7; if(firstExtentBits.get(TRE_BIT_INDEX)){ this.signalEndOfTrack = 1; } else { this.signalEndOfTrack = 0; } appendItemDebugMsg("TRE", this.signalEndOfTrack); // decode GHO final int GHO_BIT_INDEX = 6; if(firstExtentBits.get(GHO_BIT_INDEX)){ this.ghostVsTrueTarget = 1; } else { this.ghostVsTrueTarget = 0; } appendItemDebugMsg("GHO", this.ghostVsTrueTarget); // decode SUP final int SUP_BIT_INDEX = 5; if(firstExtentBits.get(SUP_BIT_INDEX)){ this.maintainedWithNeighbourSupport = 1; } else { this.maintainedWithNeighbourSupport = 0; } appendItemDebugMsg("SUP", this.maintainedWithNeighbourSupport); // decode TCC final int TCC_BIT_INDEX = 4; if(firstExtentBits.get(TCC_BIT_INDEX)){ this.coordinatePlotType = 1; } else { this.coordinatePlotType = 0; } appendItemDebugMsg("TCC", this.coordinatePlotType); } } @Override protected String setDisplayName() { return "Cat048Item170 - Track Status"; } /** * @return type of Sensor(s) maintaining Track - RAD */ public int getSensorMaintainingTrackType() { return sensorMaintainingTrackType; } public int getConfirmedTrack() { return confirmedTrack; } public int getTrackConfidenceLevel() { return trackConfidenceLevel; } public int getManoeuvreDetectionInHorizontalSense() { return manoeuvreDetectionInHorizontalSense; } public int getClimbingDescendingMode() { return climbingDescendingMode; } public int getSignalEndOfTrack() { return signalEndOfTrack; } public int getGhostVsTrueTarget() { return ghostVsTrueTarget; } public int getMaintainedWithNeighbourSupport() { return maintainedWithNeighbourSupport; } public int getCoordinatePlotType() { return coordinatePlotType; } private void decodeRAD(BitSet firstPartBits) { final int RAD_BIT0_INDEX = 5; final int RAD_BIT1_INDEX = 6; int RADBit0Value = 0; int RADBit1Value = 0; if (firstPartBits.get(RAD_BIT0_INDEX)) { RADBit0Value = 1; } if (firstPartBits.get(RAD_BIT1_INDEX)) { RADBit1Value = 1; } this.sensorMaintainingTrackType = RADBit1Value * 2 + RADBit0Value; appendItemDebugMsg("RAD", this.sensorMaintainingTrackType); } private void decodeCDM(BitSet firstPartBits) { final int CDM_BIT0_INDEX = 1; final int CMD_BIT1_INDEX = 2; int CDMBit0Value = 0; int CDMBit1Value = 0; if (firstPartBits.get(CDM_BIT0_INDEX)) { CDMBit0Value = 1; } if (firstPartBits.get(CMD_BIT1_INDEX)) { CDMBit1Value = 1; } this.climbingDescendingMode = CDMBit1Value * 2 + CDMBit0Value; appendItemDebugMsg("CDM", this.climbingDescendingMode); } }
False
3,283
119538_0
package nl.hanze.hive; import org.junit.jupiter.api.Test; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.spy; public class HiveGameLogic { //1c. Elke speler heeft aan het begin van het spel de beschikking over één // bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie // sprinkhanen in zijn eigen kleur. @Test void whenGameStartThenPlayerHaveACompleteDeck() { HiveGame hiveGame = new HiveGame(); HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE); assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1); assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2); assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2); assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3); assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3); } // 3. Spelverloop Wit heeft de eerste beurt. @Test void whenGameStartThenPlayersItsWhiteturn() { HiveGame hiveGame = new HiveGame(); Hive.Player player = hiveGame.getCurrenPlayer(); assertEquals(Hive.Player.WHITE, player); } // 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of // passen; daarna is de tegenstander aan de beurt @Test void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove { HiveGame hiveGame = new HiveGame(); hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0); assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer()); } // 3c Een speler wint als alle zes velden naast de bijenkoningin van de //tegenstander bezet zijn @Test void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertTrue(hiveGame.isWinner(Hive.Player.WHITE)); } @Test void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertTrue(hiveGame.isWinner(Hive.Player.BLACK)); } @Test void whenQueenBeeisNotSurroundedThereIsNoWinner() { HiveGame hiveGame = spy(HiveGame.class); for (Hive.Player player : Hive.Player.values()) { hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertFalse(hiveGame.isWinner(player)); } } // 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een //gelijkspel. @Test void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0); for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r); } for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r); } assertTrue(hiveGame.isDraw()); } @Test void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0); for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r); } assertFalse(hiveGame.isDraw()); } }
jparengkuan/Hive_TDD
src/test/java/nl/hanze/hive/HiveGameLogic.java
2,099
//1c. Elke speler heeft aan het begin van het spel de beschikking over één
line_comment
nl
package nl.hanze.hive; import org.junit.jupiter.api.Test; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.spy; public class HiveGameLogic { //1c. Elke<SUF> // bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie // sprinkhanen in zijn eigen kleur. @Test void whenGameStartThenPlayerHaveACompleteDeck() { HiveGame hiveGame = new HiveGame(); HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE); assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1); assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2); assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2); assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3); assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3); } // 3. Spelverloop Wit heeft de eerste beurt. @Test void whenGameStartThenPlayersItsWhiteturn() { HiveGame hiveGame = new HiveGame(); Hive.Player player = hiveGame.getCurrenPlayer(); assertEquals(Hive.Player.WHITE, player); } // 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of // passen; daarna is de tegenstander aan de beurt @Test void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove { HiveGame hiveGame = new HiveGame(); hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0); assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer()); } // 3c Een speler wint als alle zes velden naast de bijenkoningin van de //tegenstander bezet zijn @Test void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertTrue(hiveGame.isWinner(Hive.Player.WHITE)); } @Test void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertTrue(hiveGame.isWinner(Hive.Player.BLACK)); } @Test void whenQueenBeeisNotSurroundedThereIsNoWinner() { HiveGame hiveGame = spy(HiveGame.class); for (Hive.Player player : Hive.Player.values()) { hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1); hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1); assertFalse(hiveGame.isWinner(player)); } } // 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een //gelijkspel. @Test void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0); for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r); } for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r); } assertTrue(hiveGame.isDraw()); } @Test void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() { HiveGame hiveGame = spy(HiveGame.class); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0); hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0); for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) { hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r); } assertFalse(hiveGame.isDraw()); } }
True
3,003
18201_15
package novi.basics; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static novi.basics.main2.*; public class Game { private char[] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(Player player1, Player player2) { // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan maxRounds = board.length; this.player1 = player1; this.player2 = player2; drawCount = 0; activePlayer = player1; } public void play() { // opslaan hoeveel keer er gelijk spel is geweest // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord tonen printBoard(); // starten met de beurt (maximaal 9 beurten) for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan int chosenField = PLAYERINPUT.nextInt(); int chosenIndex = chosenField - 1; // als het veld bestaat if (chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe speelbord tonen printBoard(); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if (activePlayer == player1) { PLAYERPOSITION.add(chosenField); // maak de actieve speler, speler 2 activePlayer = player2; } // anders else { // maak de actieve speler weer speler 1 activePlayer = player1; PLAYER2POSITION.add(chosenField); } } //of al bezet is else { maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } String result = chekWinner(); if (result.length() > 0) { System.out.println(result); } // -- terug naar het begin van de volgende beurt } } public void printBoard() { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if (fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } public String chekWinner() { List topRow = Arrays.asList(1, 2, 3); List middleRow = Arrays.asList(4, 5, 6); List bottomrow = Arrays.asList(7, 8, 9); List leftColom = Arrays.asList(1, 4, 7); List middleColom = Arrays.asList(2, 5, 8); List rightColom = Arrays.asList(9, 6, 3); List cross1 = Arrays.asList(1, 5, 9); List cross2 = Arrays.asList(7, 5, 3); List<List> winning = new ArrayList<List>(); winning.add(topRow); winning.add(middleRow); winning.add(bottomrow); winning.add(leftColom); winning.add(middleColom); winning.add(rightColom); winning.add(cross1); winning.add(cross2); for (List l : winning) { if (PLAYERPOSITION.containsAll(l)) { player1.addscore(); return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount; } else if (PLAYER2POSITION.containsAll(l)) { player2.addscore(); return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount; } else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) { drawCount++; return "drawcount is:" + drawCount; } } return " "; } }
hogeschoolnovi/tic-tac-toe-vurgill
src/novi/basics/Game.java
1,791
// het nieuwe speelbord tonen
line_comment
nl
package novi.basics; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static novi.basics.main2.*; public class Game { private char[] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(Player player1, Player player2) { // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan maxRounds = board.length; this.player1 = player1; this.player2 = player2; drawCount = 0; activePlayer = player1; } public void play() { // opslaan hoeveel keer er gelijk spel is geweest // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord tonen printBoard(); // starten met de beurt (maximaal 9 beurten) for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan int chosenField = PLAYERINPUT.nextInt(); int chosenIndex = chosenField - 1; // als het veld bestaat if (chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe<SUF> printBoard(); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if (activePlayer == player1) { PLAYERPOSITION.add(chosenField); // maak de actieve speler, speler 2 activePlayer = player2; } // anders else { // maak de actieve speler weer speler 1 activePlayer = player1; PLAYER2POSITION.add(chosenField); } } //of al bezet is else { maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } String result = chekWinner(); if (result.length() > 0) { System.out.println(result); } // -- terug naar het begin van de volgende beurt } } public void printBoard() { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if (fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } public String chekWinner() { List topRow = Arrays.asList(1, 2, 3); List middleRow = Arrays.asList(4, 5, 6); List bottomrow = Arrays.asList(7, 8, 9); List leftColom = Arrays.asList(1, 4, 7); List middleColom = Arrays.asList(2, 5, 8); List rightColom = Arrays.asList(9, 6, 3); List cross1 = Arrays.asList(1, 5, 9); List cross2 = Arrays.asList(7, 5, 3); List<List> winning = new ArrayList<List>(); winning.add(topRow); winning.add(middleRow); winning.add(bottomrow); winning.add(leftColom); winning.add(middleColom); winning.add(rightColom); winning.add(cross1); winning.add(cross2); for (List l : winning) { if (PLAYERPOSITION.containsAll(l)) { player1.addscore(); return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount; } else if (PLAYER2POSITION.containsAll(l)) { player2.addscore(); return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount; } else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) { drawCount++; return "drawcount is:" + drawCount; } } return " "; } }
True
4,283
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() { } }
True
3,470
79029_2
package be; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.namespace.QName; import com.exlibris.dps.IEWebServices; import com.exlibris.dps.IEWebServices_Service; import com.exlibris.dps.PermanentManagerWS; import com.exlibris.dps.PermanentManagerWS_Service; public class CreateMetadataEntry { private IEWebServices ieWebServices; private PermanentManagerWS pmWebServices; public CreateMetadataEntry(String generalFileName, String metadataFileName) { super(); } private String readFile(String fileName) throws IOException { File f = new File(fileName); byte[] bytes = new byte[(int)f.length()]; FileInputStream fis = new FileInputStream(f); fis.read(bytes); return new String(bytes, "UTF-8"); } public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) { try { Thread.sleep(3000); ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort(); pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort(); String generalXml = readFile(generalFileName); String metadataXml = readFile(metadataFileName); if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml")) { Object[] parameters = new Object[] {generalXml, "", "descriptive", "dc", metadataXml}; // String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3); // extractMid(ret, metadataFileName); } else { throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie"); } } catch (IOException e) { System.err.println(e.toString()); } catch (InterruptedException e) { System.err.println(e.toString()); } } public void extractMid(String result, String metadataFileName) throws IOException { if (!result.contains("error")) { String REGEX = "<mid>(.*)</mid>"; Pattern p = Pattern.compile(REGEX); Matcher items = p.matcher(result); if (items.find()) { String mid = items.group(1); // PrintStream out = new PrintStream(System.out, true, "UTF-8"); // out.println(ret); // Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden // Maak file FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out"); BufferedWriter outPut = new BufferedWriter(fstream); // Schrijf de content outPut.write(readFile(metadataFileName)); //Sluit de file outPut.close(); } else { throw new NotFoundException("Mid niet gevonden voor: " + result); } } } }
libis/RosettaUpdater
src/be/CreateMetadataEntry.java
1,031
// Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden
line_comment
nl
package be; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.namespace.QName; import com.exlibris.dps.IEWebServices; import com.exlibris.dps.IEWebServices_Service; import com.exlibris.dps.PermanentManagerWS; import com.exlibris.dps.PermanentManagerWS_Service; public class CreateMetadataEntry { private IEWebServices ieWebServices; private PermanentManagerWS pmWebServices; public CreateMetadataEntry(String generalFileName, String metadataFileName) { super(); } private String readFile(String fileName) throws IOException { File f = new File(fileName); byte[] bytes = new byte[(int)f.length()]; FileInputStream fis = new FileInputStream(f); fis.read(bytes); return new String(bytes, "UTF-8"); } public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) { try { Thread.sleep(3000); ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort(); pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort(); String generalXml = readFile(generalFileName); String metadataXml = readFile(metadataFileName); if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml")) { Object[] parameters = new Object[] {generalXml, "", "descriptive", "dc", metadataXml}; // String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3); // extractMid(ret, metadataFileName); } else { throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie"); } } catch (IOException e) { System.err.println(e.toString()); } catch (InterruptedException e) { System.err.println(e.toString()); } } public void extractMid(String result, String metadataFileName) throws IOException { if (!result.contains("error")) { String REGEX = "<mid>(.*)</mid>"; Pattern p = Pattern.compile(REGEX); Matcher items = p.matcher(result); if (items.find()) { String mid = items.group(1); // PrintStream out = new PrintStream(System.out, true, "UTF-8"); // out.println(ret); // Schrijf het<SUF> // Maak file FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out"); BufferedWriter outPut = new BufferedWriter(fstream); // Schrijf de content outPut.write(readFile(metadataFileName)); //Sluit de file outPut.close(); } else { throw new NotFoundException("Mid niet gevonden voor: " + result); } } } }
True
1,246
107759_4
package field.graphics.core; import static org.lwjgl.opengl.GL11.GL_MODELVIEW; import static org.lwjgl.opengl.GL11.GL_PROJECTION; import static org.lwjgl.opengl.GL11.GL_TEXTURE; import static org.lwjgl.opengl.GL11.glFrustum; import static org.lwjgl.opengl.GL11.glLoadIdentity; import static org.lwjgl.opengl.GL11.glMatrixMode; import static org.lwjgl.opengl.GL11.glViewport; import static org.lwjgl.opengl.GL13.GL_TEXTURE0; import static org.lwjgl.opengl.GL13.GL_TEXTURE1; import static org.lwjgl.opengl.GL13.glActiveTexture; import java.util.Random; import org.lwjgl.util.glu.GLU; import field.graphics.windowing.FullScreenCanvasSWT; import field.launch.SystemProperties; import field.math.linalg.Vector3; public class StereoCamera extends BasicCamera { // there are two ways of doing stereo, modifying the position of the // camera and angling the cameras in // or translating the frustum a little float io_frustra = 0.0f; Vector3 io_position = new Vector3(); float io_lookat = 0.0f; boolean noStereo = SystemProperties.getIntProperty("zeroStereo", 0) == 1; float multiplyDisparity = (float) SystemProperties.getDoubleProperty("multiplyDisparity", 1); public StereoCamera setIOFrustra(float i) { this.io_frustra = i; return this; } public StereoCamera setIOPosition(Vector3 v) { this.io_position = new Vector3(v); return this; } public StereoCamera setIOPosition(float m) { this.io_position = new Vector3(m, m, m); return this; } public StereoCamera setIOLookAt(float x) { this.io_lookat = x; return this; } public float getIOLookAt() { return io_lookat; } static float flipped = (SystemProperties.getIntProperty("stereoEyeFlipped", 0) == 1 ? -1 : 1); static boolean passive = (SystemProperties.getIntProperty("passiveStereo", 0) == 1); double disparityPerDistance = SystemProperties.getDoubleProperty("defaultDisparityPerDistance", 0); boolean texture0IsRight = false; public float[] previousModelViewLeft; public float[] previousModelViewRight; float extraAmount = 1; @Override public void performPass() { pre(); boolean wasDirty = projectionDirty || modelViewDirty; { // if (passive) { // if (FullScreenCanvasSWT.getSide() == // FullScreenCanvasSWT.StereoSide.left) { // // glViewport(oX, oY, width / 2, // // height); // glViewport(oX + width / 2, oY, width / 2, height); // } else { // glViewport(oX, oY, width / 2, height); // } // // } // else // { glViewport(oX, oY, width, height); // } CoreHelpers.glMatrixMode(GL_PROJECTION); CoreHelpers.glLoadIdentity(); float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul; float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul; float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x; if (noStereo) x = 0; CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x), -top + top * tshift, top + top * tshift, near, far); CoreHelpers.glMatrixMode(GL_MODELVIEW); projectionDirty = false; } { CoreHelpers.glMatrixMode(GL_MODELVIEW); CoreHelpers.glLoadIdentity(); Vector3 left = new Vector3().cross(getViewRay(null), getUp(null)).normalize(); Vector3 io_position = new Vector3(this.io_position); io_position.x += disparityPerDistance * lookAt.distanceFrom(position); io_position.y += disparityPerDistance * lookAt.distanceFrom(position); io_position.z += disparityPerDistance * lookAt.distanceFrom(position); io_position.scale(multiplyDisparity); if (noStereo) left.scale(0); float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x; float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul; CoreHelpers.gluLookAt(position.x + flipped * (io_position.x) * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z); CoreHelpers.glActiveTexture(GL_TEXTURE0); CoreHelpers.glMatrixMode(GL_TEXTURE); CoreHelpers.glLoadIdentity(); if (!texture0IsRight) CoreHelpers.gluLookAt(position.x + flipped * io_position.x * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z); else CoreHelpers.gluLookAt(position.x + flipped * io_position.x * 1 * left.x, position.y + flipped * io_position.y * 1 * left.y, position.z + flipped * io_position.z * 1 * left.z, lookAt.x + flipped * io_lookat * 1 * left.x, lookAt.y + flipped * io_lookat * 1 * left.y, lookAt.z + flipped * io_lookat * 1 * left.z, up.x, up.y, up.z); CoreHelpers.glActiveTexture(GL_TEXTURE1); CoreHelpers.glMatrixMode(GL_TEXTURE); CoreHelpers.glLoadIdentity(); float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul; x = 0; CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount), -top + top * tshift, top + top * tshift, near, far); CoreHelpers.gluLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z); CoreHelpers.glMatrixMode(GL_MODELVIEW); CoreHelpers.glActiveTexture(GL_TEXTURE0); modelViewDirty = false; } post(); if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) randomSource.left(); else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) randomSource.right(); if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) { previousModelViewRight = modelView; previousModelView = previousModelViewLeft; } else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) { previousModelViewLeft = modelView; previousModelView = previousModelViewRight; } else { previousModelView = previousModelViewLeft; previousModelViewLeft = modelView; } projection = getCurrentProjectionMatrixNow(null); modelView = getCurrentModelViewMatrixNow(null); if (dropFrame) { if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) { previousModelViewLeft = modelView; } else { previousModelViewRight = modelView; } } currentCamera = this; } public void copyTo(BasicCamera shim) { super.copyTo(shim); if (shim instanceof StereoCamera) { ((StereoCamera) shim).io_frustra = io_frustra; ((StereoCamera) shim).io_position = io_position; ((StereoCamera) shim).io_lookat = io_lookat; } } public StereoNoiseSource randomSource = new StereoNoiseSource(); static public class StereoNoiseSource { private Random r; public StereoNoiseSource() { r = new Random(); } public float get() { return r.nextFloat(); } long leftseed = System.currentTimeMillis(); public void left() { r = new Random(leftseed); r.nextFloat(); r.nextFloat(); } public void right() { leftseed = System.currentTimeMillis(); r = new Random(leftseed); r.nextFloat(); r.nextFloat(); } } public float getIOFrustra() { return io_frustra; } public Vector3 getIOPosition() { return io_position; } public static double getRandomNumber() { return Math.random(); // // if (BasicCamera.currentCamera instanceof StereoCamera) // { // return // ((StereoCamera)BasicCamera.currentCamera).randomSource.get(); // } // else // { // ;//System.out.println(" warning: current camera is not a stereo camera "); // return Math.random(); // } } }
OpenEndedGroup/Field
Contents/core/java/field/graphics/core/StereoCamera.java
3,086
// if (FullScreenCanvasSWT.getSide() ==
line_comment
nl
package field.graphics.core; import static org.lwjgl.opengl.GL11.GL_MODELVIEW; import static org.lwjgl.opengl.GL11.GL_PROJECTION; import static org.lwjgl.opengl.GL11.GL_TEXTURE; import static org.lwjgl.opengl.GL11.glFrustum; import static org.lwjgl.opengl.GL11.glLoadIdentity; import static org.lwjgl.opengl.GL11.glMatrixMode; import static org.lwjgl.opengl.GL11.glViewport; import static org.lwjgl.opengl.GL13.GL_TEXTURE0; import static org.lwjgl.opengl.GL13.GL_TEXTURE1; import static org.lwjgl.opengl.GL13.glActiveTexture; import java.util.Random; import org.lwjgl.util.glu.GLU; import field.graphics.windowing.FullScreenCanvasSWT; import field.launch.SystemProperties; import field.math.linalg.Vector3; public class StereoCamera extends BasicCamera { // there are two ways of doing stereo, modifying the position of the // camera and angling the cameras in // or translating the frustum a little float io_frustra = 0.0f; Vector3 io_position = new Vector3(); float io_lookat = 0.0f; boolean noStereo = SystemProperties.getIntProperty("zeroStereo", 0) == 1; float multiplyDisparity = (float) SystemProperties.getDoubleProperty("multiplyDisparity", 1); public StereoCamera setIOFrustra(float i) { this.io_frustra = i; return this; } public StereoCamera setIOPosition(Vector3 v) { this.io_position = new Vector3(v); return this; } public StereoCamera setIOPosition(float m) { this.io_position = new Vector3(m, m, m); return this; } public StereoCamera setIOLookAt(float x) { this.io_lookat = x; return this; } public float getIOLookAt() { return io_lookat; } static float flipped = (SystemProperties.getIntProperty("stereoEyeFlipped", 0) == 1 ? -1 : 1); static boolean passive = (SystemProperties.getIntProperty("passiveStereo", 0) == 1); double disparityPerDistance = SystemProperties.getDoubleProperty("defaultDisparityPerDistance", 0); boolean texture0IsRight = false; public float[] previousModelViewLeft; public float[] previousModelViewRight; float extraAmount = 1; @Override public void performPass() { pre(); boolean wasDirty = projectionDirty || modelViewDirty; { // if (passive) { // if (FullScreenCanvasSWT.getSide()<SUF> // FullScreenCanvasSWT.StereoSide.left) { // // glViewport(oX, oY, width / 2, // // height); // glViewport(oX + width / 2, oY, width / 2, height); // } else { // glViewport(oX, oY, width / 2, height); // } // // } // else // { glViewport(oX, oY, width, height); // } CoreHelpers.glMatrixMode(GL_PROJECTION); CoreHelpers.glLoadIdentity(); float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul; float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul; float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x; if (noStereo) x = 0; CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x), -top + top * tshift, top + top * tshift, near, far); CoreHelpers.glMatrixMode(GL_MODELVIEW); projectionDirty = false; } { CoreHelpers.glMatrixMode(GL_MODELVIEW); CoreHelpers.glLoadIdentity(); Vector3 left = new Vector3().cross(getViewRay(null), getUp(null)).normalize(); Vector3 io_position = new Vector3(this.io_position); io_position.x += disparityPerDistance * lookAt.distanceFrom(position); io_position.y += disparityPerDistance * lookAt.distanceFrom(position); io_position.z += disparityPerDistance * lookAt.distanceFrom(position); io_position.scale(multiplyDisparity); if (noStereo) left.scale(0); float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x; float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul; CoreHelpers.gluLookAt(position.x + flipped * (io_position.x) * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z); CoreHelpers.glActiveTexture(GL_TEXTURE0); CoreHelpers.glMatrixMode(GL_TEXTURE); CoreHelpers.glLoadIdentity(); if (!texture0IsRight) CoreHelpers.gluLookAt(position.x + flipped * io_position.x * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z); else CoreHelpers.gluLookAt(position.x + flipped * io_position.x * 1 * left.x, position.y + flipped * io_position.y * 1 * left.y, position.z + flipped * io_position.z * 1 * left.z, lookAt.x + flipped * io_lookat * 1 * left.x, lookAt.y + flipped * io_lookat * 1 * left.y, lookAt.z + flipped * io_lookat * 1 * left.z, up.x, up.y, up.z); CoreHelpers.glActiveTexture(GL_TEXTURE1); CoreHelpers.glMatrixMode(GL_TEXTURE); CoreHelpers.glLoadIdentity(); float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul; x = 0; CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount), -top + top * tshift, top + top * tshift, near, far); CoreHelpers.gluLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z); CoreHelpers.glMatrixMode(GL_MODELVIEW); CoreHelpers.glActiveTexture(GL_TEXTURE0); modelViewDirty = false; } post(); if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) randomSource.left(); else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) randomSource.right(); if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) { previousModelViewRight = modelView; previousModelView = previousModelViewLeft; } else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) { previousModelViewLeft = modelView; previousModelView = previousModelViewRight; } else { previousModelView = previousModelViewLeft; previousModelViewLeft = modelView; } projection = getCurrentProjectionMatrixNow(null); modelView = getCurrentModelViewMatrixNow(null); if (dropFrame) { if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) { previousModelViewLeft = modelView; } else { previousModelViewRight = modelView; } } currentCamera = this; } public void copyTo(BasicCamera shim) { super.copyTo(shim); if (shim instanceof StereoCamera) { ((StereoCamera) shim).io_frustra = io_frustra; ((StereoCamera) shim).io_position = io_position; ((StereoCamera) shim).io_lookat = io_lookat; } } public StereoNoiseSource randomSource = new StereoNoiseSource(); static public class StereoNoiseSource { private Random r; public StereoNoiseSource() { r = new Random(); } public float get() { return r.nextFloat(); } long leftseed = System.currentTimeMillis(); public void left() { r = new Random(leftseed); r.nextFloat(); r.nextFloat(); } public void right() { leftseed = System.currentTimeMillis(); r = new Random(leftseed); r.nextFloat(); r.nextFloat(); } } public float getIOFrustra() { return io_frustra; } public Vector3 getIOPosition() { return io_position; } public static double getRandomNumber() { return Math.random(); // // if (BasicCamera.currentCamera instanceof StereoCamera) // { // return // ((StereoCamera)BasicCamera.currentCamera).randomSource.get(); // } // else // { // ;//System.out.println(" warning: current camera is not a stereo camera "); // return Math.random(); // } } }
False
1,021
121263_0
//bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk) /** *De klasse Oef2 is een java applicatie * *@author Sophie Moons *@version 1,0 */ import java.lang.*; public class Oef2{ /** *Dit is een main function, hier start het programma *@param args -> hiermee kan een array meegegeven worden via command line */ public static void main(String args[]) { String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"}; int h=1; System.out.println("Data februari 2009:\n"); while (h<29) //28 dagen toen { for(int i=0;i<dagen.length;i++) { System.out.println(dagen[i]+" "+h+" februari"); h++; } } }//einde main }//einde program
MTA-Digital-Broadcast-2/A-Moons-Sophie-De-Cock-Nicolas-Project-MHP
Sophie Moons/Labo Java/blz19/Oef2.java
263
//bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk)
line_comment
nl
//bestandsnaam: Oef2.java<SUF> /** *De klasse Oef2 is een java applicatie * *@author Sophie Moons *@version 1,0 */ import java.lang.*; public class Oef2{ /** *Dit is een main function, hier start het programma *@param args -> hiermee kan een array meegegeven worden via command line */ public static void main(String args[]) { String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"}; int h=1; System.out.println("Data februari 2009:\n"); while (h<29) //28 dagen toen { for(int i=0;i<dagen.length;i++) { System.out.println(dagen[i]+" "+h+" februari"); h++; } } }//einde main }//einde program
True
4,184
22211_0
package nl.designpatterns.builder; import java.util.Date; public class VacationBuilder { private static VacationBuilder builder = new VacationBuilder(); private VacationBuilder() {} public static VacationBuilder getInstance() { return builder; } private Vacation vacation = new Vacation(); public void addPersoon(String voornaam, String achternaam) { Persoon p = new Persoon(achternaam, voornaam, new Date()); this.vacation.addPersoon(p); } public void setHotel(String name) { this.vacation.setHotel(new Hotel(name)); } public void setReservation(String in, String uit) { // test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java. Date inDate = new Date(); Date outDate = new Date(new Date().getTime()-10000); Reservation reservation = new Reservation(inDate, outDate); this.vacation.setReservation(reservation); } public void addActivity(Activity activity) { this.vacation.addActivity(activity); } public Vacation getVacation() { return this.vacation; } }
rloman/design-patterns
src/main/java/nl/designpatterns/builder/VacationBuilder.java
356
// test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java.
line_comment
nl
package nl.designpatterns.builder; import java.util.Date; public class VacationBuilder { private static VacationBuilder builder = new VacationBuilder(); private VacationBuilder() {} public static VacationBuilder getInstance() { return builder; } private Vacation vacation = new Vacation(); public void addPersoon(String voornaam, String achternaam) { Persoon p = new Persoon(achternaam, voornaam, new Date()); this.vacation.addPersoon(p); } public void setHotel(String name) { this.vacation.setHotel(new Hotel(name)); } public void setReservation(String in, String uit) { // test normaliter<SUF> Date inDate = new Date(); Date outDate = new Date(new Date().getTime()-10000); Reservation reservation = new Reservation(inDate, outDate); this.vacation.setReservation(reservation); } public void addActivity(Activity activity) { this.vacation.addActivity(activity); } public Vacation getVacation() { return this.vacation; } }
False
4,029
18945_0
package codefromvideo.mockito;_x000D_ _x000D_ import java.util.List;_x000D_ _x000D_ public class Winkelmand {_x000D_ _x000D_ public boolean voegProductToeAanWinkelmand(_x000D_ Sessie sessie,_x000D_ Product nieuwProduct) {_x000D_ List<Product> producten = sessie.getProducten();_x000D_ _x000D_ if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_ producten.add(nieuwProduct);_x000D_ sessie.setProducten(producten);_x000D_ return true;_x000D_ } else {_x000D_ // product mag maar 1 keer in winkelmand zitten_x000D_ return false;_x000D_ }_x000D_ }_x000D_ _x000D_ private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_ return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_ }_x000D_ }_x000D_
praegus/intro-unittesten
src/main/java/codefromvideo/mockito/Winkelmand.java
234
// product mag maar 1 keer in winkelmand zitten_x000D_
line_comment
nl
package codefromvideo.mockito;_x000D_ _x000D_ import java.util.List;_x000D_ _x000D_ public class Winkelmand {_x000D_ _x000D_ public boolean voegProductToeAanWinkelmand(_x000D_ Sessie sessie,_x000D_ Product nieuwProduct) {_x000D_ List<Product> producten = sessie.getProducten();_x000D_ _x000D_ if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_ producten.add(nieuwProduct);_x000D_ sessie.setProducten(producten);_x000D_ return true;_x000D_ } else {_x000D_ // product mag<SUF> return false;_x000D_ }_x000D_ }_x000D_ _x000D_ private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_ return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_ }_x000D_ }_x000D_
True
4,597
10051_3
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP 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 any later version. * * JMTP 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 LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package jmtp; import java.math.BigInteger; import java.util.Date; import be.derycke.pieter.com.COMException; import be.derycke.pieter.com.Guid; import be.derycke.pieter.com.OleDate; /** * * @author Pieter De Rycke */ class PortableDeviceObjectImplWin32 implements PortableDeviceObject { protected PortableDeviceContentImplWin32 content; protected PortableDevicePropertiesImplWin32 properties; protected PortableDeviceKeyCollectionImplWin32 keyCollection; protected PortableDeviceValuesImplWin32 values; protected String objectID; PortableDeviceObjectImplWin32(String objectID, PortableDeviceContentImplWin32 content, PortableDevicePropertiesImplWin32 properties) { this.objectID = objectID; this.content = content; this.properties = properties; try { this.keyCollection = new PortableDeviceKeyCollectionImplWin32(); this.values = new PortableDeviceValuesImplWin32(); } catch (COMException e) { e.printStackTrace(); } } /** * Een String property opvragen. * @param key * @return */ protected String retrieveStringValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getStringValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return null; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeStringValue(PropertyKey key, String value) { try { values.clear(); values.setStringValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected long retrieveLongValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return -1; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return -1; } } } protected void changeLongValue(PropertyKey key, long value) { try { values.clear(); values.setUnsignedIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected Date retrieveDateValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key)); } catch(COMException e) { return null; } } protected void changeDateValue(PropertyKey key, Date value) { try { values.clear(); values.setFloateValue(key, (float)new OleDate(value).toDouble()); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) {} } protected boolean retrieveBooleanValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getBoolValue(key); } catch(COMException e) { return false; } } protected Guid retrieveGuidValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getGuidValue(key); } catch(COMException e) { return null; } } protected BigInteger retrieveBigIntegerValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getUnsignedLargeIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return new BigInteger("-1"); else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeBigIntegerValue(PropertyKey key, BigInteger value) { try { values.clear(); values.setUnsignedLargeIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } public String getID() { return objectID; } public String getName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME); } public String getOriginalFileName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME); } public boolean canDelete() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE); } public boolean isHidden() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN); } public boolean isSystemObject() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM); } public Date getDateModified() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED); } public Date getDateCreated() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED); } public Date getDateAuthored() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED); } public PortableDeviceObject getParent() { String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID); if(parentID != null) return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties); else return null; } public BigInteger getSize() { return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE); } public String getPersistentUniqueIdentifier() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID); } public boolean isDrmProtected() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED); } public String getSyncID() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID); } //TODO slechts tijdelijk de guids geven -> enum aanmaken public Guid getFormat() { return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT); } public void setSyncID(String value) { changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value); } public void delete() { try { PortableDevicePropVariantCollectionImplWin32 collection = new PortableDevicePropVariantCollectionImplWin32(); collection.add(new PropVariant(this.objectID)); this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection); } catch(COMException e) { //TODO -> misschien een exception gooien? e.printStackTrace(); } } @Override public String toString() { return objectID; } public boolean equals(Object o) { if(o instanceof PortableDeviceObjectImplWin32) { PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o; return object.objectID.equals(this.objectID); } else return false; } }
ultrah/jMTPe
source/java/src/jmtp/PortableDeviceObjectImplWin32.java
2,931
//comexception -> de string werd niet ingesteld
line_comment
nl
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP 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 any later version. * * JMTP 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 LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package jmtp; import java.math.BigInteger; import java.util.Date; import be.derycke.pieter.com.COMException; import be.derycke.pieter.com.Guid; import be.derycke.pieter.com.OleDate; /** * * @author Pieter De Rycke */ class PortableDeviceObjectImplWin32 implements PortableDeviceObject { protected PortableDeviceContentImplWin32 content; protected PortableDevicePropertiesImplWin32 properties; protected PortableDeviceKeyCollectionImplWin32 keyCollection; protected PortableDeviceValuesImplWin32 values; protected String objectID; PortableDeviceObjectImplWin32(String objectID, PortableDeviceContentImplWin32 content, PortableDevicePropertiesImplWin32 properties) { this.objectID = objectID; this.content = content; this.properties = properties; try { this.keyCollection = new PortableDeviceKeyCollectionImplWin32(); this.values = new PortableDeviceValuesImplWin32(); } catch (COMException e) { e.printStackTrace(); } } /** * Een String property opvragen. * @param key * @return */ protected String retrieveStringValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getStringValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return null; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -><SUF> } } } protected void changeStringValue(PropertyKey key, String value) { try { values.clear(); values.setStringValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected long retrieveLongValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return -1; else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return -1; } } } protected void changeLongValue(PropertyKey key, long value) { try { values.clear(); values.setUnsignedIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } protected Date retrieveDateValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key)); } catch(COMException e) { return null; } } protected void changeDateValue(PropertyKey key, Date value) { try { values.clear(); values.setFloateValue(key, (float)new OleDate(value).toDouble()); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) {} } protected boolean retrieveBooleanValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getBoolValue(key); } catch(COMException e) { return false; } } protected Guid retrieveGuidValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection).getGuidValue(key); } catch(COMException e) { return null; } } protected BigInteger retrieveBigIntegerValue(PropertyKey key) { try { keyCollection.clear(); keyCollection.add(key); return properties.getValues(objectID, keyCollection). getUnsignedLargeIntegerValue(key); } catch(COMException e) { if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND) return new BigInteger("-1"); else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED) throw new UnsupportedOperationException("Couldn't retrieve the specified property."); else { e.printStackTrace(); return null; //comexception -> de string werd niet ingesteld } } } protected void changeBigIntegerValue(PropertyKey key, BigInteger value) { try { values.clear(); values.setUnsignedLargeIntegerValue(key, value); PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values); if(results.count() > 0 && results.getErrorValue(key).getHresult() != COMException.S_OK) { throw new UnsupportedOperationException("Couldn't change the property."); } } catch(COMException e) { e.printStackTrace(); } } public String getID() { return objectID; } public String getName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME); } public String getOriginalFileName() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME); } public boolean canDelete() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE); } public boolean isHidden() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN); } public boolean isSystemObject() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM); } public Date getDateModified() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED); } public Date getDateCreated() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED); } public Date getDateAuthored() { return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED); } public PortableDeviceObject getParent() { String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID); if(parentID != null) return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties); else return null; } public BigInteger getSize() { return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE); } public String getPersistentUniqueIdentifier() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID); } public boolean isDrmProtected() { return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED); } public String getSyncID() { return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID); } //TODO slechts tijdelijk de guids geven -> enum aanmaken public Guid getFormat() { return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT); } public void setSyncID(String value) { changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value); } public void delete() { try { PortableDevicePropVariantCollectionImplWin32 collection = new PortableDevicePropVariantCollectionImplWin32(); collection.add(new PropVariant(this.objectID)); this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection); } catch(COMException e) { //TODO -> misschien een exception gooien? e.printStackTrace(); } } @Override public String toString() { return objectID; } public boolean equals(Object o) { if(o instanceof PortableDeviceObjectImplWin32) { PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o; return object.objectID.equals(this.objectID); } else return false; } }
True
1,608
172777_48
package io.sloeber.ui.monitor.views; import static io.sloeber.ui.Activator.*; import java.io.File; import java.net.URL; import java.nio.charset.Charset; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; import io.sloeber.core.api.ISerialUser; import io.sloeber.core.api.Serial; import io.sloeber.core.api.SerialManager; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; import io.sloeber.ui.listeners.ProjectExplorerListener; import io.sloeber.ui.monitor.internal.SerialListener; /** * SerialMonitor implements the view that shows the serial monitor. Serial * monitor get sits data from serial Listener. 1 serial listener is created per * serial connection. * */ @SuppressWarnings({ "unused" }) public class SerialMonitor extends ViewPart implements ISerialUser { /** * The ID of the view as specified by the extension. */ // public static final String ID = // "io.sloeber.ui.monitor.views.SerialMonitor"; // If you increase this number you must also assign colors in plugin.xml static private final int MY_MAX_SERIAL_PORTS = 6; static private final boolean[] serialPortAllocated = new boolean[MY_MAX_SERIAL_PORTS]; // These StringBuilders are used to create discrete lines of text when in // timestamp // mode. static private final StringBuilder[] lineBuffer = new StringBuilder[MY_MAX_SERIAL_PORTS]; static private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); //$NON-NLS-1$ static private final URL IMG_CLEAR; static private final URL IMG_LOCK; static private final URL IMG_FILTER; static private final URL IMG_TIMESTAMP; static private final String newLine = System.getProperty("line.separator"); //$NON-NLS-1$ static { IMG_CLEAR = getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$ IMG_LOCK = getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$ IMG_FILTER = getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$ IMG_TIMESTAMP = getDefault().getBundle().getEntry("icons/timestamp_console.png"); //$NON-NLS-1$ } // Connect to a serial port private Action connect; // this action will disconnect the serial port selected by the serialPorts // combo private Action disconnect; // lock serial monitor scrolling private Action scrollLock; // filter out binary data from serial monitor private Action plotterFilter; // clear serial monitor private Action clear; // Toggle timestamps on serial messages. private Action showTimestamps; // The string to send to the serial port protected Text sendString; // control contains the output of the serial port static protected StyledText monitorOutput; // Port used when doing actions protected ComboViewer serialPorts; // Add CR? LF? CR+LF? Nothing? protected ComboViewer lineTerminator; // When click will send the content of SendString to the port selected // SerialPorts // adding the postfix selected in SendPostFix private Button send; // The button to reset the arduino private Button reset; // Contains the colors that are used private String[] serialColorID = null; // link to color registry private ColorRegistry colorRegistry = null; private boolean timestampMode = true; static private Composite parent; /* * ************** Below are variables needed for good housekeeping */ // The serial connections that are open with the listeners listening to this // port protected Map<Serial, SerialListener> serialConnections; private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$ static final String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$ private static SerialMonitor instance = null; /** * Call this method to get the instance of SerialMonitor. * * @return the (singleton) instance of SerialMonitor. */ public static synchronized SerialMonitor getSerialMonitor() { if (instance == null) { instance = new SerialMonitor(); } return instance; } /** * This constructor should only be called by Eclipse or * {@link #getSerialMonitor()}. * * It is only public because Eclipse needs to call it. */ public SerialMonitor() { if (instance != null) { log(new Status(IStatus.ERROR, PLUGIN_ID, "You can only have one serial monitor")); //$NON-NLS-1$ } instance = this; serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); colorRegistry = currentTheme.getColorRegistry(); serialColorID = new String[MY_MAX_SERIAL_PORTS]; for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) { serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$ serialPortAllocated[i] = false; lineBuffer[i] = new StringBuilder(); } SerialManager.registerSerialUser(this); Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { try { IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1; myScope.putInt(MY_FLAG_MONITOR, curFsiStatus); URL mypluginStartInitiator = new URL(uri.replace(" ", new String()) //$NON-NLS-1$ + Integer.toString(curFsiStatus)); mypluginStartInitiator.getContent(); } catch (Exception e) {// JABA is not going to add code } return Status.OK_STATUS; } }; job.setPriority(Job.DECORATE); job.schedule(); } @Override public void dispose() { SerialManager.UnRegisterSerialUser(); for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { entry.getValue().dispose(); entry.getKey().dispose(); } serialConnections.clear(); instance = null; } /** * This is a callback that will allow us to create the viewer and initialize it. */ @Override public void createPartControl(Composite parent1) { parent = parent1; parent1.setLayout(new GridLayout()); GridLayout layout = new GridLayout(5, false); layout.marginHeight = 0; layout.marginWidth = 0; Composite top = new Composite(parent1, SWT.NONE); top.setLayout(layout); top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); minSizeGridData.widthHint = 150; serialPorts.getControl().setLayoutData(minSizeGridData); serialPorts.setContentProvider(new IStructuredContentProvider() { @Override public void dispose() { // no need to do something here } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // no need to do something here } @Override public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement; return items.keySet().toArray(); } }); serialPorts.setLabelProvider(new LabelProvider()); serialPorts.setInput(serialConnections); serialPorts.addSelectionChangedListener(new ComPortChanged(this)); sendString = new Text(top, SWT.SINGLE | SWT.BORDER); sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); lineTerminator.setContentProvider(new ArrayContentProvider()); lineTerminator.setLabelProvider(new LabelProvider()); lineTerminator.setInput(SerialManager.listLineEndings()); lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd()); lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { MyPreferences.setLastUsedSerialLineEnd(lineTerminator.getCombo().getSelectionIndex()); } }); send = new Button(top, SWT.BUTTON1); send.setText(Messages.serialMonitorSend); send.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { int index = lineTerminator.getCombo().getSelectionIndex(); GetSelectedSerial().write(sendString.getText(), SerialManager.getLineEnding(index)); sendString.setText(new String()); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); send.setEnabled(false); reset = new Button(top, SWT.BUTTON1); reset.setText(Messages.serialMonitorReset); reset.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GetSelectedSerial().reset(); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); reset.setEnabled(false); // register the combo as a Selection Provider getSite().setSelectionProvider(serialPorts); monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); monitorOutput.setEditable(false); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); FontRegistry fontRegistry = currentTheme.getFontRegistry(); monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$ monitorOutput.setText(Messages.serialMonitorNoInput + newLine); monitorOutput.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { // ignore } @Override public void mouseDown(MouseEvent e) { // If right button get selected text save it and start external tool if (e.button == 3) { String selectedText = monitorOutput.getSelectionText(); if (!selectedText.isEmpty()) { IProject selectedProject = ProjectExplorerListener.getSelectedProject(); if (selectedProject != null) { try { ICConfigurationDescription activeCfg = CoreModel.getDefault() .getProjectDescription(selectedProject).getActiveConfiguration(); String activeConfigName = activeCfg.getName(); IPath buildFolder = selectedProject.findMember(activeConfigName).getLocation(); File dumpFile = buildFolder.append("serialdump.txt").toFile(); //$NON-NLS-1$ FileUtils.writeStringToFile(dumpFile, selectedText, Charset.defaultCharset()); } catch (Exception e1) { // ignore e1.printStackTrace(); } } } } } @Override public void mouseDoubleClick(MouseEvent e) { // ignore } }); parent.getShell().setDefaultButton(send); makeActions(); contributeToActionBars(); } /** * GetSelectedSerial is a wrapper class that returns the serial port selected in * the combobox * * @return the serial port selected in the combobox */ protected Serial GetSelectedSerial() { return GetSerial(serialPorts.getCombo().getText()); } /** * Looks in the open com ports with a port with the name as provided. * * @param comName the name of the comport you are looking for * @return the serial port opened in the serial monitor with the name equal to * Comname of found. null if not found */ private Serial GetSerial(String comName) { for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { if (entry.getKey().toString().matches(comName)) return entry.getKey(); } return null; } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(clear); manager.add(scrollLock); manager.add(plotterFilter); manager.add(showTimestamps); manager.add(connect); manager.add(disconnect); } private void fillLocalPullDown(IMenuManager manager) { manager.add(connect); manager.add(new Separator()); manager.add(disconnect); } private void makeActions() { connect = new Action() { @Override public void run() { OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(parent.getShell()); comportSelector.create(); if (comportSelector.open() == Window.OK) { connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate(), comportSelector.GetDtr()); } } }; connect.setText(Messages.serialMonitorConnectedTo); connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor); connect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK)); disconnect = new Action() { @Override public void run() { disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText()); } }; disconnect.setText(Messages.serialMonitorDisconnectedFrom); disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor); disconnect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));// IMG_OBJS_INFO_TSK)); disconnect.setEnabled(serialConnections.size() != 0); clear = new Action(Messages.serialMonitorClear) { @Override public void run() { clearMonitor(); } }; clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR)); clear.setEnabled(true); scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) { @Override public void run() { MyPreferences.setLastUsedAutoScroll(!isChecked()); } }; scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK)); scrollLock.setEnabled(true); scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll()); plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) { @Override public void run() { SerialListener.setPlotterFilter(isChecked()); MyPreferences.setLastUsedPlotterFilter(isChecked()); } }; plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER)); plotterFilter.setEnabled(true); plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter()); SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter()); showTimestamps = new Action(Messages.serialMonitorShowTimestamps, IAction.AS_CHECK_BOX) { @Override public void run() { timestampMode = isChecked(); MyPreferences.setLastUsedShowTimestamps(isChecked()); } }; showTimestamps.setImageDescriptor(ImageDescriptor.createFromURL(IMG_TIMESTAMP)); showTimestamps.setEnabled(true); showTimestamps.setChecked(MyPreferences.getLastUsedShowTimestamps()); timestampMode = MyPreferences.getLastUsedShowTimestamps(); } /** * Passing the focus request to the viewer's control. */ @Override public void setFocus() { // MonitorOutput.setf .getControl().setFocus(); parent.getShell().setDefaultButton(send); } /** * The listener calls this method to report that serial data has arrived * * @param stInfo The serial data that has arrived * @param style The style that should be used to report the data; Actually this * is the index number of the opened port */ public void ReportSerialActivity(String stInfo, int style) { String text = stInfo; if (timestampMode) { StringBuilder sb = new StringBuilder(); String ts = LocalTime.now().format(timeFormatter) + ": "; //$NON-NLS-1$ // Normalize the line endings. text = text.replaceAll("\r", ""); //$NON-NLS-1$ //$NON-NLS-2$ int begin = 0; while (true) { int idx = text.indexOf("\n", begin); //$NON-NLS-1$ if (idx >= 0) { // Note the first time through this loop lineBuffer[style] may contain // an incomplete line from the previously received chunk of data. String substring = text.substring(begin, idx + 1); lineBuffer[style].append(substring); sb.append(ts); sb.append(lineBuffer[style]); lineBuffer[style].setLength(0); begin = idx + 1; } else { // Save any remaining data for the next time through this method. lineBuffer[style].append(text.substring(begin)); break; } } if (sb.length() < 1) { return; } text = sb.toString(); } int startPoint = monitorOutput.getCharCount(); monitorOutput.append(text); StyleRange styleRange = new StyleRange(); styleRange.start = startPoint; styleRange.length = text.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = colorRegistry.get(serialColorID[style]); monitorOutput.setStyleRange(styleRange); if (!scrollLock.isChecked()) { monitorOutput.setSelection(monitorOutput.getCharCount()); } } /** * method to make sure the visualization is correct */ void SerialPortsUpdated() { disconnect.setEnabled(serialConnections.size() != 0); Serial curSelection = GetSelectedSerial(); serialPorts.setInput(serialConnections); if (serialConnections.size() == 0) { send.setEnabled(false); reset.setEnabled(false); } else { if (serialPorts.getSelection().isEmpty()) // nothing is // selected { if (curSelection == null) // nothing was selected { curSelection = (Serial) serialConnections.keySet().toArray()[0]; } serialPorts.getCombo().setText(curSelection.toString()); ComboSerialChanged(); } } } public void connectSerial(String comPort, int baudRate) { connectSerial(comPort, baudRate, false); } /** * Connect to a serial port and sets the listener * * @param comPort the name of the com port to connect to * @param baudRate the baud rate to connect to the com port */ public void connectSerial(String comPort, int baudRate, boolean dtr) { if (serialConnections.size() < MY_MAX_SERIAL_PORTS) { int colorindex = -1; for (int idx = 0; idx < serialPortAllocated.length; idx++) { if (!serialPortAllocated[idx]) { colorindex = idx; break; } } if (colorindex < 0) { log(new Status(IStatus.ERROR, PLUGIN_ID, Messages.serialMonitorNoMoreSerialPortsSupported, null)); } Serial newSerial = new Serial(comPort, baudRate, dtr); if (newSerial.IsConnected()) { newSerial.registerService(); SerialListener theListener = new SerialListener(this, colorindex); newSerial.addListener(theListener); theListener.event(newLine + Messages.serialMonitorConnectedTo.replace(Messages.PORT, comPort) .replace(Messages.BAUD, Integer.toString(baudRate)) + newLine); serialConnections.put(newSerial, theListener); SerialPortsUpdated(); // Only mark the serial port as allocated now everything is done with no errors. serialPortAllocated[colorindex] = true; return; } } else { log(new Status(IStatus.ERROR, PLUGIN_ID, Messages.serialMonitorNoMoreSerialPortsSupported, null)); } } public void disConnectSerialPort(String comPort) { Serial newSerial = GetSerial(comPort); if (newSerial != null) { SerialListener theListener = serialConnections.get(newSerial); serialPortAllocated[theListener.getColorIndex()] = false; serialConnections.remove(newSerial); newSerial.removeListener(theListener); int idx = theListener.getColorIndex(); serialPortAllocated[idx] = false; if (lineBuffer[idx].length() > 0) { // Flush any leftover data. String str = lineBuffer[idx].toString(); str += newLine; ReportSerialActivity(str, idx); // Clear the leftover data out. lineBuffer[idx].setLength(0); } newSerial.dispose(); theListener.dispose(); } SerialPortsUpdated(); } /** * */ public void ComboSerialChanged() { send.setEnabled(serialPorts.toString().length() > 0); reset.setEnabled(serialPorts.toString().length() > 0); parent.getShell().setDefaultButton(send); } /** * PauzePort is called when the monitor needs to disconnect from a port for a * short while. For instance when a upload is started to a com port the serial * monitor will get a pauzeport for this com port. When the upload is done * ResumePort will be called */ @Override public boolean pausePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { theSerial.disconnect(); return true; } return false; } /** * see PauzePort */ @Override public void resumePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { if (MyPreferences.getCleanSerialMonitorAfterUpload()) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { monitorOutput.setText(new String()); } }); } theSerial.connect(3); } } public static List<String> getMonitorContent() { int numLines = monitorOutput.getContent().getLineCount(); List<String> ret = new ArrayList<>(); for (int curLine = 1; curLine < numLines; curLine++) { ret.add(monitorOutput.getContent().getLine(curLine - 1)); } return ret; } public static void clearMonitor() { monitorOutput.setText(new String()); } @Override public boolean stopPort(String mComPort) { // run this in the gui thread Display.getDefault().asyncExec(new Runnable() { @Override public void run() { disConnectSerialPort(mComPort); } }); return true; } }
Sloeber/arduino-eclipse-plugin
io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java
7,577
/** * see PauzePort */
block_comment
nl
package io.sloeber.ui.monitor.views; import static io.sloeber.ui.Activator.*; import java.io.File; import java.net.URL; import java.nio.charset.Charset; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; import io.sloeber.core.api.ISerialUser; import io.sloeber.core.api.Serial; import io.sloeber.core.api.SerialManager; import io.sloeber.ui.Messages; import io.sloeber.ui.helpers.MyPreferences; import io.sloeber.ui.listeners.ProjectExplorerListener; import io.sloeber.ui.monitor.internal.SerialListener; /** * SerialMonitor implements the view that shows the serial monitor. Serial * monitor get sits data from serial Listener. 1 serial listener is created per * serial connection. * */ @SuppressWarnings({ "unused" }) public class SerialMonitor extends ViewPart implements ISerialUser { /** * The ID of the view as specified by the extension. */ // public static final String ID = // "io.sloeber.ui.monitor.views.SerialMonitor"; // If you increase this number you must also assign colors in plugin.xml static private final int MY_MAX_SERIAL_PORTS = 6; static private final boolean[] serialPortAllocated = new boolean[MY_MAX_SERIAL_PORTS]; // These StringBuilders are used to create discrete lines of text when in // timestamp // mode. static private final StringBuilder[] lineBuffer = new StringBuilder[MY_MAX_SERIAL_PORTS]; static private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); //$NON-NLS-1$ static private final URL IMG_CLEAR; static private final URL IMG_LOCK; static private final URL IMG_FILTER; static private final URL IMG_TIMESTAMP; static private final String newLine = System.getProperty("line.separator"); //$NON-NLS-1$ static { IMG_CLEAR = getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$ IMG_LOCK = getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$ IMG_FILTER = getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$ IMG_TIMESTAMP = getDefault().getBundle().getEntry("icons/timestamp_console.png"); //$NON-NLS-1$ } // Connect to a serial port private Action connect; // this action will disconnect the serial port selected by the serialPorts // combo private Action disconnect; // lock serial monitor scrolling private Action scrollLock; // filter out binary data from serial monitor private Action plotterFilter; // clear serial monitor private Action clear; // Toggle timestamps on serial messages. private Action showTimestamps; // The string to send to the serial port protected Text sendString; // control contains the output of the serial port static protected StyledText monitorOutput; // Port used when doing actions protected ComboViewer serialPorts; // Add CR? LF? CR+LF? Nothing? protected ComboViewer lineTerminator; // When click will send the content of SendString to the port selected // SerialPorts // adding the postfix selected in SendPostFix private Button send; // The button to reset the arduino private Button reset; // Contains the colors that are used private String[] serialColorID = null; // link to color registry private ColorRegistry colorRegistry = null; private boolean timestampMode = true; static private Composite parent; /* * ************** Below are variables needed for good housekeeping */ // The serial connections that are open with the listeners listening to this // port protected Map<Serial, SerialListener> serialConnections; private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$ static final String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$ private static SerialMonitor instance = null; /** * Call this method to get the instance of SerialMonitor. * * @return the (singleton) instance of SerialMonitor. */ public static synchronized SerialMonitor getSerialMonitor() { if (instance == null) { instance = new SerialMonitor(); } return instance; } /** * This constructor should only be called by Eclipse or * {@link #getSerialMonitor()}. * * It is only public because Eclipse needs to call it. */ public SerialMonitor() { if (instance != null) { log(new Status(IStatus.ERROR, PLUGIN_ID, "You can only have one serial monitor")); //$NON-NLS-1$ } instance = this; serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); colorRegistry = currentTheme.getColorRegistry(); serialColorID = new String[MY_MAX_SERIAL_PORTS]; for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) { serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$ serialPortAllocated[i] = false; lineBuffer[i] = new StringBuilder(); } SerialManager.registerSerialUser(this); Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { try { IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO); int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1; myScope.putInt(MY_FLAG_MONITOR, curFsiStatus); URL mypluginStartInitiator = new URL(uri.replace(" ", new String()) //$NON-NLS-1$ + Integer.toString(curFsiStatus)); mypluginStartInitiator.getContent(); } catch (Exception e) {// JABA is not going to add code } return Status.OK_STATUS; } }; job.setPriority(Job.DECORATE); job.schedule(); } @Override public void dispose() { SerialManager.UnRegisterSerialUser(); for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { entry.getValue().dispose(); entry.getKey().dispose(); } serialConnections.clear(); instance = null; } /** * This is a callback that will allow us to create the viewer and initialize it. */ @Override public void createPartControl(Composite parent1) { parent = parent1; parent1.setLayout(new GridLayout()); GridLayout layout = new GridLayout(5, false); layout.marginHeight = 0; layout.marginWidth = 0; Composite top = new Composite(parent1, SWT.NONE); top.setLayout(layout); top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); minSizeGridData.widthHint = 150; serialPorts.getControl().setLayoutData(minSizeGridData); serialPorts.setContentProvider(new IStructuredContentProvider() { @Override public void dispose() { // no need to do something here } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // no need to do something here } @Override public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement; return items.keySet().toArray(); } }); serialPorts.setLabelProvider(new LabelProvider()); serialPorts.setInput(serialConnections); serialPorts.addSelectionChangedListener(new ComPortChanged(this)); sendString = new Text(top, SWT.SINGLE | SWT.BORDER); sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN); lineTerminator.setContentProvider(new ArrayContentProvider()); lineTerminator.setLabelProvider(new LabelProvider()); lineTerminator.setInput(SerialManager.listLineEndings()); lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd()); lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { MyPreferences.setLastUsedSerialLineEnd(lineTerminator.getCombo().getSelectionIndex()); } }); send = new Button(top, SWT.BUTTON1); send.setText(Messages.serialMonitorSend); send.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { int index = lineTerminator.getCombo().getSelectionIndex(); GetSelectedSerial().write(sendString.getText(), SerialManager.getLineEnding(index)); sendString.setText(new String()); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); send.setEnabled(false); reset = new Button(top, SWT.BUTTON1); reset.setText(Messages.serialMonitorReset); reset.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GetSelectedSerial().reset(); sendString.setFocus(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing needs to be done here } }); reset.setEnabled(false); // register the combo as a Selection Provider getSite().setSelectionProvider(serialPorts); monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); monitorOutput.setEditable(false); IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager(); ITheme currentTheme = themeManager.getCurrentTheme(); FontRegistry fontRegistry = currentTheme.getFontRegistry(); monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$ monitorOutput.setText(Messages.serialMonitorNoInput + newLine); monitorOutput.addMouseListener(new MouseListener() { @Override public void mouseUp(MouseEvent e) { // ignore } @Override public void mouseDown(MouseEvent e) { // If right button get selected text save it and start external tool if (e.button == 3) { String selectedText = monitorOutput.getSelectionText(); if (!selectedText.isEmpty()) { IProject selectedProject = ProjectExplorerListener.getSelectedProject(); if (selectedProject != null) { try { ICConfigurationDescription activeCfg = CoreModel.getDefault() .getProjectDescription(selectedProject).getActiveConfiguration(); String activeConfigName = activeCfg.getName(); IPath buildFolder = selectedProject.findMember(activeConfigName).getLocation(); File dumpFile = buildFolder.append("serialdump.txt").toFile(); //$NON-NLS-1$ FileUtils.writeStringToFile(dumpFile, selectedText, Charset.defaultCharset()); } catch (Exception e1) { // ignore e1.printStackTrace(); } } } } } @Override public void mouseDoubleClick(MouseEvent e) { // ignore } }); parent.getShell().setDefaultButton(send); makeActions(); contributeToActionBars(); } /** * GetSelectedSerial is a wrapper class that returns the serial port selected in * the combobox * * @return the serial port selected in the combobox */ protected Serial GetSelectedSerial() { return GetSerial(serialPorts.getCombo().getText()); } /** * Looks in the open com ports with a port with the name as provided. * * @param comName the name of the comport you are looking for * @return the serial port opened in the serial monitor with the name equal to * Comname of found. null if not found */ private Serial GetSerial(String comName) { for (Entry<Serial, SerialListener> entry : serialConnections.entrySet()) { if (entry.getKey().toString().matches(comName)) return entry.getKey(); } return null; } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(clear); manager.add(scrollLock); manager.add(plotterFilter); manager.add(showTimestamps); manager.add(connect); manager.add(disconnect); } private void fillLocalPullDown(IMenuManager manager) { manager.add(connect); manager.add(new Separator()); manager.add(disconnect); } private void makeActions() { connect = new Action() { @Override public void run() { OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(parent.getShell()); comportSelector.create(); if (comportSelector.open() == Window.OK) { connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate(), comportSelector.GetDtr()); } } }; connect.setText(Messages.serialMonitorConnectedTo); connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor); connect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK)); disconnect = new Action() { @Override public void run() { disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText()); } }; disconnect.setText(Messages.serialMonitorDisconnectedFrom); disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor); disconnect.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));// IMG_OBJS_INFO_TSK)); disconnect.setEnabled(serialConnections.size() != 0); clear = new Action(Messages.serialMonitorClear) { @Override public void run() { clearMonitor(); } }; clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR)); clear.setEnabled(true); scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) { @Override public void run() { MyPreferences.setLastUsedAutoScroll(!isChecked()); } }; scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK)); scrollLock.setEnabled(true); scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll()); plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) { @Override public void run() { SerialListener.setPlotterFilter(isChecked()); MyPreferences.setLastUsedPlotterFilter(isChecked()); } }; plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER)); plotterFilter.setEnabled(true); plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter()); SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter()); showTimestamps = new Action(Messages.serialMonitorShowTimestamps, IAction.AS_CHECK_BOX) { @Override public void run() { timestampMode = isChecked(); MyPreferences.setLastUsedShowTimestamps(isChecked()); } }; showTimestamps.setImageDescriptor(ImageDescriptor.createFromURL(IMG_TIMESTAMP)); showTimestamps.setEnabled(true); showTimestamps.setChecked(MyPreferences.getLastUsedShowTimestamps()); timestampMode = MyPreferences.getLastUsedShowTimestamps(); } /** * Passing the focus request to the viewer's control. */ @Override public void setFocus() { // MonitorOutput.setf .getControl().setFocus(); parent.getShell().setDefaultButton(send); } /** * The listener calls this method to report that serial data has arrived * * @param stInfo The serial data that has arrived * @param style The style that should be used to report the data; Actually this * is the index number of the opened port */ public void ReportSerialActivity(String stInfo, int style) { String text = stInfo; if (timestampMode) { StringBuilder sb = new StringBuilder(); String ts = LocalTime.now().format(timeFormatter) + ": "; //$NON-NLS-1$ // Normalize the line endings. text = text.replaceAll("\r", ""); //$NON-NLS-1$ //$NON-NLS-2$ int begin = 0; while (true) { int idx = text.indexOf("\n", begin); //$NON-NLS-1$ if (idx >= 0) { // Note the first time through this loop lineBuffer[style] may contain // an incomplete line from the previously received chunk of data. String substring = text.substring(begin, idx + 1); lineBuffer[style].append(substring); sb.append(ts); sb.append(lineBuffer[style]); lineBuffer[style].setLength(0); begin = idx + 1; } else { // Save any remaining data for the next time through this method. lineBuffer[style].append(text.substring(begin)); break; } } if (sb.length() < 1) { return; } text = sb.toString(); } int startPoint = monitorOutput.getCharCount(); monitorOutput.append(text); StyleRange styleRange = new StyleRange(); styleRange.start = startPoint; styleRange.length = text.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = colorRegistry.get(serialColorID[style]); monitorOutput.setStyleRange(styleRange); if (!scrollLock.isChecked()) { monitorOutput.setSelection(monitorOutput.getCharCount()); } } /** * method to make sure the visualization is correct */ void SerialPortsUpdated() { disconnect.setEnabled(serialConnections.size() != 0); Serial curSelection = GetSelectedSerial(); serialPorts.setInput(serialConnections); if (serialConnections.size() == 0) { send.setEnabled(false); reset.setEnabled(false); } else { if (serialPorts.getSelection().isEmpty()) // nothing is // selected { if (curSelection == null) // nothing was selected { curSelection = (Serial) serialConnections.keySet().toArray()[0]; } serialPorts.getCombo().setText(curSelection.toString()); ComboSerialChanged(); } } } public void connectSerial(String comPort, int baudRate) { connectSerial(comPort, baudRate, false); } /** * Connect to a serial port and sets the listener * * @param comPort the name of the com port to connect to * @param baudRate the baud rate to connect to the com port */ public void connectSerial(String comPort, int baudRate, boolean dtr) { if (serialConnections.size() < MY_MAX_SERIAL_PORTS) { int colorindex = -1; for (int idx = 0; idx < serialPortAllocated.length; idx++) { if (!serialPortAllocated[idx]) { colorindex = idx; break; } } if (colorindex < 0) { log(new Status(IStatus.ERROR, PLUGIN_ID, Messages.serialMonitorNoMoreSerialPortsSupported, null)); } Serial newSerial = new Serial(comPort, baudRate, dtr); if (newSerial.IsConnected()) { newSerial.registerService(); SerialListener theListener = new SerialListener(this, colorindex); newSerial.addListener(theListener); theListener.event(newLine + Messages.serialMonitorConnectedTo.replace(Messages.PORT, comPort) .replace(Messages.BAUD, Integer.toString(baudRate)) + newLine); serialConnections.put(newSerial, theListener); SerialPortsUpdated(); // Only mark the serial port as allocated now everything is done with no errors. serialPortAllocated[colorindex] = true; return; } } else { log(new Status(IStatus.ERROR, PLUGIN_ID, Messages.serialMonitorNoMoreSerialPortsSupported, null)); } } public void disConnectSerialPort(String comPort) { Serial newSerial = GetSerial(comPort); if (newSerial != null) { SerialListener theListener = serialConnections.get(newSerial); serialPortAllocated[theListener.getColorIndex()] = false; serialConnections.remove(newSerial); newSerial.removeListener(theListener); int idx = theListener.getColorIndex(); serialPortAllocated[idx] = false; if (lineBuffer[idx].length() > 0) { // Flush any leftover data. String str = lineBuffer[idx].toString(); str += newLine; ReportSerialActivity(str, idx); // Clear the leftover data out. lineBuffer[idx].setLength(0); } newSerial.dispose(); theListener.dispose(); } SerialPortsUpdated(); } /** * */ public void ComboSerialChanged() { send.setEnabled(serialPorts.toString().length() > 0); reset.setEnabled(serialPorts.toString().length() > 0); parent.getShell().setDefaultButton(send); } /** * PauzePort is called when the monitor needs to disconnect from a port for a * short while. For instance when a upload is started to a com port the serial * monitor will get a pauzeport for this com port. When the upload is done * ResumePort will be called */ @Override public boolean pausePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { theSerial.disconnect(); return true; } return false; } /** * see PauzePort <SUF>*/ @Override public void resumePort(String portName) { Serial theSerial = GetSerial(portName); if (theSerial != null) { if (MyPreferences.getCleanSerialMonitorAfterUpload()) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { monitorOutput.setText(new String()); } }); } theSerial.connect(3); } } public static List<String> getMonitorContent() { int numLines = monitorOutput.getContent().getLineCount(); List<String> ret = new ArrayList<>(); for (int curLine = 1; curLine < numLines; curLine++) { ret.add(monitorOutput.getContent().getLine(curLine - 1)); } return ret; } public static void clearMonitor() { monitorOutput.setText(new String()); } @Override public boolean stopPort(String mComPort) { // run this in the gui thread Display.getDefault().asyncExec(new Runnable() { @Override public void run() { disConnectSerialPort(mComPort); } }); return true; } }
False
2,262
2391_202
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.locale; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class LocaleUtil { public static List<Locale> getAllLocales() { // Data from https://restcountries.eu/rest/v2/all?fields=name;region;subregion;alpha2Code;languages List<Locale> allLocales = new ArrayList<>(); allLocales.add(new Locale("ps", "AF")); // Afghanistan / lang=Pashto allLocales.add(new Locale("sv", "AX")); // Åland Islands / lang=Swedish allLocales.add(new Locale("sq", "AL")); // Albania / lang=Albanian allLocales.add(new Locale("ar", "DZ")); // Algeria / lang=Arabic allLocales.add(new Locale("en", "AS")); // American Samoa / lang=English allLocales.add(new Locale("ca", "AD")); // Andorra / lang=Catalan allLocales.add(new Locale("pt", "AO")); // Angola / lang=Portuguese allLocales.add(new Locale("en", "AI")); // Anguilla / lang=English allLocales.add(new Locale("en", "AG")); // Antigua and Barbuda / lang=English allLocales.add(new Locale("es", "AR")); // Argentina / lang=Spanish allLocales.add(new Locale("hy", "AM")); // Armenia / lang=Armenian allLocales.add(new Locale("nl", "AW")); // Aruba / lang=Dutch allLocales.add(new Locale("en", "AU")); // Australia / lang=English allLocales.add(new Locale("de", "AT")); // Austria / lang=German allLocales.add(new Locale("az", "AZ")); // Azerbaijan / lang=Azerbaijani allLocales.add(new Locale("en", "BS")); // Bahamas / lang=English allLocales.add(new Locale("ar", "BH")); // Bahrain / lang=Arabic allLocales.add(new Locale("bn", "BD")); // Bangladesh / lang=Bengali allLocales.add(new Locale("en", "BB")); // Barbados / lang=English allLocales.add(new Locale("be", "BY")); // Belarus / lang=Belarusian allLocales.add(new Locale("nl", "BE")); // Belgium / lang=Dutch allLocales.add(new Locale("en", "BZ")); // Belize / lang=English allLocales.add(new Locale("fr", "BJ")); // Benin / lang=French allLocales.add(new Locale("en", "BM")); // Bermuda / lang=English allLocales.add(new Locale("dz", "BT")); // Bhutan / lang=Dzongkha allLocales.add(new Locale("es", "BO")); // Bolivia (Plurinational State of) / lang=Spanish allLocales.add(new Locale("nl", "BQ")); // Bonaire, Sint Eustatius and Saba / lang=Dutch allLocales.add(new Locale("bs", "BA")); // Bosnia and Herzegovina / lang=Bosnian allLocales.add(new Locale("en", "BW")); // Botswana / lang=English allLocales.add(new Locale("pt", "BR")); // Brazil / lang=Portuguese allLocales.add(new Locale("en", "IO")); // British Indian Ocean Territory / lang=English allLocales.add(new Locale("en", "UM")); // United States Minor Outlying Islands / lang=English allLocales.add(new Locale("en", "VG")); // Virgin Islands (British) / lang=English allLocales.add(new Locale("en", "VI")); // Virgin Islands (U.S.) / lang=English allLocales.add(new Locale("ms", "BN")); // Brunei Darussalam / lang=Malay allLocales.add(new Locale("bg", "BG")); // Bulgaria / lang=Bulgarian allLocales.add(new Locale("fr", "BF")); // Burkina Faso / lang=French allLocales.add(new Locale("fr", "BI")); // Burundi / lang=French allLocales.add(new Locale("km", "KH")); // Cambodia / lang=Khmer allLocales.add(new Locale("en", "CM")); // Cameroon / lang=English allLocales.add(new Locale("en", "CA")); // Canada / lang=English allLocales.add(new Locale("pt", "CV")); // Cabo Verde / lang=Portuguese allLocales.add(new Locale("en", "KY")); // Cayman Islands / lang=English allLocales.add(new Locale("fr", "CF")); // Central African Republic / lang=French allLocales.add(new Locale("fr", "TD")); // Chad / lang=French allLocales.add(new Locale("es", "CL")); // Chile / lang=Spanish allLocales.add(new Locale("zh", "CN")); // China / lang=Chinese allLocales.add(new Locale("en", "CX")); // Christmas Island / lang=English allLocales.add(new Locale("en", "CC")); // Cocos (Keeling) Islands / lang=English allLocales.add(new Locale("es", "CO")); // Colombia / lang=Spanish allLocales.add(new Locale("ar", "KM")); // Comoros / lang=Arabic allLocales.add(new Locale("fr", "CG")); // Congo / lang=French allLocales.add(new Locale("fr", "CD")); // Congo (Democratic Republic of the) / lang=French allLocales.add(new Locale("en", "CK")); // Cook Islands / lang=English allLocales.add(new Locale("es", "CR")); // Costa Rica / lang=Spanish allLocales.add(new Locale("hr", "HR")); // Croatia / lang=Croatian allLocales.add(new Locale("es", "CU")); // Cuba / lang=Spanish allLocales.add(new Locale("nl", "CW")); // Curaçao / lang=Dutch allLocales.add(new Locale("el", "CY")); // Cyprus / lang=Greek (modern) allLocales.add(new Locale("cs", "CZ")); // Czech Republic / lang=Czech allLocales.add(new Locale("da", "DK")); // Denmark / lang=Danish allLocales.add(new Locale("fr", "DJ")); // Djibouti / lang=French allLocales.add(new Locale("en", "DM")); // Dominica / lang=English allLocales.add(new Locale("es", "DO")); // Dominican Republic / lang=Spanish allLocales.add(new Locale("es", "EC")); // Ecuador / lang=Spanish allLocales.add(new Locale("ar", "EG")); // Egypt / lang=Arabic allLocales.add(new Locale("es", "SV")); // El Salvador / lang=Spanish allLocales.add(new Locale("es", "GQ")); // Equatorial Guinea / lang=Spanish allLocales.add(new Locale("ti", "ER")); // Eritrea / lang=Tigrinya allLocales.add(new Locale("et", "EE")); // Estonia / lang=Estonian allLocales.add(new Locale("am", "ET")); // Ethiopia / lang=Amharic allLocales.add(new Locale("en", "FK")); // Falkland Islands (Malvinas) / lang=English allLocales.add(new Locale("fo", "FO")); // Faroe Islands / lang=Faroese allLocales.add(new Locale("en", "FJ")); // Fiji / lang=English allLocales.add(new Locale("fi", "FI")); // Finland / lang=Finnish allLocales.add(new Locale("fr", "FR")); // France / lang=French allLocales.add(new Locale("fr", "GF")); // French Guiana / lang=French allLocales.add(new Locale("fr", "PF")); // French Polynesia / lang=French allLocales.add(new Locale("fr", "TF")); // French Southern Territories / lang=French allLocales.add(new Locale("fr", "GA")); // Gabon / lang=French allLocales.add(new Locale("en", "GM")); // Gambia / lang=English allLocales.add(new Locale("ka", "GE")); // Georgia / lang=Georgian allLocales.add(new Locale("de", "DE")); // Germany / lang=German allLocales.add(new Locale("en", "GH")); // Ghana / lang=English allLocales.add(new Locale("en", "GI")); // Gibraltar / lang=English allLocales.add(new Locale("el", "GR")); // Greece / lang=Greek (modern) allLocales.add(new Locale("kl", "GL")); // Greenland / lang=Kalaallisut allLocales.add(new Locale("en", "GD")); // Grenada / lang=English allLocales.add(new Locale("fr", "GP")); // Guadeloupe / lang=French allLocales.add(new Locale("en", "GU")); // Guam / lang=English allLocales.add(new Locale("es", "GT")); // Guatemala / lang=Spanish allLocales.add(new Locale("en", "GG")); // Guernsey / lang=English allLocales.add(new Locale("fr", "GN")); // Guinea / lang=French allLocales.add(new Locale("pt", "GW")); // Guinea-Bissau / lang=Portuguese allLocales.add(new Locale("en", "GY")); // Guyana / lang=English allLocales.add(new Locale("fr", "HT")); // Haiti / lang=French allLocales.add(new Locale("la", "VA")); // Holy See / lang=Latin allLocales.add(new Locale("es", "HN")); // Honduras / lang=Spanish allLocales.add(new Locale("en", "HK")); // Hong Kong / lang=English allLocales.add(new Locale("hu", "HU")); // Hungary / lang=Hungarian allLocales.add(new Locale("is", "IS")); // Iceland / lang=Icelandic allLocales.add(new Locale("hi", "IN")); // India / lang=Hindi allLocales.add(new Locale("id", "ID")); // Indonesia / lang=Indonesian allLocales.add(new Locale("fr", "CI")); // Côte d'Ivoire / lang=French allLocales.add(new Locale("fa", "IR")); // Iran (Islamic Republic of) / lang=Persian (Farsi) allLocales.add(new Locale("ar", "IQ")); // Iraq / lang=Arabic allLocales.add(new Locale("ga", "IE")); // Ireland / lang=Irish allLocales.add(new Locale("en", "IM")); // Isle of Man / lang=English allLocales.add(new Locale("he", "IL")); // Israel / lang=Hebrew (modern) allLocales.add(new Locale("it", "IT")); // Italy / lang=Italian allLocales.add(new Locale("en", "JM")); // Jamaica / lang=English allLocales.add(new Locale("ja", "JP")); // Japan / lang=Japanese allLocales.add(new Locale("en", "JE")); // Jersey / lang=English allLocales.add(new Locale("ar", "JO")); // Jordan / lang=Arabic allLocales.add(new Locale("kk", "KZ")); // Kazakhstan / lang=Kazakh allLocales.add(new Locale("en", "KE")); // Kenya / lang=English allLocales.add(new Locale("en", "KI")); // Kiribati / lang=English allLocales.add(new Locale("ar", "KW")); // Kuwait / lang=Arabic allLocales.add(new Locale("ky", "KG")); // Kyrgyzstan / lang=Kyrgyz allLocales.add(new Locale("lo", "LA")); // Lao People's Democratic Republic / lang=Lao allLocales.add(new Locale("lv", "LV")); // Latvia / lang=Latvian allLocales.add(new Locale("ar", "LB")); // Lebanon / lang=Arabic allLocales.add(new Locale("en", "LS")); // Lesotho / lang=English allLocales.add(new Locale("en", "LR")); // Liberia / lang=English allLocales.add(new Locale("ar", "LY")); // Libya / lang=Arabic allLocales.add(new Locale("de", "LI")); // Liechtenstein / lang=German allLocales.add(new Locale("lt", "LT")); // Lithuania / lang=Lithuanian allLocales.add(new Locale("fr", "LU")); // Luxembourg / lang=French allLocales.add(new Locale("zh", "MO")); // Macao / lang=Chinese allLocales.add(new Locale("mk", "MK")); // Macedonia (the former Yugoslav Republic of) / lang=Macedonian allLocales.add(new Locale("fr", "MG")); // Madagascar / lang=French allLocales.add(new Locale("en", "MW")); // Malawi / lang=English allLocales.add(new Locale("en", "MY")); // Malaysia / lang=Malaysian allLocales.add(new Locale("dv", "MV")); // Maldives / lang=Divehi allLocales.add(new Locale("fr", "ML")); // Mali / lang=French allLocales.add(new Locale("mt", "MT")); // Malta / lang=Maltese allLocales.add(new Locale("en", "MH")); // Marshall Islands / lang=English allLocales.add(new Locale("fr", "MQ")); // Martinique / lang=French allLocales.add(new Locale("ar", "MR")); // Mauritania / lang=Arabic allLocales.add(new Locale("en", "MU")); // Mauritius / lang=English allLocales.add(new Locale("fr", "YT")); // Mayotte / lang=French allLocales.add(new Locale("es", "MX")); // Mexico / lang=Spanish allLocales.add(new Locale("en", "FM")); // Micronesia (Federated States of) / lang=English allLocales.add(new Locale("ro", "MD")); // Moldova (Republic of) / lang=Romanian allLocales.add(new Locale("fr", "MC")); // Monaco / lang=French allLocales.add(new Locale("mn", "MN")); // Mongolia / lang=Mongolian allLocales.add(new Locale("sr", "ME")); // Montenegro / lang=Serbian allLocales.add(new Locale("en", "MS")); // Montserrat / lang=English allLocales.add(new Locale("ar", "MA")); // Morocco / lang=Arabic allLocales.add(new Locale("pt", "MZ")); // Mozambique / lang=Portuguese allLocales.add(new Locale("my", "MM")); // Myanmar / lang=Burmese allLocales.add(new Locale("en", "NA")); // Namibia / lang=English allLocales.add(new Locale("en", "NR")); // Nauru / lang=English allLocales.add(new Locale("ne", "NP")); // Nepal / lang=Nepali allLocales.add(new Locale("nl", "NL")); // Netherlands / lang=Dutch allLocales.add(new Locale("fr", "NC")); // New Caledonia / lang=French allLocales.add(new Locale("en", "NZ")); // New Zealand / lang=English allLocales.add(new Locale("es", "NI")); // Nicaragua / lang=Spanish allLocales.add(new Locale("fr", "NE")); // Niger / lang=French allLocales.add(new Locale("en", "NG")); // Nigeria / lang=English allLocales.add(new Locale("en", "NU")); // Niue / lang=English allLocales.add(new Locale("en", "NF")); // Norfolk Island / lang=English allLocales.add(new Locale("ko", "KP")); // Korea (Democratic People's Republic of) / lang=Korean allLocales.add(new Locale("en", "MP")); // Northern Mariana Islands / lang=English allLocales.add(new Locale("no", "NO")); // Norway / lang=Norwegian allLocales.add(new Locale("ar", "OM")); // Oman / lang=Arabic allLocales.add(new Locale("en", "PK")); // Pakistan / lang=English allLocales.add(new Locale("en", "PW")); // Palau / lang=English allLocales.add(new Locale("ar", "PS")); // Palestine, State of / lang=Arabic allLocales.add(new Locale("es", "PA")); // Panama / lang=Spanish allLocales.add(new Locale("en", "PG")); // Papua New Guinea / lang=English allLocales.add(new Locale("es", "PY")); // Paraguay / lang=Spanish allLocales.add(new Locale("es", "PE")); // Peru / lang=Spanish allLocales.add(new Locale("en", "PH")); // Philippines / lang=English allLocales.add(new Locale("en", "PN")); // Pitcairn / lang=English allLocales.add(new Locale("pl", "PL")); // Poland / lang=Polish allLocales.add(new Locale("pt", "PT")); // Portugal / lang=Portuguese allLocales.add(new Locale("es", "PR")); // Puerto Rico / lang=Spanish allLocales.add(new Locale("ar", "QA")); // Qatar / lang=Arabic allLocales.add(new Locale("sq", "XK")); // Republic of Kosovo / lang=Albanian allLocales.add(new Locale("fr", "RE")); // Réunion / lang=French allLocales.add(new Locale("ro", "RO")); // Romania / lang=Romanian allLocales.add(new Locale("ru", "RU")); // Russian Federation / lang=Russian allLocales.add(new Locale("rw", "RW")); // Rwanda / lang=Kinyarwanda allLocales.add(new Locale("fr", "BL")); // Saint Barthélemy / lang=French allLocales.add(new Locale("en", "SH")); // Saint Helena, Ascension and Tristan da Cunha / lang=English allLocales.add(new Locale("en", "KN")); // Saint Kitts and Nevis / lang=English allLocales.add(new Locale("en", "LC")); // Saint Lucia / lang=English allLocales.add(new Locale("en", "MF")); // Saint Martin (French part) / lang=English allLocales.add(new Locale("fr", "PM")); // Saint Pierre and Miquelon / lang=French allLocales.add(new Locale("en", "VC")); // Saint Vincent and the Grenadines / lang=English allLocales.add(new Locale("sm", "WS")); // Samoa / lang=Samoan allLocales.add(new Locale("it", "SM")); // San Marino / lang=Italian allLocales.add(new Locale("pt", "ST")); // Sao Tome and Principe / lang=Portuguese allLocales.add(new Locale("ar", "SA")); // Saudi Arabia / lang=Arabic allLocales.add(new Locale("fr", "SN")); // Senegal / lang=French allLocales.add(new Locale("sr", "RS")); // Serbia / lang=Serbian allLocales.add(new Locale("fr", "SC")); // Seychelles / lang=French allLocales.add(new Locale("en", "SL")); // Sierra Leone / lang=English allLocales.add(new Locale("en", "SG")); // Singapore / lang=English allLocales.add(new Locale("nl", "SX")); // Sint Maarten (Dutch part) / lang=Dutch allLocales.add(new Locale("sk", "SK")); // Slovakia / lang=Slovak allLocales.add(new Locale("sl", "SI")); // Slovenia / lang=Slovene allLocales.add(new Locale("en", "SB")); // Solomon Islands / lang=English allLocales.add(new Locale("so", "SO")); // Somalia / lang=Somali allLocales.add(new Locale("af", "ZA")); // South Africa / lang=Afrikaans allLocales.add(new Locale("en", "GS")); // South Georgia and the South Sandwich Islands / lang=English allLocales.add(new Locale("ko", "KR")); // Korea (Republic of) / lang=Korean allLocales.add(new Locale("en", "SS")); // South Sudan / lang=English allLocales.add(new Locale("es", "ES")); // Spain / lang=Spanish allLocales.add(new Locale("si", "LK")); // Sri Lanka / lang=Sinhalese allLocales.add(new Locale("ar", "SD")); // Sudan / lang=Arabic allLocales.add(new Locale("nl", "SR")); // Suriname / lang=Dutch allLocales.add(new Locale("no", "SJ")); // Svalbard and Jan Mayen / lang=Norwegian allLocales.add(new Locale("en", "SZ")); // Swaziland / lang=English allLocales.add(new Locale("sv", "SE")); // Sweden / lang=Swedish allLocales.add(new Locale("de", "CH")); // Switzerland / lang=German allLocales.add(new Locale("ar", "SY")); // Syrian Arab Republic / lang=Arabic allLocales.add(new Locale("zh", "TW")); // Taiwan / lang=Chinese allLocales.add(new Locale("tg", "TJ")); // Tajikistan / lang=Tajik allLocales.add(new Locale("sw", "TZ")); // Tanzania, United Republic of / lang=Swahili allLocales.add(new Locale("th", "TH")); // Thailand / lang=Thai allLocales.add(new Locale("pt", "TL")); // Timor-Leste / lang=Portuguese allLocales.add(new Locale("fr", "TG")); // Togo / lang=French allLocales.add(new Locale("en", "TK")); // Tokelau / lang=English allLocales.add(new Locale("en", "TO")); // Tonga / lang=English allLocales.add(new Locale("en", "TT")); // Trinidad and Tobago / lang=English allLocales.add(new Locale("ar", "TN")); // Tunisia / lang=Arabic allLocales.add(new Locale("tr", "TR")); // Turkey / lang=Turkish allLocales.add(new Locale("tk", "TM")); // Turkmenistan / lang=Turkmen allLocales.add(new Locale("en", "TC")); // Turks and Caicos Islands / lang=English allLocales.add(new Locale("en", "TV")); // Tuvalu / lang=English allLocales.add(new Locale("en", "UG")); // Uganda / lang=English allLocales.add(new Locale("uk", "UA")); // Ukraine / lang=Ukrainian allLocales.add(new Locale("ar", "AE")); // United Arab Emirates / lang=Arabic allLocales.add(new Locale("en", "GB")); // United Kingdom of Great Britain and Northern Ireland / lang=English allLocales.add(new Locale("en", "US")); // United States of America / lang=English allLocales.add(new Locale("es", "UY")); // Uruguay / lang=Spanish allLocales.add(new Locale("uz", "UZ")); // Uzbekistan / lang=Uzbek allLocales.add(new Locale("bi", "VU")); // Vanuatu / lang=Bislama allLocales.add(new Locale("es", "VE")); // Venezuela (Bolivarian Republic of) / lang=Spanish allLocales.add(new Locale("vi", "VN")); // Viet Nam / lang=Vietnamese allLocales.add(new Locale("fr", "WF")); // Wallis and Futuna / lang=French allLocales.add(new Locale("es", "EH")); // Western Sahara / lang=Spanish allLocales.add(new Locale("ar", "YE")); // Yemen / lang=Arabic allLocales.add(new Locale("en", "ZM")); // Zambia / lang=English allLocales.add(new Locale("en", "ZW")); // Zimbabwe / lang=English return allLocales; } }
bisq-network/bisq
core/src/main/java/bisq/core/locale/LocaleUtil.java
6,952
// Sint Maarten (Dutch part) / lang=Dutch
line_comment
nl
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.locale; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class LocaleUtil { public static List<Locale> getAllLocales() { // Data from https://restcountries.eu/rest/v2/all?fields=name;region;subregion;alpha2Code;languages List<Locale> allLocales = new ArrayList<>(); allLocales.add(new Locale("ps", "AF")); // Afghanistan / lang=Pashto allLocales.add(new Locale("sv", "AX")); // Åland Islands / lang=Swedish allLocales.add(new Locale("sq", "AL")); // Albania / lang=Albanian allLocales.add(new Locale("ar", "DZ")); // Algeria / lang=Arabic allLocales.add(new Locale("en", "AS")); // American Samoa / lang=English allLocales.add(new Locale("ca", "AD")); // Andorra / lang=Catalan allLocales.add(new Locale("pt", "AO")); // Angola / lang=Portuguese allLocales.add(new Locale("en", "AI")); // Anguilla / lang=English allLocales.add(new Locale("en", "AG")); // Antigua and Barbuda / lang=English allLocales.add(new Locale("es", "AR")); // Argentina / lang=Spanish allLocales.add(new Locale("hy", "AM")); // Armenia / lang=Armenian allLocales.add(new Locale("nl", "AW")); // Aruba / lang=Dutch allLocales.add(new Locale("en", "AU")); // Australia / lang=English allLocales.add(new Locale("de", "AT")); // Austria / lang=German allLocales.add(new Locale("az", "AZ")); // Azerbaijan / lang=Azerbaijani allLocales.add(new Locale("en", "BS")); // Bahamas / lang=English allLocales.add(new Locale("ar", "BH")); // Bahrain / lang=Arabic allLocales.add(new Locale("bn", "BD")); // Bangladesh / lang=Bengali allLocales.add(new Locale("en", "BB")); // Barbados / lang=English allLocales.add(new Locale("be", "BY")); // Belarus / lang=Belarusian allLocales.add(new Locale("nl", "BE")); // Belgium / lang=Dutch allLocales.add(new Locale("en", "BZ")); // Belize / lang=English allLocales.add(new Locale("fr", "BJ")); // Benin / lang=French allLocales.add(new Locale("en", "BM")); // Bermuda / lang=English allLocales.add(new Locale("dz", "BT")); // Bhutan / lang=Dzongkha allLocales.add(new Locale("es", "BO")); // Bolivia (Plurinational State of) / lang=Spanish allLocales.add(new Locale("nl", "BQ")); // Bonaire, Sint Eustatius and Saba / lang=Dutch allLocales.add(new Locale("bs", "BA")); // Bosnia and Herzegovina / lang=Bosnian allLocales.add(new Locale("en", "BW")); // Botswana / lang=English allLocales.add(new Locale("pt", "BR")); // Brazil / lang=Portuguese allLocales.add(new Locale("en", "IO")); // British Indian Ocean Territory / lang=English allLocales.add(new Locale("en", "UM")); // United States Minor Outlying Islands / lang=English allLocales.add(new Locale("en", "VG")); // Virgin Islands (British) / lang=English allLocales.add(new Locale("en", "VI")); // Virgin Islands (U.S.) / lang=English allLocales.add(new Locale("ms", "BN")); // Brunei Darussalam / lang=Malay allLocales.add(new Locale("bg", "BG")); // Bulgaria / lang=Bulgarian allLocales.add(new Locale("fr", "BF")); // Burkina Faso / lang=French allLocales.add(new Locale("fr", "BI")); // Burundi / lang=French allLocales.add(new Locale("km", "KH")); // Cambodia / lang=Khmer allLocales.add(new Locale("en", "CM")); // Cameroon / lang=English allLocales.add(new Locale("en", "CA")); // Canada / lang=English allLocales.add(new Locale("pt", "CV")); // Cabo Verde / lang=Portuguese allLocales.add(new Locale("en", "KY")); // Cayman Islands / lang=English allLocales.add(new Locale("fr", "CF")); // Central African Republic / lang=French allLocales.add(new Locale("fr", "TD")); // Chad / lang=French allLocales.add(new Locale("es", "CL")); // Chile / lang=Spanish allLocales.add(new Locale("zh", "CN")); // China / lang=Chinese allLocales.add(new Locale("en", "CX")); // Christmas Island / lang=English allLocales.add(new Locale("en", "CC")); // Cocos (Keeling) Islands / lang=English allLocales.add(new Locale("es", "CO")); // Colombia / lang=Spanish allLocales.add(new Locale("ar", "KM")); // Comoros / lang=Arabic allLocales.add(new Locale("fr", "CG")); // Congo / lang=French allLocales.add(new Locale("fr", "CD")); // Congo (Democratic Republic of the) / lang=French allLocales.add(new Locale("en", "CK")); // Cook Islands / lang=English allLocales.add(new Locale("es", "CR")); // Costa Rica / lang=Spanish allLocales.add(new Locale("hr", "HR")); // Croatia / lang=Croatian allLocales.add(new Locale("es", "CU")); // Cuba / lang=Spanish allLocales.add(new Locale("nl", "CW")); // Curaçao / lang=Dutch allLocales.add(new Locale("el", "CY")); // Cyprus / lang=Greek (modern) allLocales.add(new Locale("cs", "CZ")); // Czech Republic / lang=Czech allLocales.add(new Locale("da", "DK")); // Denmark / lang=Danish allLocales.add(new Locale("fr", "DJ")); // Djibouti / lang=French allLocales.add(new Locale("en", "DM")); // Dominica / lang=English allLocales.add(new Locale("es", "DO")); // Dominican Republic / lang=Spanish allLocales.add(new Locale("es", "EC")); // Ecuador / lang=Spanish allLocales.add(new Locale("ar", "EG")); // Egypt / lang=Arabic allLocales.add(new Locale("es", "SV")); // El Salvador / lang=Spanish allLocales.add(new Locale("es", "GQ")); // Equatorial Guinea / lang=Spanish allLocales.add(new Locale("ti", "ER")); // Eritrea / lang=Tigrinya allLocales.add(new Locale("et", "EE")); // Estonia / lang=Estonian allLocales.add(new Locale("am", "ET")); // Ethiopia / lang=Amharic allLocales.add(new Locale("en", "FK")); // Falkland Islands (Malvinas) / lang=English allLocales.add(new Locale("fo", "FO")); // Faroe Islands / lang=Faroese allLocales.add(new Locale("en", "FJ")); // Fiji / lang=English allLocales.add(new Locale("fi", "FI")); // Finland / lang=Finnish allLocales.add(new Locale("fr", "FR")); // France / lang=French allLocales.add(new Locale("fr", "GF")); // French Guiana / lang=French allLocales.add(new Locale("fr", "PF")); // French Polynesia / lang=French allLocales.add(new Locale("fr", "TF")); // French Southern Territories / lang=French allLocales.add(new Locale("fr", "GA")); // Gabon / lang=French allLocales.add(new Locale("en", "GM")); // Gambia / lang=English allLocales.add(new Locale("ka", "GE")); // Georgia / lang=Georgian allLocales.add(new Locale("de", "DE")); // Germany / lang=German allLocales.add(new Locale("en", "GH")); // Ghana / lang=English allLocales.add(new Locale("en", "GI")); // Gibraltar / lang=English allLocales.add(new Locale("el", "GR")); // Greece / lang=Greek (modern) allLocales.add(new Locale("kl", "GL")); // Greenland / lang=Kalaallisut allLocales.add(new Locale("en", "GD")); // Grenada / lang=English allLocales.add(new Locale("fr", "GP")); // Guadeloupe / lang=French allLocales.add(new Locale("en", "GU")); // Guam / lang=English allLocales.add(new Locale("es", "GT")); // Guatemala / lang=Spanish allLocales.add(new Locale("en", "GG")); // Guernsey / lang=English allLocales.add(new Locale("fr", "GN")); // Guinea / lang=French allLocales.add(new Locale("pt", "GW")); // Guinea-Bissau / lang=Portuguese allLocales.add(new Locale("en", "GY")); // Guyana / lang=English allLocales.add(new Locale("fr", "HT")); // Haiti / lang=French allLocales.add(new Locale("la", "VA")); // Holy See / lang=Latin allLocales.add(new Locale("es", "HN")); // Honduras / lang=Spanish allLocales.add(new Locale("en", "HK")); // Hong Kong / lang=English allLocales.add(new Locale("hu", "HU")); // Hungary / lang=Hungarian allLocales.add(new Locale("is", "IS")); // Iceland / lang=Icelandic allLocales.add(new Locale("hi", "IN")); // India / lang=Hindi allLocales.add(new Locale("id", "ID")); // Indonesia / lang=Indonesian allLocales.add(new Locale("fr", "CI")); // Côte d'Ivoire / lang=French allLocales.add(new Locale("fa", "IR")); // Iran (Islamic Republic of) / lang=Persian (Farsi) allLocales.add(new Locale("ar", "IQ")); // Iraq / lang=Arabic allLocales.add(new Locale("ga", "IE")); // Ireland / lang=Irish allLocales.add(new Locale("en", "IM")); // Isle of Man / lang=English allLocales.add(new Locale("he", "IL")); // Israel / lang=Hebrew (modern) allLocales.add(new Locale("it", "IT")); // Italy / lang=Italian allLocales.add(new Locale("en", "JM")); // Jamaica / lang=English allLocales.add(new Locale("ja", "JP")); // Japan / lang=Japanese allLocales.add(new Locale("en", "JE")); // Jersey / lang=English allLocales.add(new Locale("ar", "JO")); // Jordan / lang=Arabic allLocales.add(new Locale("kk", "KZ")); // Kazakhstan / lang=Kazakh allLocales.add(new Locale("en", "KE")); // Kenya / lang=English allLocales.add(new Locale("en", "KI")); // Kiribati / lang=English allLocales.add(new Locale("ar", "KW")); // Kuwait / lang=Arabic allLocales.add(new Locale("ky", "KG")); // Kyrgyzstan / lang=Kyrgyz allLocales.add(new Locale("lo", "LA")); // Lao People's Democratic Republic / lang=Lao allLocales.add(new Locale("lv", "LV")); // Latvia / lang=Latvian allLocales.add(new Locale("ar", "LB")); // Lebanon / lang=Arabic allLocales.add(new Locale("en", "LS")); // Lesotho / lang=English allLocales.add(new Locale("en", "LR")); // Liberia / lang=English allLocales.add(new Locale("ar", "LY")); // Libya / lang=Arabic allLocales.add(new Locale("de", "LI")); // Liechtenstein / lang=German allLocales.add(new Locale("lt", "LT")); // Lithuania / lang=Lithuanian allLocales.add(new Locale("fr", "LU")); // Luxembourg / lang=French allLocales.add(new Locale("zh", "MO")); // Macao / lang=Chinese allLocales.add(new Locale("mk", "MK")); // Macedonia (the former Yugoslav Republic of) / lang=Macedonian allLocales.add(new Locale("fr", "MG")); // Madagascar / lang=French allLocales.add(new Locale("en", "MW")); // Malawi / lang=English allLocales.add(new Locale("en", "MY")); // Malaysia / lang=Malaysian allLocales.add(new Locale("dv", "MV")); // Maldives / lang=Divehi allLocales.add(new Locale("fr", "ML")); // Mali / lang=French allLocales.add(new Locale("mt", "MT")); // Malta / lang=Maltese allLocales.add(new Locale("en", "MH")); // Marshall Islands / lang=English allLocales.add(new Locale("fr", "MQ")); // Martinique / lang=French allLocales.add(new Locale("ar", "MR")); // Mauritania / lang=Arabic allLocales.add(new Locale("en", "MU")); // Mauritius / lang=English allLocales.add(new Locale("fr", "YT")); // Mayotte / lang=French allLocales.add(new Locale("es", "MX")); // Mexico / lang=Spanish allLocales.add(new Locale("en", "FM")); // Micronesia (Federated States of) / lang=English allLocales.add(new Locale("ro", "MD")); // Moldova (Republic of) / lang=Romanian allLocales.add(new Locale("fr", "MC")); // Monaco / lang=French allLocales.add(new Locale("mn", "MN")); // Mongolia / lang=Mongolian allLocales.add(new Locale("sr", "ME")); // Montenegro / lang=Serbian allLocales.add(new Locale("en", "MS")); // Montserrat / lang=English allLocales.add(new Locale("ar", "MA")); // Morocco / lang=Arabic allLocales.add(new Locale("pt", "MZ")); // Mozambique / lang=Portuguese allLocales.add(new Locale("my", "MM")); // Myanmar / lang=Burmese allLocales.add(new Locale("en", "NA")); // Namibia / lang=English allLocales.add(new Locale("en", "NR")); // Nauru / lang=English allLocales.add(new Locale("ne", "NP")); // Nepal / lang=Nepali allLocales.add(new Locale("nl", "NL")); // Netherlands / lang=Dutch allLocales.add(new Locale("fr", "NC")); // New Caledonia / lang=French allLocales.add(new Locale("en", "NZ")); // New Zealand / lang=English allLocales.add(new Locale("es", "NI")); // Nicaragua / lang=Spanish allLocales.add(new Locale("fr", "NE")); // Niger / lang=French allLocales.add(new Locale("en", "NG")); // Nigeria / lang=English allLocales.add(new Locale("en", "NU")); // Niue / lang=English allLocales.add(new Locale("en", "NF")); // Norfolk Island / lang=English allLocales.add(new Locale("ko", "KP")); // Korea (Democratic People's Republic of) / lang=Korean allLocales.add(new Locale("en", "MP")); // Northern Mariana Islands / lang=English allLocales.add(new Locale("no", "NO")); // Norway / lang=Norwegian allLocales.add(new Locale("ar", "OM")); // Oman / lang=Arabic allLocales.add(new Locale("en", "PK")); // Pakistan / lang=English allLocales.add(new Locale("en", "PW")); // Palau / lang=English allLocales.add(new Locale("ar", "PS")); // Palestine, State of / lang=Arabic allLocales.add(new Locale("es", "PA")); // Panama / lang=Spanish allLocales.add(new Locale("en", "PG")); // Papua New Guinea / lang=English allLocales.add(new Locale("es", "PY")); // Paraguay / lang=Spanish allLocales.add(new Locale("es", "PE")); // Peru / lang=Spanish allLocales.add(new Locale("en", "PH")); // Philippines / lang=English allLocales.add(new Locale("en", "PN")); // Pitcairn / lang=English allLocales.add(new Locale("pl", "PL")); // Poland / lang=Polish allLocales.add(new Locale("pt", "PT")); // Portugal / lang=Portuguese allLocales.add(new Locale("es", "PR")); // Puerto Rico / lang=Spanish allLocales.add(new Locale("ar", "QA")); // Qatar / lang=Arabic allLocales.add(new Locale("sq", "XK")); // Republic of Kosovo / lang=Albanian allLocales.add(new Locale("fr", "RE")); // Réunion / lang=French allLocales.add(new Locale("ro", "RO")); // Romania / lang=Romanian allLocales.add(new Locale("ru", "RU")); // Russian Federation / lang=Russian allLocales.add(new Locale("rw", "RW")); // Rwanda / lang=Kinyarwanda allLocales.add(new Locale("fr", "BL")); // Saint Barthélemy / lang=French allLocales.add(new Locale("en", "SH")); // Saint Helena, Ascension and Tristan da Cunha / lang=English allLocales.add(new Locale("en", "KN")); // Saint Kitts and Nevis / lang=English allLocales.add(new Locale("en", "LC")); // Saint Lucia / lang=English allLocales.add(new Locale("en", "MF")); // Saint Martin (French part) / lang=English allLocales.add(new Locale("fr", "PM")); // Saint Pierre and Miquelon / lang=French allLocales.add(new Locale("en", "VC")); // Saint Vincent and the Grenadines / lang=English allLocales.add(new Locale("sm", "WS")); // Samoa / lang=Samoan allLocales.add(new Locale("it", "SM")); // San Marino / lang=Italian allLocales.add(new Locale("pt", "ST")); // Sao Tome and Principe / lang=Portuguese allLocales.add(new Locale("ar", "SA")); // Saudi Arabia / lang=Arabic allLocales.add(new Locale("fr", "SN")); // Senegal / lang=French allLocales.add(new Locale("sr", "RS")); // Serbia / lang=Serbian allLocales.add(new Locale("fr", "SC")); // Seychelles / lang=French allLocales.add(new Locale("en", "SL")); // Sierra Leone / lang=English allLocales.add(new Locale("en", "SG")); // Singapore / lang=English allLocales.add(new Locale("nl", "SX")); // Sint Maarten<SUF> allLocales.add(new Locale("sk", "SK")); // Slovakia / lang=Slovak allLocales.add(new Locale("sl", "SI")); // Slovenia / lang=Slovene allLocales.add(new Locale("en", "SB")); // Solomon Islands / lang=English allLocales.add(new Locale("so", "SO")); // Somalia / lang=Somali allLocales.add(new Locale("af", "ZA")); // South Africa / lang=Afrikaans allLocales.add(new Locale("en", "GS")); // South Georgia and the South Sandwich Islands / lang=English allLocales.add(new Locale("ko", "KR")); // Korea (Republic of) / lang=Korean allLocales.add(new Locale("en", "SS")); // South Sudan / lang=English allLocales.add(new Locale("es", "ES")); // Spain / lang=Spanish allLocales.add(new Locale("si", "LK")); // Sri Lanka / lang=Sinhalese allLocales.add(new Locale("ar", "SD")); // Sudan / lang=Arabic allLocales.add(new Locale("nl", "SR")); // Suriname / lang=Dutch allLocales.add(new Locale("no", "SJ")); // Svalbard and Jan Mayen / lang=Norwegian allLocales.add(new Locale("en", "SZ")); // Swaziland / lang=English allLocales.add(new Locale("sv", "SE")); // Sweden / lang=Swedish allLocales.add(new Locale("de", "CH")); // Switzerland / lang=German allLocales.add(new Locale("ar", "SY")); // Syrian Arab Republic / lang=Arabic allLocales.add(new Locale("zh", "TW")); // Taiwan / lang=Chinese allLocales.add(new Locale("tg", "TJ")); // Tajikistan / lang=Tajik allLocales.add(new Locale("sw", "TZ")); // Tanzania, United Republic of / lang=Swahili allLocales.add(new Locale("th", "TH")); // Thailand / lang=Thai allLocales.add(new Locale("pt", "TL")); // Timor-Leste / lang=Portuguese allLocales.add(new Locale("fr", "TG")); // Togo / lang=French allLocales.add(new Locale("en", "TK")); // Tokelau / lang=English allLocales.add(new Locale("en", "TO")); // Tonga / lang=English allLocales.add(new Locale("en", "TT")); // Trinidad and Tobago / lang=English allLocales.add(new Locale("ar", "TN")); // Tunisia / lang=Arabic allLocales.add(new Locale("tr", "TR")); // Turkey / lang=Turkish allLocales.add(new Locale("tk", "TM")); // Turkmenistan / lang=Turkmen allLocales.add(new Locale("en", "TC")); // Turks and Caicos Islands / lang=English allLocales.add(new Locale("en", "TV")); // Tuvalu / lang=English allLocales.add(new Locale("en", "UG")); // Uganda / lang=English allLocales.add(new Locale("uk", "UA")); // Ukraine / lang=Ukrainian allLocales.add(new Locale("ar", "AE")); // United Arab Emirates / lang=Arabic allLocales.add(new Locale("en", "GB")); // United Kingdom of Great Britain and Northern Ireland / lang=English allLocales.add(new Locale("en", "US")); // United States of America / lang=English allLocales.add(new Locale("es", "UY")); // Uruguay / lang=Spanish allLocales.add(new Locale("uz", "UZ")); // Uzbekistan / lang=Uzbek allLocales.add(new Locale("bi", "VU")); // Vanuatu / lang=Bislama allLocales.add(new Locale("es", "VE")); // Venezuela (Bolivarian Republic of) / lang=Spanish allLocales.add(new Locale("vi", "VN")); // Viet Nam / lang=Vietnamese allLocales.add(new Locale("fr", "WF")); // Wallis and Futuna / lang=French allLocales.add(new Locale("es", "EH")); // Western Sahara / lang=Spanish allLocales.add(new Locale("ar", "YE")); // Yemen / lang=Arabic allLocales.add(new Locale("en", "ZM")); // Zambia / lang=English allLocales.add(new Locale("en", "ZW")); // Zimbabwe / lang=English return allLocales; } }
False
1,206
71697_2
package com.hollingsworth.arsnouveau.common.entity; import com.hollingsworth.arsnouveau.ArsNouveau; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityClassification; import net.minecraft.entity.EntityType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.ObjectHolder; @ObjectHolder(ArsNouveau.MODID) public class ModEntities { public static final EntityType<EntityProjectileSpell> SPELL_PROJ = null; // public static void init() { // // Every entity in our mod has an ID (local to this mod) // int id = 1; // EntityRegistry.registerModEntity(new ResourceLocation(""), EntityProjectileSpell.class, "ProjectileSpell", id++, ExampleMod.instance, 64, 3, true); //// EntityRegistry.registerModEntity(EntityWeirdZombie.class, "WeirdZombie", id++, ModTut.instance, 64, 3, true, 0x996600, 0x00ff00); //// //// // We want our mob to spawn in Plains and ice plains biomes. If you don't add this then it will not spawn automatically //// // but you can of course still make it spawn manually //// EntityRegistry.addSpawn(EntityWeirdZombie.class, 100, 3, 5, EnumCreatureType.MONSTER, Biomes.PLAINS, Biomes.ICE_PLAINS); //// //// // This is the loot table for our mob //// LootTableList.register(EntityWeirdZombie.LOOT); // } @Mod.EventBusSubscriber(modid = ArsNouveau.MODID, bus= Mod.EventBusSubscriber.Bus.MOD) public static class RegistrationHandler { public static final int lightballID = 29; /** * Register this mod's {@link Entity} types. * * @param event The event */ @SubscribeEvent public static void registerEntities(final RegistryEvent.Register<EntityType<?>> event) { System.out.println("Registered entitites"); // final EntityEntry[] entries = { // createBuilder("mod_projectile_spell") // .entity(EntityProjectileSpell.class) // .tracker(64, 20, false) // .build(), // // // }; final EntityType<EntityProjectileSpell> spell_proj = build( "spell_proj", EntityType.Builder.<EntityProjectileSpell>create(EntityProjectileSpell::new, EntityClassification.MISC) .size(0.5f, 0.5f) .setTrackingRange(10) .setShouldReceiveVelocityUpdates(true) .setUpdateInterval(60).setCustomClientFactory(EntityProjectileSpell::new)); final EntityType<EntityEvokerFangs> evokerFangs = build( "fangs", EntityType.Builder.<EntityEvokerFangs>create(EntityEvokerFangs::new, EntityClassification.MISC) .size(0.5F, 0.8F) .setUpdateInterval(60)); final EntityType<EntityAllyVex> allyVex = build( "ally_vex", EntityType.Builder.<EntityAllyVex>create(EntityAllyVex::new, EntityClassification.MISC) .size(0.4F, 0.8F).immuneToFire() .setUpdateInterval(60)); event.getRegistry().registerAll( spell_proj, evokerFangs, allyVex ); //ENT_PROJECTILE = registerEntity(EntityType.Builder.<EntityModProjectile>create(EntityClassification.MISC).setCustomClientFactory(EntityModProjectile::new).size(0.25F, 0.25F), "ent_projectile"); // EntityRegistry.registerModEntity(new ResourceLocation(ExampleMod.MODID, "dmlightball"), // EntityProjectileSpell.class, ExampleMod.MODID + ".dmlightball", lightballID, ExampleMod.instance, // 80, 20, true); //event.getRegistry().registerAll(entries); } } /** * Build an {@link EntityType} from a {@link EntityType.Builder} using the specified name. * * @param name The entity type name * @param builder The entity type builder to build * @return The built entity type */ private static <T extends Entity> EntityType<T> build(final String name, final EntityType.Builder<T> builder) { final ResourceLocation registryName = new ResourceLocation(ArsNouveau.MODID, name); final EntityType<T> entityType = builder .build(registryName.toString()); entityType.setRegistryName(registryName); return entityType; } }
NielsPilgaard/Ars-Nouveau
src/main/java/com/hollingsworth/arsnouveau/common/entity/ModEntities.java
1,353
// int id = 1;
line_comment
nl
package com.hollingsworth.arsnouveau.common.entity; import com.hollingsworth.arsnouveau.ArsNouveau; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityClassification; import net.minecraft.entity.EntityType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.ObjectHolder; @ObjectHolder(ArsNouveau.MODID) public class ModEntities { public static final EntityType<EntityProjectileSpell> SPELL_PROJ = null; // public static void init() { // // Every entity in our mod has an ID (local to this mod) // int id<SUF> // EntityRegistry.registerModEntity(new ResourceLocation(""), EntityProjectileSpell.class, "ProjectileSpell", id++, ExampleMod.instance, 64, 3, true); //// EntityRegistry.registerModEntity(EntityWeirdZombie.class, "WeirdZombie", id++, ModTut.instance, 64, 3, true, 0x996600, 0x00ff00); //// //// // We want our mob to spawn in Plains and ice plains biomes. If you don't add this then it will not spawn automatically //// // but you can of course still make it spawn manually //// EntityRegistry.addSpawn(EntityWeirdZombie.class, 100, 3, 5, EnumCreatureType.MONSTER, Biomes.PLAINS, Biomes.ICE_PLAINS); //// //// // This is the loot table for our mob //// LootTableList.register(EntityWeirdZombie.LOOT); // } @Mod.EventBusSubscriber(modid = ArsNouveau.MODID, bus= Mod.EventBusSubscriber.Bus.MOD) public static class RegistrationHandler { public static final int lightballID = 29; /** * Register this mod's {@link Entity} types. * * @param event The event */ @SubscribeEvent public static void registerEntities(final RegistryEvent.Register<EntityType<?>> event) { System.out.println("Registered entitites"); // final EntityEntry[] entries = { // createBuilder("mod_projectile_spell") // .entity(EntityProjectileSpell.class) // .tracker(64, 20, false) // .build(), // // // }; final EntityType<EntityProjectileSpell> spell_proj = build( "spell_proj", EntityType.Builder.<EntityProjectileSpell>create(EntityProjectileSpell::new, EntityClassification.MISC) .size(0.5f, 0.5f) .setTrackingRange(10) .setShouldReceiveVelocityUpdates(true) .setUpdateInterval(60).setCustomClientFactory(EntityProjectileSpell::new)); final EntityType<EntityEvokerFangs> evokerFangs = build( "fangs", EntityType.Builder.<EntityEvokerFangs>create(EntityEvokerFangs::new, EntityClassification.MISC) .size(0.5F, 0.8F) .setUpdateInterval(60)); final EntityType<EntityAllyVex> allyVex = build( "ally_vex", EntityType.Builder.<EntityAllyVex>create(EntityAllyVex::new, EntityClassification.MISC) .size(0.4F, 0.8F).immuneToFire() .setUpdateInterval(60)); event.getRegistry().registerAll( spell_proj, evokerFangs, allyVex ); //ENT_PROJECTILE = registerEntity(EntityType.Builder.<EntityModProjectile>create(EntityClassification.MISC).setCustomClientFactory(EntityModProjectile::new).size(0.25F, 0.25F), "ent_projectile"); // EntityRegistry.registerModEntity(new ResourceLocation(ExampleMod.MODID, "dmlightball"), // EntityProjectileSpell.class, ExampleMod.MODID + ".dmlightball", lightballID, ExampleMod.instance, // 80, 20, true); //event.getRegistry().registerAll(entries); } } /** * Build an {@link EntityType} from a {@link EntityType.Builder} using the specified name. * * @param name The entity type name * @param builder The entity type builder to build * @return The built entity type */ private static <T extends Entity> EntityType<T> build(final String name, final EntityType.Builder<T> builder) { final ResourceLocation registryName = new ResourceLocation(ArsNouveau.MODID, name); final EntityType<T> entityType = builder .build(registryName.toString()); entityType.setRegistryName(registryName); return entityType; } }
False
906
124743_29
package com.bai.util; import static java.lang.Integer.parseInt; import com.bai.checkers.CheckerManager; import ghidra.util.exception.InvalidInputException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Configuration class. */ public class Config { /** * The config parser for headless mode arguments. */ public static class HeadlessParser { private static boolean checkArgument(String optionName, String[] args, int argi) throws InvalidInputException { // everything after this requires an argument if (!optionName.equalsIgnoreCase(args[argi])) { return false; } if (argi + 1 == args.length) { throw new InvalidInputException(optionName + " requires an argument"); } return true; } private static String[] getSubArguments(String[] args, int argi) { List<String> subArgs = new LinkedList<>(); int i = argi + 1; while (i < args.length && !args[i].startsWith("-")) { subArgs.add(args[i++]); } return subArgs.toArray(new String[0]); } private static void usage() { System.out.println("Usage: "); System.out.println( "analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>"); System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\""); System.out.println("where <script parameters> in following format: "); System.out.println(" [-K <kElement>]"); System.out.println(" [-callStringK <callStringMaxLen>]"); System.out.println(" [-Z3Timeout <timeout>]"); System.out.println(" [-timeout <timeout>]"); System.out.println(" [-entry <address>]"); System.out.println(" [-externalMap <file>]"); System.out.println(" [-json]"); System.out.println(" [-disableZ3]"); System.out.println(" [-all]"); System.out.println(" [-debug]"); System.out.println(" [-PreserveCalleeSavedReg]"); System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]"); } public static Config parseConfig(String fullArgs) { Config config = new Config(); if (fullArgs.isEmpty()) { return config; } if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') { System.out.println("Wrong parameters: <script parameters> should start with '@@'"); usage(); System.exit(-1); } try { String[] args = fullArgs.substring(2).split(" "); for (int argi = 0; argi < args.length; argi++) { String arg = args[argi]; if (checkArgument("-K", args, argi)) { config.setK(parseInt(args[++argi])); } else if (checkArgument("-callStringK", args, argi)) { config.setCallStringK(parseInt(args[++argi])); } else if (checkArgument("-Z3Timeout", args, argi)) { config.setZ3TimeOut(parseInt(args[++argi])); } else if (checkArgument("-timeout", args, argi)) { config.setTimeout(parseInt(args[++argi])); } else if (checkArgument("-entry", args, argi)) { config.setEntryAddress(args[++argi]); } else if (checkArgument("-externalMap", args, argi)) { config.setExternalMapPath(args[++argi]); } else if (arg.equalsIgnoreCase("-json")) { config.setOutputJson(true); } else if (arg.equalsIgnoreCase("-disableZ3")) { config.setEnableZ3(false); } else if (arg.equalsIgnoreCase("-all")) { CheckerManager.loadAllCheckers(config); } else if (arg.equalsIgnoreCase("-debug")) { config.setDebug(true); } else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) { config.setPreserveCalleeSavedReg(true); } else if (checkArgument("-check", args, argi)) { String[] checkers = getSubArguments(args, argi); Arrays.stream(checkers) .filter(CheckerManager::hasChecker) .forEach(config::addChecker); argi += checkers.length; } } } catch (InvalidInputException | IllegalArgumentException e) { System.out.println("Fail to parse config from: \"" + fullArgs + "\""); usage(); System.exit(-1); } System.out.println("Loaded config: " + config); return config; } } private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond private static final int DEFAULT_CALLSTRING_K = 3; private static final int DEFAULT_K = 50; private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default private int z3TimeOut; private boolean isDebug; private boolean isOutputJson; @SuppressWarnings("checkstyle:MemberName") private int K; private int callStringK; private List<String> checkers = new ArrayList<>(); private String entryAddress; private int timeout; private boolean isEnableZ3; private String externalMapPath; private boolean isGUI; private boolean preserveCalleeSavedReg; // for tactic tuning, see: // http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm private List<String> z3Tactics = new ArrayList<>(); public Config() { // default config this.callStringK = DEFAULT_CALLSTRING_K; this.K = DEFAULT_K; this.isDebug = false; this.isOutputJson = false; this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms this.timeout = DEFAULT_TIMEOUT; this.entryAddress = null; this.isEnableZ3 = true; this.externalMapPath = null; this.preserveCalleeSavedReg = false; } /** * Get the timeout (millisecond) for z3 constraint solving. * @return the timeout (millisecond). */ public int getZ3TimeOut() { return z3TimeOut; } /** * Set the timeout (millisecond) for z3 constraint solving. * @param z3TimeOut the timeout (millisecond). */ public void setZ3TimeOut(int z3TimeOut) { this.z3TimeOut = z3TimeOut; } /** * Get a list of z3 tactic names. * @return the list of z3 tactic names. */ public List<String> getZ3Tactics() { return z3Tactics; } /** * Checks if in debug config. * @return true if in debug config, false otherwise. */ public boolean isDebug() { return isDebug; } /** * Set debug config. * @param debug in debug config or not. */ public void setDebug(boolean debug) { this.isDebug = debug; } /** * Check if using json output. * @return ture if using json output, false otherwise. */ public boolean isOutputJson() { return isOutputJson; } /** * Set json output * @param isOutputJson use json format output or not. */ public void setOutputJson(boolean isOutputJson) { this.isOutputJson = isOutputJson; } /** * Get the K parameter. * @return the K parameter. */ public int getK() { return K; } /** * Set the K parameter. * @param k the K parameter. */ public void setK(int k) { K = k; } /** * Get the call string max length: K. * @return the call string k. */ public int getCallStringK() { return callStringK; } /** * Set the call string max length: K. * @param callStringK the call string k. */ public void setCallStringK(int callStringK) { this.callStringK = callStringK; } /** * Get a list of checker names to run. * @return a list of checker names. */ public List<String> getCheckers() { return checkers; } /** * Add a checker to run. * @param name the checker name. */ public void addChecker(String name) { checkers.add(name); } /** * Clear all checkers config. */ public void clearCheckers() { checkers.clear(); } /** * Get the analysis timeout (in second). * @return the analysis timout (in second). */ public int getTimeout() { return timeout; } /** * Set the analysis timeout (in second). * @param timeout the analysis timout (in second). */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * Get the entry address string. * @return the entry address string. */ public String getEntryAddress() { return entryAddress; } /** * Set the entry address, accept format of decimal or hexadecimal. * @param entryAddress the entry address. */ public void setEntryAddress(String entryAddress) { this.entryAddress = entryAddress; } /** * Checks if enable z3 constraint solving. * @return true if enabled, false otherwise. */ public boolean isEnableZ3() { return isEnableZ3; } /** * Enable z3 config. * @param enableZ3 enable or not. */ public void setEnableZ3(boolean enableZ3) { isEnableZ3 = enableZ3; } /** * Get the path of external map config json file. * @return the file path. */ public String getExternalMapPath() { return externalMapPath; } /** * Set the path of external map config json file. * @param externalMapPath the file path. */ public void setExternalMapPath(String externalMapPath) { this.externalMapPath = externalMapPath; } /** * Checks if running in GUI mode. * @return true if in GUI mode, false otherwise. */ public boolean isGUI() { return isGUI; } /** * @hidden * @param isGUI */ public void setGUI(boolean isGUI) { this.isGUI = isGUI; } /** * Preserve the callee saved registers. * @param preserveCalleeSavedReg preserve or not. */ public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) { this.preserveCalleeSavedReg = preserveCalleeSavedReg; } /** * Get if the callee saved registers are preserved. * @return true if preserved, false otherwise. */ public boolean getPreserveCalleeSavedReg() { return preserveCalleeSavedReg; } @Override public String toString() { return "Config{" + "z3TimeOut=" + z3TimeOut + ", isDebug=" + isDebug + ", isOutputJson=" + isOutputJson + ", K=" + K + ", callStringK=" + callStringK + ", checkers=" + checkers + ", entryAddress='" + entryAddress + '\'' + ", timeout=" + timeout + ", isEnableZ3=" + isEnableZ3 + ", z3Tactics=" + z3Tactics + ", externalMapPath=" + externalMapPath + '}'; } }
KeenSecurityLab/BinAbsInspector
src/main/java/com/bai/util/Config.java
3,334
/** * @hidden * @param isGUI */
block_comment
nl
package com.bai.util; import static java.lang.Integer.parseInt; import com.bai.checkers.CheckerManager; import ghidra.util.exception.InvalidInputException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Configuration class. */ public class Config { /** * The config parser for headless mode arguments. */ public static class HeadlessParser { private static boolean checkArgument(String optionName, String[] args, int argi) throws InvalidInputException { // everything after this requires an argument if (!optionName.equalsIgnoreCase(args[argi])) { return false; } if (argi + 1 == args.length) { throw new InvalidInputException(optionName + " requires an argument"); } return true; } private static String[] getSubArguments(String[] args, int argi) { List<String> subArgs = new LinkedList<>(); int i = argi + 1; while (i < args.length && !args[i].startsWith("-")) { subArgs.add(args[i++]); } return subArgs.toArray(new String[0]); } private static void usage() { System.out.println("Usage: "); System.out.println( "analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>"); System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\""); System.out.println("where <script parameters> in following format: "); System.out.println(" [-K <kElement>]"); System.out.println(" [-callStringK <callStringMaxLen>]"); System.out.println(" [-Z3Timeout <timeout>]"); System.out.println(" [-timeout <timeout>]"); System.out.println(" [-entry <address>]"); System.out.println(" [-externalMap <file>]"); System.out.println(" [-json]"); System.out.println(" [-disableZ3]"); System.out.println(" [-all]"); System.out.println(" [-debug]"); System.out.println(" [-PreserveCalleeSavedReg]"); System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]"); } public static Config parseConfig(String fullArgs) { Config config = new Config(); if (fullArgs.isEmpty()) { return config; } if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') { System.out.println("Wrong parameters: <script parameters> should start with '@@'"); usage(); System.exit(-1); } try { String[] args = fullArgs.substring(2).split(" "); for (int argi = 0; argi < args.length; argi++) { String arg = args[argi]; if (checkArgument("-K", args, argi)) { config.setK(parseInt(args[++argi])); } else if (checkArgument("-callStringK", args, argi)) { config.setCallStringK(parseInt(args[++argi])); } else if (checkArgument("-Z3Timeout", args, argi)) { config.setZ3TimeOut(parseInt(args[++argi])); } else if (checkArgument("-timeout", args, argi)) { config.setTimeout(parseInt(args[++argi])); } else if (checkArgument("-entry", args, argi)) { config.setEntryAddress(args[++argi]); } else if (checkArgument("-externalMap", args, argi)) { config.setExternalMapPath(args[++argi]); } else if (arg.equalsIgnoreCase("-json")) { config.setOutputJson(true); } else if (arg.equalsIgnoreCase("-disableZ3")) { config.setEnableZ3(false); } else if (arg.equalsIgnoreCase("-all")) { CheckerManager.loadAllCheckers(config); } else if (arg.equalsIgnoreCase("-debug")) { config.setDebug(true); } else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) { config.setPreserveCalleeSavedReg(true); } else if (checkArgument("-check", args, argi)) { String[] checkers = getSubArguments(args, argi); Arrays.stream(checkers) .filter(CheckerManager::hasChecker) .forEach(config::addChecker); argi += checkers.length; } } } catch (InvalidInputException | IllegalArgumentException e) { System.out.println("Fail to parse config from: \"" + fullArgs + "\""); usage(); System.exit(-1); } System.out.println("Loaded config: " + config); return config; } } private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond private static final int DEFAULT_CALLSTRING_K = 3; private static final int DEFAULT_K = 50; private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default private int z3TimeOut; private boolean isDebug; private boolean isOutputJson; @SuppressWarnings("checkstyle:MemberName") private int K; private int callStringK; private List<String> checkers = new ArrayList<>(); private String entryAddress; private int timeout; private boolean isEnableZ3; private String externalMapPath; private boolean isGUI; private boolean preserveCalleeSavedReg; // for tactic tuning, see: // http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm private List<String> z3Tactics = new ArrayList<>(); public Config() { // default config this.callStringK = DEFAULT_CALLSTRING_K; this.K = DEFAULT_K; this.isDebug = false; this.isOutputJson = false; this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms this.timeout = DEFAULT_TIMEOUT; this.entryAddress = null; this.isEnableZ3 = true; this.externalMapPath = null; this.preserveCalleeSavedReg = false; } /** * Get the timeout (millisecond) for z3 constraint solving. * @return the timeout (millisecond). */ public int getZ3TimeOut() { return z3TimeOut; } /** * Set the timeout (millisecond) for z3 constraint solving. * @param z3TimeOut the timeout (millisecond). */ public void setZ3TimeOut(int z3TimeOut) { this.z3TimeOut = z3TimeOut; } /** * Get a list of z3 tactic names. * @return the list of z3 tactic names. */ public List<String> getZ3Tactics() { return z3Tactics; } /** * Checks if in debug config. * @return true if in debug config, false otherwise. */ public boolean isDebug() { return isDebug; } /** * Set debug config. * @param debug in debug config or not. */ public void setDebug(boolean debug) { this.isDebug = debug; } /** * Check if using json output. * @return ture if using json output, false otherwise. */ public boolean isOutputJson() { return isOutputJson; } /** * Set json output * @param isOutputJson use json format output or not. */ public void setOutputJson(boolean isOutputJson) { this.isOutputJson = isOutputJson; } /** * Get the K parameter. * @return the K parameter. */ public int getK() { return K; } /** * Set the K parameter. * @param k the K parameter. */ public void setK(int k) { K = k; } /** * Get the call string max length: K. * @return the call string k. */ public int getCallStringK() { return callStringK; } /** * Set the call string max length: K. * @param callStringK the call string k. */ public void setCallStringK(int callStringK) { this.callStringK = callStringK; } /** * Get a list of checker names to run. * @return a list of checker names. */ public List<String> getCheckers() { return checkers; } /** * Add a checker to run. * @param name the checker name. */ public void addChecker(String name) { checkers.add(name); } /** * Clear all checkers config. */ public void clearCheckers() { checkers.clear(); } /** * Get the analysis timeout (in second). * @return the analysis timout (in second). */ public int getTimeout() { return timeout; } /** * Set the analysis timeout (in second). * @param timeout the analysis timout (in second). */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * Get the entry address string. * @return the entry address string. */ public String getEntryAddress() { return entryAddress; } /** * Set the entry address, accept format of decimal or hexadecimal. * @param entryAddress the entry address. */ public void setEntryAddress(String entryAddress) { this.entryAddress = entryAddress; } /** * Checks if enable z3 constraint solving. * @return true if enabled, false otherwise. */ public boolean isEnableZ3() { return isEnableZ3; } /** * Enable z3 config. * @param enableZ3 enable or not. */ public void setEnableZ3(boolean enableZ3) { isEnableZ3 = enableZ3; } /** * Get the path of external map config json file. * @return the file path. */ public String getExternalMapPath() { return externalMapPath; } /** * Set the path of external map config json file. * @param externalMapPath the file path. */ public void setExternalMapPath(String externalMapPath) { this.externalMapPath = externalMapPath; } /** * Checks if running in GUI mode. * @return true if in GUI mode, false otherwise. */ public boolean isGUI() { return isGUI; } /** * @hidden <SUF>*/ public void setGUI(boolean isGUI) { this.isGUI = isGUI; } /** * Preserve the callee saved registers. * @param preserveCalleeSavedReg preserve or not. */ public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) { this.preserveCalleeSavedReg = preserveCalleeSavedReg; } /** * Get if the callee saved registers are preserved. * @return true if preserved, false otherwise. */ public boolean getPreserveCalleeSavedReg() { return preserveCalleeSavedReg; } @Override public String toString() { return "Config{" + "z3TimeOut=" + z3TimeOut + ", isDebug=" + isDebug + ", isOutputJson=" + isOutputJson + ", K=" + K + ", callStringK=" + callStringK + ", checkers=" + checkers + ", entryAddress='" + entryAddress + '\'' + ", timeout=" + timeout + ", isEnableZ3=" + isEnableZ3 + ", z3Tactics=" + z3Tactics + ", externalMapPath=" + externalMapPath + '}'; } }
False
1,714
101133_1
package chatty; import chatty.util.DateTime; import chatty.util.Debugging; import chatty.util.DelayedActionQueue; import chatty.util.DelayedActionQueue.DelayedActionListener; import chatty.util.irc.MsgParameters; import chatty.util.irc.MsgTags; import chatty.util.irc.ParsedMsg; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.logging.Logger; import java.util.regex.Pattern; /** * * @author tduva */ public abstract class Irc { private static final Logger LOGGER = Logger.getLogger(Irc.class.getName()); /** * Delay between JOINs (in milliseconds). */ private static final int JOIN_DELAY = 750; private final AddressManager addressManager = new AddressManager(); private final DelayedActionQueue<String> joinQueue = DelayedActionQueue.create(new DelayedJoinAction(), JOIN_DELAY); private final Object lock = new Object(); private volatile String nick; private volatile String pass; private volatile Connection connection; private String quitmessage = "Quit"; private volatile String connectedIp = ""; private volatile int connectedPort; private volatile long connectedSince = -1; private volatile int state = STATE_OFFLINE; /** * State while reconnecting. */ public static final int STATE_RECONNECTING = -1; /** * State while being offline, either not connected or already disconnected * without reconnecting. */ public static final int STATE_OFFLINE = 0; /** * State value while trying to connect (opening socket and streams). */ public static final int STATE_CONNECTING = 1; /** * State value after having connected (socket and streams successfully opened). */ public static final int STATE_CONNECTED = 2; /** * State value once the connection has been accepted by the IRC Server * (registered). */ public static final int STATE_REGISTERED = 3; /** * Disconnect reason value for Unknown host. */ public static final int ERROR_UNKNOWN_HOST = 100; /** * Disconnect reason value for socket timeout. */ public static final int ERROR_SOCKET_TIMEOUT = 101; /** * Disconnect reason value for socket error. */ public static final int ERROR_SOCKET_ERROR = 102; /** * Disconnect reason value for requested disconnect, meaning the user * wanted to disconnect from the server. */ public static final int REQUESTED_DISCONNECT = 103; /** * Disconnect reason value for when the connection was closed. */ public static final int ERROR_CONNECTION_CLOSED = 104; public static final int ERROR_REGISTRATION_FAILED = 105; public static final int REQUESTED_RECONNECT = 106; public static final int SSL_ERROR = 107; /** * Indicates that the user wanted the connection to be closed. */ private volatile boolean requestedDisconnect = false; /** * The user requested the connection attempt to be canceled. If possible the * connection attempt should be canceled. */ private volatile boolean cancelConnecting = false; private final String id; private final String idPrefix; public Irc(String id) { this.id = id; this.idPrefix = "["+id+"] "; } private void info(String message) { LOGGER.info(idPrefix+message); } private void warning(String message) { LOGGER.warning(idPrefix+message); } /** * Set a new connection state. * * @param newState */ protected void setState(int newState) { this.state = newState; } /** * Get the current connection state * * @return */ public int getState() { return state; } public boolean isRegistered() { return state == STATE_REGISTERED; } public boolean isOffline() { return state == STATE_OFFLINE; } /** * The connection attempt should be canceled if possible. * * @return */ public boolean shouldCancelConnecting() { return cancelConnecting; } public String getIp() { return connectedIp; } public String getConnectionInfo() { if (state >= STATE_CONNECTED) { return connectedIp+":"+connectedPort; } return null; } public String getConnectedSince() { return DateTime.ago(connectedSince); } /** * Outputs the debug string * * @param line */ abstract public void debug(String line); /** * Connects to a server using the given credentials. This starts a new * Thread, running the Connection class, after checking if already * connected. * * @param server The ip or host of the server * @param port The port of the server * @param nick The nick to connect with * @param pass The password (required at Twitch) * @param securedPorts Which ports should be treated as SSL */ public final void connect(final String server, final String port, final String nick, final String pass, Collection<Integer> securedPorts) { String error = null; synchronized (lock) { if (state >= STATE_CONNECTING) { error = "Already trying to connect."; } if (state >= STATE_CONNECTED) { error = "Already connected."; } if (error == null) { state = STATE_CONNECTING; cancelConnecting = false; } } if (error != null) { warning(error); return; } info("Resolving "+server+" "+port); onConnectionPrepare(server); if (Debugging.isEnabled("resolvedelay")) { try { Thread.sleep(3000); } catch (InterruptedException ex) { } } InetSocketAddress address = null; try { address = addressManager.getAddress(server, port); } catch (UnknownHostException ex) { onConnectionAttempt(server, -1, false); warning("Could not resolve host: "+server); disconnected(ERROR_UNKNOWN_HOST); return; } if (address == null) { onConnectionAttempt(null, -1, false); warning("Invalid address: "+server+":"+port); setState(STATE_OFFLINE); return; } if (cancelConnecting) { cancelConnecting = false; disconnected(REQUESTED_DISCONNECT); return; } // Save for further use this.pass = pass; this.nick = nick; // Only give server and port, nick and pass are saved in this class // and sent once the initial connection has been established. //System.out.println(securedPorts+" "+address.getPort()); boolean secured = securedPorts.contains(address.getPort()); onConnectionAttempt(address.getHostString(), address.getPort(), secured); connection = new Connection(this,address, id, secured); new Thread(connection, "IRC").start(); } /** * Disconnect if connected. */ public boolean disconnect() { if (state > STATE_CONNECTING && connection != null) { requestedDisconnect = true; quit(); connection.close(); return true; } else { onConnectionAttemptCancel(); cancelConnecting = true; } return false; } /** * Send a QUIT to the server, after which the server should close the * connection. */ private void quit() { sendCommand("QUIT",quitmessage); } public void simulate(String data) { received(data); } public void debugConnection() { if (connection != null) { connection.debug(); } } /** * Parse IRC-Messages receveived from the Connection-Thread. * * @param data The line of data received */ protected void received(String data) { if (data == null) { return; } raw(data); ParsedMsg p = ParsedMsg.parse(data); if (p != null) { receivedCommand(p.getPrefix(), p.getNick(), p.getCommand(), p.getParameters(), p.getTags()); } } /** * Message has already been parsed, so let's check what command it is. * * @param prefix * @param nick * @param command The name of the command, can't be null * @param parameters String array of parameters, array can have different * length, so checking there may be necessary * @param tags The IRCv3 tags, can be null */ private void receivedCommand(String prefix, String nick, String command, MsgParameters parameters, MsgTags tags) { parsed(prefix, command, parameters); if (!parameters.isEmpty(0)) { if (parameters.isChan(0)) { onChannelCommand(tags, nick, parameters.get(0), command, parameters.getOrEmpty(1)); } else { onCommand(nick, command, parameters.get(0), parameters.getOrEmpty(1), tags); } } if (command.equals("PING")) { sendCommand("PONG", parameters.getOrEmpty(0)); } else if (command.equals("PRIVMSG")) { if (parameters.has(1)) { String channel = parameters.get(0); String message = parameters.get(1); if (parameters.get(0).startsWith("#")) { if (message.charAt(0) == (char) 1 && message.startsWith("ACTION", 1)) { onChannelMessage(channel, nick, prefix, message.substring(7).trim(), tags, true); } else { onChannelMessage(channel, nick, prefix, message, tags, false); } } else if (channel.equalsIgnoreCase(this.nick)) { onQueryMessage(nick, prefix, message); } } else if (parameters.has(0)) { /** * For hosting message, which is as follows (no channel/name as * PRIVMSG target): :jtv!jtv@jtv.tmi.twitch.tv PRIVMSG * :tduvatest is now hosting you for 0 viewers. [0] */ String message = parameters.get(0); onQueryMessage(nick, prefix, message); } } else if (command.equals("NOTICE")) { if (parameters.has(1)) { String channel = parameters.get(0); String message = parameters.get(1); if (!channel.startsWith("#")) { onNotice(nick, prefix, message); } else { onNotice(channel, message, tags); } } } else if (command.equals("USERNOTICE")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); onUsernotice(channel, message, tags); } } else if (command.equals("JOIN")) { if (parameters.has(0)) { String channel = parameters.get(0); onJoin(channel, nick); } } else if (command.equals("PART")) { if (parameters.has(0)) { String channel = parameters.get(0); onPart(channel, nick); } } else if (command.equals("MODE")) { if (parameters.size() == 3) { String chan = parameters.get(0); String mode = parameters.get(1); String name = parameters.get(2); if (mode.length() == 2) { String modeChar = mode.substring(1, 2); if (mode.startsWith("+")) { onModeChange(chan,name,true,modeChar, prefix); } else if (mode.startsWith("-")) { onModeChange(chan,name,false,modeChar, prefix); } } } } // Now the connection is really going.. ;) else if (command.equals("004")) { setState(STATE_REGISTERED); onRegistered(); } // Nick list, usually on channel join else if (command.equals("353")) { if (parameters.size() == 4 && parameters.get(1).equals("=") && parameters.isChan(2)) { String[] names = parameters.get(3).split(" "); onUserlist(parameters.get(2), names); } } // WHO response not really correct now else if (command.equals("352")) { //String[] parts = trailing.split(" "); //if (parts.length > 1) { //onWhoResponse(parts[0],parts[1]); //} } else if (command.equals("USERSTATE")) { if (tags != null && parameters.isChan(0)) { String channel = parameters.get(0); onUserstate(channel, tags); } } else if (command.equals("GLOBALUSERSTATE")) { if (tags != null) { onGlobalUserstate(tags); } } else if (command.equals("CLEARCHAT")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); if (message.isEmpty()) { onClearChat(tags, channel, null); } else { onClearChat(tags, channel, message); } } } else if (command.equals("CLEARMSG")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); onClearMsg(tags, channel, message); } } } /** * Extracts the nick from the prefix (like nick!mail@host) * * @param sender * @return */ public String getNickFromPrefix(String sender) { int endOfNick = sender.indexOf("!"); if (endOfNick == -1) { return sender; } return sender.substring(0, endOfNick); } /** * Send any command with a parameter to the server * * @param command * @param parameter */ public void sendCommand(String command,String parameter) { send(command+" :"+parameter); } /** * Joins {@code channel} on a queue, that puts some time between each join. * * @param channel The name of the channel to join */ public void joinChannel(String channel) { info("JOINING: " + channel); joinQueue.add(channel); } /** * Join a channel. This adds # in front if not there. * * @param channel */ public void joinChannelImmediately(String channel) { if (state >= STATE_REGISTERED) { if (!channel.startsWith("#")) { channel = "#" + channel; } // if-condition for testing (to simulate failed joins) //if (new Random().nextBoolean()) { send("JOIN " + channel); //} onJoinAttempt(channel); } } /** * Listener for the join queue, which is called when the next channel can * be joined. */ private class DelayedJoinAction implements DelayedActionListener<String> { @Override public void actionPerformed(String item) { info("JOIN: "+item+" (delayed)"); joinChannelImmediately(item); } } /** * Part a channel. This adds # in front if not there. * * @param channel */ public void partChannel(String channel) { if (!channel.startsWith("#")) { channel = "#"+channel; } send("PART "+channel); } /** * Send a message, usually to a channel. * * @param to * @param message * @param tags */ public void sendMessage(String to, String message, MsgTags tags) { if (!tags.isEmpty()) { send(String.format("@%s PRIVMSG %s :%s", tags.toTagsString(), to, message)); } else { send("PRIVMSG "+to+" :"+message); } } public void sendActionMessage(String to,String message) { send("PRIVMSG "+to+" :"+(char)1+"ACTION "+message+(char)1); } synchronized public void send(String data) { if (state > STATE_OFFLINE) { connection.send(data); } } /** * Called from the Connection Thread once the initial connection has * been established without an error. * * So now work on getting the connection to the IRC Server going by * sending credentials and stuff. * * @param ip * @param port */ protected void connected(String ip, int port) { this.connectedIp = ip; this.connectedPort = port; this.connectedSince = System.currentTimeMillis(); setState(Irc.STATE_CONNECTED); onConnect(); if (pass != null) { send("PASS " + pass); } //send("USER " + nick + " * * : "+nick); send("NICK " + nick); send(String.format("USER %s 0 * :Chatty", nick)); } /** * Called by the Connection Thread, when the Connection was closed, be * it because it was closed by the server, the program itself or because * of an error. * * @param reason The reason of the disconnect as defined in various * constants in this class * @param reasonMessage An error message or other information about the * disconnect */ protected void disconnected(int reason, String reasonMessage) { // Clear any potential join queue, so it doesn't carry over to the next // connection joinQueue.clear(); // Retrieve state before changing it, but must be changed before calling // onDisconnect() which might check the state when trying to reconnect int oldState = getState(); setState(Irc.STATE_OFFLINE); // If connecting failed, then add it as an error if (!requestedDisconnect && oldState != STATE_REGISTERED && connection != null) { addressManager.addError(connection.getAddress()); } if (requestedDisconnect) { // If the disconnect was requested (like the user clicking on // a menu item), include the appropriate reason requestedDisconnect = false; onDisconnect(REQUESTED_DISCONNECT, reasonMessage); } else if (reason == ERROR_CONNECTION_CLOSED && oldState != STATE_REGISTERED) { onDisconnect(ERROR_REGISTRATION_FAILED, reasonMessage); } else { onDisconnect(reason, reasonMessage); } } /** * Convenience method without a reason message. * * @param reason */ void disconnected(int reason) { disconnected(reason,""); } /* * Methods that can by overwritten by another Class */ void onChannelMessage (String channel, String nick, String from, String text, MsgTags tags, boolean action) {} void onQueryMessage (String nick, String from, String text) {} void onNotice(String nick, String from, String text) {} void onNotice(String channel, String text, MsgTags tags) { } void onJoinAttempt(String channel) {} void onJoin(String channel, String nick) {} void onPart(String channel, String nick) { } void onModeChange(String channel, String nick, boolean modeAdded, String mode, String prefix) { } void onUserlist(String channel, String[] nicks) {} void onWhoResponse(String channel, String nick) {} void onConnectionPrepare(String server) { } void onConnectionAttempt(String server, int port, boolean secured) { } void onConnectionAttemptCancel() { } void onConnect() { } void onRegistered() { } void onDisconnect(int reason, String reasonMessage) { } void parsed(String prefix, String command, MsgParameters parameters) { } void raw(String message) { } void sent(String message) { } void onUserstate(String channel, MsgTags tags) { } void onGlobalUserstate(MsgTags tags) { } void onClearChat(MsgTags tags, String channel, String name) { } void onClearMsg(MsgTags tags, String channel, String msg) { } void onChannelCommand(MsgTags tags, String nick, String channel, String command, String trailing) { } void onCommand(String nick, String command, String parameter, String text, MsgTags tags) { } void onUsernotice(String channel, String message, MsgTags tags) { } }
TheDinoDude/chatty
src/chatty/Irc.java
5,857
/** * Delay between JOINs (in milliseconds). */
block_comment
nl
package chatty; import chatty.util.DateTime; import chatty.util.Debugging; import chatty.util.DelayedActionQueue; import chatty.util.DelayedActionQueue.DelayedActionListener; import chatty.util.irc.MsgParameters; import chatty.util.irc.MsgTags; import chatty.util.irc.ParsedMsg; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.logging.Logger; import java.util.regex.Pattern; /** * * @author tduva */ public abstract class Irc { private static final Logger LOGGER = Logger.getLogger(Irc.class.getName()); /** * Delay between JOINs<SUF>*/ private static final int JOIN_DELAY = 750; private final AddressManager addressManager = new AddressManager(); private final DelayedActionQueue<String> joinQueue = DelayedActionQueue.create(new DelayedJoinAction(), JOIN_DELAY); private final Object lock = new Object(); private volatile String nick; private volatile String pass; private volatile Connection connection; private String quitmessage = "Quit"; private volatile String connectedIp = ""; private volatile int connectedPort; private volatile long connectedSince = -1; private volatile int state = STATE_OFFLINE; /** * State while reconnecting. */ public static final int STATE_RECONNECTING = -1; /** * State while being offline, either not connected or already disconnected * without reconnecting. */ public static final int STATE_OFFLINE = 0; /** * State value while trying to connect (opening socket and streams). */ public static final int STATE_CONNECTING = 1; /** * State value after having connected (socket and streams successfully opened). */ public static final int STATE_CONNECTED = 2; /** * State value once the connection has been accepted by the IRC Server * (registered). */ public static final int STATE_REGISTERED = 3; /** * Disconnect reason value for Unknown host. */ public static final int ERROR_UNKNOWN_HOST = 100; /** * Disconnect reason value for socket timeout. */ public static final int ERROR_SOCKET_TIMEOUT = 101; /** * Disconnect reason value for socket error. */ public static final int ERROR_SOCKET_ERROR = 102; /** * Disconnect reason value for requested disconnect, meaning the user * wanted to disconnect from the server. */ public static final int REQUESTED_DISCONNECT = 103; /** * Disconnect reason value for when the connection was closed. */ public static final int ERROR_CONNECTION_CLOSED = 104; public static final int ERROR_REGISTRATION_FAILED = 105; public static final int REQUESTED_RECONNECT = 106; public static final int SSL_ERROR = 107; /** * Indicates that the user wanted the connection to be closed. */ private volatile boolean requestedDisconnect = false; /** * The user requested the connection attempt to be canceled. If possible the * connection attempt should be canceled. */ private volatile boolean cancelConnecting = false; private final String id; private final String idPrefix; public Irc(String id) { this.id = id; this.idPrefix = "["+id+"] "; } private void info(String message) { LOGGER.info(idPrefix+message); } private void warning(String message) { LOGGER.warning(idPrefix+message); } /** * Set a new connection state. * * @param newState */ protected void setState(int newState) { this.state = newState; } /** * Get the current connection state * * @return */ public int getState() { return state; } public boolean isRegistered() { return state == STATE_REGISTERED; } public boolean isOffline() { return state == STATE_OFFLINE; } /** * The connection attempt should be canceled if possible. * * @return */ public boolean shouldCancelConnecting() { return cancelConnecting; } public String getIp() { return connectedIp; } public String getConnectionInfo() { if (state >= STATE_CONNECTED) { return connectedIp+":"+connectedPort; } return null; } public String getConnectedSince() { return DateTime.ago(connectedSince); } /** * Outputs the debug string * * @param line */ abstract public void debug(String line); /** * Connects to a server using the given credentials. This starts a new * Thread, running the Connection class, after checking if already * connected. * * @param server The ip or host of the server * @param port The port of the server * @param nick The nick to connect with * @param pass The password (required at Twitch) * @param securedPorts Which ports should be treated as SSL */ public final void connect(final String server, final String port, final String nick, final String pass, Collection<Integer> securedPorts) { String error = null; synchronized (lock) { if (state >= STATE_CONNECTING) { error = "Already trying to connect."; } if (state >= STATE_CONNECTED) { error = "Already connected."; } if (error == null) { state = STATE_CONNECTING; cancelConnecting = false; } } if (error != null) { warning(error); return; } info("Resolving "+server+" "+port); onConnectionPrepare(server); if (Debugging.isEnabled("resolvedelay")) { try { Thread.sleep(3000); } catch (InterruptedException ex) { } } InetSocketAddress address = null; try { address = addressManager.getAddress(server, port); } catch (UnknownHostException ex) { onConnectionAttempt(server, -1, false); warning("Could not resolve host: "+server); disconnected(ERROR_UNKNOWN_HOST); return; } if (address == null) { onConnectionAttempt(null, -1, false); warning("Invalid address: "+server+":"+port); setState(STATE_OFFLINE); return; } if (cancelConnecting) { cancelConnecting = false; disconnected(REQUESTED_DISCONNECT); return; } // Save for further use this.pass = pass; this.nick = nick; // Only give server and port, nick and pass are saved in this class // and sent once the initial connection has been established. //System.out.println(securedPorts+" "+address.getPort()); boolean secured = securedPorts.contains(address.getPort()); onConnectionAttempt(address.getHostString(), address.getPort(), secured); connection = new Connection(this,address, id, secured); new Thread(connection, "IRC").start(); } /** * Disconnect if connected. */ public boolean disconnect() { if (state > STATE_CONNECTING && connection != null) { requestedDisconnect = true; quit(); connection.close(); return true; } else { onConnectionAttemptCancel(); cancelConnecting = true; } return false; } /** * Send a QUIT to the server, after which the server should close the * connection. */ private void quit() { sendCommand("QUIT",quitmessage); } public void simulate(String data) { received(data); } public void debugConnection() { if (connection != null) { connection.debug(); } } /** * Parse IRC-Messages receveived from the Connection-Thread. * * @param data The line of data received */ protected void received(String data) { if (data == null) { return; } raw(data); ParsedMsg p = ParsedMsg.parse(data); if (p != null) { receivedCommand(p.getPrefix(), p.getNick(), p.getCommand(), p.getParameters(), p.getTags()); } } /** * Message has already been parsed, so let's check what command it is. * * @param prefix * @param nick * @param command The name of the command, can't be null * @param parameters String array of parameters, array can have different * length, so checking there may be necessary * @param tags The IRCv3 tags, can be null */ private void receivedCommand(String prefix, String nick, String command, MsgParameters parameters, MsgTags tags) { parsed(prefix, command, parameters); if (!parameters.isEmpty(0)) { if (parameters.isChan(0)) { onChannelCommand(tags, nick, parameters.get(0), command, parameters.getOrEmpty(1)); } else { onCommand(nick, command, parameters.get(0), parameters.getOrEmpty(1), tags); } } if (command.equals("PING")) { sendCommand("PONG", parameters.getOrEmpty(0)); } else if (command.equals("PRIVMSG")) { if (parameters.has(1)) { String channel = parameters.get(0); String message = parameters.get(1); if (parameters.get(0).startsWith("#")) { if (message.charAt(0) == (char) 1 && message.startsWith("ACTION", 1)) { onChannelMessage(channel, nick, prefix, message.substring(7).trim(), tags, true); } else { onChannelMessage(channel, nick, prefix, message, tags, false); } } else if (channel.equalsIgnoreCase(this.nick)) { onQueryMessage(nick, prefix, message); } } else if (parameters.has(0)) { /** * For hosting message, which is as follows (no channel/name as * PRIVMSG target): :jtv!jtv@jtv.tmi.twitch.tv PRIVMSG * :tduvatest is now hosting you for 0 viewers. [0] */ String message = parameters.get(0); onQueryMessage(nick, prefix, message); } } else if (command.equals("NOTICE")) { if (parameters.has(1)) { String channel = parameters.get(0); String message = parameters.get(1); if (!channel.startsWith("#")) { onNotice(nick, prefix, message); } else { onNotice(channel, message, tags); } } } else if (command.equals("USERNOTICE")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); onUsernotice(channel, message, tags); } } else if (command.equals("JOIN")) { if (parameters.has(0)) { String channel = parameters.get(0); onJoin(channel, nick); } } else if (command.equals("PART")) { if (parameters.has(0)) { String channel = parameters.get(0); onPart(channel, nick); } } else if (command.equals("MODE")) { if (parameters.size() == 3) { String chan = parameters.get(0); String mode = parameters.get(1); String name = parameters.get(2); if (mode.length() == 2) { String modeChar = mode.substring(1, 2); if (mode.startsWith("+")) { onModeChange(chan,name,true,modeChar, prefix); } else if (mode.startsWith("-")) { onModeChange(chan,name,false,modeChar, prefix); } } } } // Now the connection is really going.. ;) else if (command.equals("004")) { setState(STATE_REGISTERED); onRegistered(); } // Nick list, usually on channel join else if (command.equals("353")) { if (parameters.size() == 4 && parameters.get(1).equals("=") && parameters.isChan(2)) { String[] names = parameters.get(3).split(" "); onUserlist(parameters.get(2), names); } } // WHO response not really correct now else if (command.equals("352")) { //String[] parts = trailing.split(" "); //if (parts.length > 1) { //onWhoResponse(parts[0],parts[1]); //} } else if (command.equals("USERSTATE")) { if (tags != null && parameters.isChan(0)) { String channel = parameters.get(0); onUserstate(channel, tags); } } else if (command.equals("GLOBALUSERSTATE")) { if (tags != null) { onGlobalUserstate(tags); } } else if (command.equals("CLEARCHAT")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); if (message.isEmpty()) { onClearChat(tags, channel, null); } else { onClearChat(tags, channel, message); } } } else if (command.equals("CLEARMSG")) { if (parameters.isChan(0)) { String channel = parameters.get(0); String message = parameters.getOrEmpty(1); onClearMsg(tags, channel, message); } } } /** * Extracts the nick from the prefix (like nick!mail@host) * * @param sender * @return */ public String getNickFromPrefix(String sender) { int endOfNick = sender.indexOf("!"); if (endOfNick == -1) { return sender; } return sender.substring(0, endOfNick); } /** * Send any command with a parameter to the server * * @param command * @param parameter */ public void sendCommand(String command,String parameter) { send(command+" :"+parameter); } /** * Joins {@code channel} on a queue, that puts some time between each join. * * @param channel The name of the channel to join */ public void joinChannel(String channel) { info("JOINING: " + channel); joinQueue.add(channel); } /** * Join a channel. This adds # in front if not there. * * @param channel */ public void joinChannelImmediately(String channel) { if (state >= STATE_REGISTERED) { if (!channel.startsWith("#")) { channel = "#" + channel; } // if-condition for testing (to simulate failed joins) //if (new Random().nextBoolean()) { send("JOIN " + channel); //} onJoinAttempt(channel); } } /** * Listener for the join queue, which is called when the next channel can * be joined. */ private class DelayedJoinAction implements DelayedActionListener<String> { @Override public void actionPerformed(String item) { info("JOIN: "+item+" (delayed)"); joinChannelImmediately(item); } } /** * Part a channel. This adds # in front if not there. * * @param channel */ public void partChannel(String channel) { if (!channel.startsWith("#")) { channel = "#"+channel; } send("PART "+channel); } /** * Send a message, usually to a channel. * * @param to * @param message * @param tags */ public void sendMessage(String to, String message, MsgTags tags) { if (!tags.isEmpty()) { send(String.format("@%s PRIVMSG %s :%s", tags.toTagsString(), to, message)); } else { send("PRIVMSG "+to+" :"+message); } } public void sendActionMessage(String to,String message) { send("PRIVMSG "+to+" :"+(char)1+"ACTION "+message+(char)1); } synchronized public void send(String data) { if (state > STATE_OFFLINE) { connection.send(data); } } /** * Called from the Connection Thread once the initial connection has * been established without an error. * * So now work on getting the connection to the IRC Server going by * sending credentials and stuff. * * @param ip * @param port */ protected void connected(String ip, int port) { this.connectedIp = ip; this.connectedPort = port; this.connectedSince = System.currentTimeMillis(); setState(Irc.STATE_CONNECTED); onConnect(); if (pass != null) { send("PASS " + pass); } //send("USER " + nick + " * * : "+nick); send("NICK " + nick); send(String.format("USER %s 0 * :Chatty", nick)); } /** * Called by the Connection Thread, when the Connection was closed, be * it because it was closed by the server, the program itself or because * of an error. * * @param reason The reason of the disconnect as defined in various * constants in this class * @param reasonMessage An error message or other information about the * disconnect */ protected void disconnected(int reason, String reasonMessage) { // Clear any potential join queue, so it doesn't carry over to the next // connection joinQueue.clear(); // Retrieve state before changing it, but must be changed before calling // onDisconnect() which might check the state when trying to reconnect int oldState = getState(); setState(Irc.STATE_OFFLINE); // If connecting failed, then add it as an error if (!requestedDisconnect && oldState != STATE_REGISTERED && connection != null) { addressManager.addError(connection.getAddress()); } if (requestedDisconnect) { // If the disconnect was requested (like the user clicking on // a menu item), include the appropriate reason requestedDisconnect = false; onDisconnect(REQUESTED_DISCONNECT, reasonMessage); } else if (reason == ERROR_CONNECTION_CLOSED && oldState != STATE_REGISTERED) { onDisconnect(ERROR_REGISTRATION_FAILED, reasonMessage); } else { onDisconnect(reason, reasonMessage); } } /** * Convenience method without a reason message. * * @param reason */ void disconnected(int reason) { disconnected(reason,""); } /* * Methods that can by overwritten by another Class */ void onChannelMessage (String channel, String nick, String from, String text, MsgTags tags, boolean action) {} void onQueryMessage (String nick, String from, String text) {} void onNotice(String nick, String from, String text) {} void onNotice(String channel, String text, MsgTags tags) { } void onJoinAttempt(String channel) {} void onJoin(String channel, String nick) {} void onPart(String channel, String nick) { } void onModeChange(String channel, String nick, boolean modeAdded, String mode, String prefix) { } void onUserlist(String channel, String[] nicks) {} void onWhoResponse(String channel, String nick) {} void onConnectionPrepare(String server) { } void onConnectionAttempt(String server, int port, boolean secured) { } void onConnectionAttemptCancel() { } void onConnect() { } void onRegistered() { } void onDisconnect(int reason, String reasonMessage) { } void parsed(String prefix, String command, MsgParameters parameters) { } void raw(String message) { } void sent(String message) { } void onUserstate(String channel, MsgTags tags) { } void onGlobalUserstate(MsgTags tags) { } void onClearChat(MsgTags tags, String channel, String name) { } void onClearMsg(MsgTags tags, String channel, String msg) { } void onChannelCommand(MsgTags tags, String nick, String channel, String command, String trailing) { } void onCommand(String nick, String command, String parameter, String text, MsgTags tags) { } void onUsernotice(String channel, String message, MsgTags tags) { } }
False
1,132
141414_9
/**************************************************************************** Copyright 2009, Colorado School of Mines and others. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package edu.mines.jtk.sgl; import java.awt.Color; import edu.mines.jtk.dsp.*; import static edu.mines.jtk.util.ArrayMath.*; /** * An axis-aligned panel that displays a slice of a 3D metric tensor field. * The tensors correspond to symmetric positive-definite 3x3 matrices, and * are rendered as ellipsoids. * @author Chris Engelsma and Dave Hale, Colorado School of Mines. * @version 2009.08.29 */ public class TensorsPanel extends AxisAlignedPanel { /** * Constructs a tensors panel for the specified tensor field. * Assumes default unit samplings. * @param et the eigentensors; by reference, not by copy. */ public TensorsPanel(EigenTensors3 et) { this(new Sampling(et.getN1()), new Sampling(et.getN2()), new Sampling(et.getN3()), et); } /** * Constructs a tensors panel for the specified tensor field. * @param s1 sampling of 1st dimension (Z axis). * @param s2 sampling of 2nd dimension (Y axis). * @param s3 sampling of 3rd dimension (X axis). * @param et the eigentensors; by reference, not by copy. */ public TensorsPanel( Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et) { _sx = s3; _sy = s2; _sz = s1; _et = et; _emax = findMaxEigenvalue(); setStates(StateSet.forTwoSidedShinySurface(Color.CYAN)); } /** * Updates the panel. * This method should be called when the tensor field * referenced by this tensors panel has been modified. */ public void update() { dirtyDraw(); } /** * Sets the maximum size of the ellipsoids. * As this size is increased, the number of ellipsoids decreases. * @param size the maximum ellipsoid size, in samples. */ public void setEllipsoidSize(int size) { _ellipsoidSize = size; dirtyDraw(); } ///////////////////////////////////////////////////////////////////////////// // protected protected void draw(DrawContext dc) { AxisAlignedFrame aaf = this.getFrame(); if (aaf==null) return; Axis axis = aaf.getAxis(); drawEllipsoids(axis); } ///////////////////////////////////////////////////////////////////////////// // private private Sampling _sx,_sy,_sz; private EigenTensors3 _et; private float _emax; private int _ellipsoidSize = 10; private EllipsoidGlyph _eg = new EllipsoidGlyph(); /** * Draws the tensors as ellipsoids. */ private void drawEllipsoids(Axis axis) { // Tensor sampling. int nx = _sx.getCount(); int ny = _sy.getCount(); int nz = _sz.getCount(); double dx = _sx.getDelta(); double dy = _sy.getDelta(); double dz = _sz.getDelta(); double fx = _sx.getFirst(); double fy = _sy.getFirst(); double fz = _sz.getFirst(); // Min/max (x,y,z) coordinates. double xmin = _sx.getFirst(); double xmax = _sx.getLast(); double ymin = _sy.getFirst(); double ymax = _sy.getLast(); double zmin = _sz.getFirst(); double zmax = _sz.getLast(); // Maximum length of eigenvectors u, v and w. float dmax = 0.5f*_ellipsoidSize; float dxmax = (float)dx*dmax; float dymax = (float)dy*dmax; float dzmax = (float)dz*dmax; // Distance between ellipsoid centers (in samples). int kec = (int)(2.0*dmax); // Scaling factor for the eigenvectors. float scale = dmax/sqrt(_emax); // Smallest eigenvalue permitted. float etiny = 0.0001f*_emax; // Current frame. AxisAlignedFrame aaf = this.getFrame(); if (axis==Axis.X) { // Y-Axis. int nyc = (int)((ymax-ymin)/(2.0f*dymax)); double dyc = kec*dy; double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc); int jyc = (int)(fyc/dy); // Z-Axis. int nzc = (int)((zmax-zmin)/(2.0f*dzmax)); double dzc = kec*dz; double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc); int jzc = (int)(fzc/dz); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // X-Axis. float xc = 0.5f*(float)(xmax+xmin); int ix = _sx.indexOfNearest(xc); for (int iy=jyc; iy<ny; iy+=kec) { float yc = (float)(fy+iy*dy); if (ymin<yc-dymax && yc+dymax<ymax) { for (int iz=jzc; iz<nz; iz+=kec) { float zc = (float)(fz+iz*dz); if (zmin<zc-dzmax && zc+dzmax<zmax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } else if (axis==Axis.Y) { // X-Axis. int nxc = (int)((xmax-xmin)/(2.0f*dxmax)); double dxc = kec*dx; double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc); int jxc = (int)(fxc/dx); // Z-Axis. int nzc = (int)((zmax-zmin)/(2.0f*dzmax)); double dzc = kec*dz; double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc); int jzc = (int)(fzc/dz); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // Y-Axis. float yc = 0.5f*(float)(ymax+ymin); int iy = _sy.indexOfNearest(yc); for (int ix=jxc; ix<nx; ix+=kec) { float xc = (float)(fx+ix*dx); if (xmin<xc-dxmax && xc+dxmax<xmax) { for (int iz=jzc; iz<nz; iz+=kec) { float zc = (float)(fz+iz*dz); if (zmin<zc-dzmax && zc+dzmax<zmax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } else if (axis==Axis.Z) { // X-Axis. int nxc = (int)((xmax-xmin)/(2.0f*dxmax)); double dxc = kec*dx; double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc); int jxc = (int)(fxc/dx); // Y-Axis. int nyc = (int)((ymax-ymin)/(2.0f*dymax)); double dyc = kec*dy; double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc); int jyc = (int)(fyc/dy); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // Z-Axis. float zc = 0.5f*(float)(zmax+zmin); int iz = _sz.indexOfNearest(zc); for (int ix=jxc; ix<nx; ix+=kec) { float xc = (float)(fx+ix*dx); if (xmin<xc-dxmax && xc+dxmax<xmax) { for (int iy=jyc; iy<ny; iy+=kec) { float yc = (float)(fy+iy*dy); if (ymin<yc-dymax && yc+dymax<ymax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } } /** * Finds the largest eigenvalue to be used for scaling. */ private float findMaxEigenvalue() { int n1 = _et.getN1(); int n2 = _et.getN2(); int n3 = _et.getN3(); float[] e = new float[3]; float emax = 0.0f; for (int i3=0; i3<n3; ++i3) { for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { _et.getEigenvalues(i1,i2,i3,e); float emaxi = max(e[0],e[1],e[2]); if (emax<emaxi) emax = emaxi; } } } return emax; } }
MinesJTK/jtk
core/src/main/java/edu/mines/jtk/sgl/TensorsPanel.java
4,182
// Distance between ellipsoid centers (in samples).
line_comment
nl
/**************************************************************************** Copyright 2009, Colorado School of Mines and others. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package edu.mines.jtk.sgl; import java.awt.Color; import edu.mines.jtk.dsp.*; import static edu.mines.jtk.util.ArrayMath.*; /** * An axis-aligned panel that displays a slice of a 3D metric tensor field. * The tensors correspond to symmetric positive-definite 3x3 matrices, and * are rendered as ellipsoids. * @author Chris Engelsma and Dave Hale, Colorado School of Mines. * @version 2009.08.29 */ public class TensorsPanel extends AxisAlignedPanel { /** * Constructs a tensors panel for the specified tensor field. * Assumes default unit samplings. * @param et the eigentensors; by reference, not by copy. */ public TensorsPanel(EigenTensors3 et) { this(new Sampling(et.getN1()), new Sampling(et.getN2()), new Sampling(et.getN3()), et); } /** * Constructs a tensors panel for the specified tensor field. * @param s1 sampling of 1st dimension (Z axis). * @param s2 sampling of 2nd dimension (Y axis). * @param s3 sampling of 3rd dimension (X axis). * @param et the eigentensors; by reference, not by copy. */ public TensorsPanel( Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et) { _sx = s3; _sy = s2; _sz = s1; _et = et; _emax = findMaxEigenvalue(); setStates(StateSet.forTwoSidedShinySurface(Color.CYAN)); } /** * Updates the panel. * This method should be called when the tensor field * referenced by this tensors panel has been modified. */ public void update() { dirtyDraw(); } /** * Sets the maximum size of the ellipsoids. * As this size is increased, the number of ellipsoids decreases. * @param size the maximum ellipsoid size, in samples. */ public void setEllipsoidSize(int size) { _ellipsoidSize = size; dirtyDraw(); } ///////////////////////////////////////////////////////////////////////////// // protected protected void draw(DrawContext dc) { AxisAlignedFrame aaf = this.getFrame(); if (aaf==null) return; Axis axis = aaf.getAxis(); drawEllipsoids(axis); } ///////////////////////////////////////////////////////////////////////////// // private private Sampling _sx,_sy,_sz; private EigenTensors3 _et; private float _emax; private int _ellipsoidSize = 10; private EllipsoidGlyph _eg = new EllipsoidGlyph(); /** * Draws the tensors as ellipsoids. */ private void drawEllipsoids(Axis axis) { // Tensor sampling. int nx = _sx.getCount(); int ny = _sy.getCount(); int nz = _sz.getCount(); double dx = _sx.getDelta(); double dy = _sy.getDelta(); double dz = _sz.getDelta(); double fx = _sx.getFirst(); double fy = _sy.getFirst(); double fz = _sz.getFirst(); // Min/max (x,y,z) coordinates. double xmin = _sx.getFirst(); double xmax = _sx.getLast(); double ymin = _sy.getFirst(); double ymax = _sy.getLast(); double zmin = _sz.getFirst(); double zmax = _sz.getLast(); // Maximum length of eigenvectors u, v and w. float dmax = 0.5f*_ellipsoidSize; float dxmax = (float)dx*dmax; float dymax = (float)dy*dmax; float dzmax = (float)dz*dmax; // Distance between<SUF> int kec = (int)(2.0*dmax); // Scaling factor for the eigenvectors. float scale = dmax/sqrt(_emax); // Smallest eigenvalue permitted. float etiny = 0.0001f*_emax; // Current frame. AxisAlignedFrame aaf = this.getFrame(); if (axis==Axis.X) { // Y-Axis. int nyc = (int)((ymax-ymin)/(2.0f*dymax)); double dyc = kec*dy; double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc); int jyc = (int)(fyc/dy); // Z-Axis. int nzc = (int)((zmax-zmin)/(2.0f*dzmax)); double dzc = kec*dz; double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc); int jzc = (int)(fzc/dz); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // X-Axis. float xc = 0.5f*(float)(xmax+xmin); int ix = _sx.indexOfNearest(xc); for (int iy=jyc; iy<ny; iy+=kec) { float yc = (float)(fy+iy*dy); if (ymin<yc-dymax && yc+dymax<ymax) { for (int iz=jzc; iz<nz; iz+=kec) { float zc = (float)(fz+iz*dz); if (zmin<zc-dzmax && zc+dzmax<zmax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } else if (axis==Axis.Y) { // X-Axis. int nxc = (int)((xmax-xmin)/(2.0f*dxmax)); double dxc = kec*dx; double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc); int jxc = (int)(fxc/dx); // Z-Axis. int nzc = (int)((zmax-zmin)/(2.0f*dzmax)); double dzc = kec*dz; double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc); int jzc = (int)(fzc/dz); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // Y-Axis. float yc = 0.5f*(float)(ymax+ymin); int iy = _sy.indexOfNearest(yc); for (int ix=jxc; ix<nx; ix+=kec) { float xc = (float)(fx+ix*dx); if (xmin<xc-dxmax && xc+dxmax<xmax) { for (int iz=jzc; iz<nz; iz+=kec) { float zc = (float)(fz+iz*dz); if (zmin<zc-dzmax && zc+dzmax<zmax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } else if (axis==Axis.Z) { // X-Axis. int nxc = (int)((xmax-xmin)/(2.0f*dxmax)); double dxc = kec*dx; double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc); int jxc = (int)(fxc/dx); // Y-Axis. int nyc = (int)((ymax-ymin)/(2.0f*dymax)); double dyc = kec*dy; double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc); int jyc = (int)(fyc/dy); xmin = aaf.getCornerMin().x; xmax = aaf.getCornerMax().x; ymin = aaf.getCornerMin().y; ymax = aaf.getCornerMax().y; zmin = aaf.getCornerMin().z; zmax = aaf.getCornerMax().z; // Z-Axis. float zc = 0.5f*(float)(zmax+zmin); int iz = _sz.indexOfNearest(zc); for (int ix=jxc; ix<nx; ix+=kec) { float xc = (float)(fx+ix*dx); if (xmin<xc-dxmax && xc+dxmax<xmax) { for (int iy=jyc; iy<ny; iy+=kec) { float yc = (float)(fy+iy*dy); if (ymin<yc-dymax && yc+dymax<ymax) { float[] e = _et.getEigenvalues(iz,iy,ix); float[] u = _et.getEigenvectorU(iz,iy,ix); float[] v = _et.getEigenvectorV(iz,iy,ix); float[] w = _et.getEigenvectorW(iz,iy,ix); float eu = e[0], ev = e[1], ew = e[2]; if (eu<=etiny) eu = etiny; if (ev<=etiny) ev = etiny; if (ew<=etiny) ew = etiny; float uz = u[0], uy = u[1], ux = u[2]; float vz = v[0], vy = v[1], vx = v[2]; float wz = w[0], wy = w[1], wx = w[2]; float su = scale*sqrt(eu); float sv = scale*sqrt(ev); float sw = scale*sqrt(ew); ux *= su*dx; uy *= su*dy; uz *= su*dz; vx *= sv*dx; vy *= sv*dy; vz *= sv*dz; wx *= sw*dx; wy *= sw*dy; wz *= sw*dz; _eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz); } } } } } } /** * Finds the largest eigenvalue to be used for scaling. */ private float findMaxEigenvalue() { int n1 = _et.getN1(); int n2 = _et.getN2(); int n3 = _et.getN3(); float[] e = new float[3]; float emax = 0.0f; for (int i3=0; i3<n3; ++i3) { for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { _et.getEigenvalues(i1,i2,i3,e); float emaxi = max(e[0],e[1],e[2]); if (emax<emaxi) emax = emaxi; } } } return emax; } }
False
1,380
70587_16
package src; import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
ROCMondriaanTIN/project-greenfoot-game-JustDylan23
src/TileEngine.java
2,422
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
line_comment
nl
package src; import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan<SUF> // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
True
3,177
132055_29
/* * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017 * for use in SwingJS via transpilation into JavaScript using Java2Script. * * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.awt.dnd; import java.awt.Component; import java.awt.Dimension; import java.awt.HeadlessException; //import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.SystemFlavorMap; import java.awt.dnd.peer.DropTargetPeer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.io.Serializable; import java.util.TooManyListenersException; import javax.swing.Timer; /** * 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>. * * @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; } /** * 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! * */ @SuppressWarnings("deprecation") public void addNotify(ComponentPeer peer) { if (peer == componentPeer) return; componentPeer = peer; for (Component c = component; c != null && peer instanceof LightweightPeer; c = c.getParent()) { peer = /** @j2sNative c.peer || */null;//((JSComponent) c).peer;//getPeer(); // SwingJS was getPeer(), but this is only if attached. } //if (peer instanceof DropTargetPeer) { if (peer == null) peer = componentPeer; 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 */ @SuppressWarnings("deprecation") 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 = SystemFlavorMap.getDefaultFlavorMap(); }
java2script/java2script
sources/net.sf.j2s.java.core/src/java/awt/dnd/DropTarget.java
7,845
/** @j2sNative c.peer || */
block_comment
nl
/* * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017 * for use in SwingJS via transpilation into JavaScript using Java2Script. * * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.awt.dnd; import java.awt.Component; import java.awt.Dimension; import java.awt.HeadlessException; //import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.SystemFlavorMap; import java.awt.dnd.peer.DropTargetPeer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.io.Serializable; import java.util.TooManyListenersException; import javax.swing.Timer; /** * 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>. * * @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; } /** * 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! * */ @SuppressWarnings("deprecation") public void addNotify(ComponentPeer peer) { if (peer == componentPeer) return; componentPeer = peer; for (Component c = component; c != null && peer instanceof LightweightPeer; c = c.getParent()) { peer = /** @j2sNative c.peer ||<SUF>*/null;//((JSComponent) c).peer;//getPeer(); // SwingJS was getPeer(), but this is only if attached. } //if (peer instanceof DropTargetPeer) { if (peer == null) peer = componentPeer; 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 */ @SuppressWarnings("deprecation") 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 = SystemFlavorMap.getDefaultFlavorMap(); }
False
1,162
164532_2
/** * Copyright (C) <2021> <chen junwen> * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.mycat.config; /** * cjw * 294712221@qq.com */ public class MySQLServerCapabilityFlags { /** * server value * * * server: 11110111 11111111 * client_cmd: 11 10100110 10000101 * client_jdbc:10 10100010 10001111 * * see 'http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html' * */ // new more secure passwords public static final int CLIENT_LONG_PASSWORD = 1; // Found instead of affected rows // 返回找到(匹配)的行数,而不是改变了的行数。 public static final int CLIENT_FOUND_ROWS = 2; // Get all column flags public static final int CLIENT_LONG_FLAG = 4; // One can specify db on connect public static final int CLIENT_CONNECT_WITH_DB = 8; // Don't allow database.table.column // 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。 // 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。 public static final int CLIENT_NO_SCHEMA = 16; // Can use compression protocol // 使用压缩协议 public static final int CLIENT_COMPRESS = 32; // Odbc client public static final int CLIENT_ODBC = 64; // Can use LOAD DATA LOCAL public static final int CLIENT_LOCAL_FILES = 128; // Ignore spaces before '(' // 允许在函数名后使用空格。所有函数名可以预留字。 public static final int CLIENT_IGNORE_SPACE = 256; // New 4.1 protocol This is an interactive client public static final int CLIENT_PROTOCOL_41 = 512; // This is an interactive client // 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。 // 客户端的会话等待超时变量变为交互超时变量。 public static final int CLIENT_INTERACTIVE = 1024; // Switch to SSL after handshake // 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。 // 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。 public static final int CLIENT_SSL = 2048; // IGNORE sigpipes // 阻止客户端库安装一个SIGPIPE信号处理器。 // 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。 public static final int CLIENT_IGNORE_SIGPIPE = 4096; // Client knows about transactions public static final int CLIENT_TRANSACTIONS = 8192; // Old flag for 4.1 protocol public static final int CLIENT_RESERVED = 16384; // New 4.1 authentication public static final int CLIENT_SECURE_CONNECTION = 32768; // Enable/disable multi-stmt support // 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。 public static final int CLIENT_MULTI_STATEMENTS = 1 << 16; // Enable/disable multi-results // 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。 // 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。 public static final int CLIENT_MULTI_RESULTS = 1 << 1 << 16; /** ServerCan send multiple resultsets for COM_STMT_EXECUTE. Client Can handle multiple resultsets for COM_STMT_EXECUTE. Value 0x00040000 Requires CLIENT_PROTOCOL_41 */ public static final int CLIENT_PS_MULTI_RESULTS = 1 << 2 << 16; /** Server Sends extra data in Initial Handshake Packet and supports the pluggable authentication protocol. Client Supports authentication plugins. Requires CLIENT_PROTOCOL_41 */ public static final int CLIENT_PLUGIN_AUTH = 1 << 3 << 16; /** Value 0x00100000 Server Permits connection attributes in Protocol::HandshakeResponse41. Client Sends connection attributes in Protocol::HandshakeResponse41. */ public static final int CLIENT_CONNECT_ATTRS = 1 << 4 << 16; /** Value 0x00200000 Server Understands length-encoded integer for auth response data in Protocol::HandshakeResponse41. Client Length of auth response data in Protocol::HandshakeResponse41 is a length-encoded integer. The flag was introduced in 5.6.6, but had the wrong value. */ public static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 1 << 5 << 16; /** *Value * 0x00400000 * * Server * Announces support for expired password extension. * * Client * Can handle expired passwords. */ public static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 1 << 6 << 16; /** * Value * 0x00800000 * * Server * Can set SERVER_SESSION_STATE_CHANGED in the Status Flags and send session-state change data after a OK packet. * * Client * Expects the server to send sesson-state changes after a OK packet. */ public static final int CLIENT_SESSION_TRACK = 1 << 7 << 16; /** Value 0x01000000 Server Can send OK after a Text Resultset. Client Expects an OK (instead of EOF) after the resultset rows of a Text Resultset. Background To support CLIENT_SESSION_TRACK, additional information must be sent after all successful commands. Although the OK packet is extensible, the EOF packet is not due to the overlap of its bytes with the content of the Text Resultset Row. Therefore, the EOF packet in the Text Resultset is replaced with an OK packet. EOF packets are deprecated as of MySQL 5.7.5. */ public static final int CLIENT_DEPRECATE_EOF = 1 << 8 << 16; public int value = 0; public MySQLServerCapabilityFlags(int capabilities) { this.value = capabilities; } public MySQLServerCapabilityFlags() { } public static int getDefaultServerCapabilities() { int flag = 0; flag |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD; flag |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS; flag |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG; flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB; // flag |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA; // boolean usingCompress = MycatServer.getInstance().getConfig() // .getSystem().getUseCompression() == 1; // if (usingCompress) { // flag |= MySQLServerCapabilityFlags.CLIENT_COMPRESS; // } // flag |= MySQLServerCapabilityFlags.CLIENT_ODBC; flag |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES; flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE; flag |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41; flag |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE; // flag |= MySQLServerCapabilityFlags.CLIENT_SSL; flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE; flag |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS; // flag |= ServerDefs.CLIENT_RESERVED; flag |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION; flag |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH; // flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS; // flag |= (MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK); flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS; flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS; return flag; } public static boolean isLongPassword(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD) != 0; } public static boolean isFoundRows(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS) != 0; } public static boolean isConnectionWithDatabase(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB) != 0; } public static boolean isDoNotAllowDatabaseDotTableDotColumn(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA) != 0; } public static boolean isCanUseCompressionProtocol(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_COMPRESS) != 0; } public static boolean isODBCClient(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_ODBC) != 0; } public static boolean isCanUseLoadDataLocal(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES) != 0; } public static boolean isIgnoreSpacesBeforeLeftBracket(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE) != 0; } public static boolean isClientProtocol41(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41) != 0; } public static boolean isSwitchToSSLAfterHandshake(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SSL) != 0; } public static boolean isIgnoreSigpipes(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE) != 0; } public static boolean isKnowsAboutTransactions(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS) != 0; } public static boolean isInteractive(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_INTERACTIVE) != 0; } public static boolean isSpeak41Protocol(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_RESERVED) != 0; } public static boolean isCanDo41Anthentication(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION) != 0; } public static boolean isMultipleStatements(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS) != 0; } public static boolean isPSMultipleResults(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS) != 0; } public static boolean isPluginAuth(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH) != 0; } public static boolean isConnectAttrs(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS) != 0; } public static boolean isPluginAuthLenencClientData(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0; } public static boolean isSessionVariableTracking(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK) != 0; } public static boolean isDeprecateEOF(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF) != 0; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MySQLServerCapabilityFlags{"); sb.append("value=").append(Integer.toBinaryString(value << 7)); sb.append('}'); return sb.toString(); } public int getLower2Bytes() { return value & 0x0000ffff; } public int getUpper2Bytes() { return value >>> 16; } public boolean isLongPassword() { return isLongPassword(value); } public void setLongPassword() { value |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD; } public boolean isFoundRows() { return isFoundRows(value); } public void setFoundRows() { value |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS; } public boolean isLongColumnWithFLags() { return isLongColumnWithFLags(value); } public boolean isLongColumnWithFLags(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LONG_FLAG) != 0; } public void setLongColumnWithFLags() { value |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG; } public boolean isConnectionWithDatabase() { return isConnectionWithDatabase(value); } public void setConnectionWithDatabase() { value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB; } public boolean isDoNotAllowDatabaseDotTableDotColumn() { return isDoNotAllowDatabaseDotTableDotColumn(value); } public void setDoNotAllowDatabaseDotTableDotColumn() { value |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA; } public boolean isCanUseCompressionProtocol() { return isCanUseCompressionProtocol(value); } public void setCanUseCompressionProtocol() { value |= MySQLServerCapabilityFlags.CLIENT_COMPRESS; } public boolean isODBCClient() { return isODBCClient(value); } public void setODBCClient() { value |= MySQLServerCapabilityFlags.CLIENT_ODBC; } public boolean isCanUseLoadDataLocal() { return isCanUseLoadDataLocal(value); } public void setCanUseLoadDataLocal() { value |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES; } public boolean isIgnoreSpacesBeforeLeftBracket() { return isIgnoreSpacesBeforeLeftBracket(value); } public void setIgnoreSpacesBeforeLeftBracket() { value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE; } public boolean isClientProtocol41() { return isClientProtocol41(value); } public void setClientProtocol41() { value |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41; } public boolean isSwitchToSSLAfterHandshake() { return isSwitchToSSLAfterHandshake(value); } public void setSwitchToSSLAfterHandshake() { value |= MySQLServerCapabilityFlags.CLIENT_SSL; } public boolean isIgnoreSigpipes() { return isIgnoreSigpipes(value); } public void setIgnoreSigpipes() { value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE; } public boolean isKnowsAboutTransactions() { return isKnowsAboutTransactions(value); } public void setKnowsAboutTransactions() { value |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS; } public void setInteractive() { value |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE; } public boolean isInteractive() { return isInteractive(value); } public boolean isSpeak41Protocol() { return isSpeak41Protocol(value); } public void setSpeak41Protocol() { value |= MySQLServerCapabilityFlags.CLIENT_RESERVED; } public boolean isCanDo41Anthentication() { return isCanDo41Anthentication(value); } public void setCanDo41Anthentication() { value |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION; } public boolean isMultipleStatements() { return isMultipleStatements(value); } public void setMultipleStatements() { value |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS; } public boolean isMultipleResults() { return isMultipleResults(value); } public boolean isMultipleResults(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS) != 0; } public void setMultipleResults() { value |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS; } public boolean isPSMultipleResults() { return isPSMultipleResults(value); } public void setPSMultipleResults() { value |= MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS; } public boolean isPluginAuth() { return isPluginAuth(value); } public void setPluginAuth() { value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH; } public boolean isConnectAttrs() { return isConnectAttrs(value); } public void setConnectAttrs() { value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS; } public boolean isPluginAuthLenencClientData() { return isPluginAuthLenencClientData(value); } public void setPluginAuthLenencClientData() { value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA; } public boolean isClientCanHandleExpiredPasswords() { return isClientCanHandleExpiredPasswords(value); } public boolean isClientCanHandleExpiredPasswords(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) != 0; } public void setClientCanHandleExpiredPasswords() { value |= MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS; } public boolean isSessionVariableTracking() { return isSessionVariableTracking(value); } public void setSessionVariableTracking() { value |= MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK; } public boolean isDeprecateEOF() { return isDeprecateEOF(value); } public void setDeprecateEOF() { value |= MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MySQLServerCapabilityFlags)) return false; MySQLServerCapabilityFlags that = (MySQLServerCapabilityFlags) o; return hashCode() == that.hashCode(); } @Override public int hashCode() { return value << 7; } }
MyCATApache/Mycat2
config/src/main/java/io/mycat/config/MySQLServerCapabilityFlags.java
5,366
/** * server value * * * server: 11110111 11111111 * client_cmd: 11 10100110 10000101 * client_jdbc:10 10100010 10001111 * * see 'http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html' * */
block_comment
nl
/** * Copyright (C) <2021> <chen junwen> * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.mycat.config; /** * cjw * 294712221@qq.com */ public class MySQLServerCapabilityFlags { /** * server value <SUF>*/ // new more secure passwords public static final int CLIENT_LONG_PASSWORD = 1; // Found instead of affected rows // 返回找到(匹配)的行数,而不是改变了的行数。 public static final int CLIENT_FOUND_ROWS = 2; // Get all column flags public static final int CLIENT_LONG_FLAG = 4; // One can specify db on connect public static final int CLIENT_CONNECT_WITH_DB = 8; // Don't allow database.table.column // 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。 // 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。 public static final int CLIENT_NO_SCHEMA = 16; // Can use compression protocol // 使用压缩协议 public static final int CLIENT_COMPRESS = 32; // Odbc client public static final int CLIENT_ODBC = 64; // Can use LOAD DATA LOCAL public static final int CLIENT_LOCAL_FILES = 128; // Ignore spaces before '(' // 允许在函数名后使用空格。所有函数名可以预留字。 public static final int CLIENT_IGNORE_SPACE = 256; // New 4.1 protocol This is an interactive client public static final int CLIENT_PROTOCOL_41 = 512; // This is an interactive client // 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。 // 客户端的会话等待超时变量变为交互超时变量。 public static final int CLIENT_INTERACTIVE = 1024; // Switch to SSL after handshake // 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。 // 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。 public static final int CLIENT_SSL = 2048; // IGNORE sigpipes // 阻止客户端库安装一个SIGPIPE信号处理器。 // 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。 public static final int CLIENT_IGNORE_SIGPIPE = 4096; // Client knows about transactions public static final int CLIENT_TRANSACTIONS = 8192; // Old flag for 4.1 protocol public static final int CLIENT_RESERVED = 16384; // New 4.1 authentication public static final int CLIENT_SECURE_CONNECTION = 32768; // Enable/disable multi-stmt support // 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。 public static final int CLIENT_MULTI_STATEMENTS = 1 << 16; // Enable/disable multi-results // 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。 // 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。 public static final int CLIENT_MULTI_RESULTS = 1 << 1 << 16; /** ServerCan send multiple resultsets for COM_STMT_EXECUTE. Client Can handle multiple resultsets for COM_STMT_EXECUTE. Value 0x00040000 Requires CLIENT_PROTOCOL_41 */ public static final int CLIENT_PS_MULTI_RESULTS = 1 << 2 << 16; /** Server Sends extra data in Initial Handshake Packet and supports the pluggable authentication protocol. Client Supports authentication plugins. Requires CLIENT_PROTOCOL_41 */ public static final int CLIENT_PLUGIN_AUTH = 1 << 3 << 16; /** Value 0x00100000 Server Permits connection attributes in Protocol::HandshakeResponse41. Client Sends connection attributes in Protocol::HandshakeResponse41. */ public static final int CLIENT_CONNECT_ATTRS = 1 << 4 << 16; /** Value 0x00200000 Server Understands length-encoded integer for auth response data in Protocol::HandshakeResponse41. Client Length of auth response data in Protocol::HandshakeResponse41 is a length-encoded integer. The flag was introduced in 5.6.6, but had the wrong value. */ public static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 1 << 5 << 16; /** *Value * 0x00400000 * * Server * Announces support for expired password extension. * * Client * Can handle expired passwords. */ public static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 1 << 6 << 16; /** * Value * 0x00800000 * * Server * Can set SERVER_SESSION_STATE_CHANGED in the Status Flags and send session-state change data after a OK packet. * * Client * Expects the server to send sesson-state changes after a OK packet. */ public static final int CLIENT_SESSION_TRACK = 1 << 7 << 16; /** Value 0x01000000 Server Can send OK after a Text Resultset. Client Expects an OK (instead of EOF) after the resultset rows of a Text Resultset. Background To support CLIENT_SESSION_TRACK, additional information must be sent after all successful commands. Although the OK packet is extensible, the EOF packet is not due to the overlap of its bytes with the content of the Text Resultset Row. Therefore, the EOF packet in the Text Resultset is replaced with an OK packet. EOF packets are deprecated as of MySQL 5.7.5. */ public static final int CLIENT_DEPRECATE_EOF = 1 << 8 << 16; public int value = 0; public MySQLServerCapabilityFlags(int capabilities) { this.value = capabilities; } public MySQLServerCapabilityFlags() { } public static int getDefaultServerCapabilities() { int flag = 0; flag |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD; flag |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS; flag |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG; flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB; // flag |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA; // boolean usingCompress = MycatServer.getInstance().getConfig() // .getSystem().getUseCompression() == 1; // if (usingCompress) { // flag |= MySQLServerCapabilityFlags.CLIENT_COMPRESS; // } // flag |= MySQLServerCapabilityFlags.CLIENT_ODBC; flag |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES; flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE; flag |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41; flag |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE; // flag |= MySQLServerCapabilityFlags.CLIENT_SSL; flag |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE; flag |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS; // flag |= ServerDefs.CLIENT_RESERVED; flag |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION; flag |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH; // flag |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS; // flag |= (MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK); flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS; flag |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS; return flag; } public static boolean isLongPassword(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD) != 0; } public static boolean isFoundRows(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS) != 0; } public static boolean isConnectionWithDatabase(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB) != 0; } public static boolean isDoNotAllowDatabaseDotTableDotColumn(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA) != 0; } public static boolean isCanUseCompressionProtocol(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_COMPRESS) != 0; } public static boolean isODBCClient(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_ODBC) != 0; } public static boolean isCanUseLoadDataLocal(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES) != 0; } public static boolean isIgnoreSpacesBeforeLeftBracket(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE) != 0; } public static boolean isClientProtocol41(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41) != 0; } public static boolean isSwitchToSSLAfterHandshake(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SSL) != 0; } public static boolean isIgnoreSigpipes(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE) != 0; } public static boolean isKnowsAboutTransactions(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS) != 0; } public static boolean isInteractive(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_INTERACTIVE) != 0; } public static boolean isSpeak41Protocol(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_RESERVED) != 0; } public static boolean isCanDo41Anthentication(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION) != 0; } public static boolean isMultipleStatements(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS) != 0; } public static boolean isPSMultipleResults(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS) != 0; } public static boolean isPluginAuth(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH) != 0; } public static boolean isConnectAttrs(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS) != 0; } public static boolean isPluginAuthLenencClientData(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0; } public static boolean isSessionVariableTracking(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK) != 0; } public static boolean isDeprecateEOF(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF) != 0; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MySQLServerCapabilityFlags{"); sb.append("value=").append(Integer.toBinaryString(value << 7)); sb.append('}'); return sb.toString(); } public int getLower2Bytes() { return value & 0x0000ffff; } public int getUpper2Bytes() { return value >>> 16; } public boolean isLongPassword() { return isLongPassword(value); } public void setLongPassword() { value |= MySQLServerCapabilityFlags.CLIENT_LONG_PASSWORD; } public boolean isFoundRows() { return isFoundRows(value); } public void setFoundRows() { value |= MySQLServerCapabilityFlags.CLIENT_FOUND_ROWS; } public boolean isLongColumnWithFLags() { return isLongColumnWithFLags(value); } public boolean isLongColumnWithFLags(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_LONG_FLAG) != 0; } public void setLongColumnWithFLags() { value |= MySQLServerCapabilityFlags.CLIENT_LONG_FLAG; } public boolean isConnectionWithDatabase() { return isConnectionWithDatabase(value); } public void setConnectionWithDatabase() { value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_WITH_DB; } public boolean isDoNotAllowDatabaseDotTableDotColumn() { return isDoNotAllowDatabaseDotTableDotColumn(value); } public void setDoNotAllowDatabaseDotTableDotColumn() { value |= MySQLServerCapabilityFlags.CLIENT_NO_SCHEMA; } public boolean isCanUseCompressionProtocol() { return isCanUseCompressionProtocol(value); } public void setCanUseCompressionProtocol() { value |= MySQLServerCapabilityFlags.CLIENT_COMPRESS; } public boolean isODBCClient() { return isODBCClient(value); } public void setODBCClient() { value |= MySQLServerCapabilityFlags.CLIENT_ODBC; } public boolean isCanUseLoadDataLocal() { return isCanUseLoadDataLocal(value); } public void setCanUseLoadDataLocal() { value |= MySQLServerCapabilityFlags.CLIENT_LOCAL_FILES; } public boolean isIgnoreSpacesBeforeLeftBracket() { return isIgnoreSpacesBeforeLeftBracket(value); } public void setIgnoreSpacesBeforeLeftBracket() { value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SPACE; } public boolean isClientProtocol41() { return isClientProtocol41(value); } public void setClientProtocol41() { value |= MySQLServerCapabilityFlags.CLIENT_PROTOCOL_41; } public boolean isSwitchToSSLAfterHandshake() { return isSwitchToSSLAfterHandshake(value); } public void setSwitchToSSLAfterHandshake() { value |= MySQLServerCapabilityFlags.CLIENT_SSL; } public boolean isIgnoreSigpipes() { return isIgnoreSigpipes(value); } public void setIgnoreSigpipes() { value |= MySQLServerCapabilityFlags.CLIENT_IGNORE_SIGPIPE; } public boolean isKnowsAboutTransactions() { return isKnowsAboutTransactions(value); } public void setKnowsAboutTransactions() { value |= MySQLServerCapabilityFlags.CLIENT_TRANSACTIONS; } public void setInteractive() { value |= MySQLServerCapabilityFlags.CLIENT_INTERACTIVE; } public boolean isInteractive() { return isInteractive(value); } public boolean isSpeak41Protocol() { return isSpeak41Protocol(value); } public void setSpeak41Protocol() { value |= MySQLServerCapabilityFlags.CLIENT_RESERVED; } public boolean isCanDo41Anthentication() { return isCanDo41Anthentication(value); } public void setCanDo41Anthentication() { value |= MySQLServerCapabilityFlags.CLIENT_SECURE_CONNECTION; } public boolean isMultipleStatements() { return isMultipleStatements(value); } public void setMultipleStatements() { value |= MySQLServerCapabilityFlags.CLIENT_MULTI_STATEMENTS; } public boolean isMultipleResults() { return isMultipleResults(value); } public boolean isMultipleResults(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS) != 0; } public void setMultipleResults() { value |= MySQLServerCapabilityFlags.CLIENT_MULTI_RESULTS; } public boolean isPSMultipleResults() { return isPSMultipleResults(value); } public void setPSMultipleResults() { value |= MySQLServerCapabilityFlags.CLIENT_PS_MULTI_RESULTS; } public boolean isPluginAuth() { return isPluginAuth(value); } public void setPluginAuth() { value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH; } public boolean isConnectAttrs() { return isConnectAttrs(value); } public void setConnectAttrs() { value |= MySQLServerCapabilityFlags.CLIENT_CONNECT_ATTRS; } public boolean isPluginAuthLenencClientData() { return isPluginAuthLenencClientData(value); } public void setPluginAuthLenencClientData() { value |= MySQLServerCapabilityFlags.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA; } public boolean isClientCanHandleExpiredPasswords() { return isClientCanHandleExpiredPasswords(value); } public boolean isClientCanHandleExpiredPasswords(int value) { return (value & MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) != 0; } public void setClientCanHandleExpiredPasswords() { value |= MySQLServerCapabilityFlags.CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS; } public boolean isSessionVariableTracking() { return isSessionVariableTracking(value); } public void setSessionVariableTracking() { value |= MySQLServerCapabilityFlags.CLIENT_SESSION_TRACK; } public boolean isDeprecateEOF() { return isDeprecateEOF(value); } public void setDeprecateEOF() { value |= MySQLServerCapabilityFlags.CLIENT_DEPRECATE_EOF; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MySQLServerCapabilityFlags)) return false; MySQLServerCapabilityFlags that = (MySQLServerCapabilityFlags) o; return hashCode() == that.hashCode(); } @Override public int hashCode() { return value << 7; } }
False
3,445
201219_19
package com.etiennelawlor.quickreturn.activities; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import com.android.vending.billing.IInAppBillingService; import com.etiennelawlor.quickreturn.R; import com.etiennelawlor.quickreturn.library.utils.QuickReturnUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class QuickReturnBaseActivity extends AppCompatActivity { // region Constants // Server Response Codes (http://developer.android.com/google/play/billing/billing_reference.html) private static final int BILLING_RESPONSE_RESULT_OK = 0; private static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; private static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; private static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; private static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; private static final int BILLING_RESPONSE_RESULT_ERROR = 6; private static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; private static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; private static final int BUY_REQUEST_CODE = 4; private static final String ITEM_TYPE_INAPP = "inapp"; private static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; private static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; private static final String RESPONSE_CODE = "RESPONSE_CODE"; private static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; private static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; private static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; private static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; private static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; private static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; private static final String RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST = "INAPP_PURCHASE_SIGNATURE_LIST"; private static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // endregion // region Member Variables private IInAppBillingService mService; private ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); } }; // endregion // region Lifecycle Methods @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); intent.setPackage("com.android.vending"); bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (mService != null) { unbindService(mServiceConn); } Crouton.cancelAllCroutons(); } // endregion @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BUY_REQUEST_CODE) { int responseCode; switch (resultCode) { case RESULT_OK: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_OK"); responseCode = data.getIntExtra(RESPONSE_CODE, -5); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: String signature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); JSONObject object; try { object = new JSONObject(purchaseData); // sample data // "purchaseToken" -> "inapp:com.etiennelawlor.quickreturn:android.test.purchased" // "developerPayload" -> "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK" // "packageName" -> "com.etiennelawlor.quickreturn" // "purchaseState" -> "0" // "orderId" -> "transactionId.android.test.purchased" // "purchaseTime" -> "0" // "productId" -> "android.test.purchased" // String sku = object.getString("productId"); if (!TextUtils.isEmpty(sku)) { if (sku.equals(getString(R.string.buy_one_beer))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 1, 1)); } else if (sku.equals(getString(R.string.buy_two_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 2, 2)); } else if (sku.equals(getString(R.string.buy_four_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 4, 4)); } else if (sku.equals("android.test.purchased")) { showCrouton(android.R.color.holo_green_light, "Test Purchase completed"); } } } catch (JSONException e) { e.printStackTrace(); } // handle purchase here (for a permanent item like a premium upgrade, // this means dispensing the benefits of the upgrade; for a consumable // item like "X gold coins", typically the application would initiate // consumption of the purchase here) break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } break; case RESULT_CANCELED: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_CANCELED"); // responseCode = data.getIntExtra(RESPONSE_CODE, -5); showCrouton(android.R.color.holo_red_light, R.string.beer_order_canceled); break; default: break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.quick_return, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_github: openWebPage("https://github.com/lawloretienne/QuickReturn"); return true; case R.id.buy_one_beer: donate(getString(R.string.buy_one_beer)); return true; case R.id.buy_two_beers: donate(getString(R.string.buy_two_beers)); return true; case R.id.buy_four_beers: donate(getString(R.string.buy_four_beers)); return true; default: break; } return super.onOptionsItemSelected(item); } // region Helper Methods private void openWebPage(String url) { Uri webpage = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, webpage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } private void donate(String productSku) { try { // getAllSkus(); // getAllPurchases(); // consumePurchase(); String developerPayload = "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK"; if (mService != null) { Bundle bundle = mService.getBuyIntent(3, getPackageName(), productSku, ITEM_TYPE_INAPP, developerPayload); // Test Item // Bundle bundle = mService.getBuyIntent(3, getPackageName(), // "android.test.purchased", ITEM_TYPE_INAPP, developerPayload); PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); int responseCode = bundle.getInt(RESPONSE_CODE); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: startIntentSenderForResult(pendingIntent.getIntentSender(), BUY_REQUEST_CODE, new Intent(), 0, 0, 0); break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } } } catch (RemoteException e) { e.printStackTrace(); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } private void consumePurchase() { // "purchaseToken": "inapp:com.etiennelawlor.quickreturn:android.test.purchased" String token = "inapp:com.etiennelawlor.quickreturn:android.test.purchased"; try { int response = mService.consumePurchase(3, getPackageName(), token); Log.d(getClass().getSimpleName(), "consumePurchase() : response - " + response); } catch (RemoteException e) { e.printStackTrace(); } } private void getAllSkus() { ArrayList<String> skuList = new ArrayList<>(); skuList.add("buy_one_beer"); skuList.add("buy_two_beers"); skuList.add("buy_four_beers"); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); try { Bundle skuDetails = mService.getSkuDetails(3, getPackageName(), ITEM_TYPE_INAPP, querySkus); int response = skuDetails.getInt(RESPONSE_CODE); if (response == BILLING_RESPONSE_RESULT_OK) { ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { JSONObject object; try { object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(getString(R.string.buy_one_beer))) { Log.d(getClass().getSimpleName(), "price - " + price); // mPremiumUpgradePrice = price; } else if (sku.equals(getString(R.string.buy_two_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } else if (sku.equals(getString(R.string.buy_four_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } } catch (JSONException e) { e.printStackTrace(); } } } } catch (RemoteException e) { e.printStackTrace(); } } private void getAllPurchases() { try { Bundle purchases = mService.getPurchases(3, getPackageName(), ITEM_TYPE_INAPP, INAPP_CONTINUATION_TOKEN); if (purchases.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { ArrayList mySkus, myPurchases, mySignatures; mySkus = purchases.getStringArrayList(RESPONSE_INAPP_ITEM_LIST); myPurchases = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST); mySignatures = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST); Log.d(getClass().getSimpleName(), "getAllPurchases() : purchases"); // handle items here } } catch (RemoteException e) { e.printStackTrace(); } } private void showCrouton(int colorRes, int messageRes) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, messageRes, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } private void showCrouton(int colorRes, String message) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, message, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } // endregion }
lawloretienne/QuickReturn
sample/src/main/java/com/etiennelawlor/quickreturn/activities/QuickReturnBaseActivity.java
5,371
// region Helper Methods
line_comment
nl
package com.etiennelawlor.quickreturn.activities; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import com.android.vending.billing.IInAppBillingService; import com.etiennelawlor.quickreturn.R; import com.etiennelawlor.quickreturn.library.utils.QuickReturnUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class QuickReturnBaseActivity extends AppCompatActivity { // region Constants // Server Response Codes (http://developer.android.com/google/play/billing/billing_reference.html) private static final int BILLING_RESPONSE_RESULT_OK = 0; private static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; private static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; private static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; private static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; private static final int BILLING_RESPONSE_RESULT_ERROR = 6; private static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; private static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; private static final int BUY_REQUEST_CODE = 4; private static final String ITEM_TYPE_INAPP = "inapp"; private static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; private static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; private static final String RESPONSE_CODE = "RESPONSE_CODE"; private static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; private static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; private static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; private static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; private static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; private static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; private static final String RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST = "INAPP_PURCHASE_SIGNATURE_LIST"; private static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // endregion // region Member Variables private IInAppBillingService mService; private ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); } }; // endregion // region Lifecycle Methods @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); intent.setPackage("com.android.vending"); bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (mService != null) { unbindService(mServiceConn); } Crouton.cancelAllCroutons(); } // endregion @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BUY_REQUEST_CODE) { int responseCode; switch (resultCode) { case RESULT_OK: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_OK"); responseCode = data.getIntExtra(RESPONSE_CODE, -5); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: String signature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); JSONObject object; try { object = new JSONObject(purchaseData); // sample data // "purchaseToken" -> "inapp:com.etiennelawlor.quickreturn:android.test.purchased" // "developerPayload" -> "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK" // "packageName" -> "com.etiennelawlor.quickreturn" // "purchaseState" -> "0" // "orderId" -> "transactionId.android.test.purchased" // "purchaseTime" -> "0" // "productId" -> "android.test.purchased" // String sku = object.getString("productId"); if (!TextUtils.isEmpty(sku)) { if (sku.equals(getString(R.string.buy_one_beer))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 1, 1)); } else if (sku.equals(getString(R.string.buy_two_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 2, 2)); } else if (sku.equals(getString(R.string.buy_four_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 4, 4)); } else if (sku.equals("android.test.purchased")) { showCrouton(android.R.color.holo_green_light, "Test Purchase completed"); } } } catch (JSONException e) { e.printStackTrace(); } // handle purchase here (for a permanent item like a premium upgrade, // this means dispensing the benefits of the upgrade; for a consumable // item like "X gold coins", typically the application would initiate // consumption of the purchase here) break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } break; case RESULT_CANCELED: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_CANCELED"); // responseCode = data.getIntExtra(RESPONSE_CODE, -5); showCrouton(android.R.color.holo_red_light, R.string.beer_order_canceled); break; default: break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.quick_return, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_github: openWebPage("https://github.com/lawloretienne/QuickReturn"); return true; case R.id.buy_one_beer: donate(getString(R.string.buy_one_beer)); return true; case R.id.buy_two_beers: donate(getString(R.string.buy_two_beers)); return true; case R.id.buy_four_beers: donate(getString(R.string.buy_four_beers)); return true; default: break; } return super.onOptionsItemSelected(item); } // region Helper<SUF> private void openWebPage(String url) { Uri webpage = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, webpage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } private void donate(String productSku) { try { // getAllSkus(); // getAllPurchases(); // consumePurchase(); String developerPayload = "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK"; if (mService != null) { Bundle bundle = mService.getBuyIntent(3, getPackageName(), productSku, ITEM_TYPE_INAPP, developerPayload); // Test Item // Bundle bundle = mService.getBuyIntent(3, getPackageName(), // "android.test.purchased", ITEM_TYPE_INAPP, developerPayload); PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); int responseCode = bundle.getInt(RESPONSE_CODE); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: startIntentSenderForResult(pendingIntent.getIntentSender(), BUY_REQUEST_CODE, new Intent(), 0, 0, 0); break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } } } catch (RemoteException e) { e.printStackTrace(); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } private void consumePurchase() { // "purchaseToken": "inapp:com.etiennelawlor.quickreturn:android.test.purchased" String token = "inapp:com.etiennelawlor.quickreturn:android.test.purchased"; try { int response = mService.consumePurchase(3, getPackageName(), token); Log.d(getClass().getSimpleName(), "consumePurchase() : response - " + response); } catch (RemoteException e) { e.printStackTrace(); } } private void getAllSkus() { ArrayList<String> skuList = new ArrayList<>(); skuList.add("buy_one_beer"); skuList.add("buy_two_beers"); skuList.add("buy_four_beers"); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); try { Bundle skuDetails = mService.getSkuDetails(3, getPackageName(), ITEM_TYPE_INAPP, querySkus); int response = skuDetails.getInt(RESPONSE_CODE); if (response == BILLING_RESPONSE_RESULT_OK) { ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { JSONObject object; try { object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(getString(R.string.buy_one_beer))) { Log.d(getClass().getSimpleName(), "price - " + price); // mPremiumUpgradePrice = price; } else if (sku.equals(getString(R.string.buy_two_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } else if (sku.equals(getString(R.string.buy_four_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } } catch (JSONException e) { e.printStackTrace(); } } } } catch (RemoteException e) { e.printStackTrace(); } } private void getAllPurchases() { try { Bundle purchases = mService.getPurchases(3, getPackageName(), ITEM_TYPE_INAPP, INAPP_CONTINUATION_TOKEN); if (purchases.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { ArrayList mySkus, myPurchases, mySignatures; mySkus = purchases.getStringArrayList(RESPONSE_INAPP_ITEM_LIST); myPurchases = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST); mySignatures = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST); Log.d(getClass().getSimpleName(), "getAllPurchases() : purchases"); // handle items here } } catch (RemoteException e) { e.printStackTrace(); } } private void showCrouton(int colorRes, int messageRes) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, messageRes, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } private void showCrouton(int colorRes, String message) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, message, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } // endregion }
False
2,070
49880_4
/* * Geotoolkit.org - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2014, Geomatys * * 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; * version 2.1 of the License. * * 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. */ package org.geotoolkit.processing.coverage.shadedrelief; import org.apache.sis.parameter.ParameterBuilder; import org.geotoolkit.coverage.grid.GridCoverage2D; import org.geotoolkit.processing.AbstractProcessDescriptor; import org.geotoolkit.process.Process; import org.geotoolkit.process.ProcessDescriptor; import org.geotoolkit.processing.GeotkProcessingRegistry; import org.geotoolkit.processing.ProcessBundle; import org.opengis.parameter.ParameterDescriptor; import org.opengis.parameter.ParameterDescriptorGroup; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.operation.MathTransform1D; import org.opengis.util.InternationalString; /** * * @author Johann Sorel (Geomatys) */ public class ShadedReliefDescriptor extends AbstractProcessDescriptor { public static final String NAME = "coverage:shadedrelief"; public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract); /* * Coverage base image */ public static final String IN_COVERAGE_PARAM_NAME = "inCoverage"; public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage); public static final ParameterDescriptor<GridCoverage2D> COVERAGE = new ParameterBuilder() .addName(IN_COVERAGE_PARAM_NAME) .setRemarks(IN_COVERAGE_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /* * Coverage elevation */ public static final String IN_ELEVATION_PARAM_NAME = "inElevation"; public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation); public static final ParameterDescriptor<GridCoverage2D> ELEVATION = new ParameterBuilder() .addName(IN_ELEVATION_PARAM_NAME) .setRemarks(IN_ELEVATION_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /* * Coverage elevation value to meters */ public static final String IN_ELECONV_PARAM_NAME = "inEleEnv"; public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation); public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder() .addName(IN_ELECONV_PARAM_NAME) .setRemarks(IN_ELECONV_PARAM_REMARKS) .setRequired(true) .create(MathTransform1D.class, null); /**Input parameters */ public static final ParameterDescriptorGroup INPUT_DESC = new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV); /* * Coverage result */ public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage"; public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage); public static final ParameterDescriptor<GridCoverage2D> OUTCOVERAGE = new ParameterBuilder() .addName(OUT_COVERAGE_PARAM_NAME) .setRemarks(OUT_COVERAGE_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /**Output parameters */ public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE); public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor(); private ShadedReliefDescriptor() { super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC); } @Override public Process createProcess(final ParameterValueGroup input) { return new ShadedRelief(INSTANCE, input); } }
anttileppa/geotoolkit
modules/processing/geotk-processing/src/main/java/org/geotoolkit/processing/coverage/shadedrelief/ShadedReliefDescriptor.java
1,324
/* * Coverage elevation value to meters */
block_comment
nl
/* * Geotoolkit.org - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2014, Geomatys * * 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; * version 2.1 of the License. * * 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. */ package org.geotoolkit.processing.coverage.shadedrelief; import org.apache.sis.parameter.ParameterBuilder; import org.geotoolkit.coverage.grid.GridCoverage2D; import org.geotoolkit.processing.AbstractProcessDescriptor; import org.geotoolkit.process.Process; import org.geotoolkit.process.ProcessDescriptor; import org.geotoolkit.processing.GeotkProcessingRegistry; import org.geotoolkit.processing.ProcessBundle; import org.opengis.parameter.ParameterDescriptor; import org.opengis.parameter.ParameterDescriptorGroup; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.operation.MathTransform1D; import org.opengis.util.InternationalString; /** * * @author Johann Sorel (Geomatys) */ public class ShadedReliefDescriptor extends AbstractProcessDescriptor { public static final String NAME = "coverage:shadedrelief"; public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract); /* * Coverage base image */ public static final String IN_COVERAGE_PARAM_NAME = "inCoverage"; public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage); public static final ParameterDescriptor<GridCoverage2D> COVERAGE = new ParameterBuilder() .addName(IN_COVERAGE_PARAM_NAME) .setRemarks(IN_COVERAGE_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /* * Coverage elevation */ public static final String IN_ELEVATION_PARAM_NAME = "inElevation"; public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation); public static final ParameterDescriptor<GridCoverage2D> ELEVATION = new ParameterBuilder() .addName(IN_ELEVATION_PARAM_NAME) .setRemarks(IN_ELEVATION_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /* * Coverage elevation value<SUF>*/ public static final String IN_ELECONV_PARAM_NAME = "inEleEnv"; public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation); public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder() .addName(IN_ELECONV_PARAM_NAME) .setRemarks(IN_ELECONV_PARAM_REMARKS) .setRequired(true) .create(MathTransform1D.class, null); /**Input parameters */ public static final ParameterDescriptorGroup INPUT_DESC = new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV); /* * Coverage result */ public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage"; public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage); public static final ParameterDescriptor<GridCoverage2D> OUTCOVERAGE = new ParameterBuilder() .addName(OUT_COVERAGE_PARAM_NAME) .setRemarks(OUT_COVERAGE_PARAM_REMARKS) .setRequired(true) .create(GridCoverage2D.class, null); /**Output parameters */ public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE); public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor(); private ShadedReliefDescriptor() { super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC); } @Override public Process createProcess(final ParameterValueGroup input) { return new ShadedRelief(INSTANCE, input); } }
False
2,839
200247_32
/** * openHAB, the open Home Automation Bus. * Copyright (C) 2010-2013, openHAB.org <admin@openhab.org> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ 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; } }; /** 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 + "'"); } }
google-code-export/openhab
bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java
2,883
// in german Massentrom
line_comment
nl
/** * openHAB, the open Home Automation Bus. * Copyright (C) 2010-2013, openHAB.org <admin@openhab.org> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ 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; } }; /** 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 + "'"); } }
False
3,714
8823_0
package com.github.monkeywie.proxyee.util; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.util.AsciiString; public class HttpUtil { /** * 检测url是否匹配 */ public static boolean checkUrl(HttpRequest httpRequest, String regex) { String host = httpRequest.headers().get(HttpHeaderNames.HOST); if (host != null && regex != null) { String url; if (httpRequest.uri().indexOf("/") == 0) { if (httpRequest.uri().length() > 1) { url = host + httpRequest.uri(); } else { url = host; } } else { url = httpRequest.uri(); } return url.matches(regex); } return false; } /** * 检测头中的值是否为预期 * * @param httpHeaders * @param name * @param regex * @return */ public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) { String s = httpHeaders.get(name); return s != null && s.matches(regex); } /** * 检测是否为请求网页资源 */ public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) { String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT); String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE); return httpResponse.status().code() == 200 && accept != null && accept .matches("^.*text/html.*$") && contentType != null && contentType .matches("^text/html.*$"); } }
monkeyWie/proxyee
src/main/java/com/github/monkeywie/proxyee/util/HttpUtil.java
509
/** * 检测url是否匹配 */
block_comment
nl
package com.github.monkeywie.proxyee.util; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.util.AsciiString; public class HttpUtil { /** * 检测url是否匹配 <SUF>*/ public static boolean checkUrl(HttpRequest httpRequest, String regex) { String host = httpRequest.headers().get(HttpHeaderNames.HOST); if (host != null && regex != null) { String url; if (httpRequest.uri().indexOf("/") == 0) { if (httpRequest.uri().length() > 1) { url = host + httpRequest.uri(); } else { url = host; } } else { url = httpRequest.uri(); } return url.matches(regex); } return false; } /** * 检测头中的值是否为预期 * * @param httpHeaders * @param name * @param regex * @return */ public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) { String s = httpHeaders.get(name); return s != null && s.matches(regex); } /** * 检测是否为请求网页资源 */ public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) { String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT); String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE); return httpResponse.status().code() == 200 && accept != null && accept .matches("^.*text/html.*$") && contentType != null && contentType .matches("^text/html.*$"); } }
False
4,134
74020_0
package Controller; import Firebase.FirebaseActionObserver; import Firebase.FirebaseGameObserver; import Firebase.FirebaseGameService; import com.google.cloud.firestore.DocumentChange; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import javafx.application.Platform; import java.util.HashMap; import java.util.List; import java.util.Map; public class FirebaseGameController implements FirebaseActionObserver { private GameController gameCon; private FirebaseGameService service; private Map<String, FirebaseGameObserver> observers = new HashMap<>(); public FirebaseGameController(String gameName, GameController gameCon) { this.gameCon = gameCon; service = new FirebaseGameService(gameName); turnActionListener(this); } private void placeAction(Map<String, Object> map) { service.placeAction(getEventNumber(), map); } //Met 3 is het grootste aantal private String getEventNumber(){ String id = String.valueOf(service.getLastestEventNumber()); StringBuilder str = new StringBuilder(id); while(str.length() < 3) str.insert(0, "0"); return str.toString(); } public void nextPhaseAction() { Map<String, Object> map = new HashMap<>(); map.put("division", "phase"); map.put("id", "nextPhase"); map.put("action", "nextPhase"); placeAction(map); } public void buyCombiAction(int number) { Map<String, Object> map = new HashMap<>(); map.put("division", "shop"); map.put("id", "buy"); map.put("item", number); placeAction(map); } public void addCombiAction(String race, String power) { Map<String, Object> map = new HashMap<>(); map.put("division", "shop"); map.put("id", "add"); map.put("race", race); map.put("power", power); placeAction(map); } public void attackAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "attack"); map.put("areaId", areaId); placeAction(map); } public void addsFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "add"); map.put("areaId", areaId); placeAction(map); } public void removeFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "remove"); map.put("areaId", areaId); placeAction(map); } public void leavesFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "leaves"); map.put("areaId", areaId); placeAction(map); } public void declineAction() { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "decline"); map.put("action", "decline"); placeAction(map); } private void turnActionListener(final FirebaseActionObserver controller) { service.actionListener(controller); } public void register(String id, FirebaseGameObserver observer) { observers.put(id, observer); } @Override public void update(QuerySnapshot qs) { List<DocumentChange> updateList = qs.getDocumentChanges(); for (DocumentChange documentChange : updateList) { DocumentSnapshot doc = documentChange.getDocument(); System.out.println("Id: " + doc.getId()); System.out.println(doc.getData()); Platform.runLater(() -> observers.get(doc.getString("division")).update(doc)); } } }
realDragonium/SmallWorld3D
src/main/java/Controller/FirebaseGameController.java
1,106
//Met 3 is het grootste aantal
line_comment
nl
package Controller; import Firebase.FirebaseActionObserver; import Firebase.FirebaseGameObserver; import Firebase.FirebaseGameService; import com.google.cloud.firestore.DocumentChange; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import javafx.application.Platform; import java.util.HashMap; import java.util.List; import java.util.Map; public class FirebaseGameController implements FirebaseActionObserver { private GameController gameCon; private FirebaseGameService service; private Map<String, FirebaseGameObserver> observers = new HashMap<>(); public FirebaseGameController(String gameName, GameController gameCon) { this.gameCon = gameCon; service = new FirebaseGameService(gameName); turnActionListener(this); } private void placeAction(Map<String, Object> map) { service.placeAction(getEventNumber(), map); } //Met 3<SUF> private String getEventNumber(){ String id = String.valueOf(service.getLastestEventNumber()); StringBuilder str = new StringBuilder(id); while(str.length() < 3) str.insert(0, "0"); return str.toString(); } public void nextPhaseAction() { Map<String, Object> map = new HashMap<>(); map.put("division", "phase"); map.put("id", "nextPhase"); map.put("action", "nextPhase"); placeAction(map); } public void buyCombiAction(int number) { Map<String, Object> map = new HashMap<>(); map.put("division", "shop"); map.put("id", "buy"); map.put("item", number); placeAction(map); } public void addCombiAction(String race, String power) { Map<String, Object> map = new HashMap<>(); map.put("division", "shop"); map.put("id", "add"); map.put("race", race); map.put("power", power); placeAction(map); } public void attackAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "attack"); map.put("areaId", areaId); placeAction(map); } public void addsFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "add"); map.put("areaId", areaId); placeAction(map); } public void removeFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "remove"); map.put("areaId", areaId); placeAction(map); } public void leavesFicheAction(String areaId) { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "leaves"); map.put("areaId", areaId); placeAction(map); } public void declineAction() { Map<String, Object> map = new HashMap<>(); map.put("division", "currentplayer"); map.put("id", "decline"); map.put("action", "decline"); placeAction(map); } private void turnActionListener(final FirebaseActionObserver controller) { service.actionListener(controller); } public void register(String id, FirebaseGameObserver observer) { observers.put(id, observer); } @Override public void update(QuerySnapshot qs) { List<DocumentChange> updateList = qs.getDocumentChanges(); for (DocumentChange documentChange : updateList) { DocumentSnapshot doc = documentChange.getDocument(); System.out.println("Id: " + doc.getId()); System.out.println(doc.getData()); Platform.runLater(() -> observers.get(doc.getString("division")).update(doc)); } } }
True
2,243
42419_13
package org.beykery.eu.event; import io.reactivex.Flowable; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.beykery.eu.util.EthContractUtil; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.web3j.abi.datatypes.Event; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.response.EthBlock; import org.web3j.protocol.core.methods.response.EthChainId; import org.web3j.protocol.core.methods.response.Transaction; import org.web3j.protocol.geth.Geth; import org.web3j.protocol.websocket.events.PendingTransactionNotification; import java.io.IOException; import java.math.BigInteger; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; /** * scan log event */ @Slf4j public class LogEventScanner implements Runnable { /** * eth 主网nft mint事件最早块高 */ public static final long MIN_ETH_MAINNET_NFT_MINT_HEIGHT = 937821L; /** * 监听 */ private final LogEventListener listener; /** * web3j */ private Geth web3j; /** * for pending transactions */ private Geth pxWeb3j; /** * scan start * -- GETTER -- * scanning * * @return */ @Getter private volatile boolean scanning; /** * pending */ private volatile boolean pending; /** * queue for hash */ private final LinkedBlockingDeque<PendingHash> pendingQueue; /** * 事件 */ private List<Event> events; /** * from block */ private long from; /** * 爬取的合约集合 */ private List<String> contracts; /** * 是否从tx中分析log */ private final boolean logFromTx; /** * 出块间隔(ms) */ private final long blockInterval; /** * pending interval */ private final long pendingInterval; /** * pending max delay, greater than 0 and no longer than blockInterval */ private final long pendingMaxDelay; /** * pending tx parallel */ private final int pendingParallel; /** * pending tx batch size */ private final int pendingBatchSize; /** * 当前高 * -- GETTER -- * 当前块高 * * @return */ @Getter private long current; /** * 当前高度的时间(second) * -- GETTER -- * 当前块高时间(second) * * @return */ @Getter private long currentTime; /** * 块高提供者 */ private CurrentBlockProvider currentBlockProvider; /** * 统计平均出块间隔,计算滑动平均值(ms) * -- GETTER -- * 平均出块间隔(ms) * * @return */ @Getter private long averageBlockInterval; /** * 敏感因子,新块间隔在均值里的比重 */ private double sensitivity; /** * 固定步长 */ private long step; /** * 最多重试次数 */ private final int maxRetry; /** * retry sleep (ms) */ private final long retryInterval; /** * log event scanner * * @param web3j * @param blockInterval * @param pendingInterval * @param pendingParallel * @param pendingBatchSize * @param maxRetry * @param retryInterval * @param logFromTx * @param listener */ public LogEventScanner( Geth web3j, Geth pxWeb3j, long blockInterval, long pendingInterval, long pendingMaxDelay, int pendingParallel, int pendingBatchSize, int maxRetry, long retryInterval, boolean logFromTx, LogEventListener listener ) { this.web3j = web3j; this.pxWeb3j = pxWeb3j == null ? web3j : pxWeb3j; this.blockInterval = blockInterval; this.listener = listener; this.maxRetry = maxRetry; this.retryInterval = retryInterval; this.logFromTx = logFromTx; this.pendingInterval = pendingInterval; this.pendingMaxDelay = pendingMaxDelay <= 0 ? blockInterval : pendingMaxDelay; this.pendingParallel = pendingParallel; this.pendingBatchSize = pendingBatchSize <= 0 ? 1 : pendingBatchSize; this.pendingQueue = new LinkedBlockingDeque<>(); } /** * start * * @param from * @param events * @param contracts * @param currentBlockProvider * @param sensitivity * @param step * @return */ public boolean start( long from, List<Event> events, List<String> contracts, CurrentBlockProvider currentBlockProvider, double sensitivity, long step ) { if (currentBlockProvider == null) { currentBlockProvider = () -> { EthBlock block = web3j.ethGetBlockByNumber(DefaultBlockParameterName.fromString("latest"), false).send(); long current = block.getBlock().getNumber().longValue(); long currentTime = block.getBlock().getTimestamp().longValue(); return new long[]{current, currentTime}; }; } this.currentBlockProvider = currentBlockProvider; this.sensitivity = sensitivity <= 0 || sensitivity >= 1 ? 1.0 / 4 : sensitivity; this.averageBlockInterval = blockInterval * 1000; if (!scanning) { scanning = true; this.events = events; this.from = from; this.step = step; this.contracts = contracts; // 尝试启动pending if (pendingInterval > 0) { startPending(); } Thread thread = new Thread(this); thread.setName("thread - event"); thread.start(); } return scanning; } /** * lock for pending txs */ private static final Object PX_LOCK = new Object(); /** * 尝试启动pending */ public void startPending() { if (!pending) { pending = true; Runnable run = () -> { try { Flowable<PendingTransactionNotification> f = pxWeb3j.newPendingTransactionsNotifications(); f.blockingForEach(item -> { String hash = item.getParams().getResult(); boolean processed = this.listener.onPendingTransactionHash(hash, this.current, this.currentTime); if (!processed) { pendingQueue.offer(new PendingHash(hash, System.currentTimeMillis(), true)); synchronized (PX_LOCK) { PX_LOCK.notifyAll(); } } }); } catch (WebsocketNotConnectedException ex) { pending = false; log.error("websocket connection broken", ex); this.listener.onWebsocketBroken(ex, current, currentTime); } catch (Throwable ex) { pending = false; this.listener.onPendingError(ex, this.current, this.currentTime); } log.error("pending quited. "); }; Thread thread = new Thread(run); thread.setName("thread - pending"); thread.start(); } } /** * 停止pending */ public void stopPending() { this.pending = false; } /** * stop scan */ public void stop() { this.scanning = false; this.pending = false; } /** * @return */ public BigInteger chainId() throws IOException { EthChainId cd = web3j.ethChainId().send(); return cd.getChainId(); } /** * 是否为eth主网 * * @return */ public boolean isEthMainnet() throws IOException { return chainId().equals(BigInteger.ONE); } /** * scan */ @Override public void run() { try { long[] c = this.currentBlockProvider.currentBlockNumberAndTimestamp(); current = c[0]; currentTime = c[1]; } catch (Exception ex) { scanning = false; throw new RuntimeException(ex); } from = from < 0 ? current : from; // from long step = 1; // 步长 long f = from; // 起始位置 while (scanning) { if (this.step > 0) { step = this.step; } long t = Math.min(f + step - 1, current); if (f <= t) { List<LogEvent> les = null; int retry = 0; int maxRetry = this.maxRetry; while ((les == null || les.isEmpty()) && (retry <= 0 || retry <= maxRetry)) { try { les = EthContractUtil.getLogEvents(web3j, f, t, events, contracts, logFromTx); if (les.isEmpty()) { retry++; if (retry <= maxRetry) { try { Thread.sleep(retryInterval); } catch (Exception x) { } } } else if (retry > 0) { // retry 后成功 log.info("fetch {} logs success from {} to {} with {} retry", les.size(), f, t, retry); } } catch (Throwable ex) { retry++; maxRetry = Math.max(this.maxRetry, 1); log.error("fetch logs error from {} to {} with {} retry", f, t, retry); listener.onError(ex, f, t, current, currentTime); step = 1; if (retry <= maxRetry) { try { Thread.sleep(retryInterval); } catch (Exception x) { } } } } les = les == null ? Collections.EMPTY_LIST : les; long logSize = les.size(); // 用来调整步长 if (logSize > 0 && listener.reverse()) { Collections.reverse(les); } // 通知 listener.onLogEvents(les, f, t, current, currentTime); listener.onOnceScanOver(f, t, current, currentTime, logSize); f = t + 1; // step adjust long targetSize = 1024 * 4; long maxStep = 1024; long rate = 60; step = logSize > 0 ? ((step * targetSize / logSize) * rate + step * (100 - rate)) / 100 : step + 1; step = step < 1 ? 1 : (Math.min(step, maxStep)); } // reach 't' height else { listener.onReachHighest(t); step = 1; } long next = currentTime * 1000 + blockInterval; // 下次出块时间 if (pendingInterval >= 0) { do { // pending tx List<PendingTransaction> pendingTxs = pendingTxs(); if (pendingTxs != null && !pendingTxs.isEmpty()) { listener.onPendingTransactions(pendingTxs, current, currentTime); } long now = System.currentTimeMillis(); if (now < next) { long maxSleep = next - now; synchronized (PX_LOCK) { try { PX_LOCK.wait(maxSleep); } catch (Throwable th) { log.error("PX_LOCK wait error", th); } } } } while (System.currentTimeMillis() - next + blockInterval < pendingMaxDelay); } // 等待下一个块到来 long delta = next - System.currentTimeMillis(); if (delta > 0) { synchronized (PX_LOCK) { try { PX_LOCK.wait(delta); } catch (Throwable th) { log.error("PX_LOCK wait error", th); } } } // 求当前最高块 try { long[] c = this.currentBlockProvider.currentBlockNumberAndTimestamp(); if (c[0] > current) { this.averageBlockInterval = (long) (this.averageBlockInterval * (1 - sensitivity) + 1000.0 * (c[1] - currentTime) / (c[0] - current) * sensitivity); current = c[0]; currentTime = c[1]; } else if (c[0] < current) { log.debug("block {} less than current block {}, ignore it .", c[0], current); Thread.sleep(1); } } catch (WebsocketNotConnectedException ex) { log.error("websocket connection broken", ex); this.listener.onWebsocketBroken(ex, current, currentTime); } catch (Throwable e) { log.error("fetch the current block number and timestamp failed", e); } } } private BigInteger fid; /** * pending txs * * @return */ private List<PendingTransaction> pendingTxs() { if (pending) { Map<String, PendingHash> hash = new HashMap<>(); while (!pendingQueue.isEmpty()) { PendingHash ph = pendingQueue.remove(); hash.put(ph.getHash().toLowerCase(), ph); } if (!hash.isEmpty()) { List<org.web3j.protocol.core.methods.response.Transaction> txs = EthContractUtil.pendingTransactions(pxWeb3j, new ArrayList<>(hash.keySet()), pendingParallel <= 0 ? 3 : pendingParallel, pendingBatchSize); return txs.stream().map(item -> { String h = item.getHash().toLowerCase(); PendingHash ph = hash.get(h); if (ph == null) { return new PendingTransaction(item, System.currentTimeMillis(), true); } else { return new PendingTransaction(item, ph.getTime(), ph.isFromWs()); } }).toList(); } else { return Collections.EMPTY_LIST; } } else { try { if (fid == null) { fid = EthContractUtil.newPendingTransactionFilterId(web3j); } return EthContractUtil.pendingTransactions(web3j, fid, pendingParallel <= 0 ? 3 : pendingParallel, pendingBatchSize); } catch (Exception ex) { log.error("fetch pending transactions error", ex); fid = null; return Collections.EMPTY_LIST; } } } /** * 重新连接 */ public void reconnect(Geth web3j) { this.pxWeb3j = web3j; this.startPending(); } }
beykery/eu
src/main/java/org/beykery/eu/event/LogEventScanner.java
4,228
/** * pending interval */
block_comment
nl
package org.beykery.eu.event; import io.reactivex.Flowable; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.beykery.eu.util.EthContractUtil; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.web3j.abi.datatypes.Event; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.response.EthBlock; import org.web3j.protocol.core.methods.response.EthChainId; import org.web3j.protocol.core.methods.response.Transaction; import org.web3j.protocol.geth.Geth; import org.web3j.protocol.websocket.events.PendingTransactionNotification; import java.io.IOException; import java.math.BigInteger; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; /** * scan log event */ @Slf4j public class LogEventScanner implements Runnable { /** * eth 主网nft mint事件最早块高 */ public static final long MIN_ETH_MAINNET_NFT_MINT_HEIGHT = 937821L; /** * 监听 */ private final LogEventListener listener; /** * web3j */ private Geth web3j; /** * for pending transactions */ private Geth pxWeb3j; /** * scan start * -- GETTER -- * scanning * * @return */ @Getter private volatile boolean scanning; /** * pending */ private volatile boolean pending; /** * queue for hash */ private final LinkedBlockingDeque<PendingHash> pendingQueue; /** * 事件 */ private List<Event> events; /** * from block */ private long from; /** * 爬取的合约集合 */ private List<String> contracts; /** * 是否从tx中分析log */ private final boolean logFromTx; /** * 出块间隔(ms) */ private final long blockInterval; /** * pending interval <SUF>*/ private final long pendingInterval; /** * pending max delay, greater than 0 and no longer than blockInterval */ private final long pendingMaxDelay; /** * pending tx parallel */ private final int pendingParallel; /** * pending tx batch size */ private final int pendingBatchSize; /** * 当前高 * -- GETTER -- * 当前块高 * * @return */ @Getter private long current; /** * 当前高度的时间(second) * -- GETTER -- * 当前块高时间(second) * * @return */ @Getter private long currentTime; /** * 块高提供者 */ private CurrentBlockProvider currentBlockProvider; /** * 统计平均出块间隔,计算滑动平均值(ms) * -- GETTER -- * 平均出块间隔(ms) * * @return */ @Getter private long averageBlockInterval; /** * 敏感因子,新块间隔在均值里的比重 */ private double sensitivity; /** * 固定步长 */ private long step; /** * 最多重试次数 */ private final int maxRetry; /** * retry sleep (ms) */ private final long retryInterval; /** * log event scanner * * @param web3j * @param blockInterval * @param pendingInterval * @param pendingParallel * @param pendingBatchSize * @param maxRetry * @param retryInterval * @param logFromTx * @param listener */ public LogEventScanner( Geth web3j, Geth pxWeb3j, long blockInterval, long pendingInterval, long pendingMaxDelay, int pendingParallel, int pendingBatchSize, int maxRetry, long retryInterval, boolean logFromTx, LogEventListener listener ) { this.web3j = web3j; this.pxWeb3j = pxWeb3j == null ? web3j : pxWeb3j; this.blockInterval = blockInterval; this.listener = listener; this.maxRetry = maxRetry; this.retryInterval = retryInterval; this.logFromTx = logFromTx; this.pendingInterval = pendingInterval; this.pendingMaxDelay = pendingMaxDelay <= 0 ? blockInterval : pendingMaxDelay; this.pendingParallel = pendingParallel; this.pendingBatchSize = pendingBatchSize <= 0 ? 1 : pendingBatchSize; this.pendingQueue = new LinkedBlockingDeque<>(); } /** * start * * @param from * @param events * @param contracts * @param currentBlockProvider * @param sensitivity * @param step * @return */ public boolean start( long from, List<Event> events, List<String> contracts, CurrentBlockProvider currentBlockProvider, double sensitivity, long step ) { if (currentBlockProvider == null) { currentBlockProvider = () -> { EthBlock block = web3j.ethGetBlockByNumber(DefaultBlockParameterName.fromString("latest"), false).send(); long current = block.getBlock().getNumber().longValue(); long currentTime = block.getBlock().getTimestamp().longValue(); return new long[]{current, currentTime}; }; } this.currentBlockProvider = currentBlockProvider; this.sensitivity = sensitivity <= 0 || sensitivity >= 1 ? 1.0 / 4 : sensitivity; this.averageBlockInterval = blockInterval * 1000; if (!scanning) { scanning = true; this.events = events; this.from = from; this.step = step; this.contracts = contracts; // 尝试启动pending if (pendingInterval > 0) { startPending(); } Thread thread = new Thread(this); thread.setName("thread - event"); thread.start(); } return scanning; } /** * lock for pending txs */ private static final Object PX_LOCK = new Object(); /** * 尝试启动pending */ public void startPending() { if (!pending) { pending = true; Runnable run = () -> { try { Flowable<PendingTransactionNotification> f = pxWeb3j.newPendingTransactionsNotifications(); f.blockingForEach(item -> { String hash = item.getParams().getResult(); boolean processed = this.listener.onPendingTransactionHash(hash, this.current, this.currentTime); if (!processed) { pendingQueue.offer(new PendingHash(hash, System.currentTimeMillis(), true)); synchronized (PX_LOCK) { PX_LOCK.notifyAll(); } } }); } catch (WebsocketNotConnectedException ex) { pending = false; log.error("websocket connection broken", ex); this.listener.onWebsocketBroken(ex, current, currentTime); } catch (Throwable ex) { pending = false; this.listener.onPendingError(ex, this.current, this.currentTime); } log.error("pending quited. "); }; Thread thread = new Thread(run); thread.setName("thread - pending"); thread.start(); } } /** * 停止pending */ public void stopPending() { this.pending = false; } /** * stop scan */ public void stop() { this.scanning = false; this.pending = false; } /** * @return */ public BigInteger chainId() throws IOException { EthChainId cd = web3j.ethChainId().send(); return cd.getChainId(); } /** * 是否为eth主网 * * @return */ public boolean isEthMainnet() throws IOException { return chainId().equals(BigInteger.ONE); } /** * scan */ @Override public void run() { try { long[] c = this.currentBlockProvider.currentBlockNumberAndTimestamp(); current = c[0]; currentTime = c[1]; } catch (Exception ex) { scanning = false; throw new RuntimeException(ex); } from = from < 0 ? current : from; // from long step = 1; // 步长 long f = from; // 起始位置 while (scanning) { if (this.step > 0) { step = this.step; } long t = Math.min(f + step - 1, current); if (f <= t) { List<LogEvent> les = null; int retry = 0; int maxRetry = this.maxRetry; while ((les == null || les.isEmpty()) && (retry <= 0 || retry <= maxRetry)) { try { les = EthContractUtil.getLogEvents(web3j, f, t, events, contracts, logFromTx); if (les.isEmpty()) { retry++; if (retry <= maxRetry) { try { Thread.sleep(retryInterval); } catch (Exception x) { } } } else if (retry > 0) { // retry 后成功 log.info("fetch {} logs success from {} to {} with {} retry", les.size(), f, t, retry); } } catch (Throwable ex) { retry++; maxRetry = Math.max(this.maxRetry, 1); log.error("fetch logs error from {} to {} with {} retry", f, t, retry); listener.onError(ex, f, t, current, currentTime); step = 1; if (retry <= maxRetry) { try { Thread.sleep(retryInterval); } catch (Exception x) { } } } } les = les == null ? Collections.EMPTY_LIST : les; long logSize = les.size(); // 用来调整步长 if (logSize > 0 && listener.reverse()) { Collections.reverse(les); } // 通知 listener.onLogEvents(les, f, t, current, currentTime); listener.onOnceScanOver(f, t, current, currentTime, logSize); f = t + 1; // step adjust long targetSize = 1024 * 4; long maxStep = 1024; long rate = 60; step = logSize > 0 ? ((step * targetSize / logSize) * rate + step * (100 - rate)) / 100 : step + 1; step = step < 1 ? 1 : (Math.min(step, maxStep)); } // reach 't' height else { listener.onReachHighest(t); step = 1; } long next = currentTime * 1000 + blockInterval; // 下次出块时间 if (pendingInterval >= 0) { do { // pending tx List<PendingTransaction> pendingTxs = pendingTxs(); if (pendingTxs != null && !pendingTxs.isEmpty()) { listener.onPendingTransactions(pendingTxs, current, currentTime); } long now = System.currentTimeMillis(); if (now < next) { long maxSleep = next - now; synchronized (PX_LOCK) { try { PX_LOCK.wait(maxSleep); } catch (Throwable th) { log.error("PX_LOCK wait error", th); } } } } while (System.currentTimeMillis() - next + blockInterval < pendingMaxDelay); } // 等待下一个块到来 long delta = next - System.currentTimeMillis(); if (delta > 0) { synchronized (PX_LOCK) { try { PX_LOCK.wait(delta); } catch (Throwable th) { log.error("PX_LOCK wait error", th); } } } // 求当前最高块 try { long[] c = this.currentBlockProvider.currentBlockNumberAndTimestamp(); if (c[0] > current) { this.averageBlockInterval = (long) (this.averageBlockInterval * (1 - sensitivity) + 1000.0 * (c[1] - currentTime) / (c[0] - current) * sensitivity); current = c[0]; currentTime = c[1]; } else if (c[0] < current) { log.debug("block {} less than current block {}, ignore it .", c[0], current); Thread.sleep(1); } } catch (WebsocketNotConnectedException ex) { log.error("websocket connection broken", ex); this.listener.onWebsocketBroken(ex, current, currentTime); } catch (Throwable e) { log.error("fetch the current block number and timestamp failed", e); } } } private BigInteger fid; /** * pending txs * * @return */ private List<PendingTransaction> pendingTxs() { if (pending) { Map<String, PendingHash> hash = new HashMap<>(); while (!pendingQueue.isEmpty()) { PendingHash ph = pendingQueue.remove(); hash.put(ph.getHash().toLowerCase(), ph); } if (!hash.isEmpty()) { List<org.web3j.protocol.core.methods.response.Transaction> txs = EthContractUtil.pendingTransactions(pxWeb3j, new ArrayList<>(hash.keySet()), pendingParallel <= 0 ? 3 : pendingParallel, pendingBatchSize); return txs.stream().map(item -> { String h = item.getHash().toLowerCase(); PendingHash ph = hash.get(h); if (ph == null) { return new PendingTransaction(item, System.currentTimeMillis(), true); } else { return new PendingTransaction(item, ph.getTime(), ph.isFromWs()); } }).toList(); } else { return Collections.EMPTY_LIST; } } else { try { if (fid == null) { fid = EthContractUtil.newPendingTransactionFilterId(web3j); } return EthContractUtil.pendingTransactions(web3j, fid, pendingParallel <= 0 ? 3 : pendingParallel, pendingBatchSize); } catch (Exception ex) { log.error("fetch pending transactions error", ex); fid = null; return Collections.EMPTY_LIST; } } } /** * 重新连接 */ public void reconnect(Geth web3j) { this.pxWeb3j = web3j; this.startPending(); } }
False
2,725
206820_5
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods *************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods *************************************************************************/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
fracpete/princeton-java-algorithms
src/main/java/edu/princeton/cs/algorithms/RedBlackBST.java
5,595
/************************************************************************* * Node helper methods *************************************************************************/
block_comment
nl
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods<SUF>*/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods *************************************************************************/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
False
1,683
174029_21
package Graph; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Float; import java.io.Serializable; import org.openstreetmap.gui.jmapviewer.Coordinate; import allgemein.Konstanten; public class Kante implements Serializable, Comparable<Kante> { private static final long serialVersionUID = 3225424268243577145L; // StartKnoten private final Knoten from; // EndKnoten private final Knoten to; // Abstand der Start und Endknoten in Metern private float abstand; private Point2D.Float midPoint; private String typ; private boolean gesperrt; private boolean erreichbar; private float plastikMenge = 0f; private float restMenge = 0f; private float papierMenge = 0f; private float bioMenge = 0f; private float muellmenge = 0f; public int id; public Kante(Knoten from, Knoten to, boolean gesperrt, String typ) { this.from = from; this.to = to; this.abstand = Kante.CalcDistance(from, to); this.gesperrt = gesperrt; this.typ = typ; this.calcMidPoint(); this.calcMuellmenge(); } // TODO Methode verteileMuell, die für jede Muellart den float Wert auf den // Wert dert Variable muellmenge setzt public void calcMuellmenge() { this.muellmenge = Konstanten.getMengeTyp(this.typ) * this.abstand; this.plastikMenge = muellmenge; this.restMenge = muellmenge; this.bioMenge = muellmenge; this.papierMenge = muellmenge; } public void addMuell(float muell) { this.muellmenge += muell; this.bioMenge += muell; this.papierMenge += muell; this.plastikMenge += muell; this.restMenge += muell; } /** * Liefert die Menge fuer eine bestimmte Muellart (bei einem leeren String * wird das Attribut muellMenge zurueckgeliefert) * * @param muellArt * @return die Menge einer bestimmten Muellart */ public float getMuellMengeArt(String muellArt) { if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) { return plastikMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) { return restMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) { return papierMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) { return bioMenge; } else { return this.muellmenge; } } public void setMuellMengeArt(float muellMenge, String muellArt) { if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) { this.plastikMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) { this.restMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) { this.papierMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) { this.bioMenge = muellMenge; } else { this.muellmenge = muellMenge; } } public void setMuellMengeAll(float muellMenge) { this.muellmenge = muellMenge; this.bioMenge = muellMenge; this.papierMenge = muellMenge; this.plastikMenge = muellMenge; this.restMenge = muellMenge; } public void setTyp(String typ) { this.typ = typ; } public String getTyp() { return this.typ; } public void setGeperrt(boolean gesperrt) { this.gesperrt = gesperrt; } public boolean getGesperrt() { return this.gesperrt; } public void setErreichbar(boolean erreichbar) { this.erreichbar = erreichbar; } public boolean getErreichbar() { return this.erreichbar; } public Knoten getTo() { return this.to; } public Knoten getFrom() { return this.from; } public float getAbstand() { return this.abstand; } public void setAbstand(float abstand) { this.abstand = abstand; } public Point2D.Float getMidPoint() { return this.midPoint; } public void calcMidPoint() { this.midPoint = new Point2D.Float((this.getTo().getLat() + this .getFrom().getLat()) / 2, (this.getTo().getLon() + this .getFrom().getLon()) / 2); } public Knoten getOther(Knoten knoten) { if (knoten == from) return to; else if (knoten == to) return from; else return null; } static private float CalcDistance(Knoten from, Knoten to) { final int R = 6371; // Radius of the earth float lat1 = from.getLat(); float lon1 = from.getLon(); float lat2 = to.getLat(); float lon2 = to.getLon(); Double latDistance = toRad(lat2 - lat1); Double lonDistance = toRad(lon2 - lon1); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); float abstand = (float) (R * c) * 1000; return abstand; } private static Double toRad(float value) { return value * Math.PI / 180; } @Override public String toString() { StringBuilder result = new StringBuilder(); // result.append("[[abstand=" + this.abstand + "] [typ=" + this.typ // + "] [erreichbar=" + this.erreichbar + "] [zu=" + this.gesperrt // + "]]\n"); result.append(" " + to + "\n"); result.append(" " + from + "\n"); return result.toString(); } @Override public int compareTo(Kante k) { if (this.getAbstand() == k.getAbstand()) return 0; else if (this.getAbstand() > k.getAbstand()) return 1; else return -1; } } // TODO vor Release entfernen, wenn nicht benoetigt // public void writeExternal(ObjectOutput out) { // try { // System.out.println("Coming into the writeExternal of Kante :"); // out.writeFloat(abstand); // out.writeObject(typ); // out.writeBoolean(gesperrt); // out.writeBoolean(erreichbar); // out.writeBoolean(besucht); // out.writeFloat(plastikMenge); // out.writeFloat(restMenge); // out.writeFloat(papierMenge); // out.writeFloat(bioMenge); // out.writeFloat(muellmenge); // out.writeInt(id); // // // out.writeObject(innerObject); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void readExternal(ObjectInput in) { // try { // System.out.println("Coming into the readExternal of Kante:"); // // min = (Point2D.Float) in.readObject(); // max = (Point2D.Float) in.readObject(); // // // knoten = (ArrayList<Knoten>) in.readObject(); // int knotenAnzahl = in.readInt(); // knoten.clear(); // for (int i = 0; i < knotenAnzahl; i++) { // knoten.add((Knoten) in.readObject()); // } // // plastik = (Knoten) in.readObject(); // papier = (Knoten) in.readObject(); // rest = (Knoten) in.readObject(); // bio = (Knoten) in.readObject(); // depot = (Knoten) in.readObject(); // // // innerObject=(Obj)in.readObject(); // } catch (Exception e) { // e.printStackTrace(); // } // }
Tandrial/AI-SE-Bsc
SEP_SoSe13/Abnahme/SourceCode/Graph/Kante.java
2,508
// bio = (Knoten) in.readObject();
line_comment
nl
package Graph; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Float; import java.io.Serializable; import org.openstreetmap.gui.jmapviewer.Coordinate; import allgemein.Konstanten; public class Kante implements Serializable, Comparable<Kante> { private static final long serialVersionUID = 3225424268243577145L; // StartKnoten private final Knoten from; // EndKnoten private final Knoten to; // Abstand der Start und Endknoten in Metern private float abstand; private Point2D.Float midPoint; private String typ; private boolean gesperrt; private boolean erreichbar; private float plastikMenge = 0f; private float restMenge = 0f; private float papierMenge = 0f; private float bioMenge = 0f; private float muellmenge = 0f; public int id; public Kante(Knoten from, Knoten to, boolean gesperrt, String typ) { this.from = from; this.to = to; this.abstand = Kante.CalcDistance(from, to); this.gesperrt = gesperrt; this.typ = typ; this.calcMidPoint(); this.calcMuellmenge(); } // TODO Methode verteileMuell, die für jede Muellart den float Wert auf den // Wert dert Variable muellmenge setzt public void calcMuellmenge() { this.muellmenge = Konstanten.getMengeTyp(this.typ) * this.abstand; this.plastikMenge = muellmenge; this.restMenge = muellmenge; this.bioMenge = muellmenge; this.papierMenge = muellmenge; } public void addMuell(float muell) { this.muellmenge += muell; this.bioMenge += muell; this.papierMenge += muell; this.plastikMenge += muell; this.restMenge += muell; } /** * Liefert die Menge fuer eine bestimmte Muellart (bei einem leeren String * wird das Attribut muellMenge zurueckgeliefert) * * @param muellArt * @return die Menge einer bestimmten Muellart */ public float getMuellMengeArt(String muellArt) { if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) { return plastikMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) { return restMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) { return papierMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) { return bioMenge; } else { return this.muellmenge; } } public void setMuellMengeArt(float muellMenge, String muellArt) { if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) { this.plastikMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) { this.restMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) { this.papierMenge = muellMenge; } else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) { this.bioMenge = muellMenge; } else { this.muellmenge = muellMenge; } } public void setMuellMengeAll(float muellMenge) { this.muellmenge = muellMenge; this.bioMenge = muellMenge; this.papierMenge = muellMenge; this.plastikMenge = muellMenge; this.restMenge = muellMenge; } public void setTyp(String typ) { this.typ = typ; } public String getTyp() { return this.typ; } public void setGeperrt(boolean gesperrt) { this.gesperrt = gesperrt; } public boolean getGesperrt() { return this.gesperrt; } public void setErreichbar(boolean erreichbar) { this.erreichbar = erreichbar; } public boolean getErreichbar() { return this.erreichbar; } public Knoten getTo() { return this.to; } public Knoten getFrom() { return this.from; } public float getAbstand() { return this.abstand; } public void setAbstand(float abstand) { this.abstand = abstand; } public Point2D.Float getMidPoint() { return this.midPoint; } public void calcMidPoint() { this.midPoint = new Point2D.Float((this.getTo().getLat() + this .getFrom().getLat()) / 2, (this.getTo().getLon() + this .getFrom().getLon()) / 2); } public Knoten getOther(Knoten knoten) { if (knoten == from) return to; else if (knoten == to) return from; else return null; } static private float CalcDistance(Knoten from, Knoten to) { final int R = 6371; // Radius of the earth float lat1 = from.getLat(); float lon1 = from.getLon(); float lat2 = to.getLat(); float lon2 = to.getLon(); Double latDistance = toRad(lat2 - lat1); Double lonDistance = toRad(lon2 - lon1); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); float abstand = (float) (R * c) * 1000; return abstand; } private static Double toRad(float value) { return value * Math.PI / 180; } @Override public String toString() { StringBuilder result = new StringBuilder(); // result.append("[[abstand=" + this.abstand + "] [typ=" + this.typ // + "] [erreichbar=" + this.erreichbar + "] [zu=" + this.gesperrt // + "]]\n"); result.append(" " + to + "\n"); result.append(" " + from + "\n"); return result.toString(); } @Override public int compareTo(Kante k) { if (this.getAbstand() == k.getAbstand()) return 0; else if (this.getAbstand() > k.getAbstand()) return 1; else return -1; } } // TODO vor Release entfernen, wenn nicht benoetigt // public void writeExternal(ObjectOutput out) { // try { // System.out.println("Coming into the writeExternal of Kante :"); // out.writeFloat(abstand); // out.writeObject(typ); // out.writeBoolean(gesperrt); // out.writeBoolean(erreichbar); // out.writeBoolean(besucht); // out.writeFloat(plastikMenge); // out.writeFloat(restMenge); // out.writeFloat(papierMenge); // out.writeFloat(bioMenge); // out.writeFloat(muellmenge); // out.writeInt(id); // // // out.writeObject(innerObject); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void readExternal(ObjectInput in) { // try { // System.out.println("Coming into the readExternal of Kante:"); // // min = (Point2D.Float) in.readObject(); // max = (Point2D.Float) in.readObject(); // // // knoten = (ArrayList<Knoten>) in.readObject(); // int knotenAnzahl = in.readInt(); // knoten.clear(); // for (int i = 0; i < knotenAnzahl; i++) { // knoten.add((Knoten) in.readObject()); // } // // plastik = (Knoten) in.readObject(); // papier = (Knoten) in.readObject(); // rest = (Knoten) in.readObject(); // bio =<SUF> // depot = (Knoten) in.readObject(); // // // innerObject=(Obj)in.readObject(); // } catch (Exception e) { // e.printStackTrace(); // } // }
False
1,546
95112_3
package simu.test;_x000D_ import simu.eduni.distributions.Normal;_x000D_ import simu.framework.Kello;_x000D_ import simu.framework.ITapahtumanTyyppi;_x000D_ import simu.framework.Tapahtuma;_x000D_ _x000D_ import static simu.model.TapahtumanTyyppi.ARR1;_x000D_ import static simu.model.TapahtumanTyyppi.*;_x000D_ _x000D_ /** Saapumisprosessin test -luokka */_x000D_ public class SaapumisprosessiForTest {_x000D_ /** Tapahtumalista */_x000D_ private TapahtumalistaForTest tapahtumalista;_x000D_ /** Tapahtuman tyyppi */_x000D_ private ITapahtumanTyyppi tyyppi;_x000D_ _x000D_ /** Ulkomaan lentojen lahtoaika */_x000D_ private double ulkoLahtoAika;_x000D_ _x000D_ /** Lentojen vali */_x000D_ private double lentojenVali;_x000D_ _x000D_ /** Saapumisprosessin test -luokan konstruktori */_x000D_ public SaapumisprosessiForTest(TapahtumalistaForTest tl, ITapahtumanTyyppi tyyppi, double ulkoLahtoAika, double lentojenVali) {_x000D_ //this.generaattori = g;_x000D_ this.tapahtumalista = tl;_x000D_ this.tyyppi = tyyppi;_x000D_ this.ulkoLahtoAika = ulkoLahtoAika;_x000D_ this.lentojenVali = lentojenVali;_x000D_ }_x000D_ _x000D_ /** Metodi generoi seuraavat tapahtumat */_x000D_ public void generoiSeuraava() {_x000D_ _x000D_ // Lahtoaika ulkomaalennoille_x000D_ double ulkoLahtoAika = Kello.getInstance().getAika() + new Normal(this.ulkoLahtoAika, 5).sample();_x000D_ _x000D_ // Lahtoaika sisalennoille_x000D_ double lahtoAika = ulkoLahtoAika + this.lentojenVali; //new Normal(this.lentojenVali, 5).sample() ;_x000D_ _x000D_ // Luodaan tapahtuma "Ulkomaan lento"_x000D_ Tapahtuma tUlko = new Tapahtuma(tyyppi, ulkoLahtoAika, true);_x000D_ tapahtumalista.lisaa(tUlko);_x000D_ _x000D_ // Luodaan tapahtuma "Sisamaan lento"_x000D_ Tapahtuma tSisa = new Tapahtuma(SISA, lahtoAika, false);_x000D_ tapahtumalista.lisaa(tSisa);_x000D_ _x000D_ // Luodaan 10 tapahtumaa "Saapuva asiakas ulkomaalle"_x000D_ for (int i=0; i<10; i++) {_x000D_ Tapahtuma t1 = new Tapahtuma(ARR1, ulkoLahtoAika - (new Normal(240, 15).sample()), true);_x000D_ tapahtumalista.lisaa(t1);_x000D_ }_x000D_ _x000D_ // Luodaan 10 tapahtumaa "Saapuva asiakas sisalennolle"_x000D_ for (int i=0; i<10; i++) {_x000D_ Tapahtuma t2 = new Tapahtuma(ARR2, lahtoAika - (new Normal(240, 15).sample()), false);_x000D_ tapahtumalista.lisaa(t2);_x000D_ }_x000D_ }_x000D_ }
Sami-Juhani/AP-Simulation-Java
src/main/java/simu/test/SaapumisprosessiForTest.java
877
//this.generaattori = g;_x000D_
line_comment
nl
package simu.test;_x000D_ import simu.eduni.distributions.Normal;_x000D_ import simu.framework.Kello;_x000D_ import simu.framework.ITapahtumanTyyppi;_x000D_ import simu.framework.Tapahtuma;_x000D_ _x000D_ import static simu.model.TapahtumanTyyppi.ARR1;_x000D_ import static simu.model.TapahtumanTyyppi.*;_x000D_ _x000D_ /** Saapumisprosessin test -luokka */_x000D_ public class SaapumisprosessiForTest {_x000D_ /** Tapahtumalista */_x000D_ private TapahtumalistaForTest tapahtumalista;_x000D_ /** Tapahtuman tyyppi */_x000D_ private ITapahtumanTyyppi tyyppi;_x000D_ _x000D_ /** Ulkomaan lentojen lahtoaika */_x000D_ private double ulkoLahtoAika;_x000D_ _x000D_ /** Lentojen vali */_x000D_ private double lentojenVali;_x000D_ _x000D_ /** Saapumisprosessin test -luokan konstruktori */_x000D_ public SaapumisprosessiForTest(TapahtumalistaForTest tl, ITapahtumanTyyppi tyyppi, double ulkoLahtoAika, double lentojenVali) {_x000D_ //this.generaattori =<SUF> this.tapahtumalista = tl;_x000D_ this.tyyppi = tyyppi;_x000D_ this.ulkoLahtoAika = ulkoLahtoAika;_x000D_ this.lentojenVali = lentojenVali;_x000D_ }_x000D_ _x000D_ /** Metodi generoi seuraavat tapahtumat */_x000D_ public void generoiSeuraava() {_x000D_ _x000D_ // Lahtoaika ulkomaalennoille_x000D_ double ulkoLahtoAika = Kello.getInstance().getAika() + new Normal(this.ulkoLahtoAika, 5).sample();_x000D_ _x000D_ // Lahtoaika sisalennoille_x000D_ double lahtoAika = ulkoLahtoAika + this.lentojenVali; //new Normal(this.lentojenVali, 5).sample() ;_x000D_ _x000D_ // Luodaan tapahtuma "Ulkomaan lento"_x000D_ Tapahtuma tUlko = new Tapahtuma(tyyppi, ulkoLahtoAika, true);_x000D_ tapahtumalista.lisaa(tUlko);_x000D_ _x000D_ // Luodaan tapahtuma "Sisamaan lento"_x000D_ Tapahtuma tSisa = new Tapahtuma(SISA, lahtoAika, false);_x000D_ tapahtumalista.lisaa(tSisa);_x000D_ _x000D_ // Luodaan 10 tapahtumaa "Saapuva asiakas ulkomaalle"_x000D_ for (int i=0; i<10; i++) {_x000D_ Tapahtuma t1 = new Tapahtuma(ARR1, ulkoLahtoAika - (new Normal(240, 15).sample()), true);_x000D_ tapahtumalista.lisaa(t1);_x000D_ }_x000D_ _x000D_ // Luodaan 10 tapahtumaa "Saapuva asiakas sisalennolle"_x000D_ for (int i=0; i<10; i++) {_x000D_ Tapahtuma t2 = new Tapahtuma(ARR2, lahtoAika - (new Normal(240, 15).sample()), false);_x000D_ tapahtumalista.lisaa(t2);_x000D_ }_x000D_ }_x000D_ }
False
4,589
74627_34
package com.uber.okbuck; import com.facebook.infer.annotation.Initializer; import com.google.common.collect.Sets; import com.uber.okbuck.core.annotation.AnnotationProcessorCache; import com.uber.okbuck.core.dependency.DependencyCache; import com.uber.okbuck.core.dependency.DependencyFactory; import com.uber.okbuck.core.dependency.exporter.DependencyExporter; import com.uber.okbuck.core.dependency.exporter.JsonDependencyExporter; import com.uber.okbuck.core.manager.BuckFileManager; import com.uber.okbuck.core.manager.BuckManager; import com.uber.okbuck.core.manager.D8Manager; import com.uber.okbuck.core.manager.DependencyManager; import com.uber.okbuck.core.manager.GroovyManager; import com.uber.okbuck.core.manager.JetifierManager; import com.uber.okbuck.core.manager.KotlinManager; import com.uber.okbuck.core.manager.LintManager; import com.uber.okbuck.core.manager.ManifestMergerManager; import com.uber.okbuck.core.manager.RobolectricManager; import com.uber.okbuck.core.manager.ScalaManager; import com.uber.okbuck.core.manager.TransformManager; import com.uber.okbuck.core.model.base.ProjectType; import com.uber.okbuck.core.task.OkBuckCleanTask; import com.uber.okbuck.core.task.OkBuckTask; import com.uber.okbuck.core.util.FileUtil; import com.uber.okbuck.core.util.MoreCollectors; import com.uber.okbuck.core.util.ProjectCache; import com.uber.okbuck.core.util.ProjectUtil; import com.uber.okbuck.extension.KotlinExtension; import com.uber.okbuck.extension.OkBuckExtension; import com.uber.okbuck.extension.ScalaExtension; import com.uber.okbuck.extension.WrapperExtension; import com.uber.okbuck.generator.BuckFileGenerator; import com.uber.okbuck.template.common.ExportFile; import com.uber.okbuck.template.core.Rule; import com.uber.okbuck.wrapper.BuckWrapperTask; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; // Dependency Tree // // rootOkBuckTask // / \ // / v // / okbuckClean // / / | \ // / v v v // / :p1:okbuck :p2:okbuck :p3:okbuck ... // | / / / // v v v v // setupOkbuck // public class OkBuckGradlePlugin implements Plugin<Project> { public static final String OKBUCK = "okbuck"; private static final String DOT_OKBUCK = "." + OKBUCK; public static final String WORKSPACE_PATH = DOT_OKBUCK + "/workspace"; public static final String GROUP = OKBUCK; public static final String BUCK_LINT = "buckLint"; private static final String OKBUCK_TARGETS_BZL = "okbuck_targets.bzl"; public static final String OKBUCK_TARGETS_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_TARGETS_BZL; public static final String OKBUCK_TARGETS_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_TARGETS_BZL; private static final String OKBUCK_PREBUILT_BZL = "okbuck_prebuilt.bzl"; public static final String OKBUCK_PREBUILT_FOLDER = DOT_OKBUCK + "/defs"; public static final String OKBUCK_PREBUILT_FILE = OKBUCK_PREBUILT_FOLDER + "/" + OKBUCK_PREBUILT_BZL; public static final String OKBUCK_PREBUILT_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_PREBUILT_BZL; private static final String OKBUCK_ANDROID_MODULES_BZL = "okbuck_android_modules.bzl"; public static final String OKBUCK_ANDROID_MODULES_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_ANDROID_MODULES_BZL; public static final String OKBUCK_ANDROID_MODULES_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_ANDROID_MODULES_BZL; public static final String OKBUCK_CONFIG = DOT_OKBUCK + "/config"; private static final String OKBUCK_STATE_DIR = DOT_OKBUCK + "/state"; private static final String OKBUCK_CLEAN = "okbuckClean"; private static final String BUCK_WRAPPER = "buckWrapper"; private static final String FORCED_OKBUCK = "forcedOkbuck"; private static final String PROCESSOR_BUILD_FOLDER = WORKSPACE_PATH + "/processor"; private static final String LINT_BUILD_FOLDER = WORKSPACE_PATH + "/lint"; public static final String OKBUCK_STATE = OKBUCK_STATE_DIR + "/STATE"; public static final String DEFAULT_OKBUCK_SHA256 = OKBUCK_STATE_DIR + "/SHA256"; public final Set<String> exportedPaths = Sets.newConcurrentHashSet(); public DependencyCache depCache; public DependencyFactory dependencyFactory; public DependencyManager dependencyManager; public AnnotationProcessorCache annotationProcessorCache; public LintManager lintManager; public KotlinManager kotlinManager; public ScalaManager scalaManager; public GroovyManager groovyManager; public JetifierManager jetifierManager; public TransformManager transformManager; public D8Manager d8Manager; ManifestMergerManager manifestMergerManager; RobolectricManager robolectricManager; BuckManager buckManager; // Only apply to the root project @Initializer @SuppressWarnings("NullAway") @Override public void apply(Project rootProject) { // Create extensions OkBuckExtension okbuckExt = rootProject.getExtensions().create(OKBUCK, OkBuckExtension.class, rootProject); // Create configurations rootProject.getConfigurations().maybeCreate(TransformManager.CONFIGURATION_TRANSFORM); rootProject.getConfigurations().maybeCreate(FORCED_OKBUCK); rootProject.afterEvaluate( rootBuckProject -> { // Create autovalue extension configurations Set<String> configs = okbuckExt.getExternalDependenciesExtension().getAutoValueConfigurations(); for (String config : configs) { rootBuckProject.getConfigurations().maybeCreate(config); } // Create tasks Task setupOkbuck = rootBuckProject.getTasks().create("setupOkbuck"); setupOkbuck.setGroup(GROUP); setupOkbuck.setDescription("Setup okbuck cache and dependencies"); // Create buck file manager. BuckFileManager buckFileManager = new BuckFileManager(okbuckExt.getRuleOverridesExtension()); dependencyFactory = new DependencyFactory(); // Create Annotation Processor cache String processorBuildFile = PROCESSOR_BUILD_FOLDER + "/" + okbuckExt.buildFileName; annotationProcessorCache = new AnnotationProcessorCache(rootBuckProject, buckFileManager, processorBuildFile); // Create Dependency manager dependencyManager = new DependencyManager( rootBuckProject, okbuckExt, buckFileManager, createDependencyExporter(okbuckExt)); // Create Lint Manager String lintBuildFile = LINT_BUILD_FOLDER + "/" + okbuckExt.buildFileName; lintManager = new LintManager(rootBuckProject, lintBuildFile, buckFileManager); // Create Kotlin Manager kotlinManager = new KotlinManager(rootBuckProject, buckFileManager); // Create Scala Manager scalaManager = new ScalaManager(rootBuckProject, buckFileManager); // Create Scala Manager groovyManager = new GroovyManager(rootBuckProject, buckFileManager); // Create Jetifier Manager jetifierManager = new JetifierManager(rootBuckProject, buckFileManager); // Create Robolectric Manager robolectricManager = new RobolectricManager(rootBuckProject, buckFileManager); // Create Transform Manager transformManager = new TransformManager(rootBuckProject, buckFileManager); // Create D8 Manager d8Manager = new D8Manager(rootBuckProject); // Create Buck Manager buckManager = new BuckManager(rootBuckProject); // Create Manifest Merger Manager manifestMergerManager = new ManifestMergerManager(rootBuckProject, buckFileManager); KotlinExtension kotlin = okbuckExt.getKotlinExtension(); ScalaExtension scala = okbuckExt.getScalaExtension(); Task rootOkBuckTask = rootBuckProject .getTasks() .create(OKBUCK, OkBuckTask.class, okbuckExt, kotlin, scala, buckFileManager); rootOkBuckTask.dependsOn(setupOkbuck); rootOkBuckTask.doLast( task -> { annotationProcessorCache.finalizeProcessors(); dependencyManager.resolveCurrentRawDeps(); dependencyManager.finalizeDependencies(okbuckExt); jetifierManager.finalizeDependencies(okbuckExt); lintManager.finalizeDependencies(); kotlinManager.finalizeDependencies(okbuckExt); scalaManager.finalizeDependencies(okbuckExt); groovyManager.finalizeDependencies(okbuckExt); robolectricManager.finalizeDependencies(okbuckExt); transformManager.finalizeDependencies(okbuckExt); buckManager.finalizeDependencies(); manifestMergerManager.finalizeDependencies(okbuckExt); dependencyFactory.finalizeDependencies(); writeExportedFileRules(rootBuckProject, okbuckExt); // Reset root project's scope cache at the very end ProjectCache.resetScopeCache(rootProject); // Reset all project's target cache at the very end. // This cannot be done for a project just after its okbuck task since, // the target cache is accessed by other projects and have to // be available until okbuck tasks of all the projects finishes. ProjectCache.resetTargetCacheForAll(rootProject); }); WrapperExtension wrapper = okbuckExt.getWrapperExtension(); // Create wrapper task rootBuckProject .getTasks() .create( BUCK_WRAPPER, BuckWrapperTask.class, wrapper.repo, wrapper.watch, wrapper.sourceRoots, wrapper.ignoredDirs); Map<String, Configuration> extraConfigurations = okbuckExt.extraDepCachesMap.keySet().stream() .collect( Collectors.toMap( Function.identity(), cacheName -> rootBuckProject .getConfigurations() .maybeCreate(cacheName + "ExtraDepCache"))); setupOkbuck.doFirst( task -> { if (System.getProperty("okbuck.wrapper", "false").equals("false")) { throw new IllegalArgumentException( "Okbuck cannot be invoked without 'okbuck.wrapper' set to true. Use buckw instead"); } }); // Configure setup task setupOkbuck.doLast( task -> { // Init all project's target cache at the very start since a project // can access other project's target cache. Hence, all target cache // needs to be initialized before any okbuck task starts. ProjectCache.initTargetCacheForAll(rootProject); // Init root project's scope cache. ProjectCache.initScopeCache(rootProject); depCache = new DependencyCache(rootBuckProject, dependencyManager, FORCED_OKBUCK); // Fetch Lint deps if needed if (!okbuckExt.getLintExtension().disabled && okbuckExt.getLintExtension().version != null) { lintManager.fetchLintDeps(okbuckExt.getLintExtension().version); } // Fetch transform deps if needed if (!okbuckExt.getTransformExtension().transforms.isEmpty()) { transformManager.fetchTransformDeps(); } // Setup d8 deps d8Manager.copyDeps(buckFileManager, okbuckExt); // Fetch robolectric deps if needed if (okbuckExt.getTestExtension().robolectric) { robolectricManager.download(); } if (JetifierManager.isJetifierEnabled(rootProject)) { jetifierManager.setupJetifier(okbuckExt.getJetifierExtension().version); } extraConfigurations.forEach( (cacheName, extraConfiguration) -> new DependencyCache( rootBuckProject, dependencyManager, okbuckExt.extraDepCachesMap.getOrDefault(cacheName, false)) .build(extraConfiguration)); buckManager.setupBuckBinary(); manifestMergerManager.fetchManifestMergerDeps(); }); // Create clean task Task okBuckClean = rootBuckProject .getTasks() .create(OKBUCK_CLEAN, OkBuckCleanTask.class, okbuckExt.buckProjects); rootOkBuckTask.dependsOn(okBuckClean); // Create okbuck task on each project to generate their buck file okbuckExt.buckProjects.stream() .filter(p -> p.getBuildFile().exists()) .forEach( bp -> { bp.getConfigurations().maybeCreate(BUCK_LINT); Task okbuckProjectTask = bp.getTasks().maybeCreate(OKBUCK); okbuckProjectTask.doLast( task -> { ProjectCache.initScopeCache(bp); BuckFileGenerator.generate(bp, buckFileManager, okbuckExt); ProjectCache.resetScopeCache(bp); }); okbuckProjectTask.dependsOn(setupOkbuck); okBuckClean.dependsOn(okbuckProjectTask); }); }); } private void writeExportedFileRules(Project rootBuckProject, OkBuckExtension okBuckExtension) { Set<String> currentProjectPaths = okBuckExtension.buckProjects.stream() .filter(project -> ProjectUtil.getType(project) != ProjectType.UNKNOWN) .map( project -> rootBuckProject .getProjectDir() .toPath() .relativize(project.getProjectDir().toPath()) .toString()) .collect(MoreCollectors.toImmutableSet()); Map<String, Set<Rule>> pathToRules = new HashMap<>(); for (String exportedPath : exportedPaths) { File exportedFile = rootBuckProject.file(exportedPath); String containingPath = FileUtil.getRelativePath(rootBuckProject.getProjectDir(), exportedFile.getParentFile()); Set<Rule> rules = pathToRules.getOrDefault(containingPath, new HashSet<>()); rules.add(new ExportFile().name(exportedFile.getName())); pathToRules.put(containingPath, rules); } for (Map.Entry<String, Set<Rule>> entry : pathToRules.entrySet()) { File buckFile = rootBuckProject .getRootDir() .toPath() .resolve(entry.getKey()) .resolve(okBuckExtension.buildFileName) .toFile(); try (OutputStream os = new FileOutputStream(buckFile, currentProjectPaths.contains(entry.getKey()))) { entry.getValue().stream() .sorted((rule1, rule2) -> rule1.name().compareToIgnoreCase(rule2.name())) .forEach(rule -> rule.render(os)); } catch (IOException e) { throw new IllegalStateException(e); } } } private static DependencyExporter createDependencyExporter(OkBuckExtension okbuckExt) { return new JsonDependencyExporter(okbuckExt.getExportDependenciesExtension()); } }
uber/okbuck
buildSrc/src/main/java/com/uber/okbuck/OkBuckGradlePlugin.java
4,580
// Fetch Lint deps if needed
line_comment
nl
package com.uber.okbuck; import com.facebook.infer.annotation.Initializer; import com.google.common.collect.Sets; import com.uber.okbuck.core.annotation.AnnotationProcessorCache; import com.uber.okbuck.core.dependency.DependencyCache; import com.uber.okbuck.core.dependency.DependencyFactory; import com.uber.okbuck.core.dependency.exporter.DependencyExporter; import com.uber.okbuck.core.dependency.exporter.JsonDependencyExporter; import com.uber.okbuck.core.manager.BuckFileManager; import com.uber.okbuck.core.manager.BuckManager; import com.uber.okbuck.core.manager.D8Manager; import com.uber.okbuck.core.manager.DependencyManager; import com.uber.okbuck.core.manager.GroovyManager; import com.uber.okbuck.core.manager.JetifierManager; import com.uber.okbuck.core.manager.KotlinManager; import com.uber.okbuck.core.manager.LintManager; import com.uber.okbuck.core.manager.ManifestMergerManager; import com.uber.okbuck.core.manager.RobolectricManager; import com.uber.okbuck.core.manager.ScalaManager; import com.uber.okbuck.core.manager.TransformManager; import com.uber.okbuck.core.model.base.ProjectType; import com.uber.okbuck.core.task.OkBuckCleanTask; import com.uber.okbuck.core.task.OkBuckTask; import com.uber.okbuck.core.util.FileUtil; import com.uber.okbuck.core.util.MoreCollectors; import com.uber.okbuck.core.util.ProjectCache; import com.uber.okbuck.core.util.ProjectUtil; import com.uber.okbuck.extension.KotlinExtension; import com.uber.okbuck.extension.OkBuckExtension; import com.uber.okbuck.extension.ScalaExtension; import com.uber.okbuck.extension.WrapperExtension; import com.uber.okbuck.generator.BuckFileGenerator; import com.uber.okbuck.template.common.ExportFile; import com.uber.okbuck.template.core.Rule; import com.uber.okbuck.wrapper.BuckWrapperTask; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; // Dependency Tree // // rootOkBuckTask // / \ // / v // / okbuckClean // / / | \ // / v v v // / :p1:okbuck :p2:okbuck :p3:okbuck ... // | / / / // v v v v // setupOkbuck // public class OkBuckGradlePlugin implements Plugin<Project> { public static final String OKBUCK = "okbuck"; private static final String DOT_OKBUCK = "." + OKBUCK; public static final String WORKSPACE_PATH = DOT_OKBUCK + "/workspace"; public static final String GROUP = OKBUCK; public static final String BUCK_LINT = "buckLint"; private static final String OKBUCK_TARGETS_BZL = "okbuck_targets.bzl"; public static final String OKBUCK_TARGETS_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_TARGETS_BZL; public static final String OKBUCK_TARGETS_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_TARGETS_BZL; private static final String OKBUCK_PREBUILT_BZL = "okbuck_prebuilt.bzl"; public static final String OKBUCK_PREBUILT_FOLDER = DOT_OKBUCK + "/defs"; public static final String OKBUCK_PREBUILT_FILE = OKBUCK_PREBUILT_FOLDER + "/" + OKBUCK_PREBUILT_BZL; public static final String OKBUCK_PREBUILT_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_PREBUILT_BZL; private static final String OKBUCK_ANDROID_MODULES_BZL = "okbuck_android_modules.bzl"; public static final String OKBUCK_ANDROID_MODULES_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_ANDROID_MODULES_BZL; public static final String OKBUCK_ANDROID_MODULES_TARGET = "//" + DOT_OKBUCK + "/defs:" + OKBUCK_ANDROID_MODULES_BZL; public static final String OKBUCK_CONFIG = DOT_OKBUCK + "/config"; private static final String OKBUCK_STATE_DIR = DOT_OKBUCK + "/state"; private static final String OKBUCK_CLEAN = "okbuckClean"; private static final String BUCK_WRAPPER = "buckWrapper"; private static final String FORCED_OKBUCK = "forcedOkbuck"; private static final String PROCESSOR_BUILD_FOLDER = WORKSPACE_PATH + "/processor"; private static final String LINT_BUILD_FOLDER = WORKSPACE_PATH + "/lint"; public static final String OKBUCK_STATE = OKBUCK_STATE_DIR + "/STATE"; public static final String DEFAULT_OKBUCK_SHA256 = OKBUCK_STATE_DIR + "/SHA256"; public final Set<String> exportedPaths = Sets.newConcurrentHashSet(); public DependencyCache depCache; public DependencyFactory dependencyFactory; public DependencyManager dependencyManager; public AnnotationProcessorCache annotationProcessorCache; public LintManager lintManager; public KotlinManager kotlinManager; public ScalaManager scalaManager; public GroovyManager groovyManager; public JetifierManager jetifierManager; public TransformManager transformManager; public D8Manager d8Manager; ManifestMergerManager manifestMergerManager; RobolectricManager robolectricManager; BuckManager buckManager; // Only apply to the root project @Initializer @SuppressWarnings("NullAway") @Override public void apply(Project rootProject) { // Create extensions OkBuckExtension okbuckExt = rootProject.getExtensions().create(OKBUCK, OkBuckExtension.class, rootProject); // Create configurations rootProject.getConfigurations().maybeCreate(TransformManager.CONFIGURATION_TRANSFORM); rootProject.getConfigurations().maybeCreate(FORCED_OKBUCK); rootProject.afterEvaluate( rootBuckProject -> { // Create autovalue extension configurations Set<String> configs = okbuckExt.getExternalDependenciesExtension().getAutoValueConfigurations(); for (String config : configs) { rootBuckProject.getConfigurations().maybeCreate(config); } // Create tasks Task setupOkbuck = rootBuckProject.getTasks().create("setupOkbuck"); setupOkbuck.setGroup(GROUP); setupOkbuck.setDescription("Setup okbuck cache and dependencies"); // Create buck file manager. BuckFileManager buckFileManager = new BuckFileManager(okbuckExt.getRuleOverridesExtension()); dependencyFactory = new DependencyFactory(); // Create Annotation Processor cache String processorBuildFile = PROCESSOR_BUILD_FOLDER + "/" + okbuckExt.buildFileName; annotationProcessorCache = new AnnotationProcessorCache(rootBuckProject, buckFileManager, processorBuildFile); // Create Dependency manager dependencyManager = new DependencyManager( rootBuckProject, okbuckExt, buckFileManager, createDependencyExporter(okbuckExt)); // Create Lint Manager String lintBuildFile = LINT_BUILD_FOLDER + "/" + okbuckExt.buildFileName; lintManager = new LintManager(rootBuckProject, lintBuildFile, buckFileManager); // Create Kotlin Manager kotlinManager = new KotlinManager(rootBuckProject, buckFileManager); // Create Scala Manager scalaManager = new ScalaManager(rootBuckProject, buckFileManager); // Create Scala Manager groovyManager = new GroovyManager(rootBuckProject, buckFileManager); // Create Jetifier Manager jetifierManager = new JetifierManager(rootBuckProject, buckFileManager); // Create Robolectric Manager robolectricManager = new RobolectricManager(rootBuckProject, buckFileManager); // Create Transform Manager transformManager = new TransformManager(rootBuckProject, buckFileManager); // Create D8 Manager d8Manager = new D8Manager(rootBuckProject); // Create Buck Manager buckManager = new BuckManager(rootBuckProject); // Create Manifest Merger Manager manifestMergerManager = new ManifestMergerManager(rootBuckProject, buckFileManager); KotlinExtension kotlin = okbuckExt.getKotlinExtension(); ScalaExtension scala = okbuckExt.getScalaExtension(); Task rootOkBuckTask = rootBuckProject .getTasks() .create(OKBUCK, OkBuckTask.class, okbuckExt, kotlin, scala, buckFileManager); rootOkBuckTask.dependsOn(setupOkbuck); rootOkBuckTask.doLast( task -> { annotationProcessorCache.finalizeProcessors(); dependencyManager.resolveCurrentRawDeps(); dependencyManager.finalizeDependencies(okbuckExt); jetifierManager.finalizeDependencies(okbuckExt); lintManager.finalizeDependencies(); kotlinManager.finalizeDependencies(okbuckExt); scalaManager.finalizeDependencies(okbuckExt); groovyManager.finalizeDependencies(okbuckExt); robolectricManager.finalizeDependencies(okbuckExt); transformManager.finalizeDependencies(okbuckExt); buckManager.finalizeDependencies(); manifestMergerManager.finalizeDependencies(okbuckExt); dependencyFactory.finalizeDependencies(); writeExportedFileRules(rootBuckProject, okbuckExt); // Reset root project's scope cache at the very end ProjectCache.resetScopeCache(rootProject); // Reset all project's target cache at the very end. // This cannot be done for a project just after its okbuck task since, // the target cache is accessed by other projects and have to // be available until okbuck tasks of all the projects finishes. ProjectCache.resetTargetCacheForAll(rootProject); }); WrapperExtension wrapper = okbuckExt.getWrapperExtension(); // Create wrapper task rootBuckProject .getTasks() .create( BUCK_WRAPPER, BuckWrapperTask.class, wrapper.repo, wrapper.watch, wrapper.sourceRoots, wrapper.ignoredDirs); Map<String, Configuration> extraConfigurations = okbuckExt.extraDepCachesMap.keySet().stream() .collect( Collectors.toMap( Function.identity(), cacheName -> rootBuckProject .getConfigurations() .maybeCreate(cacheName + "ExtraDepCache"))); setupOkbuck.doFirst( task -> { if (System.getProperty("okbuck.wrapper", "false").equals("false")) { throw new IllegalArgumentException( "Okbuck cannot be invoked without 'okbuck.wrapper' set to true. Use buckw instead"); } }); // Configure setup task setupOkbuck.doLast( task -> { // Init all project's target cache at the very start since a project // can access other project's target cache. Hence, all target cache // needs to be initialized before any okbuck task starts. ProjectCache.initTargetCacheForAll(rootProject); // Init root project's scope cache. ProjectCache.initScopeCache(rootProject); depCache = new DependencyCache(rootBuckProject, dependencyManager, FORCED_OKBUCK); // Fetch Lint<SUF> if (!okbuckExt.getLintExtension().disabled && okbuckExt.getLintExtension().version != null) { lintManager.fetchLintDeps(okbuckExt.getLintExtension().version); } // Fetch transform deps if needed if (!okbuckExt.getTransformExtension().transforms.isEmpty()) { transformManager.fetchTransformDeps(); } // Setup d8 deps d8Manager.copyDeps(buckFileManager, okbuckExt); // Fetch robolectric deps if needed if (okbuckExt.getTestExtension().robolectric) { robolectricManager.download(); } if (JetifierManager.isJetifierEnabled(rootProject)) { jetifierManager.setupJetifier(okbuckExt.getJetifierExtension().version); } extraConfigurations.forEach( (cacheName, extraConfiguration) -> new DependencyCache( rootBuckProject, dependencyManager, okbuckExt.extraDepCachesMap.getOrDefault(cacheName, false)) .build(extraConfiguration)); buckManager.setupBuckBinary(); manifestMergerManager.fetchManifestMergerDeps(); }); // Create clean task Task okBuckClean = rootBuckProject .getTasks() .create(OKBUCK_CLEAN, OkBuckCleanTask.class, okbuckExt.buckProjects); rootOkBuckTask.dependsOn(okBuckClean); // Create okbuck task on each project to generate their buck file okbuckExt.buckProjects.stream() .filter(p -> p.getBuildFile().exists()) .forEach( bp -> { bp.getConfigurations().maybeCreate(BUCK_LINT); Task okbuckProjectTask = bp.getTasks().maybeCreate(OKBUCK); okbuckProjectTask.doLast( task -> { ProjectCache.initScopeCache(bp); BuckFileGenerator.generate(bp, buckFileManager, okbuckExt); ProjectCache.resetScopeCache(bp); }); okbuckProjectTask.dependsOn(setupOkbuck); okBuckClean.dependsOn(okbuckProjectTask); }); }); } private void writeExportedFileRules(Project rootBuckProject, OkBuckExtension okBuckExtension) { Set<String> currentProjectPaths = okBuckExtension.buckProjects.stream() .filter(project -> ProjectUtil.getType(project) != ProjectType.UNKNOWN) .map( project -> rootBuckProject .getProjectDir() .toPath() .relativize(project.getProjectDir().toPath()) .toString()) .collect(MoreCollectors.toImmutableSet()); Map<String, Set<Rule>> pathToRules = new HashMap<>(); for (String exportedPath : exportedPaths) { File exportedFile = rootBuckProject.file(exportedPath); String containingPath = FileUtil.getRelativePath(rootBuckProject.getProjectDir(), exportedFile.getParentFile()); Set<Rule> rules = pathToRules.getOrDefault(containingPath, new HashSet<>()); rules.add(new ExportFile().name(exportedFile.getName())); pathToRules.put(containingPath, rules); } for (Map.Entry<String, Set<Rule>> entry : pathToRules.entrySet()) { File buckFile = rootBuckProject .getRootDir() .toPath() .resolve(entry.getKey()) .resolve(okBuckExtension.buildFileName) .toFile(); try (OutputStream os = new FileOutputStream(buckFile, currentProjectPaths.contains(entry.getKey()))) { entry.getValue().stream() .sorted((rule1, rule2) -> rule1.name().compareToIgnoreCase(rule2.name())) .forEach(rule -> rule.render(os)); } catch (IOException e) { throw new IllegalStateException(e); } } } private static DependencyExporter createDependencyExporter(OkBuckExtension okbuckExt) { return new JsonDependencyExporter(okbuckExt.getExportDependenciesExtension()); } }
False
1,073
8369_0
package be.jpendel.application; import be.jpendel.domain.person.Person; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer */ class PersonMapper { private PersonMapper() { } static List<PersonDTO> map(Collection<Person> persons) { return persons.stream().map(PersonMapper::map).collect(Collectors.toList()); } static PersonDTO map(Person person) { return PersonDTO.newBuilder() .withUuid(person.getId()) .withFirstName(person.getFirstName()) .withLastName(person.getLastName()) .withBirthDate(person.getBirthDate()) .withPhone(person.getPhone()) .build(); } }
MarkDechamps/jpendel
application/src/main/java/be/jpendel/application/PersonMapper.java
233
/* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer */
block_comment
nl
package be.jpendel.application; import be.jpendel.domain.person.Person; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /* TODO : mark:<SUF>*/ class PersonMapper { private PersonMapper() { } static List<PersonDTO> map(Collection<Person> persons) { return persons.stream().map(PersonMapper::map).collect(Collectors.toList()); } static PersonDTO map(Person person) { return PersonDTO.newBuilder() .withUuid(person.getId()) .withFirstName(person.getFirstName()) .withLastName(person.getLastName()) .withBirthDate(person.getBirthDate()) .withPhone(person.getPhone()) .build(); } }
True
3,282
30023_26
/* Jackson JSON-processor. * * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi * * Licensed under the License specified in file LICENSE, included with * the source code and binary code bundles. * You may not use this file except in compliance with the License. * * 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.fasterxml.jackson.core; import java.util.Arrays; /** * Abstract base class used to define specific details of which * variant of Base64 encoding/decoding is to be used. Although there is * somewhat standard basic version (so-called "MIME Base64"), other variants * exists, see <a href="http://en.wikipedia.org/wiki/Base64">Base64 Wikipedia entry</a> for details. * * @author Tatu Saloranta */ public final class Base64Variant implements java.io.Serializable { // We'll only serialize name private static final long serialVersionUID = 1L; /** * Placeholder used by "no padding" variant, to be used when a character * value is needed. */ final static char PADDING_CHAR_NONE = '\0'; /** * Marker used to denote ascii characters that do not correspond * to a 6-bit value (in this variant), and is not used as a padding * character. */ public final static int BASE64_VALUE_INVALID = -1; /** * Marker used to denote ascii character (in decoding table) that * is the padding character using this variant (if any). */ public final static int BASE64_VALUE_PADDING = -2; /* /********************************************************** /* Encoding/decoding tables /********************************************************** */ /** * Decoding table used for base 64 decoding. */ private final transient int[] _asciiToBase64 = new int[128]; /** * Encoding table used for base 64 decoding when output is done * as characters. */ private final transient char[] _base64ToAsciiC = new char[64]; /** * Alternative encoding table used for base 64 decoding when output is done * as ascii bytes. */ private final transient byte[] _base64ToAsciiB = new byte[64]; /* /********************************************************** /* Other configuration /********************************************************** */ /** * Symbolic name of variant; used for diagnostics/debugging. *<p> * Note that this is the only non-transient field; used when reading * back from serialized state */ protected final String _name; /** * Whether this variant uses padding or not. */ protected final transient boolean _usesPadding; /** * Characted used for padding, if any ({@link #PADDING_CHAR_NONE} if not). */ protected final transient char _paddingChar; /** * Maximum number of encoded base64 characters to output during encoding * before adding a linefeed, if line length is to be limited * ({@link java.lang.Integer#MAX_VALUE} if not limited). *<p> * Note: for some output modes (when writing attributes) linefeeds may * need to be avoided, and this value ignored. */ protected final transient int _maxLineLength; /* /********************************************************** /* Life-cycle /********************************************************** */ public Base64Variant(String name, String base64Alphabet, boolean usesPadding, char paddingChar, int maxLineLength) { _name = name; _usesPadding = usesPadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; // Ok and then we need to create codec tables. // First the main encoding table: int alphaLen = base64Alphabet.length(); if (alphaLen != 64) { throw new IllegalArgumentException("Base64Alphabet length must be exactly 64 (was "+alphaLen+")"); } // And then secondary encoding table and decoding table: base64Alphabet.getChars(0, alphaLen, _base64ToAsciiC, 0); Arrays.fill(_asciiToBase64, BASE64_VALUE_INVALID); for (int i = 0; i < alphaLen; ++i) { char alpha = _base64ToAsciiC[i]; _base64ToAsciiB[i] = (byte) alpha; _asciiToBase64[alpha] = i; } // Plus if we use padding, add that in too if (usesPadding) { _asciiToBase64[(int) paddingChar] = BASE64_VALUE_PADDING; } } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant except for the maximum line length * (and obviously, name). */ public Base64Variant(Base64Variant base, String name, int maxLineLength) { this(base, name, base._usesPadding, base._paddingChar, maxLineLength); } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant, but other details (padding, maximum * line length) differ */ public Base64Variant(Base64Variant base, String name, boolean usesPadding, char paddingChar, int maxLineLength) { _name = name; byte[] srcB = base._base64ToAsciiB; System.arraycopy(srcB, 0, this._base64ToAsciiB, 0, srcB.length); char[] srcC = base._base64ToAsciiC; System.arraycopy(srcC, 0, this._base64ToAsciiC, 0, srcC.length); int[] srcV = base._asciiToBase64; System.arraycopy(srcV, 0, this._asciiToBase64, 0, srcV.length); _usesPadding = usesPadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; } /* /********************************************************** /* Serializable overrides /********************************************************** */ /** * Method used to "demote" deserialized instances back to * canonical ones */ protected Object readResolve() { return Base64Variants.valueOf(_name); } /* /********************************************************** /* Public accessors /********************************************************** */ public String getName() { return _name; } public boolean usesPadding() { return _usesPadding; } public boolean usesPaddingChar(char c) { return c == _paddingChar; } public boolean usesPaddingChar(int ch) { return ch == (int) _paddingChar; } public char getPaddingChar() { return _paddingChar; } public byte getPaddingByte() { return (byte)_paddingChar; } public int getMaxLineLength() { return _maxLineLength; } /* /********************************************************** /* Decoding support /********************************************************** */ /** * @return 6-bit decoded value, if valid character; */ public int decodeBase64Char(char c) { int ch = (int) c; return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Char(int ch) { return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Byte(byte b) { int ch = (int) b; return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } /* /********************************************************** /* Encoding support /********************************************************** */ public char encodeBase64BitsAsChar(int value) { /* Let's assume caller has done necessary checks; this * method must be fast and inlinable */ return _base64ToAsciiC[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 characters, stored in given result buffer. */ public int encodeBase64Chunk(int b24, char[] buffer, int ptr) { buffer[ptr++] = _base64ToAsciiC[(b24 >> 18) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[(b24 >> 12) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[(b24 >> 6) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[b24 & 0x3F]; return ptr; } public void encodeBase64Chunk(StringBuilder sb, int b24) { sb.append(_base64ToAsciiC[(b24 >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 12) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 6) & 0x3F]); sb.append(_base64ToAsciiC[b24 & 0x3F]); } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param outputBytes Number of encoded bytes included (either 1 or 2) */ public int encodeBase64Partial(int bits, int outputBytes, char[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[(bits >> 12) & 0x3F]; if (_usesPadding) { buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar; buffer[outPtr++] = _paddingChar; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 6) & 0x3F]; } } return outPtr; } public void encodeBase64Partial(StringBuilder sb, int bits, int outputBytes) { sb.append(_base64ToAsciiC[(bits >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(bits >> 12) & 0x3F]); if (_usesPadding) { sb.append((outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar); sb.append(_paddingChar); } else { if (outputBytes == 2) { sb.append(_base64ToAsciiC[(bits >> 6) & 0x3F]); } } } public byte encodeBase64BitsAsByte(int value) { // As with above, assuming it is 6-bit value return _base64ToAsciiB[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 bytes (ascii), stored in given result buffer. */ public int encodeBase64Chunk(int b24, byte[] buffer, int ptr) { buffer[ptr++] = _base64ToAsciiB[(b24 >> 18) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[(b24 >> 12) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[(b24 >> 6) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[b24 & 0x3F]; return ptr; } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param outputBytes Number of encoded bytes included (either 1 or 2) */ public int encodeBase64Partial(int bits, int outputBytes, byte[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[(bits >> 12) & 0x3F]; if (_usesPadding) { byte pb = (byte) _paddingChar; buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiB[(bits >> 6) & 0x3F] : pb; buffer[outPtr++] = pb; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 6) & 0x3F]; } } return outPtr; } /** * Convenience method for converting given byte array as base64 encoded * String using this variant's settings. * Resulting value is "raw", that is, not enclosed in double-quotes. * * @param input Byte array to encode */ public String encode(byte[] input) { return encode(input, false); } /** * Convenience method for converting given byte array as base64 encoded * String using this variant's settings, optionally enclosed in * double-quotes. * * @param input Byte array to encode * @param addQuotes Whether to surround resulting value in double quotes or not */ public String encode(byte[] input, boolean addQuotes) { int inputEnd = input.length; StringBuilder sb; { // let's approximate... 33% overhead, ~= 3/8 (0.375) int outputLen = inputEnd + (inputEnd >> 2) + (inputEnd >> 3); sb = new StringBuilder(outputLen); } if (addQuotes) { sb.append('"'); } int chunksBeforeLF = getMaxLineLength() >> 2; // Ok, first we loop through all full triplets of data: int inputPtr = 0; int safeInputEnd = inputEnd-3; // to get only full triplets while (inputPtr <= safeInputEnd) { // First, mash 3 bytes into lsb of 32-bit int int b24 = ((int) input[inputPtr++]) << 8; b24 |= ((int) input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); encodeBase64Chunk(sb, b24); if (--chunksBeforeLF <= 0) { // note: must quote in JSON value, so not really useful... sb.append('\\'); sb.append('n'); chunksBeforeLF = getMaxLineLength() >> 2; } } // And then we may have 1 or 2 leftover bytes to encode int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 if (inputLeft > 0) { // yes, but do we have room for output? int b24 = ((int) input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= (((int) input[inputPtr++]) & 0xFF) << 8; } encodeBase64Partial(sb, b24, inputLeft); } if (addQuotes) { sb.append('"'); } return sb.toString(); } /* /********************************************************** /* other methods /********************************************************** */ @Override public String toString() { return _name; } }
joyplus/joyplus-tv
joytv/src/com/fasterxml/jackson/core/Base64Variant.java
4,317
/** * @return 6-bit decoded value, if valid character; */
block_comment
nl
/* Jackson JSON-processor. * * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi * * Licensed under the License specified in file LICENSE, included with * the source code and binary code bundles. * You may not use this file except in compliance with the License. * * 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.fasterxml.jackson.core; import java.util.Arrays; /** * Abstract base class used to define specific details of which * variant of Base64 encoding/decoding is to be used. Although there is * somewhat standard basic version (so-called "MIME Base64"), other variants * exists, see <a href="http://en.wikipedia.org/wiki/Base64">Base64 Wikipedia entry</a> for details. * * @author Tatu Saloranta */ public final class Base64Variant implements java.io.Serializable { // We'll only serialize name private static final long serialVersionUID = 1L; /** * Placeholder used by "no padding" variant, to be used when a character * value is needed. */ final static char PADDING_CHAR_NONE = '\0'; /** * Marker used to denote ascii characters that do not correspond * to a 6-bit value (in this variant), and is not used as a padding * character. */ public final static int BASE64_VALUE_INVALID = -1; /** * Marker used to denote ascii character (in decoding table) that * is the padding character using this variant (if any). */ public final static int BASE64_VALUE_PADDING = -2; /* /********************************************************** /* Encoding/decoding tables /********************************************************** */ /** * Decoding table used for base 64 decoding. */ private final transient int[] _asciiToBase64 = new int[128]; /** * Encoding table used for base 64 decoding when output is done * as characters. */ private final transient char[] _base64ToAsciiC = new char[64]; /** * Alternative encoding table used for base 64 decoding when output is done * as ascii bytes. */ private final transient byte[] _base64ToAsciiB = new byte[64]; /* /********************************************************** /* Other configuration /********************************************************** */ /** * Symbolic name of variant; used for diagnostics/debugging. *<p> * Note that this is the only non-transient field; used when reading * back from serialized state */ protected final String _name; /** * Whether this variant uses padding or not. */ protected final transient boolean _usesPadding; /** * Characted used for padding, if any ({@link #PADDING_CHAR_NONE} if not). */ protected final transient char _paddingChar; /** * Maximum number of encoded base64 characters to output during encoding * before adding a linefeed, if line length is to be limited * ({@link java.lang.Integer#MAX_VALUE} if not limited). *<p> * Note: for some output modes (when writing attributes) linefeeds may * need to be avoided, and this value ignored. */ protected final transient int _maxLineLength; /* /********************************************************** /* Life-cycle /********************************************************** */ public Base64Variant(String name, String base64Alphabet, boolean usesPadding, char paddingChar, int maxLineLength) { _name = name; _usesPadding = usesPadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; // Ok and then we need to create codec tables. // First the main encoding table: int alphaLen = base64Alphabet.length(); if (alphaLen != 64) { throw new IllegalArgumentException("Base64Alphabet length must be exactly 64 (was "+alphaLen+")"); } // And then secondary encoding table and decoding table: base64Alphabet.getChars(0, alphaLen, _base64ToAsciiC, 0); Arrays.fill(_asciiToBase64, BASE64_VALUE_INVALID); for (int i = 0; i < alphaLen; ++i) { char alpha = _base64ToAsciiC[i]; _base64ToAsciiB[i] = (byte) alpha; _asciiToBase64[alpha] = i; } // Plus if we use padding, add that in too if (usesPadding) { _asciiToBase64[(int) paddingChar] = BASE64_VALUE_PADDING; } } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant except for the maximum line length * (and obviously, name). */ public Base64Variant(Base64Variant base, String name, int maxLineLength) { this(base, name, base._usesPadding, base._paddingChar, maxLineLength); } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant, but other details (padding, maximum * line length) differ */ public Base64Variant(Base64Variant base, String name, boolean usesPadding, char paddingChar, int maxLineLength) { _name = name; byte[] srcB = base._base64ToAsciiB; System.arraycopy(srcB, 0, this._base64ToAsciiB, 0, srcB.length); char[] srcC = base._base64ToAsciiC; System.arraycopy(srcC, 0, this._base64ToAsciiC, 0, srcC.length); int[] srcV = base._asciiToBase64; System.arraycopy(srcV, 0, this._asciiToBase64, 0, srcV.length); _usesPadding = usesPadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; } /* /********************************************************** /* Serializable overrides /********************************************************** */ /** * Method used to "demote" deserialized instances back to * canonical ones */ protected Object readResolve() { return Base64Variants.valueOf(_name); } /* /********************************************************** /* Public accessors /********************************************************** */ public String getName() { return _name; } public boolean usesPadding() { return _usesPadding; } public boolean usesPaddingChar(char c) { return c == _paddingChar; } public boolean usesPaddingChar(int ch) { return ch == (int) _paddingChar; } public char getPaddingChar() { return _paddingChar; } public byte getPaddingByte() { return (byte)_paddingChar; } public int getMaxLineLength() { return _maxLineLength; } /* /********************************************************** /* Decoding support /********************************************************** */ /** * @return 6-bit decoded<SUF>*/ public int decodeBase64Char(char c) { int ch = (int) c; return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Char(int ch) { return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Byte(byte b) { int ch = (int) b; return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } /* /********************************************************** /* Encoding support /********************************************************** */ public char encodeBase64BitsAsChar(int value) { /* Let's assume caller has done necessary checks; this * method must be fast and inlinable */ return _base64ToAsciiC[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 characters, stored in given result buffer. */ public int encodeBase64Chunk(int b24, char[] buffer, int ptr) { buffer[ptr++] = _base64ToAsciiC[(b24 >> 18) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[(b24 >> 12) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[(b24 >> 6) & 0x3F]; buffer[ptr++] = _base64ToAsciiC[b24 & 0x3F]; return ptr; } public void encodeBase64Chunk(StringBuilder sb, int b24) { sb.append(_base64ToAsciiC[(b24 >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 12) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 6) & 0x3F]); sb.append(_base64ToAsciiC[b24 & 0x3F]); } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param outputBytes Number of encoded bytes included (either 1 or 2) */ public int encodeBase64Partial(int bits, int outputBytes, char[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[(bits >> 12) & 0x3F]; if (_usesPadding) { buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar; buffer[outPtr++] = _paddingChar; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 6) & 0x3F]; } } return outPtr; } public void encodeBase64Partial(StringBuilder sb, int bits, int outputBytes) { sb.append(_base64ToAsciiC[(bits >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(bits >> 12) & 0x3F]); if (_usesPadding) { sb.append((outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar); sb.append(_paddingChar); } else { if (outputBytes == 2) { sb.append(_base64ToAsciiC[(bits >> 6) & 0x3F]); } } } public byte encodeBase64BitsAsByte(int value) { // As with above, assuming it is 6-bit value return _base64ToAsciiB[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 bytes (ascii), stored in given result buffer. */ public int encodeBase64Chunk(int b24, byte[] buffer, int ptr) { buffer[ptr++] = _base64ToAsciiB[(b24 >> 18) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[(b24 >> 12) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[(b24 >> 6) & 0x3F]; buffer[ptr++] = _base64ToAsciiB[b24 & 0x3F]; return ptr; } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param outputBytes Number of encoded bytes included (either 1 or 2) */ public int encodeBase64Partial(int bits, int outputBytes, byte[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[(bits >> 12) & 0x3F]; if (_usesPadding) { byte pb = (byte) _paddingChar; buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiB[(bits >> 6) & 0x3F] : pb; buffer[outPtr++] = pb; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 6) & 0x3F]; } } return outPtr; } /** * Convenience method for converting given byte array as base64 encoded * String using this variant's settings. * Resulting value is "raw", that is, not enclosed in double-quotes. * * @param input Byte array to encode */ public String encode(byte[] input) { return encode(input, false); } /** * Convenience method for converting given byte array as base64 encoded * String using this variant's settings, optionally enclosed in * double-quotes. * * @param input Byte array to encode * @param addQuotes Whether to surround resulting value in double quotes or not */ public String encode(byte[] input, boolean addQuotes) { int inputEnd = input.length; StringBuilder sb; { // let's approximate... 33% overhead, ~= 3/8 (0.375) int outputLen = inputEnd + (inputEnd >> 2) + (inputEnd >> 3); sb = new StringBuilder(outputLen); } if (addQuotes) { sb.append('"'); } int chunksBeforeLF = getMaxLineLength() >> 2; // Ok, first we loop through all full triplets of data: int inputPtr = 0; int safeInputEnd = inputEnd-3; // to get only full triplets while (inputPtr <= safeInputEnd) { // First, mash 3 bytes into lsb of 32-bit int int b24 = ((int) input[inputPtr++]) << 8; b24 |= ((int) input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); encodeBase64Chunk(sb, b24); if (--chunksBeforeLF <= 0) { // note: must quote in JSON value, so not really useful... sb.append('\\'); sb.append('n'); chunksBeforeLF = getMaxLineLength() >> 2; } } // And then we may have 1 or 2 leftover bytes to encode int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 if (inputLeft > 0) { // yes, but do we have room for output? int b24 = ((int) input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= (((int) input[inputPtr++]) & 0xFF) << 8; } encodeBase64Partial(sb, b24, inputLeft); } if (addQuotes) { sb.append('"'); } return sb.toString(); } /* /********************************************************** /* other methods /********************************************************** */ @Override public String toString() { return _name; } }
False
4,172
46346_1
package com.example.plugindemo.activity.category; import java.text.Collator; import android.app.TwsActivity; import android.os.Bundle; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.plugindemo.R; import com.tencent.tws.assistant.widget.SideBar; import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener; public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener { private ListView mListView; private SideBar mSideBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sidebar_widget); setTitle("测试共享控件SideBar"); mListView = (ListView) findViewById(R.id.listview); mSideBar = (SideBar) findViewById(R.id.sidebar); mSideBar.setIsCSP(true); mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener); mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); mSideBar.updateEntriesPropWithContentArray(mStrings); mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000 mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is 0xFFe5e5e5 mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is // 0xFFFFFFFF mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000 mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000 mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6 mSideBar.updateEntriesPropWithContentArray(mStrings); mListView.setOnScrollListener(this); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int index = getSectionForPosition(firstVisibleItem); mSideBar.updateCurrentIndex(index); } public void onScrollStateChanged(AbsListView view, int scrollState) { } OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() { @Override public void onTouchingLetterChanged(int letterIndex) { } @Override public void onTouchingLetterChanged(String touchIndexString) { int index = getPositionForSection(touchIndexString); mListView.setSelection(index); } @Override public void onTouchUp() { } }; public int getPositionForSection(String s) { for (int i = 0; i < mStrings.length; i++) { char firstLetter = mStrings[i].charAt(0); if (compare(firstLetter + "", s) == 0) { return i; } } return -1; } public int getSectionForPosition(int position) { char firstLetter = mStrings[position].charAt(0); String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries(); for (int i = 0; i < DEFALUT_ENTRIES.length; i++) { if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) { return i; } } return 0; // Don't recognize the letter - falls under zero'th section } protected int compare(String word, String letter) { final String firstLetter; if (word.length() == 0) { firstLetter = " "; } else { firstLetter = word.substring(0, 1); } Collator collator = java.text.Collator.getInstance(); collator.setStrength(java.text.Collator.PRIMARY); return collator.compare(firstLetter, letter); } public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie", "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola", "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost", "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi", "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa", "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger", "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin", "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio", "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel", "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela", "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse", "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" }; }
rickdynasty/TwsPluginFramework
TwsPluginDemo/src/main/java/com/example/plugindemo/activity/category/SideBarActivity.java
3,132
// default is 0xFFe5e5e5
line_comment
nl
package com.example.plugindemo.activity.category; import java.text.Collator; import android.app.TwsActivity; import android.os.Bundle; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.plugindemo.R; import com.tencent.tws.assistant.widget.SideBar; import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener; public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener { private ListView mListView; private SideBar mSideBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sidebar_widget); setTitle("测试共享控件SideBar"); mListView = (ListView) findViewById(R.id.listview); mSideBar = (SideBar) findViewById(R.id.sidebar); mSideBar.setIsCSP(true); mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener); mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); mSideBar.updateEntriesPropWithContentArray(mStrings); mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000 mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is<SUF> mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is // 0xFFFFFFFF mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000 mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000 mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6 mSideBar.updateEntriesPropWithContentArray(mStrings); mListView.setOnScrollListener(this); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int index = getSectionForPosition(firstVisibleItem); mSideBar.updateCurrentIndex(index); } public void onScrollStateChanged(AbsListView view, int scrollState) { } OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() { @Override public void onTouchingLetterChanged(int letterIndex) { } @Override public void onTouchingLetterChanged(String touchIndexString) { int index = getPositionForSection(touchIndexString); mListView.setSelection(index); } @Override public void onTouchUp() { } }; public int getPositionForSection(String s) { for (int i = 0; i < mStrings.length; i++) { char firstLetter = mStrings[i].charAt(0); if (compare(firstLetter + "", s) == 0) { return i; } } return -1; } public int getSectionForPosition(int position) { char firstLetter = mStrings[position].charAt(0); String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries(); for (int i = 0; i < DEFALUT_ENTRIES.length; i++) { if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) { return i; } } return 0; // Don't recognize the letter - falls under zero'th section } protected int compare(String word, String letter) { final String firstLetter; if (word.length() == 0) { firstLetter = " "; } else { firstLetter = word.substring(0, 1); } Collator collator = java.text.Collator.getInstance(); collator.setStrength(java.text.Collator.PRIMARY); return collator.compare(firstLetter, letter); } public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie", "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola", "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost", "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi", "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa", "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger", "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin", "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio", "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel", "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela", "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse", "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" }; }
False
2,942
29048_15
package pca; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import cern.colt.matrix.linalg.Algebra; import cern.jet.math.Functions; import util.Log; import util.Log.LogType; import util.TimeCounter; public class PCA { protected int numComponents; /* Dimension of reduced data. */ protected DoubleMatrix2D data = null; /* Original data */ private DoubleMatrix2D reducedData = null; /* Data after PCA */ protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */ protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */ private DoubleMatrix1D mean = null; private boolean meanDirty = true; private boolean dataLock = false; /* If the data already has been centered. */ public PCA() { } public PCA(int numComponents, DoubleMatrix2D reducedData, DoubleMatrix1D eigenValues, DoubleMatrix1D mean) { this.numComponents = numComponents; this.reducedData = reducedData; this.eigenValues = eigenValues; this.mean = mean; this.meanDirty = false; this.dataLock = true; } /** Create a new PCA with the provided data, with one column = one sample. */ public PCA(DoubleMatrix2D data) { this.data = data; } /** Add a new sample in the PCA. The first sample added decide the sample's size. * If further add is done with a different size, an exception is throw. */ public void addSample(DoubleMatrix1D sample) { if(dataLock) throw new RuntimeException("Data already locked."); if(data == null) { /* Sub-optimal, involve 2 copies. */ data = DoubleFactory2D.dense.make(sample.toArray(), sample.size()); } else { if(data.rows() != sample.size()) throw new RuntimeException("Unexpected sample length."); /* Sub-optimal, involve 3 copies. */ DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size()); data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy(); } } /** Compute the PCA and reduce the data. */ public void computePCA(int numComponents) { TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data."); this.numComponents = numComponents; Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions."); centerData(); doComputeBasis(); /* Compute reduced data. */ reducedData = new Algebra().mult(data, basis.viewDice()); t.stop(); } public boolean computationDone() { return dataLock; } /** This method should compute the basis matrix and the eigenValue matrix. */ protected void doComputeBasis() { /* This class need to be subclassed to implement a PCA method. */ assert(false); } /** @return the basis vector. */ public DoubleMatrix2D getBasis() { assert basis != null; return basis; } /** @return a vector of the feature space basis. */ public DoubleMatrix1D getBasisVector(int index) { assert basis != null; return basis.viewColumn(index); } /** @return one eigen value. */ public double getEigenValue(int index) { ensureReducedData(); return eigenValues.get(index); } /** @return the number of component of the feature space. */ public int getNumComponents() { ensureReducedData(); return numComponents; } /** @return the size of one sample. */ public int getSampleSize() { if(data == null) return 0; return data.rows(); } /** @return how many sample are stored. */ public int getSampleNumber() { if(data == null) return 0; return data.columns(); } /** @return one original sample. */ public DoubleMatrix1D getSample(int index) { return data.viewColumn(index); } /** @return one of the reduced model. */ public DoubleMatrix1D getFeatureSample(int index) { return reducedData.viewColumn(index).copy().assign(mean, Functions.plus); } /** @return a sample from the original data expressed in the feature space. * @param index the index of the sample in the original data. */ public DoubleMatrix1D sampleToFeatureSpace(int index) { return sampleToFeatureSpaceNoMean(data.viewColumn(index)); } /** @return an arbitrary sample expressed in the feature space. * @param sample the sample data. Length should be the same as the original data. */ public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) { ensureMean(); return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus)); } /** Internal sampleToFeatureSpace, for data that are already mean subtracted. * @param sample the sample to convert. */ private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) { ensureReducedData(); if(sample.size() != data.rows()) throw new IllegalArgumentException("Unexpected sample length."); return new Algebra().mult(basis, sample); } /** @return an arbitrary sample expressed in the sample space. * @param sample the sample data. Length should be the same as the feature space dimension. */ public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) { if(sample.size() != numComponents) throw new IllegalArgumentException("Unexpected sample length."); ensureMean(); DoubleMatrix1D s_copy = sample.copy(); s_copy.assign(eigenValues, Functions.mult); DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy); return result.assign(mean, Functions.plus); } /** Compute the error resulting for a projection to feature space and back for a sample. * This could be used to test the membership of a sample to the feature space. */ public double errorMembership(DoubleMatrix1D sample) { DoubleMatrix1D feat = sampleToFeatureSpace(sample); DoubleMatrix1D back = sampleToSampleSpace(feat); sample.assign(back, Functions.minus); sample.assign(Functions.square); return Math.sqrt(sample.zSum()); } /** @return the mean sample. */ public DoubleMatrix1D getMean() { ensureMean(); return mean; } @Override public String toString() { return "PCA: \n" + basis; } /** Update the mean sample of the original data. */ private void computeMean() { Log.debug(LogType.MODEL, "PCA: compute mean sample."); if(mean == null) mean = new DenseDoubleMatrix1D(data.rows()); else mean.assign(0.0); for(int i = 0; i < data.rows(); i++) { mean.set(i, data.viewRow(i).zSum() / data.columns()); } meanDirty = false; } /** Subtract the mean from all samples. */ private void centerData() { Log.debug(LogType.MODEL, "PCA: lock data."); this.dataLock = true; ensureMean(); for(int i = 0; i < data.columns(); i++) data.viewColumn(i).assign(mean, Functions.minus); } /** If no explicit computeBasis call have been made with a numComponents, * we compute the PCA with the same dimension as the original data. */ private void ensureReducedData() { if(reducedData == null) computePCA(data.rows()); } /** Ensure that the mean is properly computed. */ private void ensureMean() { if(meanDirty) computeMean(); } }
hillday/3DMM
src/pca/PCA.java
2,160
/** @return one eigen value. */
block_comment
nl
package pca; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import cern.colt.matrix.linalg.Algebra; import cern.jet.math.Functions; import util.Log; import util.Log.LogType; import util.TimeCounter; public class PCA { protected int numComponents; /* Dimension of reduced data. */ protected DoubleMatrix2D data = null; /* Original data */ private DoubleMatrix2D reducedData = null; /* Data after PCA */ protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */ protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */ private DoubleMatrix1D mean = null; private boolean meanDirty = true; private boolean dataLock = false; /* If the data already has been centered. */ public PCA() { } public PCA(int numComponents, DoubleMatrix2D reducedData, DoubleMatrix1D eigenValues, DoubleMatrix1D mean) { this.numComponents = numComponents; this.reducedData = reducedData; this.eigenValues = eigenValues; this.mean = mean; this.meanDirty = false; this.dataLock = true; } /** Create a new PCA with the provided data, with one column = one sample. */ public PCA(DoubleMatrix2D data) { this.data = data; } /** Add a new sample in the PCA. The first sample added decide the sample's size. * If further add is done with a different size, an exception is throw. */ public void addSample(DoubleMatrix1D sample) { if(dataLock) throw new RuntimeException("Data already locked."); if(data == null) { /* Sub-optimal, involve 2 copies. */ data = DoubleFactory2D.dense.make(sample.toArray(), sample.size()); } else { if(data.rows() != sample.size()) throw new RuntimeException("Unexpected sample length."); /* Sub-optimal, involve 3 copies. */ DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size()); data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy(); } } /** Compute the PCA and reduce the data. */ public void computePCA(int numComponents) { TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data."); this.numComponents = numComponents; Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions."); centerData(); doComputeBasis(); /* Compute reduced data. */ reducedData = new Algebra().mult(data, basis.viewDice()); t.stop(); } public boolean computationDone() { return dataLock; } /** This method should compute the basis matrix and the eigenValue matrix. */ protected void doComputeBasis() { /* This class need to be subclassed to implement a PCA method. */ assert(false); } /** @return the basis vector. */ public DoubleMatrix2D getBasis() { assert basis != null; return basis; } /** @return a vector of the feature space basis. */ public DoubleMatrix1D getBasisVector(int index) { assert basis != null; return basis.viewColumn(index); } /** @return one eigen<SUF>*/ public double getEigenValue(int index) { ensureReducedData(); return eigenValues.get(index); } /** @return the number of component of the feature space. */ public int getNumComponents() { ensureReducedData(); return numComponents; } /** @return the size of one sample. */ public int getSampleSize() { if(data == null) return 0; return data.rows(); } /** @return how many sample are stored. */ public int getSampleNumber() { if(data == null) return 0; return data.columns(); } /** @return one original sample. */ public DoubleMatrix1D getSample(int index) { return data.viewColumn(index); } /** @return one of the reduced model. */ public DoubleMatrix1D getFeatureSample(int index) { return reducedData.viewColumn(index).copy().assign(mean, Functions.plus); } /** @return a sample from the original data expressed in the feature space. * @param index the index of the sample in the original data. */ public DoubleMatrix1D sampleToFeatureSpace(int index) { return sampleToFeatureSpaceNoMean(data.viewColumn(index)); } /** @return an arbitrary sample expressed in the feature space. * @param sample the sample data. Length should be the same as the original data. */ public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) { ensureMean(); return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus)); } /** Internal sampleToFeatureSpace, for data that are already mean subtracted. * @param sample the sample to convert. */ private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) { ensureReducedData(); if(sample.size() != data.rows()) throw new IllegalArgumentException("Unexpected sample length."); return new Algebra().mult(basis, sample); } /** @return an arbitrary sample expressed in the sample space. * @param sample the sample data. Length should be the same as the feature space dimension. */ public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) { if(sample.size() != numComponents) throw new IllegalArgumentException("Unexpected sample length."); ensureMean(); DoubleMatrix1D s_copy = sample.copy(); s_copy.assign(eigenValues, Functions.mult); DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy); return result.assign(mean, Functions.plus); } /** Compute the error resulting for a projection to feature space and back for a sample. * This could be used to test the membership of a sample to the feature space. */ public double errorMembership(DoubleMatrix1D sample) { DoubleMatrix1D feat = sampleToFeatureSpace(sample); DoubleMatrix1D back = sampleToSampleSpace(feat); sample.assign(back, Functions.minus); sample.assign(Functions.square); return Math.sqrt(sample.zSum()); } /** @return the mean sample. */ public DoubleMatrix1D getMean() { ensureMean(); return mean; } @Override public String toString() { return "PCA: \n" + basis; } /** Update the mean sample of the original data. */ private void computeMean() { Log.debug(LogType.MODEL, "PCA: compute mean sample."); if(mean == null) mean = new DenseDoubleMatrix1D(data.rows()); else mean.assign(0.0); for(int i = 0; i < data.rows(); i++) { mean.set(i, data.viewRow(i).zSum() / data.columns()); } meanDirty = false; } /** Subtract the mean from all samples. */ private void centerData() { Log.debug(LogType.MODEL, "PCA: lock data."); this.dataLock = true; ensureMean(); for(int i = 0; i < data.columns(); i++) data.viewColumn(i).assign(mean, Functions.minus); } /** If no explicit computeBasis call have been made with a numComponents, * we compute the PCA with the same dimension as the original data. */ private void ensureReducedData() { if(reducedData == null) computePCA(data.rows()); } /** Ensure that the mean is properly computed. */ private void ensureMean() { if(meanDirty) computeMean(); } }
True
394
175634_1
package gameEngine.ramses.events; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; public class EventQueueRoom { //static class die een add en resolved event functie heeft. //als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het. //private static ArrayList<Event> _allEvents = new ArrayList<Event>(); public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners(); EventDispatcher currentParent; event.dispatcher = dispatcher; event.caster = dispatcher; callMethodsInListOfEvent(listListeners,event); if(event.isBubbles()){ currentParent = dispatcher.getParentListener(); while(currentParent != null){ event.caster = currentParent; listListeners = currentParent.getAllListeners(); callMethodsInListOfEvent(listListeners,event); currentParent = currentParent.getParentListener(); } } } private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ListenerItem currentItem; ArrayList<ListenerItem> list = listToLoop; if(list.size() > 0){ for(int i = list.size() - 1; i >= 0 ; i--){ currentItem = list.get(i); if(currentItem.getType() == event.getType()){ currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event); } } } } }
Darkfafi/JavaFrameworkRDP
src/gameEngine/ramses/events/EventQueueRoom.java
475
//als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het.
line_comment
nl
package gameEngine.ramses.events; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; public class EventQueueRoom { //static class die een add en resolved event functie heeft. //als een<SUF> //private static ArrayList<Event> _allEvents = new ArrayList<Event>(); public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners(); EventDispatcher currentParent; event.dispatcher = dispatcher; event.caster = dispatcher; callMethodsInListOfEvent(listListeners,event); if(event.isBubbles()){ currentParent = dispatcher.getParentListener(); while(currentParent != null){ event.caster = currentParent; listListeners = currentParent.getAllListeners(); callMethodsInListOfEvent(listListeners,event); currentParent = currentParent.getParentListener(); } } } private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ListenerItem currentItem; ArrayList<ListenerItem> list = listToLoop; if(list.size() > 0){ for(int i = list.size() - 1; i >= 0 ; i--){ currentItem = list.get(i); if(currentItem.getType() == event.getType()){ currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event); } } } } }
True
958
97801_0
package gui.screens; import domein.DomeinController; import gui.company.CompanyCardComponent; import gui.components.CustomMenu; import gui.components.LanguageBundle; import io.github.palexdev.materialfx.controls.MFXButton; import io.github.palexdev.materialfx.controls.MFXCheckbox; import io.github.palexdev.materialfx.controls.MFXScrollPane; import io.github.palexdev.materialfx.controls.MFXSlider; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import resources.ResourceController; import java.util.Locale; public class SettingScreen extends MFXScrollPane { private DomeinController dc; private ResourceController rs; private BorderPane root; private CustomMenu menu; private VBox pane = new VBox(); private ComboBox<String> languageComboBox; private static Label title; private static MFXCheckbox checkbox; private static Label soundLabel; private static Label languageLabel; public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) { this.dc = dc; pane.setAlignment(Pos.TOP_CENTER); pane.setSpacing(200); this.rs = rs; this.root = root; this.menu = menu; this.setContent(pane); this.setFitToHeight(true); this.setFitToWidth(true); setup(); } public void setup() { title = new Label(LanguageBundle.getString("SettingScreen_setting")); title.getStyleClass().add("title"); soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound")); VBox layoutBox = new VBox(); MFXSlider slider = new MFXSlider(); slider.setMin(0); slider.setMax(100); slider.setValue(rs.getCurrentVolume()*100); slider.setOnMouseReleased(e -> { System.out.println(slider.getValue()); rs.changeVolume(slider.getValue()); }); languageLabel = new Label("Language"); languageComboBox = new ComboBox<>(); HBox.setHgrow(languageComboBox, Priority.ALWAYS); languageComboBox.getItems().addAll("en", "nl"); languageComboBox.setValue("en"); // voeg een listener toe aan de ComboBox om de taal te wijzigen languageComboBox.setOnAction(e -> switchLanguage()); layoutBox.setAlignment(Pos.CENTER); checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute")); checkbox.setSelected(rs.isMute()); checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected())); layoutBox.setSpacing(20); layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox); pane.getChildren().addAll(title, layoutBox); } private void switchLanguage() { Locale selectedLocale; String selectedLanguage = languageComboBox.getValue(); if (selectedLanguage.equals("en")) { selectedLocale = new Locale("en"); } else { selectedLocale = new Locale("nl"); } // Wijzig de taal in de hele applicatie LanguageBundle.setLocale(selectedLocale); //update taal van pagina waarop je staat updateText(); /*LoginScreen.updateText(); MainScreen.updateText(); CompanyCardComponent.updateText(); NotificationScreen.updateText(); OrderScreen.updateText(); TransportDienstScreen.updateText(); RegisterScreen.updateText(); MyProductsScreen.updateText();*/ } public static void updateText() { title.setText(LanguageBundle.getString("SettingScreen_setting")); checkbox.setText(LanguageBundle.getString("SettingScreen_mute")); soundLabel.setText(LanguageBundle.getString("SettingScreen_sound")); } }
LaurensDM/Webshop-desktop
src/main/java/gui/screens/SettingScreen.java
1,144
// voeg een listener toe aan de ComboBox om de taal te wijzigen
line_comment
nl
package gui.screens; import domein.DomeinController; import gui.company.CompanyCardComponent; import gui.components.CustomMenu; import gui.components.LanguageBundle; import io.github.palexdev.materialfx.controls.MFXButton; import io.github.palexdev.materialfx.controls.MFXCheckbox; import io.github.palexdev.materialfx.controls.MFXScrollPane; import io.github.palexdev.materialfx.controls.MFXSlider; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import resources.ResourceController; import java.util.Locale; public class SettingScreen extends MFXScrollPane { private DomeinController dc; private ResourceController rs; private BorderPane root; private CustomMenu menu; private VBox pane = new VBox(); private ComboBox<String> languageComboBox; private static Label title; private static MFXCheckbox checkbox; private static Label soundLabel; private static Label languageLabel; public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) { this.dc = dc; pane.setAlignment(Pos.TOP_CENTER); pane.setSpacing(200); this.rs = rs; this.root = root; this.menu = menu; this.setContent(pane); this.setFitToHeight(true); this.setFitToWidth(true); setup(); } public void setup() { title = new Label(LanguageBundle.getString("SettingScreen_setting")); title.getStyleClass().add("title"); soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound")); VBox layoutBox = new VBox(); MFXSlider slider = new MFXSlider(); slider.setMin(0); slider.setMax(100); slider.setValue(rs.getCurrentVolume()*100); slider.setOnMouseReleased(e -> { System.out.println(slider.getValue()); rs.changeVolume(slider.getValue()); }); languageLabel = new Label("Language"); languageComboBox = new ComboBox<>(); HBox.setHgrow(languageComboBox, Priority.ALWAYS); languageComboBox.getItems().addAll("en", "nl"); languageComboBox.setValue("en"); // voeg een<SUF> languageComboBox.setOnAction(e -> switchLanguage()); layoutBox.setAlignment(Pos.CENTER); checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute")); checkbox.setSelected(rs.isMute()); checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected())); layoutBox.setSpacing(20); layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox); pane.getChildren().addAll(title, layoutBox); } private void switchLanguage() { Locale selectedLocale; String selectedLanguage = languageComboBox.getValue(); if (selectedLanguage.equals("en")) { selectedLocale = new Locale("en"); } else { selectedLocale = new Locale("nl"); } // Wijzig de taal in de hele applicatie LanguageBundle.setLocale(selectedLocale); //update taal van pagina waarop je staat updateText(); /*LoginScreen.updateText(); MainScreen.updateText(); CompanyCardComponent.updateText(); NotificationScreen.updateText(); OrderScreen.updateText(); TransportDienstScreen.updateText(); RegisterScreen.updateText(); MyProductsScreen.updateText();*/ } public static void updateText() { title.setText(LanguageBundle.getString("SettingScreen_setting")); checkbox.setText(LanguageBundle.getString("SettingScreen_mute")); soundLabel.setText(LanguageBundle.getString("SettingScreen_sound")); } }
True