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\n * \n * This file is part of (...TRUNCATED) | 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(...TRUNCATED) | line_comment | nl | "/* Copyright (C) 2008 Human Media Interaction - University of Twente\n * \n * This file is part of (...TRUNCATED) | False |
645 | 69594_0 | "package AbsentieLijst.userInterfaceLaag;_x000D_\n_x000D_\nimport AbsentieLijst.*;_x000D_\nimport ja(...TRUNCATED) | 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_\n_x000D_\nimport AbsentieLijst.*;_x000D_\nimport ja(...TRUNCATED) | True |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 24