answer
stringlengths 17
10.2M
|
|---|
package opendap.semantics.IRISail;
import opendap.wcs.v1_1_2.*;
import org.jdom.Element;
import org.jdom.filter.ElementFilter;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import org.openrdf.query.*;
import org.slf4j.Logger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.ConcurrentHashMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import org.openrdf.model.Value;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import com.ontotext.trree.owlim_ext.SailImpl;
/**
* A colon of LocalFileCatalog
*/
public class NewStaticRDFCatalog implements WcsCatalog, Runnable {
private Logger log; // = LoggerFactory.getLogger(StaticRDFCatalog.class);
private AtomicBoolean repositoryUpdateActive;
private ReentrantReadWriteLock _repositoryLock;
private XMLfromRDF buildDoc;
private long _catalogLastModifiedTime;
private ConcurrentHashMap<String, CoverageDescription> coverages;
private ReentrantReadWriteLock _catalogLock;
private Thread catalogUpdateThread;
private long firstUpdateDelay;
private long catalogUpdateInterval;
private long timeOfLastUpdate;
private boolean stopWorking = false;
private Element _config;
private String catalogCacheDirectory;
private String owlim_storage_folder;
private String resourcePath;
private boolean backgroundUpdates;
private boolean overrideBackgroundUpdates;
private HashMap<String, Vector<String> > coverageIDServer;
private boolean initialized;
public NewStaticRDFCatalog() {
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
catalogUpdateInterval = 20 * 60 * 1000; // 20 minutes worth of milliseconds
firstUpdateDelay = 5 * 1000; // 5 seconds worth of milliseconds
timeOfLastUpdate = 0;
stopWorking = false;
_catalogLock = new ReentrantReadWriteLock();
coverages = new ConcurrentHashMap<String, CoverageDescription>();
_repositoryLock = new ReentrantReadWriteLock();
repositoryUpdateActive = new AtomicBoolean();
repositoryUpdateActive.set(false);
backgroundUpdates = false;
overrideBackgroundUpdates = false;
buildDoc = null;
_catalogLastModifiedTime = -1;
_config = null;
catalogCacheDirectory = ".";
owlim_storage_folder ="owlim-storage";
resourcePath = ".";
initialized = false;
}
/**
*
* @param args Command line arguments
*/
public static void main(String[] args) {
long startTime, endTime;
double elapsedTime;
NewStaticRDFCatalog catalog = new NewStaticRDFCatalog();
try {
if(args.length>0)
System.out.println("arg[0]= " + args[0]);
catalog.resourcePath = ".";
catalog.catalogCacheDirectory = ".";
String configFileName;
configFileName = "file:///data/haibo/workspace/ioos/wcs_service.xml";
if (args.length > 0)
configFileName = args[0];
catalog.log.debug("main() using config file: " + configFileName);
Element olfsConfig = opendap.xml.Util.getDocumentRoot(configFileName);
catalog._config = (Element) olfsConfig.getDescendants(new ElementFilter("WcsCatalog")).next();
catalog.overrideBackgroundUpdates = true;
startTime = new Date().getTime();
catalog.init(catalog._config, catalog.catalogCacheDirectory, catalog.resourcePath);
endTime = new Date().getTime();
elapsedTime = (endTime - startTime) / 1000.0;
catalog.log.debug("Completed catalog update in " + elapsedTime + " seconds.");
catalog.log.debug("
catalog.log.debug("
catalog.log.debug("
} catch (Exception e) {
catalog.log.error("Caught "+e.getClass().getName()+" in main(): "
+ e.getMessage());
e.printStackTrace();
}
}
public void init(Element config, String defaultCacheDirectory, String defaultResourcePath) throws Exception {
if (initialized)
return;
backgroundUpdates = false;
_config = config;
processConfig(_config,defaultCacheDirectory, defaultResourcePath );
loadWcsCatalogFromRepository();
if (backgroundUpdates && !overrideBackgroundUpdates) {
catalogUpdateThread = new Thread(this);
catalogUpdateThread.start();
} else {
updateCatalog();
}
initialized = true;
}
public void updateCatalog() throws RepositoryException, InterruptedException{
IRISailRepository repository = setupRepository();
try {
log.debug("updateRepository(): Getting starting points (RDF imports).");
Vector<String> startingPoints = getRdfImports(_config);
log.info("updateCatalog(): Updating Repository...");
if (updateRepository(repository, startingPoints)) {
log.info("updateCatalog(): Extracting CoverageDescriptions from the Repository...");
extractCoverageDescrptionsFromRepository(repository);
String filename = catalogCacheDirectory + "coverageXMLfromRDF.xml";
log.info("updateCatalog(): Dumping CoverageDescriptions Document to: "+filename);
dumpCoverageDescriptionsDocument(filename);
log.info("updateCatalog(): Updating catalog cache....");
updateCatalogCache(repository);
}
else {
log.info("updateCatalog(): The repository was unchanged, nothing else to do.");
}
}
finally {
shutdownRepository(repository);
}
}
public boolean updateRepository(IRISailRepository repository, Vector <String> startingPoints) throws RepositoryException, InterruptedException{
boolean repositoryChanged = RdfPersistence.updateSemanticRepository(repository, startingPoints);
String filename = catalogCacheDirectory + "owlimHorstRepository.nt";
log.debug("updateRepository(): Dumping Semantic Repository to: " + filename);
RepositoryUtility.dumpRepository(repository, filename);
filename = catalogCacheDirectory + "owlimHorstRepository.trig";
log.debug("updateRepository(): Dumping Semantic Repository to: " + filename);
RepositoryUtility.dumpRepository(repository, filename);
return repositoryChanged;
}
public void loadWcsCatalogFromRepository() throws InterruptedException, RepositoryException {
long startTime, endTime;
double elapsedTime;
log.info("
log.info("
log.info("Loading WCS Catalog from Semantic Repository.");
startTime = new Date().getTime();
IRISailRepository repository = setupRepository();
try {
extractCoverageDescrptionsFromRepository(repository);
updateCatalogCache(repository);
}
finally {
shutdownRepository(repository);
}
endTime = new Date().getTime();
elapsedTime = (endTime - startTime) / 1000.0;
log.info("WCS Catalog loaded from the Semantic Repository. Loaded in " + elapsedTime + " seconds.");
log.info("
log.info("
}
public String getDataAccessUrl(String coverageID){
return coverageIDServer.get(coverageID).firstElement();
}
private void processConfig(Element config,String defaultCacheDirectory, String defaultResourcePath){
Element e;
File file;
catalogCacheDirectory = defaultCacheDirectory;
e = config.getChild("CacheDirectory");
if (e != null)
catalogCacheDirectory = e.getTextTrim();
if (catalogCacheDirectory != null &&
catalogCacheDirectory.length() > 0 &&
!catalogCacheDirectory.endsWith("/"))
catalogCacheDirectory += "/";
file = new File(catalogCacheDirectory);
if (!file.exists()) {
if (!file.mkdirs()) {
log.error("Unable to create cache directory: " + catalogCacheDirectory);
if(!catalogCacheDirectory.equals(defaultCacheDirectory)){
file = new File(defaultCacheDirectory);
if (!file.exists()) {
if (!file.mkdirs()) {
log.error("Unable to create cache directory: " + defaultCacheDirectory);
log.error("Process probably doomed...");
}
}
}
else {
log.error("Process probably doomed...");
}
}
}
log.info("Using catalogCacheDirectory: "+ catalogCacheDirectory);
resourcePath = defaultResourcePath;
e = config.getChild("ResourcePath");
if (e != null)
resourcePath = e.getTextTrim();
if (resourcePath != null &&
resourcePath.length() > 0 &&
!resourcePath.endsWith("/"))
resourcePath += "/";
file = new File(this.resourcePath);
if (!file.exists()) {
log.error("Unable to locate resource directory: " + resourcePath);
file = new File(defaultResourcePath);
if (!file.exists()) {
log.error("Unable to locate default resource directory: " + defaultResourcePath);
log.error("Process probably doomed...");
}
}
log.info("Using resourcePath: "+resourcePath);
e = config.getChild("useUpdateCatalogThread");
if(e != null){
backgroundUpdates = true;
String s = e.getAttributeValue("updateInterval");
if (s != null){
catalogUpdateInterval = Long.parseLong(s) * 1000;
}
s = e.getAttributeValue("firstUpdateDelay");
if (s != null){
firstUpdateDelay = Long.parseLong(s) * 1000;
}
}
log.info("backgroundUpdates: "+backgroundUpdates);
log.info("Catalog update interval: "+catalogUpdateInterval+"ms");
log.info("First update delay: "+firstUpdateDelay+"ms");
}
private void shutdownRepository(IRISailRepository repository) throws RepositoryException {
log.debug("shutdownRepository)(): Shutting down Repository...");
repository.shutDown();
log.debug("shutdownRepository(): Repository shutdown complete.");
}
private IRISailRepository setupRepository() throws RepositoryException, InterruptedException {
log.info("Setting up Semantic Repository.");
//OWLIM Sail Repository (inferencing makes this somewhat slow)
SailImpl owlimSail = new com.ontotext.trree.owlim_ext.SailImpl();
IRISailRepository repository = new IRISailRepository(owlimSail, resourcePath, catalogCacheDirectory); //owlim inferencing
log.info("Configuring Semantic Repository.");
File storageDir = new File(catalogCacheDirectory); //define local copy of repository
owlimSail.setDataDir(storageDir);
log.debug("Semantic Repository Data directory set to: "+ catalogCacheDirectory);
// prepare config
owlimSail.setParameter("storage-folder", owlim_storage_folder);
log.debug("Semantic Repository 'storage-folder' set to: "+owlim_storage_folder);
// Choose the operational ruleset
String ruleset;
ruleset = "owl-horst";
//ruleset = "owl-max";
owlimSail.setParameter("ruleset", ruleset);
//owlimSail.setParameter("ruleset", "owl-max");
//owlimSail.setParameter("partialRDFs", "false");
log.debug("Semantic Repository 'ruleset' set to: "+ ruleset);
log.info("Intializing Semantic Repository.");
// Initialize repository
repository.startup(); //needed
log.info("Adding InternalStartingPoint to repository.");
RepositoryUtility.addInternalStartingPoint(repository);
log.info("Semantic Repository Ready.");
if(Thread.currentThread().isInterrupted())
throw new InterruptedException("Thread.currentThread.isInterrupted() returned 'true'.");
return repository;
}
private void extractCoverageDescrptionsFromRepository(IRISailRepository repository) throws RepositoryException {
RepositoryConnection con = repository.getConnection();
log.info("Repository connection has been opened.");
extractCoverageDescrptionsFromRepository(con);
log.info("Closing repository connection.");
con.close(); //close connection first
}
private void extractCoverageDescrptionsFromRepository(RepositoryConnection con) {
//retrieve XML from the RDF store.
log.info("extractCoverageDescrptionsFromRepository() - Extracting CoverageDescriptions from repository.");
log.info("extractCoverageDescrptionsFromRepository() - Building CoverageDescription XML from repository.");
buildDoc = new XMLfromRDF(con, "CoverageDescriptions", "http://www.opengis.net/wcs/1.1#CoverageDescription");
buildDoc.getXMLfromRDF("http://www.opengis.net/wcs/1.1#CoverageDescription"); //build a JDOM doc by querying against the RDF store
// Next we update the cached maps of datasetUrl/serverIDs and datasetUrl/wcsID
// held in the CoverageIDGenerator so that subsequent calls to the CoverageIdGenerator
// create new IDs correctly.
try {
log.info("extractCoverageDescrptionsFromRepository() - Updating CoverageIdGenerator Id Caches.");
HashMap<String, Vector<String>> coverageIdToServerMap = getCoverageIDServerURL(con);
CoverageIdGenerator.updateIdCaches(coverageIdToServerMap);
} catch (RepositoryException e) {
log.error("extractCoverageDescrptionsFromRepository(): Caught RepositoryException. msg: "
+ e.getMessage());
} catch (MalformedQueryException e) {
log.error("extractCoverageDescrptionsFromRepository(): Caught MalformedQueryException. msg: "
+ e.getMessage());
} catch (QueryEvaluationException e) {
log.error("extractCoverageDescrptionsFromRepository(): Caught QueryEvaluationException. msg: "
+ e.getMessage());
}
}
private void dumpCoverageDescriptionsDocument(String filename) {
//print out the XML
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
try {
FileOutputStream fos = new FileOutputStream(filename);
outputter.output(buildDoc.getDoc(), fos);
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void destroy() {
log.debug("destroy(): Attempting to aquire WriteLock from _catalogLock and _repositoryLock.");
ReentrantReadWriteLock.WriteLock catLock = _catalogLock.writeLock();
ReentrantReadWriteLock.WriteLock reposLock = _repositoryLock.writeLock();
try {
catLock.lock();
reposLock.lock();
log.debug("destroy(): WriteLocks Aquired.");
setStopFlag(true);
if(catalogUpdateThread!=null){
log.debug("destroy() Current thread '"+Thread.currentThread().getName()+"' Interrupting catalogUpdateThread '"+catalogUpdateThread+"'");
catalogUpdateThread.interrupt();
log.debug("destroy(): catalogUpdateThread '"+catalogUpdateThread+"' interrupt() called.");
}
}
finally{
catLock.unlock();
reposLock.unlock();
log.debug("destroy(): Released WriteLock for _catalogLock and _repositoryLock.");
log.debug("destroy(): Complete.");
}
}
private Vector<String> getRdfImports(Element config) {
Vector<String> rdfImports = new Vector<String>();
Element e;
String s;
/**
* Load individual dataset references
*/
Iterator i = config.getChildren("dataset").iterator();
String datasetURL;
while (i.hasNext()) {
e = (Element) i.next();
datasetURL = e.getTextNormalize();
if (!datasetURL.endsWith(".rdf")) {
if (datasetURL.endsWith(".ddx") |
datasetURL.endsWith(".dds") |
datasetURL.endsWith(".das")
) {
datasetURL = datasetURL.substring(0, datasetURL.lastIndexOf("."));
}
datasetURL += ".rdf";
}
rdfImports.add(datasetURL);
log.info("Added dataset reference " + datasetURL + " to RDF imports list.");
log.debug("<wcs:Identifier>"+CoverageIdGenerator.getWcsIdString(datasetURL)+"</wcs:Identifier>");
}
/**
* Load THREDDS Catalog references.
*/
i = config.getChildren("ThreddsCatalog").iterator();
String catalogURL;
boolean recurse;
while (i.hasNext()) {
e = (Element) i.next();
catalogURL = e.getTextNormalize();
recurse = false;
s = e.getAttributeValue("recurse");
if (s != null && s.equalsIgnoreCase("true"))
recurse = true;
ThreddsCatalogUtil tcu = null;
try {
// Passing false means no caching but also no exception.
// Maybe there's a better way to code the TCU ctor?
tcu = new ThreddsCatalogUtil();
}
catch (Exception e1) {
log.debug("ThreddsCatalogUtil exception: " + e1.getMessage());
}
Vector<String> datasetURLs = tcu.getDataAccessURLs(catalogURL, ThreddsCatalogUtil.SERVICE.OPeNDAP, recurse);
for (String dataset : datasetURLs) {
dataset += ".rdf";
rdfImports.add(dataset);
log.info("Added dataset reference " + dataset + " to RDF imports list.");
}
}
/**
* Load RDF Imports
*/
i = config.getChildren("RdfImport").iterator();
while (i.hasNext()) {
e = (Element) i.next();
s = e.getTextNormalize();
rdfImports.add(s);
log.info("Added reference " + s + " to RDF imports list.");
}
return rdfImports;
}
private void ingestCatalog(IRISailRepository repository) throws Exception {
log.info("Ingesting catalog from CoverageDescriptions Document built by the XMLFromRDF object...");
HashMap<String, String> lmtfc;
String contextLMT;
String coverageID;
Element idElement;
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
long lastModifiedTime;
String dapVariableID;
RepositoryConnection con = null;
List<Element> coverageDescriptions = buildDoc.getDoc().getRootElement().getChildren();
try {
con = repository.getConnection();
lmtfc = RepositoryUtility.getLastModifiedTimesForContexts(con);
for(Element cde: coverageDescriptions){
idElement = cde.getChild("Identifier",WCS.WCS_NS);
if(idElement!=null){
coverageID = idElement.getTextTrim();
contextLMT = lmtfc.get(coverageID);
String dateTime = contextLMT.substring(0, 10) + " " + contextLMT.substring(11, 19) + " +0000";
log.debug("CoverageDescription '"+coverageID+"' has a last modified time of " + dateTime);
lastModifiedTime = sdf.parse(dateTime).getTime();
CoverageDescription coverageDescription = ingestCoverageDescription(cde, lastModifiedTime);
if(_catalogLastModifiedTime <lastModifiedTime)
_catalogLastModifiedTime = lastModifiedTime;
if(coverageDescription!=null){
for(String fieldID: coverageDescription.getFieldIDs()){
log.debug("Getting DAP Coordinate IDs for FieldID: "+fieldID);
dapVariableID = getLatitudeCoordinateDapId( con, coverageID, fieldID);
coverageDescription.setLatitudeCoordinateDapId(fieldID,dapVariableID);
dapVariableID = getLongitudeCoordinateDapId( con, coverageID, fieldID);
coverageDescription.setLongitudeCoordinateDapId(fieldID,dapVariableID);
dapVariableID = getElevationCoordinateDapId( con, coverageID, fieldID);
coverageDescription.setElevationCoordinateDapId(fieldID,dapVariableID);
dapVariableID = getTimeCoordinateDapId( con, coverageID, fieldID);
coverageDescription.setTimeCoordinateDapId(fieldID,dapVariableID);
}
}
log.debug("Ingested CoverageDescription '" + coverageID + "'");
}
}
}
finally {
if(con!=null)
con.close();
}
}
private CoverageDescription ingestCoverageDescription(Element cde, long lastModified) {
CoverageDescription cd = null;
try {
cd = new CoverageDescription(cde, lastModified);
coverages.put(cd.getIdentifier(), cd);
log.info("Ingested CoverageDescription: " + cd.getIdentifier());
} catch (WcsException e) {
XMLOutputter xmlo = new XMLOutputter(Format.getCompactFormat());
String wcseElem = xmlo.outputString(e.getExceptionElement());
String cvgDesc = xmlo.outputString(cde);
log.error("ingestCoverageDescription(): Failed to ingest CoverageDescription!");
log.error("ingestCoverageDescription(): WcsException: " + wcseElem + "");
log.error("ingestCoverageDescription(): Here is the XML element that failed to ingest: " + cvgDesc);
}
return cd;
}
public boolean hasCoverage(String id) {
log.debug("Looking for a coverage with ID: " + id);
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
return coverages.containsKey(id);
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
}
public Element getCoverageDescriptionElement(String id) {
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
CoverageDescription cd = coverages.get(id);
if(cd==null)
return null;
return cd.getElement();
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
}
public List<Element> getCoverageDescriptionElements() throws WcsException {
throw new WcsException("getCoverageDescriptionElements() method Not Implemented", WcsException.NO_APPLICABLE_CODE);
}
public CoverageDescription getCoverageDescription(String id) {
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
return coverages.get(id);
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
}
public Element getCoverageSummaryElement(String id) throws WcsException {
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
return coverages.get(id).getCoverageSummary();
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
}
public List<Element> getCoverageSummaryElements() throws WcsException {
ArrayList<Element> coverageSummaries = new ArrayList<Element>();
Enumeration e;
CoverageDescription cd;
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
// Get all of the unique formats.
e = coverages.elements();
while (e.hasMoreElements()) {
cd = (CoverageDescription) e.nextElement();
coverageSummaries.add(cd.getCoverageSummary());
}
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
return coverageSummaries;
}
public List<Element> getSupportedFormatElements() {
ArrayList<Element> supportedFormats = new ArrayList<Element>();
HashMap<String, Element> uniqueFormats = new HashMap<String, Element>();
Enumeration enm;
Element e;
Iterator i;
CoverageDescription cd;
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
// Get all of the unique formats.
enm = coverages.elements();
while (enm.hasMoreElements()) {
cd = (CoverageDescription) enm.nextElement();
i = cd.getSupportedFormatElements().iterator();
while (i.hasNext()) {
e = (Element) i.next();
uniqueFormats.put(e.getTextTrim(), e);
}
}
i = uniqueFormats.values().iterator();
while (i.hasNext()) {
supportedFormats.add((Element) i.next());
}
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
return supportedFormats;
}
public List<Element> getSupportedCrsElements() {
ArrayList<Element> supportedCRSs = new ArrayList<Element>();
HashMap<String, Element> uniqueCRSs = new HashMap<String, Element>();
Enumeration enm;
Element e;
Iterator i;
CoverageDescription cd;
ReentrantReadWriteLock.ReadLock lock = _catalogLock.readLock();
try {
lock.lock();
log.debug("_catalogLock ReadLock Acquired.");
// Get all of the unique formats.
enm = coverages.elements();
while (enm.hasMoreElements()) {
cd = (CoverageDescription) enm.nextElement();
i = cd.getSupportedCrsElements().iterator();
while (i.hasNext()) {
e = (Element) i.next();
uniqueCRSs.put(e.getTextTrim(), e);
}
}
i = uniqueCRSs.values().iterator();
while (i.hasNext()) {
supportedCRSs.add((Element) i.next());
}
}
finally {
lock.unlock();
log.debug("_catalogLock ReadLock Released.");
}
return supportedCRSs;
}
private String getLatitudeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) {
log.debug("getLatitudeCoordinateDapId(): Getting the DAP variable ID the represents the latitude coordinate for FieldID: "+fieldId);
String qString = createCoordinateIdQuery("A_1D_latitude", fieldId);
String coordinateDapId = runQuery(con, qString);
return coordinateDapId;
}
private String getLongitudeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) {
String qString = createCoordinateIdQuery("A_1D_longitude", fieldId);
String coordinateDapId = runQuery(con, qString);
return coordinateDapId;
}
private String getElevationCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) {
String qString = createCoordinateIdQuery("A_elevation", fieldId);
String coordinateDapId = runQuery(con, qString);
return coordinateDapId;
}
private String getTimeCoordinateDapId(RepositoryConnection con, String coverageId, String fieldId) {
String qString = createCoordinateIdQuery("A_time", fieldId);
String coordinateDapId = runQuery(con, qString);
return coordinateDapId;
}
private String runQuery(RepositoryConnection con, String qString){
String coordinateDapId = null;
try {
TupleQueryResult result = null;
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,qString);
result = tupleQuery.evaluate();
if (result != null) {
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Value firstValue = bindingSet.getValue("cid");
coordinateDapId = firstValue.stringValue();
}
} else {
log.debug("No query result!");
}
} catch (RepositoryException e) {
log.error("getTimeCoordinateDapId(String coverageId, String fieldId) has a problem: " +
e.getMessage()) ;
e.printStackTrace();
} catch (MalformedQueryException e) {
log.error("getTimeCoordinateDapId(String coverageId, String fieldId) has a problem: " +
e.getMessage()) ;
e.printStackTrace();
} catch (QueryEvaluationException e) {
log.error("getTimeCoordinateDapId(String coverageId, String fieldId) has a problem: " +
e.getMessage()) ;
e.printStackTrace();
}
return coordinateDapId;
}
private String createCoordinateIdQuery(String coordinateName, String fieldStr){
String qString = "select cid " +
"FROM {cover} wcs:Identifier {covid} ; wcs:Range {} wcs:Field "+
"{field} wcs:Identifier {fieldid}, "+
"{field} ncobj:hasCoordinate {cid} rdf:type {cfobj:A_time} "+
"WHERE covid= " +coordinateName + " "+
"AND fieldid="+ fieldStr +
" USING NAMESPACE " +
"wcs=<http://www.opengis.net/wcs/1.1
"ncobj=<http://iridl.ldeo.columbia.edu/ontologies/netcdf-obj.owl
"cfobj=<http://iridl.ldeo.columbia.edu/ontologies/cf-obj.owl
log.debug("createCoordinateIdQuery: Built query string: '"+qString+"'");
return qString ;
}
public long getLastModified() {
return _catalogLastModifiedTime;
}
public void setStopFlag(boolean flag){
stopWorking = flag;
}
public void updateCatalogCache(IRISailRepository repository) throws InterruptedException{
Thread thread = Thread.currentThread();
int biffCount = 0;
if (!stopWorking && !thread.isInterrupted() ) {
ReentrantReadWriteLock.WriteLock catlock = _catalogLock.writeLock();
ReentrantReadWriteLock.ReadLock repLock = _repositoryLock.readLock();
try {
repLock.lock();
catlock.lock();
log.debug("_catalogLock WriteLock Acquired.");
if (!stopWorking && !thread.isInterrupted()) {
coverageIDServer = getCoverageIDServerURL(repository);
addSupportedFormats(buildDoc.getRootElement());
ingestCatalog(repository);
timeOfLastUpdate = new Date().getTime();
log.debug("Catalog Cache updated at "+ new Date(timeOfLastUpdate));
}
}
catch (Exception e) {
log.error("updateCatalogCache() has a problem: " +
e.getMessage() +
" biffCount: " + (++biffCount));
e.printStackTrace();
}
finally {
catlock.unlock();
repLock.unlock();
log.debug("_catalogLock WriteLock Released.");
}
}
if(thread.isInterrupted()) {
log.warn("updateCatalog(): WARNING! Thread "+thread.getName()+" was interrupted!");
throw new InterruptedException();
}
}
public HashMap<String, Vector<String>> getCoverageIDServerURL(IRISailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
RepositoryConnection con = null;
HashMap<String, Vector<String>> coverageIDServer;
try {
con = repo.getConnection();
coverageIDServer = getCoverageIDServerURL(con);
return coverageIDServer;
} finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error(e.getClass().getName()+": Failed to close repository connection. Msg: "
+ e.getMessage());
}
}
}
}
/**
*
* @param con
* @return
* @throws RepositoryException
* @throws MalformedQueryException
* @throws QueryEvaluationException
*/
public HashMap<String, Vector<String>> getCoverageIDServerURL(RepositoryConnection con) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
TupleQueryResult result;
HashMap<String, Vector<String>> coverageIDServer = new HashMap<String, Vector<String>>();
String queryString = "SELECT coverageurl,coverageid " +
"FROM " +
"{} wcs:CoverageDescription {coverageurl} wcs:Identifier {coverageid} " +
"USING NAMESPACE " +
"wcs = <http://www.opengis.net/wcs/1.1
log.debug("getCoverageIDServerURL() - QueryString (coverage ID and server URL): \n" + queryString);
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString);
result = tupleQuery.evaluate();
log.debug("getCoverageIDServerURL() - Qresult: " + result.hasNext());
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Vector<String> coverageURL = new Vector<String>();
if (bindingSet.getValue("coverageid") != null && bindingSet.getValue("coverageurl") != null) {
Value valueOfcoverageid = bindingSet.getValue("coverageid");
Value valueOfcoverageurl = bindingSet.getValue("coverageurl");
coverageURL.addElement(valueOfcoverageurl.stringValue());
log.debug("getCoverageIDServerURL() - coverageid: "+valueOfcoverageid.stringValue());
log.debug("getCoverageIDServerURL() - coverageurl: "+valueOfcoverageurl.stringValue());
if (coverageIDServer.containsKey(valueOfcoverageid.stringValue()))
coverageIDServer.get(valueOfcoverageid.stringValue()).addElement(valueOfcoverageurl.stringValue());
else
coverageIDServer.put(valueOfcoverageid.stringValue(), coverageURL);
}
}
return coverageIDServer;
}
public void run() {
try {
log.info("************* STARTING CATALOG UPDATE THREAD.");
try {
log.info("************* CATALOG UPDATE THREAD sleeping for " + firstUpdateDelay / 1000.0 + " seconds.");
Thread.sleep(firstUpdateDelay);
} catch (InterruptedException e) {
log.warn("Caught Interrupted Exception.");
stopWorking = true;
}
int updateCounter = 0;
long startTime, endTime;
long elapsedTime, sleepTime;
stopWorking = false;
Thread thread = Thread.currentThread();
while (!stopWorking) {
try {
startTime = new Date().getTime();
try {
updateCatalog();
} catch (RepositoryException e) {
log.error("Problem using Repository! msg: "+e.getMessage());
}
endTime = new Date().getTime();
elapsedTime = (endTime - startTime);
updateCounter++;
log.debug("Completed catalog update " + updateCounter + " in " + elapsedTime / 1000.0 + " seconds.");
sleepTime = catalogUpdateInterval - elapsedTime;
stopWorking = thread.isInterrupted();
if (!stopWorking && sleepTime > 0) {
log.debug("Catalog Update thread sleeping for " + sleepTime / 1000.0 + " seconds.");
Thread.sleep(sleepTime);
}
} catch (InterruptedException e) {
log.warn("Caught Interrupted Exception.");
stopWorking = true;
}
}
}
finally {
destroy();
}
log.info("************* EXITING CATALOG UPDATE THREAD.");
}
private void addSupportedFormats(Element coverages) throws MalformedURLException {
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
Element coverageDescription;
Element identifierElem;
Iterator i;
String coverageID;
String msg;
Vector<String> servers;
i = coverages.getChildren().iterator();
while(i.hasNext()){
coverageDescription = (Element)i.next();
identifierElem = coverageDescription.getChild("Identifier",WCS.WCS_NS);
if(identifierElem!=null){
coverageID = identifierElem.getTextTrim();
servers = coverageIDServer.get(coverageID);
Vector<Element> supportedFormats = getWcsSupportedFormatElements(new URL(servers.get(0)));
coverageDescription.addContent(supportedFormats);
msg = "Adding supported formats to coverage "+coverageID+ "\n"+
"CoverageDescription Element: \n "+xmlo.outputString(coverageDescription)+"\n"+
"Coverage "+coverageID+" held at: \n";
for(String s: servers){
msg += " "+s+"\n";
}
log.debug(msg);
}
else {
log.error("addSupportedFormats() - Failed to locate wcs:Identifier element for Coverage!");
//@todo Throw an exception (what kind??) here!!
}
}
}
private Vector<Element> getWcsSupportedFormatElements(URL dapServerUrl){
Vector<Element> sfEs = new Vector<Element>();
String[] formats = ServerCapabilities.getSupportedFormatStrings(dapServerUrl);
Element sf;
for(String format: formats){
sf = new Element("SupportedFormat",WCS.WCS_NS);
sf.setText(format);
sfEs.add(sf);
}
return sfEs;
}
private void checkExecutionState() throws InterruptedException {
Thread thread = Thread.currentThread();
boolean isInterrupted = thread.isInterrupted();
if(isInterrupted || stopWorking){
log.warn("updateRepository2(): WARNING! Thread "+thread.getName()+" was interrupted!");
throw new InterruptedException("Thread.currentThread.isInterrupted() returned '"+isInterrupted+"'. stopWorking='"+stopWorking+"'");
}
}
}
|
package beast.math.distributions;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.ContinuousDistribution;
import org.apache.commons.math.distribution.IntegerDistribution;
import beast.core.CalculationNode;
import beast.core.Description;
import beast.core.Input;
import beast.core.Valuable;
/**
* A class that describes a parametric distribution
*
* @author Alexei Drummond
* @version $Id: ParametricDistributionModel.java,v 1.4 2005/05/24 20:25:59 rambaut Exp $
*/
@Description("A class that describes a parametric distribution, that is, a distribution that takes some " +
"parameters/valuables as inputs and can produce (cummulative) densities and inverse " +
"cummulative densities.")
public abstract class ParametricDistribution extends CalculationNode implements ContinuousDistribution {
public Input<Double> m_offset = new Input<Double>("offset","offset of origin (defaults to 0)", 0.0);
abstract public org.apache.commons.math.distribution.Distribution getDistribution();
/** Calculate log probability of a valuable x for this distribution.
* If x is multidimensional, the components of x are assumed to be independent,
* so the sum of log probabilities of all elements of x is returned as the prior.
**/
public double calcLogP(Valuable x) throws Exception {
double fOffset = m_offset.get();
double fLogP = 0;
for (int i = 0; i < x.getDimension(); i++) {
double fX = x.getArrayValue(i) - fOffset;
//fLogP += Math.log(density(fX));
fLogP += logDensity(fX);
}
return fLogP;
}
/**
* For this distribution, X, this method returns x such that P(X < x) = p.
* @param p the cumulative probability.
* @return x.
* @throws MathException if the inverse cumulative probability can not be
* computed due to convergence or other numerical errors.
*/
@Override
public double inverseCumulativeProbability(double p) throws MathException {
org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).inverseCumulativeProbability(p);
} else if (dist instanceof IntegerDistribution) {
return dist.cumulativeProbability(p);
}
return 0.0;
}
/**
* Return the probability density for a particular point.
* @param x The point at which the density should be computed.
* @return The pdf at point x.
*/
@Override
public double density(double x) {
org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).density(x);
} else if (dist instanceof IntegerDistribution) {
return ((IntegerDistribution)dist).probability(x);
}
return 0.0;
}
@Override
public double logDensity(double x) {
org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).logDensity(x);
} else if (dist instanceof IntegerDistribution) {
return Math.log(((IntegerDistribution)dist).probability(x));
}
return 0.0;
}
/**
* For a random variable X whose values are distributed according
* to this distribution, this method returns P(X ≤ x). In other words,
* this method represents the (cumulative) distribution function, or
* CDF, for this distribution.
*
* @param x the value at which the distribution function is evaluated.
* @return the probability that a random variable with this
* distribution takes a value less than or equal to <code>x</code>
* @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors.
*/
@Override
public double cumulativeProbability(double x) throws MathException {
return getDistribution().cumulativeProbability(x);
}
@Override
public double cumulativeProbability(double x0, double x1) throws MathException {
return getDistribution().cumulativeProbability(x0, x1);
}
}
|
package beast.math.distributions;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.ContinuousDistribution;
import org.apache.commons.math.distribution.IntegerDistribution;
import beast.core.CalculationNode;
import beast.core.Description;
import beast.core.Function;
import beast.core.Input;
import beast.util.Randomizer;
import java.sql.Types;
/**
* A class that describes a parametric distribution
*
* * (FIXME) cumulative functions disregard offset. Serious bug if they are used.
*
* @author Alexei Drummond
* @version $Id: ParametricDistributionModel.java,v 1.4 2005/05/24 20:25:59 rambaut Exp $
*/
@Description("A class that describes a parametric distribution, that is, a distribution that takes some " +
"parameters/valuables as inputs and can produce (cummulative) densities and inverse " +
"cummulative densities.")
public abstract class ParametricDistribution extends CalculationNode implements ContinuousDistribution {
public final Input<Double> offsetInput = new Input<Double>("offset", "offset of origin (defaults to 0)", 0.0);
abstract public org.apache.commons.math.distribution.Distribution getDistribution();
/**
* Calculate log probability of a valuable x for this distribution.
* If x is multidimensional, the components of x are assumed to be independent,
* so the sum of log probabilities of all elements of x is returned as the prior.
*/
public double calcLogP(final Function x) throws Exception {
final double fOffset = offsetInput.get();
double fLogP = 0;
for (int i = 0; i < x.getDimension(); i++) {
final double fX = x.getArrayValue(i) - fOffset;
//fLogP += Math.log(density(fX));
fLogP += logDensity(fX);
}
return fLogP;
}
/*
* This implemenatation is only suitable for univariate distributions.
* Must be overwritten for multivariate ones.
*/
public Double[][] sample(final int size) throws Exception {
final Double[][] sample = new Double[size][];
for (int i = 0; i < sample.length; i++) {
final double p = Randomizer.nextDouble();
sample[i] = new Double[]{inverseCumulativeProbability(p)+offsetInput.get()};
}
return sample;
}
/**
* For this distribution, X, this method returns x such that P(X < x) = p.
*
* @param p the cumulative probability.
* @return x.
* @throws MathException if the inverse cumulative probability can not be
* computed due to convergence or other numerical errors.
*/
//@Override
public double inverseCumulativeProbability(final double p) throws MathException {
final org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).inverseCumulativeProbability(p);
} else if (dist instanceof IntegerDistribution) {
return dist.cumulativeProbability(p);
}
return 0.0;
}
/**
* Return the probability density for a particular point.
* NB this does not take offset in account
*
* @param x The point at which the density should be computed.
* @return The pdf at point x.
*/
//@Override
public double density(double x) {
final double offset = getOffset();
if( x >= offset ) {
x -= offset;
final org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).density(x);
} else if (dist instanceof IntegerDistribution) {
return ((IntegerDistribution) dist).probability(x);
}
}
return 0.0;
}
//@Override
public double logDensity(double x) {
final double offset = getOffset();
if( x >= offset ) {
x -= offset;
final org.apache.commons.math.distribution.Distribution dist = getDistribution();
if (dist instanceof ContinuousDistribution) {
return ((ContinuousDistribution) dist).logDensity(x);
} else if (dist instanceof IntegerDistribution) {
return Math.log(((IntegerDistribution) dist).probability(x));
}
}
return Double.NEGATIVE_INFINITY;
}
/**
* For a random variable X whose values are distributed according
* to this distribution, this method returns P(X ≤ x). In other words,
* this method represents the (cumulative) distribution function, or
* CDF, for this distribution.
*
* @param x the value at which the distribution function is evaluated.
* @return the probability that a random variable with this
* distribution takes a value less than or equal to <code>x</code>
* @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors.
*/
//@Override
public double cumulativeProbability(final double x) throws MathException {
return getDistribution().cumulativeProbability(x);
}
//@Override
public double cumulativeProbability(final double x0, final double x1) throws MathException {
return getDistribution().cumulativeProbability(x0, x1);
}
/**
* @return offset of distribution.
*/
public double getOffset() {
return offsetInput.get();
}
/** returns mean of distribution, if implemented **/
public double getMean() {
throw new RuntimeException("Not implemented yet");
}
}
|
package org.anddev.andengine.entity.sprite;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.entity.primitives.Rectangle;
import org.anddev.andengine.opengl.GLHelper;
import org.anddev.andengine.opengl.texture.TextureRegion;
/**
* @author Nicolas Gramlich
* @since 11:38:53 - 08.03.2010
*/
public abstract class BaseSprite extends Rectangle {
// Constants
private static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_SRC_ALPHA;
private static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA;
// Fields
protected TextureRegion mTextureRegion;
// Constructors
public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final TextureRegion pTextureRegion) {
super(pX, pY, pWidth, pHeight);
assert(pTextureRegion != null);
this.mTextureRegion = pTextureRegion;
this.setBlendFunction(BLENDFUNCTION_SOURCE_DEFAULT, BLENDFUNCTION_DESTINATION_DEFAULT);
}
// Getter & Setter
public TextureRegion getTextureRegion() {
return this.mTextureRegion;
}
public void setTextureRegion(final TextureRegion pTextureRegion){
this.mTextureRegion = pTextureRegion;
}
// Methods for/from SuperClass/Interfaces
@Override
public void reset() {
super.reset();
this.setBlendFunction(BLENDFUNCTION_SOURCE_DEFAULT, BLENDFUNCTION_DESTINATION_DEFAULT);
}
@Override
protected void onInitDraw(final GL10 pGL) {
super.onInitDraw(pGL);
GLHelper.enableTextures(pGL);
GLHelper.enableTexCoordArray(pGL);
}
@Override
protected void onPostTransformations(final GL10 pGL) {
super.onPostTransformations(pGL);
this.mTextureRegion.onApply(pGL);
}
// Methods
// Inner and Anonymous Classes
}
|
package org.voltdb.utils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TimeZone;
import java.util.TreeSet;
import jline.console.CursorBuffer;
import jline.console.KeyMap;
import jline.console.history.FileHistory;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.NoConnectionsException;
import org.voltdb.client.ProcCallException;
import org.voltdb.parser.SQLParser;
import org.voltdb.parser.SQLParser.ParseRecallResults;
import com.google_voltpatches.common.collect.ImmutableMap;
public class SQLCommand
{
private static boolean m_stopOnError = true;
private static boolean m_debug = false;
private static boolean m_interactive;
private static boolean m_returningToPromptAfterError = false;
private static int m_exitCode = 0;
private static final String readme = "SQLCommandReadme.txt";
public static String getReadme() {
return readme;
}
// Command line interaction
private static SQLConsoleReader lineInputReader = null;
private static FileHistory historyFile = null;
private static List<String> RecallableSessionLines = new ArrayList<String>();
/// The main loop for interactive mode.
public static void interactWithTheUser() throws Exception
{
List<String> parsedQueries = null;
while ((parsedQueries = getInteractiveQueries()) != null) {
for (String parsedQuery : parsedQueries) {
executeQuery(parsedQuery);
}
}
}
//TODO: If we can rework the interactive mode unit test framework, we can eliminate this
// unit test entry point and inline this code into interactWithTheUser.
// This would eliminate an extra layer of looping and needless bouncing
// out of and back into getInteractiveQueries for some kinds of input
// but not others.
public static List<String> getInteractiveQueries() throws Exception
{
// Reset the error state to avoid accidentally ignoring future FILE content
// after a file had runtime errors (ENG-7335).
m_returningToPromptAfterError = false;
//TODO: add to this multiLineStatementBuffer to disable processing of "directives"
// while there is a multi-line statement in progress.
// For now, for backward compatibility, keep this empty. This undesirably allows the
// directives at the start of any line to temporarily interrupt statements in progress.
List<String> multiLineStatementBuffer = new ArrayList<>();
List<String> parsedQueries = new ArrayList<>();
StringBuilder query = new StringBuilder();
boolean isRecall = false;
boolean executeImmediate = false;
while ( ! executeImmediate) {
String prompt = isRecall ? "" : ((RecallableSessionLines.size() + 1) + "> ");
isRecall = false;
String line = lineInputReader.readLine(prompt);
assert(line != null);
// Was there a line-ending semicolon typed at the prompt?
// This mostly matters for "non-directive" statements, but, for
// now, for backward compatibility, it needs to be noted for FILE
// commands prior to their processing.
executeImmediate = SQLParser.isSemiColonTerminated(line);
// When we are tracking the progress of a multi-line statement,
// avoid coincidentally recognizing mid-statement SQL content as sqlcmd
// "directives".
if (multiLineStatementBuffer.isEmpty()) {
// EXIT command - exit immediately
if (SQLParser.isExitCommand(line)) {
return null;
}
// RECALL command
ParseRecallResults recallParseResults = SQLParser.parseRecallStatement(line, RecallableSessionLines.size() - 1);
if (recallParseResults != null) {
if (recallParseResults.error == null) {
line = RecallableSessionLines.get(recallParseResults.line);
lineInputReader.putString(line);
lineInputReader.flush();
isRecall = true;
}
else {
System.out.printf("%d> %s\n%d", RecallableSessionLines.size(), recallParseResults.error);
}
executeImmediate = false; // let user edit the recalled line.
continue;
}
// Queue up the line to the recall stack
//TODO: In the future, we may not want to have simple directives count as recallable
// lines, so this call would move down a ways.
RecallableSessionLines.add(line);
if (executesAsSimpleDirective(line)) {
executeImmediate = false; // return to prompt.
continue;
}
// GO commands - signal the end of any pending multi-line statements.
//TODO: to be deprecated in favor of just typing a semicolon on its own line to finalize
// a multi-line statement.
if (SQLParser.isGoCommand(line)) {
executeImmediate = true;
line = ";";
}
// handle statements that are converted to regular database commands
line = handleTranslatedCommands(line);
if (line == null) {
// something bad happened interpreting the translated command
executeImmediate = false; // return to prompt
continue;
}
// If the line is a FILE command - include the content of the file into the query queue
//TODO: executing statements (from files) as they are read rather than queuing them
// would improve performance and error handling.
File file = SQLParser.parseFileStatement(line);
if (file != null) {
// Get the line(s) from the file(s) to queue as regular database commands
// or get back a null if, in the recursive call, stopOrContinue decided to continue.
line = readScriptFile(file);
if (m_returningToPromptAfterError) {
// readScriptFile stopped because of an error. Wipe the slate clean.
query = new StringBuilder();
// Until we execute statements as they are read, there will always be a
// chance that errors in queued statements are still waiting to be detected,
// so, this reset is not 100% effective (as discovered in ENG-7335).
m_returningToPromptAfterError = false;
executeImmediate = false; // return to prompt.
continue;
}
// else treat the line(s) from the file(s) as regular database commands
}
// else treat the input line as a regular database command
}
else {
// With a multi-line statement pending, queue up the line continuation to the recall list.
//TODO: arguably, it would be more useful to append continuation lines to the last
// existing Lines entry to build each complete statement as a single recallable
// unit. Experiments indicated that joining the lines with a single space, while not
// very pretty for very long statements, behaved best for line editing (cursor synch)
// purposes.
// The multiLineStatementBuffer MAY become useful here.
RecallableSessionLines.add(line);
}
//TODO: Here's where we might use multiLineStatementBuffer to note a sql statement
// in progress -- if the line(s) so far contained anything more than whitespace.
// Collect lines ...
query.append(line);
query.append("\n");
}
parsedQueries = SQLParser.parseQuery(query.toString());
return parsedQueries;
}
/// Returns the original command, a replacement command, or null (on error).
private static String handleTranslatedCommands(String lineIn)
{
try {
return SQLParser.translateStatement(lineIn);
}
catch(SQLParser.Exception e) {
System.out.printf("%d> %s\n", RecallableSessionLines.size(), e.getMessage());
}
//* enable to debug */ if (lineOut != null && !lineOut.equals(lineIn)) System.err.printf("Translated: %s -> %s\n", lineIn, lineOut);
return lineIn;
}
/// A stripped down variant of the processing in "interactWithTheUser" suitable for
/// applying to a command script. It skips all the interactive-only options.
public static void executeNoninteractive() throws Exception
{
//TODO: increase code reuse between the processing of stdin (piped file) here
// and the processing of explicitly opened files in readScriptFile.
// Both of these methods should be using more of an execute-as-you-go approach rather than
// so much statement queueing.
StringBuilder query = new StringBuilder();
while (true) {
String line = lineInputReader.readLine();
if (line == null) {
//* enable to debug */ System.err.println("Read null batch line.");
List<String> parsedQueries = SQLParser.parseQuery(query.toString());
for (String parsedQuery : parsedQueries) {
executeQuery(parsedQuery);
}
return;
}
//* enable to debug */ else System.err.println("Read non-null batch line: (" + line + ")");
// handle statements that are converted to regular database commands
line = handleTranslatedCommands(line);
if (line == null) {
continue;
}
// If the line is a FILE command - include the content of the file into the query queue
File file = SQLParser.parseFileStatement(line);
if (file != null) {
// Get the line(s) from the file(s) to queue as regular database commands,
// or get back a null if in the recursive call, stopOrContinue decided to continue.
line = readScriptFile(file);
if (line == null) {
continue;
}
}
// else treat the input line as a regular database command
// Collect the lines ...
query.append(line);
query.append("\n");
}
}
/// Simple directives require only the input line and no other context from the input loop.
/// Return true if the line is a directive that has been completely handled here, so that the
/// input loop can proceed to the next line.
//TODO: There have been suggestions that some or all of these directives could be made
// available in non-interactive contexts. This function is available to enable that.
private static boolean executesAsSimpleDirective(String line) throws Exception {
// SHOW or LIST <blah> statement
String subcommand = SQLParser.parseShowStatementSubcommand(line);
if (subcommand != null) {
if (subcommand.equals("proc") || subcommand.equals("procedure")) {
execListProcedures();
}
else if (subcommand.equals("tables")) {
execListTables();
}
else if (subcommand.equals("classes")) {
execListClasses();
}
else {
System.out.printf("%d> Bad SHOW target: %s\n%d", RecallableSessionLines.size(), subcommand);
}
// Consider it handled here, whether or not it was a good SHOW statement.
return true;
}
// HELP commands - ONLY in interactive mode, close batch and parse for execution
// Parser returns null if it isn't a HELP command. If no arguments are specified
// the returned string will be empty.
String helpSubcommand = SQLParser.parseHelpStatement(line);
if (helpSubcommand != null) {
// Ignore the arguments for now.
if (!helpSubcommand.isEmpty()) {
System.out.printf("Ignoring extra HELP argument(s): %s\n", helpSubcommand);
}
printHelp(System.out); // Print readme to the screen
return true;
}
// It wasn't a locally-interpreted directive.
return false;
}
private static void execListClasses() {
//TODO: since sqlcmd makes no intrinsic use of the Classlist, it would be more
// efficient to load the Classlist only "on demand" from here and to cache a
// complete formatted String result rather than the complex map representation.
// This would save churn on startup and on DDL update.
if (Classlist.isEmpty()) {
System.out.println();
System.out.println("
System.out.println();
}
List<String> list = new LinkedList<String>(Classlist.keySet());
Collections.sort(list);
int padding = 0;
for (String classname : list) {
padding = Math.max(padding, classname.length());
}
String format = " %1$-" + padding + "s";
String categoryHeader[] = new String[] {
"
"
"
for (int i = 0; i<3; i++) {
boolean firstInCategory = true;
for (String classname : list) {
List<Boolean> stuff = Classlist.get(classname);
// Print non-active procs first
if (i == 0 && !(stuff.get(0) && !stuff.get(1))) {
continue;
} else if (i == 1 && !(stuff.get(0) && stuff.get(1))) {
continue;
} else if (i == 2 && stuff.get(0)) {
continue;
}
if (firstInCategory) {
firstInCategory = false;
System.out.println();
System.out.println(categoryHeader[i]);
}
System.out.printf(format, classname);
System.out.println();
}
}
System.out.println();
}
private static void execListTables() throws Exception {
//TODO: since sqlcmd makes no intrinsic use of the tables list, it would be more
// efficient to load the list only "on demand" from here and to cache a
// complete formatted String result rather than the multiple lists.
// This would save churn on startup and on DDL update.
Tables tables = getTables();
printTables("User Tables", tables.tables);
printTables("User Views", tables.views);
printTables("User Export Streams", tables.exports);
System.out.println();
}
private static void execListProcedures() {
List<String> list = new LinkedList<String>(Procedures.keySet());
Collections.sort(list);
int padding = 0;
for (String procedure : list) {
if (padding < procedure.length()) {
padding = procedure.length();
}
}
padding++;
String format = "%1$-" + padding + "s";
boolean firstSysProc = true;
boolean firstUserProc = true;
for (String procedure : list) {
//TODO: it would be much easier over all to maintain sysprocs and user procs in
// in two separate maps.
if (procedure.startsWith("@")) {
if (firstSysProc) {
firstSysProc = false;
System.out.println("
}
}
else {
if (firstUserProc) {
firstUserProc = false;
System.out.println();
System.out.println("
}
}
for (List<String> parameterSet : Procedures.get(procedure).values()) {
System.out.printf(format, procedure);
String sep = "\t";
for (String paramType : parameterSet) {
System.out.print(sep + paramType);
sep = ", ";
}
System.out.println();
}
}
System.out.println();
}
private static void printTables(final String name, final Collection<String> tables)
{
System.out.println();
System.out.println("
for (String table : tables) {
System.out.println(table);
}
System.out.println();
}
public static String readScriptFile(File file)
{
BufferedReader script = null;
try {
script = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {
System.err.println("Script file '" + file + "' could not be found.");
stopOrContinue(e);
return null; // continue to the next line after the FILE command
}
try {
StringBuilder query = new StringBuilder();
String line;
while ((line = script.readLine()) != null) {
// Strip out RECALL, EXIT and GO commands
//TODO: There is inconsistent handling of other "interactive mode" commands
// between batch commands in a file and batch commands from stdin or "--query=".
// The LIST commands are not covered here in particular, causing them to get
// piled onto the query string to mix with any statements or statement fragments
// currently being queued there. We COULD add them to this filter.
// But if INSTEAD we removed the filter completely both here and in the other input
// reader in "non-interactive" mode, then the user would soon learn not to
// put these garbage lines uselessly into their batch inputs.
// This would have the advantage of simplicity and would avoid possible
// edge case confusion when one of these "commands" like EXIT or GO happened to be
// a name in the user's schema that fell on a line of its own in the input and so
// got ignored.
// Maybe we should bypass these potential snafus in non-interactive mode by
// taking all of the user's command input more "literally".
// FILE is arguably the only useful one -- it could be improved by giving it a name
// less likely to be accidentally used in database commands like @File or #include.
if (SQLParser.parseRecallStatement(line, RecallableSessionLines.size() - 1) != null ||
SQLParser.isExitCommand(line) ||
SQLParser.isGoCommand(line)) {
continue;
}
// handle statements that are converted to regular database commands
line = handleTranslatedCommands(line);
if (line == null) {
continue;
}
// Recursively process FILE commands, any failure will cause a recursive failure
File nestedFile = SQLParser.parseFileStatement(line);
if (nestedFile != null) {
// Get the line(s) from the file(s) to queue as regular database commands
// or get back a null if in the recursive call, stopOrContinue decided to continue.
line = readScriptFile(nestedFile);
if (line == null) {
if (m_returningToPromptAfterError) {
// The recursive readScriptFile stopped because of an error.
// Escape to the outermost readScriptFile caller so it can exit or
// return to the interactive prompt.
return null;
}
// Continue after a bad nested file command by processing the next line
// in the current file.
continue;
}
}
query.append(line);
query.append("\n");
}
return query.toString().trim();
}
catch (Exception x) {
stopOrContinue(x);
return null;
}
finally {
if (script != null) {
try {
script.close();
} catch (IOException e) { }
}
}
}
private static long m_startTime;
private static void executeQuery(String statement)
{
try {
// EXEC <procedure> <params>...
m_startTime = System.nanoTime();
SQLParser.ExecuteCallResults execCallResults = SQLParser.parseExecuteCall(statement, Procedures);
if (execCallResults != null) {
Object[] objectParams = execCallResults.getParameterObjects();
if (execCallResults.procedure.equals("@UpdateApplicationCatalog")) {
File catfile = null;
if (objectParams[0] != null) {
catfile = new File((String)objectParams[0]);
}
File depfile = null;
if (objectParams[1] != null) {
depfile = new File((String)objectParams[1]);
}
printDdlResponse(VoltDB.updateApplicationCatalog(catfile, depfile));
// Need to update the stored procedures after a catalog change (could have added/removed SPs!). ENG-3726
loadStoredProcedures(Procedures, Classlist);
}
else if (execCallResults.procedure.equals("@UpdateClasses")) {
File jarfile = null;
if (objectParams[0] != null) {
jarfile = new File((String)objectParams[0]);
}
printDdlResponse(VoltDB.updateClasses(jarfile, (String)objectParams[1]));
// Need to reload the procedures and classes
loadStoredProcedures(Procedures, Classlist);
}
else {
// @SnapshotDelete needs array parameters.
if (execCallResults.procedure.equals("@SnapshotDelete")) {
objectParams[0] = new String[] { (String)objectParams[0] };
objectParams[1] = new String[] { (String)objectParams[1] };
}
printResponse(VoltDB.callProcedure(execCallResults.procedure, objectParams));
}
return;
}
String explainQuery = SQLParser.parseExplainCall(statement);
if (explainQuery != null) {
// We've got a query that starts with "explain", send the query to
// @Explain (after parseExplainCall() strips "explain").
printResponse(VoltDB.callProcedure("@Explain", explainQuery));
return;
}
String explainProcQuery = SQLParser.parseExplainProcCall(statement);
if (explainProcQuery != null) {
// We've got a query that starts with "explainproc", send the query to
// @Explain (after parseExplainCall() strips "explainproc").
// Clean up any extra spaces from between explainproc and the proc name.
explainProcQuery = explainProcQuery.trim();
printResponse(VoltDB.callProcedure("@ExplainProc", explainProcQuery));
return;
}
// All other commands get forwarded to @AdHoc
if (SQLParser.queryIsDDL(statement)) {
// if the query is DDL, reload the stored procedures.
printDdlResponse(VoltDB.callProcedure("@AdHoc", statement));
loadStoredProcedures(Procedures, Classlist);
}
else {
printResponse(VoltDB.callProcedure("@AdHoc", statement));
}
} catch(Exception exc) {
stopOrContinue(exc);
}
}
private static void stopOrContinue(Exception exc) {
System.err.println(exc.getMessage());
if (m_debug) {
exc.printStackTrace(System.err);
}
// Let the final exit code reflect any error(s) in the run.
// This is useful for debugging a script that may have multiple errors
// and multiple valid statements.
m_exitCode = -1;
if (m_stopOnError) {
if ( ! m_interactive ) {
System.exit(m_exitCode);
}
// Setting this member to drive a fast stack unwind from
// recursive readScriptFile requires explicit checks in that code,
// but still seems easier than a "throw" here from a catch block that
// would require additional exception handlers in the caller(s)
m_returningToPromptAfterError = true;
}
}
// Output generation
private static SQLCommandOutputFormatter m_outputFormatter = new SQLCommandOutputFormatterDefault();
private static boolean m_outputShowMetadata = true;
private static boolean isUpdateResult(VoltTable table)
{
return ((table.getColumnName(0).isEmpty() || table.getColumnName(0).equals("modified_tuples")) &&
table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT);
}
private static void printResponse(ClientResponse response) throws Exception
{
if (response.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Execution Error: " + response.getStatusString());
}
long elapsedTime = System.nanoTime() - m_startTime;
for (VoltTable t : response.getResults()) {
long rowCount;
if (!isUpdateResult(t)) {
rowCount = t.getRowCount();
// Run it through the output formatter.
m_outputFormatter.printTable(System.out, t, m_outputShowMetadata);
}
else {
rowCount = t.fetchRow(0).getLong(0);
}
if (m_outputShowMetadata) {
System.out.printf("(Returned %d rows in %.2fs)\n",
rowCount, elapsedTime / 1000000000.0);
}
}
}
private static void printDdlResponse(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
throw new Exception("Execution Error: " + response.getStatusString());
}
//TODO: In the future, if/when we change the prompt when waiting for the remainder of an unfinished command,
// successful DDL commands may just silently return to a normal prompt without this verbose feedback.
System.out.println("Command succeeded.");
}
// VoltDB connection support
private static Client VoltDB;
static Map<String,Map<Integer, List<String>>> Procedures =
Collections.synchronizedMap(new HashMap<String,Map<Integer, List<String>>>());
private static Map<String, List<Boolean>> Classlist =
Collections.synchronizedMap(new HashMap<String, List<Boolean>>());
private static void loadSystemProcedures()
{
Procedures.put("@Pause",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Quiesce",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Resume",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Shutdown",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@StopNode",
ImmutableMap.<Integer, List<String>>builder().put(1, Arrays.asList("int")).build());
Procedures.put("@SnapshotDelete",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()
);
Procedures.put("@SnapshotRestore",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar"))
.put( 1, Arrays.asList("varchar")).build()
);
Procedures.put("@SnapshotSave",
ImmutableMap.<Integer, List<String>>builder().put( 3, Arrays.asList("varchar", "varchar", "bit")).
put( 1, Arrays.asList("varchar")).build()
);
Procedures.put("@SnapshotScan",
ImmutableMap.<Integer, List<String>>builder().put( 1,
Arrays.asList("varchar")).build());
Procedures.put("@Statistics",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("statisticscomponent", "bit")).build());
Procedures.put("@SystemCatalog",
ImmutableMap.<Integer, List<String>>builder().put( 1,Arrays.asList("metadataselector")).build());
Procedures.put("@SystemInformation",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("sysinfoselector")).build());
Procedures.put("@UpdateApplicationCatalog",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build());
Procedures.put("@UpdateClasses",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build());
Procedures.put("@UpdateLogging",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@Promote",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@SnapshotStatus",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@Explain",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@ExplainProc",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@ValidatePartitioning",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("int", "varbinary")).build());
Procedures.put("@GetPartitionKeys",
ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build());
Procedures.put("@GC",
ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build());
Procedures.put("@ApplyBinaryLogSP",
ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varbinary", "varbinary")).build());
}
public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception
{
final Client client = ClientFactory.createClient(config);
for (String server : servers) {
client.createConnection(server.trim(), port);
}
return client;
}
// General application support
private static void printUsage(String msg)
{
System.out.print(msg);
System.out.println("\n");
printUsage(-1);
}
private static void printUsage(int exitCode)
{
System.out.println(
"Usage: sqlcmd --help\n"
+ " or sqlcmd [--servers=comma_separated_server_list]\n"
+ " [--port=port_number]\n"
+ " [--user=user]\n"
+ " [--password=password]\n"
+ " [--kerberos=jaas_login_configuration_entry_key]\n"
+ " [--query=query]\n"
+ " [--output-format=(fixed|csv|tab)]\n"
+ " [--output-skip-metadata]\n"
+ " [--stop-on-error=(true|false)]\n"
+ " [--debug]\n"
+ "\n"
+ "[--servers=comma_separated_server_list]\n"
+ " List of servers to connect to.\n"
+ " Default: localhost.\n"
+ "\n"
+ "[--port=port_number]\n"
+ " Client port to connect to on cluster nodes.\n"
+ " Default: 21212.\n"
+ "\n"
+ "[--user=user]\n"
+ " Name of the user for database login.\n"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--password=password]\n"
+ " Password of the user for database login.\n"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--kerberos=jaas_login_configuration_entry_key]\n"
+ " Enable kerberos authentication for user database login by specifying\n"
+ " the JAAS login configuration file entry name"
+ " Default: (not defined - connection made without credentials).\n"
+ "\n"
+ "[--query=query]\n"
+ " Execute a non-interactive query. Multiple query options are allowed.\n"
+ " Default: (runs the interactive shell when no query options are present).\n"
+ "\n"
+ "[--output-format=(fixed|csv|tab)]\n"
+ " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n"
+ " Default: fixed.\n"
+ "\n"
+ "[--output-skip-metadata]\n"
+ " Removes metadata information such as column headers and row count from\n"
+ " produced output.\n"
+ "\n"
+ "[--stop-on-error=(true|false)]\n"
+ " Causes the utility to stop immediately or continue after detecting an error.\n"
+ " In interactive mode, a value of \"true\" discards any unprocessed input\n"
+ " and returns to the command prompt.\n"
+ "\n"
+ "[--debug]\n"
+ " Causes the utility to print out stack traces for all exceptions.\n"
);
System.exit(exitCode);
}
// printHelp() can print readme either to a file or to the screen
// depending on the argument passed in
public static void printHelp(OutputStream prtStr)
{
try {
InputStream is = SQLCommand.class.getResourceAsStream(readme);
while (is.available() > 0) {
byte[] bytes = new byte[is.available()]; // Fix for ENG-3440
is.read(bytes, 0, bytes.length);
prtStr.write(bytes); // For JUnit test
}
}
catch (Exception x) {
System.err.println(x.getMessage());
System.exit(-1);
}
}
private static class Tables
{
TreeSet<String> tables = new TreeSet<String>();
TreeSet<String> exports = new TreeSet<String>();
TreeSet<String> views = new TreeSet<String>();
}
private static Tables getTables() throws Exception
{
Tables tables = new Tables();
VoltTable tableData = VoltDB.callProcedure("@SystemCatalog", "TABLES").getResults()[0];
while (tableData.advanceRow()) {
String tableName = tableData.getString("TABLE_NAME");
String tableType = tableData.getString("TABLE_TYPE");
if (tableType.equalsIgnoreCase("EXPORT")) {
tables.exports.add(tableName);
}
else if (tableType.equalsIgnoreCase("VIEW")) {
tables.views.add(tableName);
}
else {
tables.tables.add(tableName);
}
}
return tables;
}
private static void loadStoredProcedures(Map<String,Map<Integer, List<String>>> procedures,
Map<String, List<Boolean>> classlist)
{
VoltTable procs = null;
VoltTable params = null;
VoltTable classes = null;
try {
procs = VoltDB.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0];
params = VoltDB.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0];
classes = VoltDB.callProcedure("@SystemCatalog", "CLASSES").getResults()[0];
}
catch (NoConnectionsException e) {
e.printStackTrace();
return;
}
catch (IOException e) {
e.printStackTrace();
return;
}
catch (ProcCallException e) {
e.printStackTrace();
return;
}
Map<String, Integer> proc_param_counts = Collections.synchronizedMap(new HashMap<String, Integer>());
while (params.advanceRow()) {
String this_proc = params.getString("PROCEDURE_NAME");
Integer curr_val = proc_param_counts.get(this_proc);
if (curr_val == null) {
curr_val = 1;
} else {
++curr_val;
}
proc_param_counts.put(this_proc, curr_val);
}
params.resetRowPosition();
while (procs.advanceRow()) {
String proc_name = procs.getString("PROCEDURE_NAME");
Integer param_count = proc_param_counts.get(proc_name);
ArrayList<String> this_params = new ArrayList<String>();
// prepopulate it to make sure the size is right
if (param_count != null) {
for (int i = 0; i < param_count; i++) {
this_params.add(null);
}
}
else {
param_count = 0;
}
HashMap<Integer, List<String>> argLists = new HashMap<Integer, List<String>>();
argLists.put(param_count, this_params);
procedures.put(proc_name, argLists);
}
classlist.clear();
while (classes.advanceRow()) {
String classname = classes.getString("CLASS_NAME");
boolean isProc = (classes.getLong("VOLT_PROCEDURE") == 1L);
boolean isActive = (classes.getLong("ACTIVE_PROC") == 1L);
if (!classlist.containsKey(classname)) {
List<Boolean> stuff = Collections.synchronizedList(new ArrayList<Boolean>());
stuff.add(isProc);
stuff.add(isActive);
classlist.put(classname, stuff);
}
}
// Retrieve the parameter types. Note we have to do some special checking
// for array types. ENG-3101
params.resetRowPosition();
while (params.advanceRow()) {
Map<Integer, List<String>> argLists = procedures.get(params.getString("PROCEDURE_NAME"));
assert(argLists.size() == 1);
List<String> this_params = argLists.values().iterator().next();
int idx = (int)params.getLong("ORDINAL_POSITION") - 1;
String param_type = params.getString("TYPE_NAME").toLowerCase();
// Detect if this parameter is supposed to be an array. It's kind of clunky, we have to
// look in the remarks column...
String param_remarks = params.getString("REMARKS");
if (null != param_remarks) {
param_type += (param_remarks.equalsIgnoreCase("ARRAY_PARAMETER") ? "_array" : "");
}
this_params.set(idx, param_type);
}
}
/// Parser unit test entry point
///TODO: it would be simpler if this testing entry point could just set up some mocking
/// of io and statement "execution" -- mocking with statement capture instead of actual execution
/// to better isolate the parser.
/// Then it could call a new simplified version of interactWithTheUser().
/// But the current parser tests expect to call a SQLCommand function that can return for
/// some progress checking before its input stream has been permanently terminated.
/// They would need to be able to check parser progress in one thread while
/// SQLCommand.interactWithTheUser() was awaiting further input on another thread
/// (or in its own process).
public static List<String> getParserTestQueries(InputStream inmocked, OutputStream outmocked)
{
try {
SQLConsoleReader reader = new SQLConsoleReader(inmocked, outmocked);
lineInputReader = reader;
return getInteractiveQueries();
} catch (Exception ioe) {}
return null;
}
private static InputStream in = null;
private static OutputStream out = null;
private static String extractArgInput(String arg) {
// the input arguments has "=" character when this function is called
String[] splitStrings = arg.split("=", 2);
if (splitStrings[1].isEmpty()) {
printUsage("Missing input value for " + splitStrings[0]);
}
return splitStrings[1];
}
// Application entry point
public static void main(String args[])
{
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
// Initialize parameter defaults
String serverList = "localhost";
int port = 21212;
String user = "";
String password = "";
String kerberos = "";
List<String> queries = null;
String ddlFile = "";
// Parse out parameters
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--servers=")) {
serverList = extractArgInput(arg);
} else if (arg.startsWith("--port=")) {
port = Integer.valueOf(extractArgInput(arg));
} else if (arg.startsWith("--user=")) {
user = extractArgInput(arg);
} else if (arg.startsWith("--password=")) {
password = extractArgInput(arg);
} else if (arg.startsWith("--kerberos=")) {
kerberos = extractArgInput(arg);
} else if (arg.startsWith("--kerberos")) {
kerberos = "VoltDBClient";
} else if (arg.startsWith("--query=")) {
List<String> argQueries = SQLParser.parseQuery(arg.substring(8));
if (!argQueries.isEmpty()) {
if (queries == null) {
queries = argQueries;
}
else {
queries.addAll(argQueries);
}
}
}
else if (arg.startsWith("--output-format=")) {
String formatName = extractArgInput(arg).toLowerCase();
if (formatName.equals("fixed")) {
m_outputFormatter = new SQLCommandOutputFormatterDefault();
}
else if (formatName.equals("csv")) {
m_outputFormatter = new SQLCommandOutputFormatterCSV();
}
else if (formatName.equals("tab")) {
m_outputFormatter = new SQLCommandOutputFormatterTabDelimited();
}
else {
printUsage("Invalid value for --output-format");
}
}
else if (arg.equals("--output-skip-metadata")) {
m_outputShowMetadata = false;
}
else if (arg.equals("--debug")) {
m_debug = true;
}
else if (arg.startsWith("--stop-on-error=")) {
String optionName = extractArgInput(arg).toLowerCase();
if (optionName.equals("true")) {
m_stopOnError = true;
}
else if (optionName.equals("false")) {
m_stopOnError = false;
}
else {
printUsage("Invalid value for --stop-on-error");
}
}
else if (arg.startsWith("--ddl-file=")) {
String ddlFilePath = extractArgInput(arg);
try {
ddlFile = new Scanner(new File(ddlFilePath)).useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
printUsage("DDL file not found at path:" + ddlFilePath);
}
}
else if (arg.equals("--help")) {
printHelp(System.out); // Print readme to the screen
System.out.println("\n\n");
printUsage(0);
}
else if ((arg.equals("--usage")) || (arg.equals("-?"))) {
printUsage(0);
}
else {
printUsage("Invalid Parameter: " + arg);
}
}
// Split server list
String[] servers = serverList.split(",");
// Phone home to see if there is a newer version of VoltDB
openURLAsync();
// Create connection
ClientConfig config = new ClientConfig(user, password);
config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670
try {
// if specified enable kerberos
if (!kerberos.isEmpty()) {
config.enableKerberosAuthentication(kerberos);
}
VoltDB = getClient(config, servers, port);
} catch (Exception exc) {
System.err.println(exc.getMessage());
System.exit(-1);
}
try {
if (! ddlFile.equals("")) {
// fast DDL Loader mode
// System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile);
VoltDB.callProcedure("@AdHoc", ddlFile);
System.exit(m_exitCode);
}
// Load system procedures
loadSystemProcedures();
// Load user stored procs
loadStoredProcedures(Procedures, Classlist);
in = new FileInputStream(FileDescriptor.in);
out = System.out;
lineInputReader = new SQLConsoleReader(in, out);
lineInputReader.setBellEnabled(false);
// Maintain persistent history in ~/.sqlcmd_history.
historyFile = new FileHistory(new File(System.getProperty("user.home"), ".sqlcmd_history"));
lineInputReader.setHistory(historyFile);
// Make Ctrl-D (EOF) exit if on an empty line, otherwise delete the next character.
KeyMap keyMap = lineInputReader.getKeys();
keyMap.bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
CursorBuffer cursorBuffer = lineInputReader.getCursorBuffer();
if (cursorBuffer.length() == 0) {
System.exit(m_exitCode);
}
else {
try {
lineInputReader.delete();
}
catch (IOException e1) {}
}
}
});
// Removed code to prevent Ctrl-C from exiting. The original code is visible
// in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20.
m_interactive = true;
if (queries != null && !queries.isEmpty()) {
// If queries are provided via command line options run them in
// non-interactive mode.
//TODO: Someday we should honor batching.
m_interactive = false;
for (String query : queries) {
executeQuery(query);
}
}
if (System.in.available() > 0) {
// If Standard input comes loaded with data, run in non-interactive mode
m_interactive = false;
executeNoninteractive();
}
if (m_interactive) {
// Print out welcome message
System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port);
interactWithTheUser();
}
}
catch (Exception x) {
stopOrContinue(x);
}
finally {
try { VoltDB.close(); } catch (Exception x) { }
// Flush input history to a file.
if (historyFile != null) {
try {
historyFile.flush();
}
catch (IOException e) {
System.err.printf("* Unable to write history to \"%s\" *\n",
historyFile.getFile().getPath());
if (m_debug) {
e.printStackTrace();
}
}
}
// Clean up jline2 resources.
if (lineInputReader != null) {
lineInputReader.shutdown();
}
}
// Processing may have been continued after one or more errors.
// Reflect them in the exit code.
// This might be a little unconventional for an interactive session,
// but it's also likely to be ignored in that case, so "no great harm done".
//* enable to debug */ System.err.println("Exiting with code " + m_exitCode);
System.exit(m_exitCode);
}
// The following two methods implement a "phone home" version check for VoltDB.
// Asynchronously ping VoltDB to see what the current released version is.
// If it is newer than the one running here, then notify the user in some manner TBD.
// Note that this processing should not impact utility use in any way. Ignore all
// errors.
private static void openURLAsync()
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
openURL();
}
});
// Set the daemon flag so that this won't hang the process if it runs into difficulty
t.setDaemon(true);
t.start();
}
private static void openURL()
{
URL url;
try {
// Read the response from VoltDB
String a="http://community.voltdb.com/versioncheck?app=sqlcmd&ver=" + org.voltdb.VoltDB.instance().getVersionString();
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while (br.readLine() != null) {
// At this time do nothing, just drain the stream.
// In the future we'll notify the user that a new version of VoltDB is available.
}
br.close();
} catch (Throwable e) {
// ignore any error
}
}
}
|
package org.appwork.utils.ImageProvider;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Level;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import org.appwork.utils.Application;
import org.appwork.utils.logging.Log;
import sun.awt.image.ToolkitImage;
public class ImageProvider {
/**
* Hashcashmap to cache images.
*/
private static HashMap<String, BufferedImage> IMAGE_CACHE = new HashMap<String, BufferedImage>();
private static HashMap<String, ImageIcon> IMAGEICON_CACHE = new HashMap<String, ImageIcon>();
private static HashMap<Icon, Icon> DISABLED_ICON_CACHE = new HashMap<Icon, Icon>();
private static Object LOCK = new Object();
// stringbuilder die concat strings fast
private static StringBuilder SB = new StringBuilder();
/**
* @param bufferedImage
* @return
*/
public static BufferedImage convertToGrayScale(final BufferedImage bufferedImage) {
final BufferedImage dest = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(bufferedImage, 0, 0, null);
g2.dispose();
return dest;
}
/**
* Creates a dummy Icon
*
* @param string
* @param i
* @param j
* @return
*/
public static Image createIcon(final String string, final int width, final int height) {
final int w = width;
final int h = height;
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
int size = 1 + width / string.length();
// find max font size
int ww = 0;
int hh = 0;
while (size > 0) {
size
g.setFont(new Font("Arial", Font.BOLD, size));
ww = g.getFontMetrics().stringWidth(string);
hh = g.getFontMetrics().getAscent();
if (ww < w - 4 && hh < h - 2) {
break;
}
}
g.setColor(Color.WHITE);
g.fillRect(0, 0, w - 1, h - 1);
g.draw3DRect(0, 0, w - 1, h - 1, true);
g.setColor(Color.BLACK);
g.drawString(string, (w - ww) / 2, hh + (h - hh) / 2);
g.dispose();
return image;
}
/**
*
* @param name
* to the png file
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static Image getBufferedImage(final String name, final boolean createDummy) throws IOException {
synchronized (ImageProvider.LOCK) {
if (ImageProvider.IMAGE_CACHE.containsKey(name)) { return ImageProvider.IMAGE_CACHE.get(name); }
final URL absolutePath = Application.getRessourceURL("images/" + name + ".png");
try {
Log.L.info("Init Image: " + absolutePath);
final BufferedImage image = ImageProvider.read(absolutePath);
ImageProvider.IMAGE_CACHE.put(name, image);
return image;
} catch (final IOException e) {
Log.L.severe("Could not Init Image: " + absolutePath);
if (createDummy) {
Log.exception(Level.WARNING, e);
return ImageProvider.createIcon(name.toUpperCase(), 48, 48);
} else {
throw e;
}
}
}
}
/**
* Uses the uimanager to get a grayscaled disabled Icon
*
* @param icon
* @return
*/
public static Icon getDisabledIcon(final Icon icon) {
if (icon == null) { return null; }
Icon ret = ImageProvider.DISABLED_ICON_CACHE.get(icon);
if (ret != null) { return ret; }
ret = UIManager.getLookAndFeel().getDisabledIcon(null, icon);
ImageProvider.DISABLED_ICON_CACHE.put(icon, ret);
return ret;
}
/**
* @param string
* @param i
* @param j
* @return
*/
public static ImageIcon getImageIcon(final String name, final int x, final int y) {
// TODO Auto-generated method stub
try {
return ImageProvider.getImageIcon(name, x, y, true);
} catch (final IOException e) {
// can not happen. true creates a dummyicon in case of io errors
Log.exception(e);
return null;
}
}
/**
* Loads the image, scales it to the desired size and returns it as an
* imageicon
*
* @param name
* @param width
* @param height
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static ImageIcon getImageIcon(final String name, int width, int height, final boolean createDummy) throws IOException {
synchronized (ImageProvider.LOCK) {
ImageProvider.SB.delete(0, ImageProvider.SB.capacity());
ImageProvider.SB.append(name);
ImageProvider.SB.append('_');
ImageProvider.SB.append(width);
ImageProvider.SB.append('_');
ImageProvider.SB.append(height);
String key;
if (ImageProvider.IMAGEICON_CACHE.containsKey(key = ImageProvider.SB.toString())) { return ImageProvider.IMAGEICON_CACHE.get(key); }
final Image image = ImageProvider.getBufferedImage(name, createDummy);
final double faktor = Math.max((double) image.getWidth(null) / width, (double) image.getHeight(null) / height);
width = (int) (image.getWidth(null) / faktor);
height = (int) (image.getHeight(null) / faktor);
final ImageIcon imageicon = new ImageIcon(image.getScaledInstance(width, height, Image.SCALE_SMOOTH));
ImageProvider.IMAGEICON_CACHE.put(key, imageicon);
return imageicon;
}
}
public static BufferedImage getScaledInstance(final BufferedImage img, int width, int height, final Object hint, final boolean higherQuality) {
final double faktor = Math.max((double) img.getWidth() / width, (double) img.getHeight() / height);
width = (int) (img.getWidth() / faktor);
height = (int) (img.getHeight() / faktor);
if (faktor == 1.0) { return img; }
final int type = img.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = img.getWidth();
h = img.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = width;
h = height;
}
do {
if (higherQuality && w > width) {
w /= 2;
if (w < width) {
w = width;
}
}
if (higherQuality && h > height) {
h /= 2;
if (h < height) {
h = height;
}
}
final BufferedImage tmp = new BufferedImage(w, h, type);
final Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != width || h != height);
return ret;
}
/**
* @param image
* @param imageIcon
* @param i
* @param j
*/
public static BufferedImage merge(final Image image, final Image b, final int xoffset, final int yoffset) {
final int width = Math.max(image.getWidth(null), xoffset + b.getWidth(null));
final int height = Math.max(image.getHeight(null), yoffset + b.getHeight(null));
final BufferedImage dest = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.drawImage(b, xoffset, yoffset, null);
g2.dispose();
return dest;
}
/* copied from ImageIO, to close the inputStream */
public static BufferedImage read(final File input) throws IOException {
if (!input.canRead()) { throw new IIOException("Can't read input file!"); }
return ImageProvider.read(input.toURI().toURL());
}
/**
* @param absolutePath
* @return
* @throws IOException
*/
private static BufferedImage read(final URL absolutePath) throws IOException {
if (absolutePath == null) { throw new IllegalArgumentException("input == null!"); }
final ImageInputStream stream = ImageIO.createImageInputStream(absolutePath.openStream());
BufferedImage bi = null;
try {
if (stream == null) { throw new IIOException("Can't create an ImageInputStream!"); }
bi = ImageIO.read(stream);
} finally {
try {
stream.close();
} catch (final Throwable e) {
}
}
return bi;
}
/**
* @param scaleBufferedImage
* @param width
* @param height
* @return
*/
public static Image resizeWorkSpace(final Image scaleBufferedImage, final int width, final int height) {
// final GraphicsEnvironment ge =
// GraphicsEnvironment.getLocalGraphicsEnvironment();
// final GraphicsDevice gd = ge.getDefaultScreenDevice();
// final GraphicsConfiguration gc = gd.getDefaultConfiguration();
// final BufferedImage image = gc.createCompatibleImage(width, height,
// Transparency.BITMASK);
final BufferedImage image = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g = image.createGraphics();
g.drawImage(scaleBufferedImage, (width - scaleBufferedImage.getWidth(null)) / 2, (height - scaleBufferedImage.getHeight(null)) / 2, null);
g.dispose();
return image;
}
/**
* Scales a buffered Image to the given size. This method is NOT cached. so
* take care to cache it externally if you use it frequently
*
* @param img
* @param width
* @param height
* @return
*/
public static Image scaleBufferedImage(final BufferedImage img, int width, int height) {
if (img == null) { return null; }
final double faktor = Math.max((double) img.getWidth() / width, (double) img.getHeight() / height);
width = (int) (img.getWidth() / faktor);
height = (int) (img.getHeight() / faktor);
if (faktor == 1.0) { return img; }
return img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
/**
* Scales an imageicon to w x h.<br>
* like {@link #scaleBufferedImage(BufferedImage, int, int)}, this Function
* is NOT cached. USe an external cache if you use it frequently
*
* @param img
* @param w
* @param h
* @return
*/
public static ImageIcon scaleImageIcon(final ImageIcon img, final int w, final int h) {
// already has the desired size?
if (img.getIconHeight() == h && img.getIconWidth() == w) { return img; }
BufferedImage dest;
if (img.getImage() instanceof ToolkitImage) {
dest = new BufferedImage(w, h, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(img.getImage(), 0, 0, null);
g2.dispose();
} else {
dest = (BufferedImage) img.getImage();
}
return new ImageIcon(ImageProvider.scaleBufferedImage(dest, w, h));
}
/**
* Converts an Icon to an Imageicon.
*
* @param icon
* @return
*/
public static ImageIcon toImageIcon(final Icon icon) {
if (icon == null) { return null; }
if (icon instanceof ImageIcon) {
return (ImageIcon) icon;
} else {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return new ImageIcon(image);
}
}
}
|
package org.appwork.utils.ImageProvider;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Level;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import org.appwork.storage.config.MinTimeWeakReference;
import org.appwork.utils.Application;
import org.appwork.utils.logging.Log;
import sun.awt.image.ToolkitImage;
public class ImageProvider {
private static final long MIN_LIFETIME = 20000l;
/**
* Hashcashmap to cache images.
*/
private static HashMap<String, MinTimeWeakReference<BufferedImage>> IMAGE_CACHE = new HashMap<String, MinTimeWeakReference<BufferedImage>>();
private static HashMap<String, MinTimeWeakReference<ImageIcon>> IMAGEICON_CACHE = new HashMap<String, MinTimeWeakReference<ImageIcon>>();
private static HashMap<Icon, MinTimeWeakReference<Icon>> DISABLED_ICON_CACHE = new HashMap<Icon, MinTimeWeakReference<Icon>>();
private static Object LOCK = new Object();
// stringbuilder die concat strings fast
static {
/* we dont want images to get cached on disk */
ImageIO.setUseCache(false);
}
/* Thx to flubshi */
public static BufferedImage convertToGrayScale(final BufferedImage bufferedImage) {
final BufferedImage dest = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
Color tmp;
int val, alpha;
for (int y = 0; y < dest.getHeight(); y++) {
for (int x = 0; x < dest.getWidth(); x++) {
alpha = bufferedImage.getRGB(x, y) & 0xFF000000;
tmp = new Color(bufferedImage.getRGB(x, y));
// val = (int) (tmp.getRed()+tmp.getGreen()+tmp.getBlue())/3;
// val =
// Math.max(tmp.getRed(),Math.max(tmp.getGreen(),tmp.getBlue()));
val = (int) (tmp.getRed() * 0.3 + tmp.getGreen() * 0.59 + tmp.getBlue() * 0.11);
dest.setRGB(x, y, alpha | val | val << 8 & 0x0000FF00 | val << 16 & 0x00FF0000);
}
}
return dest;
}
/**
* Creates a dummy Icon
*
* @param string
* @param i
* @param j
* @return
*/
public static BufferedImage createIcon(final String string, final int width, final int height) {
final int w = width;
final int h = height;
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
int size = 1 + width / string.length();
// find max font size
int ww = 0;
int hh = 0;
while (size > 0) {
size
g.setFont(new Font("Arial", Font.BOLD, size));
ww = g.getFontMetrics().stringWidth(string);
hh = g.getFontMetrics().getAscent();
if (ww < w - 4 && hh < h - 2) {
break;
}
}
g.setColor(Color.WHITE);
g.fillRect(0, 0, w - 1, h - 1);
g.draw3DRect(0, 0, w - 1, h - 1, true);
g.setColor(Color.BLACK);
g.drawString(string, (w - ww) / 2, hh + (h - hh) / 2);
g.dispose();
return image;
}
/**
* this creates a new BufferedImage from an existing Image. Is used for
* dereferencing the sourceImage in scaled Images created with
* image.getScaledInstance, which always keeps a reference to its original
* image
*
* @param image
* @return
* @throws IOException
*/
public static BufferedImage dereferenceImage(final Image image) throws IOException {
final BufferedImage bu = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
final Graphics g = bu.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bu;
}
/**
*
* @param name
* to the png file
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static BufferedImage getBufferedImage(final String name, final boolean createDummy) throws IOException {
return ImageProvider.getBufferedImage(name, createDummy, true);
}
public static BufferedImage getBufferedImage(final String name, final boolean createDummy, final boolean putIntoCache) throws IOException {
synchronized (ImageProvider.LOCK) {
if (ImageProvider.IMAGE_CACHE.containsKey(name)) {
final MinTimeWeakReference<BufferedImage> cache = ImageProvider.IMAGE_CACHE.get(name);
if (cache.get() != null) { return cache.get(); }
}
final URL absolutePath = Application.getRessourceURL("images/" + name + ".png");
try {
Log.L.info("Init Image: " + name + ": " + absolutePath);
final BufferedImage image = ImageProvider.read(absolutePath);
if (putIntoCache) {
if (image.getHeight() * image.getWidth() > 100 * 100) {
// Log.exception(new Throwable("BIG IMAGE IN CACHE: " +
// name));
}
ImageProvider.IMAGE_CACHE.put(name, new MinTimeWeakReference<BufferedImage>(image, ImageProvider.MIN_LIFETIME, name));
}
return image;
} catch (final IOException e) {
Log.L.severe("Could not Init Image: " + absolutePath);
if (createDummy) {
Log.exception(Level.WARNING, e);
return ImageProvider.createIcon(name.toUpperCase(Locale.ENGLISH), 48, 48);
} else {
throw e;
}
} catch (final Throwable e) {
Log.L.severe("Could not Init Image: " + absolutePath);
Log.exception(Level.WARNING, e);
return ImageProvider.createIcon(name.toUpperCase(Locale.ENGLISH), 48, 48);
}
}
}
/**
* Uses the uimanager to get a grayscaled disabled Icon
*
* @param icon
* @return
*/
public static Icon getDisabledIcon(final Icon icon) {
if (icon == null) { return null; }
final MinTimeWeakReference<Icon> cache = ImageProvider.DISABLED_ICON_CACHE.get(icon);
Icon ret = cache == null ? null : cache.get();
if (ret != null) { return ret; }
ret = UIManager.getLookAndFeel().getDisabledIcon(null, icon);
ImageProvider.DISABLED_ICON_CACHE.put(icon, new MinTimeWeakReference<Icon>(ret, ImageProvider.MIN_LIFETIME, "disabled icon"));
return ret;
}
/**
* @param string
* @param i
* @param j
* @return
*/
public static ImageIcon getImageIcon(final String name, final int x, final int y) {
// TODO Auto-generated method stub
try {
return ImageProvider.getImageIcon(name, x, y, true);
} catch (final IOException e) {
// can not happen. true creates a dummyicon in case of io errors
Log.exception(e);
return null;
}
}
/**
* Loads the image, scales it to the desired size and returns it as an
* imageicon
*
* @param name
* @param width
* @param height
* @param createDummy
* TODO
* @return
* @throws IOException
*/
public static ImageIcon getImageIcon(final String name, final int width, final int height, final boolean createDummy) throws IOException {
return ImageProvider.getImageIcon(name, width, height, createDummy, true);
}
public static ImageIcon getImageIcon(final String name, int width, int height, final boolean createDummy, final boolean putIntoCache) throws IOException {
synchronized (ImageProvider.LOCK) {
final StringBuilder SB = new StringBuilder();
SB.append(name);
SB.append('_');
SB.append(width);
SB.append('_');
SB.append(height);
String key;
if (ImageProvider.IMAGEICON_CACHE.containsKey(key = SB.toString())) {
final MinTimeWeakReference<ImageIcon> cache = ImageProvider.IMAGEICON_CACHE.get(key);
if (cache.get() != null) { return cache.get(); }
}
final BufferedImage image = ImageProvider.getBufferedImage(name, createDummy, putIntoCache);
final double faktor = Math.max((double) image.getWidth(null) / width, (double) image.getHeight(null) / height);
width = (int) (image.getWidth(null) / faktor);
height = (int) (image.getHeight(null) / faktor);
/**
* WARNING: getScaledInstance will return a scaled image, BUT keeps
* a reference to original unscaled image
*/
final Image scaledWithFuckingReference = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
final BufferedImage referencelessVersion = ImageProvider.dereferenceImage(scaledWithFuckingReference);
final ImageIcon imageicon = new ImageIcon(referencelessVersion);
if (putIntoCache) {
ImageProvider.IMAGEICON_CACHE.put(key, new MinTimeWeakReference<ImageIcon>(imageicon, ImageProvider.MIN_LIFETIME, key));
}
return imageicon;
}
}
public static ImageIcon getImageIconUnCached(final String name, final int x, final int y) {
// TODO Auto-generated method stub
try {
return ImageProvider.getImageIcon(name, x, y, true, false);
} catch (final IOException e) {
// can not happen. true creates a dummyicon in case of io errors
Log.exception(e);
return null;
}
}
public static BufferedImage getScaledInstance(final BufferedImage img, int width, int height, final Object hint, final boolean higherQuality) {
final double faktor = Math.max((double) img.getWidth() / width, (double) img.getHeight() / height);
width = (int) (img.getWidth() / faktor);
height = (int) (img.getHeight() / faktor);
if (faktor == 1.0) { return img; }
BufferedImage ret = img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = Math.max(width, img.getWidth());
h = Math.max(height, img.getHeight());
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = width;
h = height;
}
do {
if (higherQuality && w > width) {
w /= 2;
if (w < width) {
w = width;
}
}
if (higherQuality && h > height) {
h /= 2;
if (h < height) {
h = height;
}
}
// use 6 as default image type. java versions <16 u17 return type 0
// for loaded pngs
final BufferedImage tmp = new BufferedImage(w, h, ret.getType() == 0 ? 6 : ret.getType());
final Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != width || h != height);
return ret;
}
/**
* @param back
* @param imageIcon
* @param i
* @param j
*/
public static BufferedImage merge(final Image back, final Image front, final int xoffset, final int yoffset) {
int xoffsetTop, yoffsetTop, xoffsetBottom, yoffsetBottom;
if (xoffset >= 0) {
xoffsetTop = 0;
xoffsetBottom = xoffset;
} else {
xoffsetTop = -xoffset;
xoffsetBottom = 0;
}
if (yoffset >= 0) {
yoffsetTop = 0;
yoffsetBottom = yoffset;
} else {
yoffsetTop = -yoffset;
yoffsetBottom = 0;
}
return ImageProvider.merge(back, front, xoffsetTop, yoffsetTop, xoffsetBottom, yoffsetBottom);
}
public static BufferedImage merge(final Image back, final Image front, final int xoffsetBack, final int yoffsetBack, final int xoffsetFront, final int yoffsetFront) {
final int width = Math.max(xoffsetBack + back.getWidth(null), xoffsetFront + front.getWidth(null));
final int height = Math.max(yoffsetBack + back.getHeight(null), yoffsetFront + front.getHeight(null));
final BufferedImage dest = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(back, xoffsetBack, yoffsetBack, null);
g2.drawImage(front, xoffsetFront, yoffsetFront, null);
g2.setColor(Color.RED);
g2.dispose();
return dest;
}
/* copied from ImageIO, to close the inputStream */
public static BufferedImage read(final File input) throws IOException {
if (!input.canRead()) { throw new IIOException("Can't read input file!"); }
return ImageProvider.read(input.toURI().toURL());
}
/**
* @param absolutePath
* @return
* @throws IOException
*/
private static BufferedImage read(final URL absolutePath) throws IOException {
if (absolutePath == null) { throw new IllegalArgumentException("input == null!"); }
final ImageInputStream stream = ImageIO.createImageInputStream(absolutePath.openStream());
BufferedImage bi = null;
try {
if (stream == null) { throw new IIOException("Can't create an ImageInputStream!"); }
bi = ImageIO.read(stream);
} finally {
try {
stream.close();
} catch (final Throwable e) {
}
}
return bi;
}
/**
* @param scaleBufferedImage
* @param width
* @param height
* @return
*/
public static BufferedImage resizeWorkSpace(final Image scaleBufferedImage, final int width, final int height) {
// final GraphicsEnvironment ge =
// GraphicsEnvironment.getLocalGraphicsEnvironment();
// final GraphicsDevice gd = ge.getDefaultScreenDevice();
// final GraphicsConfiguration gc = gd.getDefaultConfiguration();
// final BufferedImage image = gc.createCompatibleImage(width, height,
// Transparency.BITMASK);
final BufferedImage image = new BufferedImage(width, height, Transparency.TRANSLUCENT);
final Graphics2D g = image.createGraphics();
g.drawImage(scaleBufferedImage, (width - scaleBufferedImage.getWidth(null)) / 2, (height - scaleBufferedImage.getHeight(null)) / 2, null);
g.dispose();
return image;
}
/**
* Scales a buffered Image to the given size. This method is NOT cached. so
* take care to cache it externally if you use it frequently
*
* @param img
* @param width
* @param height
* @return
*/
public static Image scaleBufferedImage(final BufferedImage img, int width, int height) {
if (img == null) { return null; }
final double faktor = Math.max((double) img.getWidth() / width, (double) img.getHeight() / height);
width = (int) (img.getWidth() / faktor);
height = (int) (img.getHeight() / faktor);
if (faktor == 1.0) { return img; }
final Image image = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
try {
return ImageProvider.dereferenceImage(image);
} catch (final IOException e) {
Log.exception(e);
return null;
}
}
/**
* Scales an imageicon to w x h.<br>
* like {@link #scaleBufferedImage(BufferedImage, int, int)}, this Function
* is NOT cached. USe an external cache if you use it frequently
*
* @param img
* @param w
* @param h
* @return
*/
public static ImageIcon scaleImageIcon(final ImageIcon img, final int w, final int h) {
// already has the desired size?
if (img.getIconHeight() == h && img.getIconWidth() == w) { return img; }
BufferedImage dest;
if (img.getImage() instanceof ToolkitImage) {
dest = new BufferedImage(w, h, Transparency.TRANSLUCENT);
final Graphics2D g2 = dest.createGraphics();
g2.drawImage(img.getImage(), 0, 0, null);
g2.dispose();
} else {
dest = (BufferedImage) img.getImage();
}
return new ImageIcon(ImageProvider.scaleBufferedImage(dest, w, h));
}
/**
* Converts an Icon to an Imageicon.
*
* @param icon
* @return
*/
public static ImageIcon toImageIcon(final Icon icon) {
if (icon == null) { return null; }
if (icon instanceof ImageIcon) {
return (ImageIcon) icon;
} else {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.BITMASK);
final Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return new ImageIcon(image);
}
}
}
|
package org.appwork.utils.swing.dialog;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.appwork.app.gui.MigPanel;
import org.appwork.resources.AWUTheme;
import org.appwork.storage.JSonStorage;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.locale._AWU;
import org.appwork.utils.logging.Log;
import org.appwork.utils.os.CrossSystem;
import org.appwork.utils.swing.EDTRunner;
import org.appwork.utils.swing.SwingUtils;
public abstract class AbstractDialog<T> extends TimerDialog implements ActionListener, WindowListener {
private static final long serialVersionUID = 1831761858087385862L;
private static final HashMap<String, Integer> SESSION_DONTSHOW_AGAIN = new HashMap<String, Integer>();
public static Integer getSessionDontShowAgainValue(final String key) {
final Integer ret = AbstractDialog.SESSION_DONTSHOW_AGAIN.get(key);
if (ret == null) { return -1; }
return ret;
}
public static void resetDialogInformations() {
try {
AbstractDialog.SESSION_DONTSHOW_AGAIN.clear();
JSonStorage.getStorage("Dialogs").clear();
} catch (final Exception e) {
Log.exception(e);
}
}
protected JButton cancelButton;
private final String cancelOption;
private JPanel defaultButtons;
protected JCheckBox dontshowagain;
protected int flagMask;
private ImageIcon icon;
private boolean initialized = false;
protected JButton okButton;
private final String okOption;
protected JComponent panel;
protected int returnBitMask = 0;
private AbstractAction[] actions = null;
private String title;
private JLabel iconLabel;
protected boolean doNotShowAgainSelected = false;
private FocusListener defaultButton;
public AbstractDialog(final int flag, final String title, final ImageIcon icon, final String okOption, final String cancelOption) {
super();
this.title = title;
this.flagMask = flag;
this.icon = BinaryLogic.containsAll(flag, Dialog.STYLE_HIDE_ICON) ? null : icon;
this.okOption = okOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_OK() : okOption;
this.cancelOption = cancelOption == null ? _AWU.T.ABSTRACTDIALOG_BUTTON_CANCEL() : cancelOption;
}
public boolean isHiddenByDontShowAgain() {
if(dontshowagain!=null&&this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()){
return false;
}
final int i = BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getStorage("Dialogs").get(this.getDontShowAgainKey(), -1);
return i >= 0;
}
/**
* this function will init and show the dialog
*/
protected void _init() {
this.layoutDialog();
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
this.timerLbl.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
AbstractDialog.this.cancel();
AbstractDialog.this.timerLbl.removeMouseListener(this);
}
});
this.timerLbl.setToolTipText(_AWU.T.TIMERDIALOG_TOOLTIP_TIMERLABEL());
this.timerLbl.setIcon(AWUTheme.I().getIcon("dialog/cancel", 16));
}
/**
* this is very important so the new shown dialog will become root for
* all following dialogs! we save old parentWindow, then set current
* dialogwindow as new root and show dialog. after dialog has been
* shown, we restore old parentWindow
*/
final Component parentOwner = Dialog.getInstance().getParentOwner();
Dialog.getInstance().setParentOwner(this.getDialog());
try {
this.setTitle(this.title);
dont: if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
try {
final int i = BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getStorage("Dialogs").get(this.getDontShowAgainKey(), -1);
if (i >= 0) {
// filter saved return value
int ret = i & (Dialog.RETURN_OK | Dialog.RETURN_CANCEL);
// add flags
ret |= Dialog.RETURN_DONT_SHOW_AGAIN | Dialog.RETURN_SKIPPED_BY_DONT_SHOW;
/*
* if LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL or
* LOGIC_DONT_SHOW_AGAIN_IGNORES_OK are used, we check
* here if we should handle the dont show again feature
*/
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL) && BinaryLogic.containsAll(ret, Dialog.RETURN_CANCEL)) {
break dont;
}
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_OK) && BinaryLogic.containsAll(ret, Dialog.RETURN_OK)) {
break dont;
}
this.returnBitMask = ret;
return;
}
} catch (final Exception e) {
Log.exception(e);
}
}
if (parentOwner == null || !parentOwner.isShowing()) {
this.getDialog().setAlwaysOnTop(true);
}
// The Dialog Modal
this.getDialog().setModal(true);
// Layout manager
// Dispose dialog on close
this.getDialog().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.getDialog().addWindowListener(this);
defaultButton = new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
final JRootPane root = SwingUtilities.getRootPane(e.getComponent());
if (root != null) {
root.setDefaultButton(null);
}
}
@Override
public void focusGained(FocusEvent e) {
final JRootPane root = SwingUtilities.getRootPane(e.getComponent());
if (root != null && e.getComponent() instanceof JButton) {
root.setDefaultButton((JButton) e.getComponent());
}
}
};
// create panel for the dialog's buttons
this.okButton = new JButton(this.okOption);
this.cancelButton = new JButton(this.cancelOption);
cancelButton.addFocusListener(defaultButton);
okButton.addFocusListener(defaultButton);
this.defaultButtons = this.getDefaultButtonPanel();
/*
* We set the focus on the ok button. if no ok button is shown, we
* set the focus on cancel button
*/
JButton focus = null;
// add listeners here
this.okButton.addActionListener(this);
this.cancelButton.addActionListener(this);
// add icon if available
if (this.icon != null) {
this.getDialog().setLayout(new MigLayout("ins 5,wrap 2", "[][grow,fill]", "[grow,fill][]"));
this.getDialog().add(getIconComponent(), getIconConstraints());
} else {
this.getDialog().setLayout(new MigLayout("ins 5,wrap 1", "[grow,fill]", "[grow,fill][]"));
}
// Layout the dialog content and add it to the contentpane
this.panel = this.layoutDialogContent();
this.getDialog().add(this.panel, "");
// add the countdown timer
final MigPanel bottom = new MigPanel("ins 0", "[]20[grow,fill][]", "[]");
bottom.setOpaque(false);
bottom.add(this.timerLbl);
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
this.dontshowagain = new JCheckBox(getDontShowAgainLabelText());
this.dontshowagain.setHorizontalAlignment(SwingConstants.TRAILING);
this.dontshowagain.setHorizontalTextPosition(SwingConstants.LEADING);
this.dontshowagain.setSelected(this.doNotShowAgainSelected);
bottom.add(this.dontshowagain, "alignx right");
} else {
bottom.add(Box.createHorizontalGlue());
}
bottom.add(this.defaultButtons);
if ((this.flagMask & Dialog.BUTTONS_HIDE_OK) == 0) {
// Set OK as defaultbutton
this.getDialog().getRootPane().setDefaultButton(this.okButton);
this.okButton.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(final HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
final JButton defaultButton = (JButton) e.getComponent();
final JRootPane root = SwingUtilities.getRootPane(defaultButton);
if (root != null) {
root.setDefaultButton(defaultButton);
System.out.println("Set default " + defaultButton);
}
}
}
});
focus = this.okButton;
this.defaultButtons.add(this.okButton, "alignx right,tag ok,sizegroup confirms");
}
if (!BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_CANCEL)) {
this.defaultButtons.add(this.cancelButton, "alignx right,tag cancel,sizegroup confirms");
if (BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_OK)) {
this.getDialog().getRootPane().setDefaultButton(this.cancelButton);
this.cancelButton.requestFocusInWindow();
// focus is on cancel if OK is hidden
focus = this.cancelButton;
}
}
this.addButtons(this.defaultButtons);
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
// show timer
this.initTimer(this.getCountdown());
} else {
this.timerLbl.setText(null);
}
this.getDialog().add(bottom, "spanx,growx,pushx");
// pack dialog
this.getDialog().invalidate();
// this.setMinimumSize(this.getPreferredSize());
if (!this.getDialog().isMinimumSizeSet()) {
this.getDialog().setMinimumSize(new Dimension(300, 80));
}
this.getDialog().setResizable(this.isResizable());
this.pack();
// minimum size foir a dialog
// // Dimension screenDim =
// Toolkit.getDefaultToolkit().getScreenSize();
// this.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());
this.getDialog().toFront();
// if (this.getDesiredSize() != null) {
// this.setSize(this.getDesiredSize());
if (!this.getDialog().getParent().isDisplayable() || !this.getDialog().getParent().isVisible()) {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.getDialog().setLocation(new Point((int) (screenSize.getWidth() - this.getDialog().getWidth()) / 2, (int) (screenSize.getHeight() - this.getDialog().getHeight()) / 2));
} else if (this.getDialog().getParent() instanceof Frame && ((Frame) this.getDialog().getParent()).getExtendedState() == Frame.ICONIFIED) {
// dock dialog at bottom right if mainframe is not visible
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.getDialog().setLocation(new Point((int) (screenSize.getWidth() - this.getDialog().getWidth() - 20), (int) (screenSize.getHeight() - this.getDialog().getHeight() - 60)));
} else {
this.getDialog().setLocation(getDesiredLocation());
}
// register an escape listener to cancel the dialog
this.registerEscape(focus);
this.packed();
// System.out.println("NEW ONE "+this.getDialog());
/*
* workaround a javabug that forces the parentframe to stay always
* on top
*/
if (this.getDialog().getParent() != null && !CrossSystem.isMac()) {
((Window) this.getDialog().getParent()).setAlwaysOnTop(true);
((Window) this.getDialog().getParent()).setAlwaysOnTop(false);
}
this.setVisible(true);
// dialog gets closed
// 17.11.2011 I did not comment this - may be debug code while
// finding the problem with dialogs with closed parent...s
// this code causes a dialog which gets disposed without setting
// return mask to appear again.
// System.out.println("Unlocked " +
// this.getDialog().isDisplayable());
// if (this.returnBitMask == 0) {
// this.setVisible(true);
// Log.L.fine("Answer: Parent Closed ");
// this.returnBitMask |= Dialog.RETURN_CLOSED;
// this.setVisible(false);
// this.dispose();
} finally {
// System.out.println("SET OLD");
Dialog.getInstance().setParentOwner(this.getDialog().getParent());
}
/*
* workaround a javabug that forces the parentframe to stay always on
* top
*/
if (this.getDialog().getParent() != null && !CrossSystem.isMac()) {
((Window) this.getDialog().getParent()).setAlwaysOnTop(true);
((Window) this.getDialog().getParent()).setAlwaysOnTop(false);
}
}
/**
* @return
*/
protected String getDontShowAgainLabelText() {
return _AWU.T.ABSTRACTDIALOG_STYLE_SHOW_DO_NOT_DISPLAY_AGAIN();
}
/**
* @return
*/
protected Point getDesiredLocation() {
return SwingUtils.getCenter(this.getDialog().getParent(), this.getDialog());
}
/**
* @return
*/
protected JComponent getIconComponent() {
this.iconLabel = new JLabel(this.icon);
// iconLabel.setVerticalAlignment(JLabel.TOP);
return iconLabel;
}
/**
* @return
*/
protected String getIconConstraints() {
// TODO Auto-generated method stub
return "gapright 10,gaptop 2";
}
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == this.okButton) {
Log.L.fine("Answer: Button<OK:" + this.okButton.getText() + ">");
this.setReturnmask(true);
} else if (e.getSource() == this.cancelButton) {
Log.L.fine("Answer: Button<CANCEL:" + this.cancelButton.getText() + ">");
this.setReturnmask(false);
}
this.dispose();
}
/**
* Overwrite this method to add additional buttons
*/
protected void addButtons(final JPanel buttonBar) {
}
/**
* called when user closes the window
*
* @return <code>true</code>, if and only if the dialog should be closeable
**/
public boolean closeAllowed() {
return true;
}
protected abstract T createReturnValue();
/**
* This method has to be called to display the dialog. make sure that all
* settings have beens et before, becvause this call very likly display a
* dialog that blocks the rest of the gui until it is closed
*/
public void displayDialog() {
if (this.initialized) { return; }
this.initialized = true;
this._init();
}
@Override
public void dispose() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
new EDTRunner() {
@Override
protected void runInEDT() {
AbstractDialog.super.dispose();
if (AbstractDialog.this.timer != null) {
AbstractDialog.this.timer.interrupt();
AbstractDialog.this.timer = null;
}
}
};
}
/**
* @return
*/
protected JPanel getDefaultButtonPanel() {
final JPanel ret = new JPanel(new MigLayout("ins 0", "[]", "0[]0"));
if (this.actions != null) {
for (final AbstractAction a : this.actions) {
String tag = (String) a.getValue("tag");
if (tag == null) {
tag = "help";
}
JButton bt;
ret.add(bt=new JButton(a), "tag " + tag + ",sizegroup confirms");
bt.addFocusListener(defaultButton);
}
}
return ret;
}
/**
* Create the key to save the don't showmagain state in database. should be
* overwritten in same dialogs. by default, the dialogs get differed by
* their title and their classname
*
* @return
*/
protected String getDontShowAgainKey() {
return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_" + this.getClass().getSimpleName() + "_" + this.toString();
}
public ImageIcon getIcon() {
return this.icon;
}
/**
* Return the returnbitmask
*
* @return
*/
public int getReturnmask() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.returnBitMask;
}
public T getReturnValue() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.createReturnValue();
}
/**
* @return
*/
public String getTitle() {
try {
return this.getDialog().getTitle();
} catch (final NullPointerException e) {
// not initialized yet
return this.title;
}
}
/**
* @return the initialized
*/
public boolean isInitialized() {
return this.initialized;
}
/**
* override to change default resizable flag
*
* @return
*/
protected boolean isResizable() {
// TODO Auto-generated method stub
return false;
}
// /**
// * should be overwritten and return a Dimension of the dialog should have
// a
// * special size
// *
// * @return
// */
// protected Dimension getDesiredSize() {
// return null;
/**
* This method has to be overwritten to implement custom content
*
* @return musst return a JComponent
*/
abstract public JComponent layoutDialogContent();
/**
* Handle timeout
*/
@Override
protected void onTimeout() {
this.setReturnmask(false);
this.returnBitMask |= Dialog.RETURN_TIMEOUT;
this.dispose();
}
/**
* may be overwritten to set focus to special components etc.
*/
protected void packed() {
}
protected void registerEscape(final JComponent focus) {
if (focus != null) {
final KeyStroke ks = KeyStroke.getKeyStroke("ESCAPE");
focus.getInputMap().put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "ESCAPE");
focus.getActionMap().put("ESCAPE", new AbstractAction() {
private static final long serialVersionUID = -6666144330707394562L;
public void actionPerformed(final ActionEvent e) {
Log.L.fine("Answer: Key<ESCAPE>");
AbstractDialog.this.setReturnmask(false);
AbstractDialog.this.dispose();
}
});
focus.requestFocus();
}
}
/**
* @param b
*/
public void setDoNotShowAgainSelected(final boolean b) {
if (!BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) { throw new IllegalStateException("You have to set the Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN flag to use this method");
}
this.doNotShowAgainSelected = b;
}
public void setIcon(final ImageIcon icon) {
this.icon = icon;
if (this.iconLabel != null) {
new EDTRunner() {
@Override
protected void runInEDT() {
AbstractDialog.this.iconLabel.setIcon(AbstractDialog.this.icon);
}
};
}
}
/**
* Add Additional BUttons on the left side of ok and cancel button. You can
* add a "tag" property to the action in ordner to help the layouter,
*
* <pre>
* abstractActions[0].putValue("tag", "ok")
* </pre>
*
* @param abstractActions
* list
*/
public void setLeftActions(final AbstractAction... abstractActions) {
this.actions = abstractActions;
}
/**
* Sets the returnvalue and saves the don't show again states to the
* database
*
* @param b
*/
protected void setReturnmask(final boolean b) {
this.returnBitMask = b ? Dialog.RETURN_OK : Dialog.RETURN_CANCEL;
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
if (this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) {
this.returnBitMask |= Dialog.RETURN_DONT_SHOW_AGAIN;
try {
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT)) {
AbstractDialog.SESSION_DONTSHOW_AGAIN.put(this.getDontShowAgainKey(), this.returnBitMask);
} else {
JSonStorage.getStorage("Dialogs").put(this.getDontShowAgainKey(), this.returnBitMask);
}
} catch (final Exception e) {
Log.exception(e);
}
}
}
}
/**
* @param title2
*/
protected void setTitle(final String title2) {
try {
this.getDialog().setTitle(title2);
} catch (final NullPointerException e) {
this.title = title2;
}
}
/**
* Returns an id of the dialog based on it's title;
*/
@Override
public String toString() {
return ("dialog-" + this.getTitle()).replaceAll("\\W", "_");
}
public void windowActivated(final WindowEvent arg0) {
}
public void windowClosed(final WindowEvent arg0) {
}
public void windowClosing(final WindowEvent arg0) {
if (this.closeAllowed()) {
Log.L.fine("Answer: Button<[X]>");
this.returnBitMask |= Dialog.RETURN_CLOSED;
this.dispose();
} else {
Log.L.fine("(Answer: Tried [X] bot not allowed)");
}
}
public void windowDeactivated(final WindowEvent arg0) {
}
public void windowDeiconified(final WindowEvent arg0) {
}
public void windowIconified(final WindowEvent arg0) {
}
public void windowOpened(final WindowEvent arg0) {
}
}
|
package org.marsik.elshelves.backend.entities;
import gnu.trove.set.hash.THashSet;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.joda.time.DateTime;
import org.marsik.elshelves.api.entities.fields.LotAction;
import org.marsik.elshelves.backend.services.StickerCapable;
import org.marsik.elshelves.backend.services.UuidGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.EnumSet;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
@Entity
@Data
@ToString(of = {}, callSuper = true)
@EqualsAndHashCode(of = {}, callSuper = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@EntityListeners({AuditingEntityListener.class})
public class Lot extends OwnedEntity implements StickerCapable {
public Lot() {
}
@NotNull
@Min(1)
Long count;
@NotNull
LotAction status;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE },
fetch = FetchType.EAGER)
@NotNull
LotHistory history;
@NotNull
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE },
fetch = FetchType.EAGER)
Purchase purchase;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
Box location;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
Requirement usedBy;
@org.hibernate.annotations.Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
DateTime expiration;
@ElementCollection
Set<String> serials;
public Long usedCount() {
return isCanBeAssigned() ? 0 : count;
}
public Long freeCount() {
return getCount() - usedCount();
}
public static class SplitResult {
final Lot requested;
final Lot remainder;
public SplitResult(Lot requested, Lot remainder) {
this.requested = requested;
this.remainder = remainder;
}
public Lot getRequested() {
return requested;
}
public Lot getRemainder() {
return remainder;
}
}
public Lot take(Long count, User performedBy, UuidGenerator uuidGenerator, Requirement requirement) {
// Not available for split
if (!isCanBeSplit()) {
return null;
}
// Use the exact amount or all if not enough available
if (getCount() <= count) {
count = getCount();
}
Lot result = null;
// No remainder..
if (getCount().equals(count)) {
result = this;
} else {
// Create the taken Lot and substract the count
setCount(getCount() - count);
result = new Lot();
result.setId(uuidGenerator.generate());
result.setHistory(getHistory());
result.setCount(count);
result.setStatus(getStatus());
result.setLocation(getLocation());
result.setUsedBy(getUsedBy());
result.setExpiration(getExpiration());
Set<String> serials = new THashSet<>();
getSerials().stream().skip(getCount() - count).forEach(new Consumer<String>() {
@Override
public void accept(String s) {
serials.add(s);
}
});
result.setSerials(serials); // TODO take a specific serials
getSerials().removeAll(result.getSerials());
}
if (requirement != null && result.isCanBeAssigned()) {
result.recordChange(LotAction.ASSIGNED, performedBy, uuidGenerator);
}
return result;
}
protected Lot copy(Long count) {
Lot l = new Lot();
l.setCount(count);
return l;
}
public LotHistory move(User performedBy, Box location, UuidGenerator uuidGenerator) {
setLocation(location);
LotHistory h = recordChange(LotAction.MOVED, performedBy, uuidGenerator);
h.setLocation(location);
return h;
}
public LotHistory solder(User performedBy, Requirement requirement, UuidGenerator uuidGenerator) {
if (requirement != null) {
assign(performedBy, requirement, uuidGenerator);
}
return recordChange(LotAction.SOLDERED, performedBy, uuidGenerator);
}
public LotHistory unsolder(User performedBy, UuidGenerator uuidGenerator) {
return recordChange(LotAction.UNSOLDERED, performedBy, uuidGenerator);
}
public LotHistory destroy(User performedBy, UuidGenerator uuidGenerator) {
return recordChange(LotAction.DESTROYED, performedBy, uuidGenerator);
}
public LotHistory assign(User performedBy, Requirement where, UuidGenerator uuidGenerator) {
setUsedBy(where);
LotHistory h = recordChange(LotAction.ASSIGNED, performedBy, uuidGenerator);
h.setAssignedTo(where);
return h;
}
public LotHistory unassign(User performedBy, UuidGenerator uuidGenerator) {
setUsedBy(null);
LotHistory h = recordChange(LotAction.UNASSIGNED, performedBy, uuidGenerator);
h.setAssignedTo(null);
return h;
}
private LotHistory recordChange(LotAction action, User performedBy, UuidGenerator uuidGenerator) {
setStatus(action);
LotHistory h = new LotHistory();
h.setId(uuidGenerator.generate());
h.setPrevious(getHistory());
setHistory(h);
h.setPerformedBy(performedBy);
h.setAction(action);
return h;
}
public static Lot delivery(Purchase purchase, UUID uuid, Long count,
Box location, DateTime expiration, User performedBy, UuidGenerator uuidGenerator) {
Lot l = new Lot();
l.setOwner(purchase.getOwner());
l.setId(uuid);
l.setLocation(location);
l.setCount(count);
l.setPurchase(purchase);
l.setExpiration(expiration);
LotHistory h = l.recordChange(LotAction.DELIVERY, performedBy, uuidGenerator);
h.setLocation(location);
return l;
}
public boolean isCanBeSoldered() {
return isValid()
&& getUsedBy() != null
&& !getStatus().equals(LotAction.DESTROYED)
&& !getStatus().equals(LotAction.SOLDERED);
}
public boolean isCanBeUnsoldered() {
return isValid()
&& getStatus().equals(LotAction.SOLDERED);
}
public boolean isCanBeAssigned() {
return isValid()
&& getUsedBy() == null
&& !getStatus().equals(LotAction.DESTROYED);
}
public boolean isCanBeUnassigned() {
return isCanBeSoldered();
}
public boolean isCanBeSplit() {
return isValid()
&& EnumSet.of(LotAction.SPLIT, LotAction.DELIVERY, LotAction.UNASSIGNED, LotAction.EVENT, LotAction.MOVED).contains(getStatus());
}
public boolean isCanBeMoved() {
return isValid()
&& (isCanBeAssigned() || isCanBeSoldered());
}
/**
* Return true if this Lot record is currently a valid Lot.
* Return false if the Lot represents a destroyed part and also when this record
* represents a historical state only.
*/
public boolean isValid() {
return !getStatus().equals(LotAction.DESTROYED);
}
@Override
public String getName() {
return getType().getName();
}
@Override
public String getSummary() {
return getPurchase().getTransaction().getName();
}
@Override
public String getBaseUrl() {
return "lots";
}
public boolean canBeDeleted() {
return false;
}
public boolean canBeUpdated() {
return false;
}
@Transient
public Type getType() {
return getPurchase().getType();
}
}
|
package team316;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotController;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.Signal;
import battlecode.common.Team;
import team316.navigation.ChargedParticle;
import team316.navigation.EnemyLocationModel;
import team316.navigation.ParticleType;
import team316.navigation.PotentialField;
import team316.navigation.motion.MotionController;
import team316.utils.Battle;
import team316.utils.EncodedMessage;
import team316.utils.EncodedMessage.MessageType;
import team316.utils.Grid;
import team316.utils.Probability;
import team316.utils.RCWrapper;
import team316.utils.Turn;
public class Archon implements Player {
private final static int BLITZKRIEG_NOTIFICATION_PERIOD_TURNS = 100;
private final static int DEN_GATHER_PERIOD_TURNS = 200;
// For archonRank;
// 1 is the leader.
// 0 is unassigned
// -1 is dead archon: an archon that can't build anymore;
private int archonRank = 0;
private ArrayList<ArrayList<Integer>> toBroadcastNextTurnList = new ArrayList<>();
// private RobotType lastBuilt = RobotType.ARCHON;
private Map<RobotType, Double> buildDistribution = new HashMap<>();
private RobotType toBuild = null;
private int healthyArchonCount = 0;
private final int ARCHON_UNHEALTHY_HP_THRESHOLD = 100;
private int leaderID;
private boolean isDying = false;
private final PotentialField field;
private final MotionController mc;
private boolean inDanger = false;
private MapLocation myCurrentLocation = null;
// maps Locations with parts to the turns they were added at.
private Set<MapLocation> consideredPartsBeforeFrom = new HashSet<>();
private Set<MapLocation> partsAdded = new HashSet<>();
private int helpMessageDelay = 0;
private int gatherMessageDelay = 0;
private final RCWrapper rcWrapper;
private MapLocation targetLocation = null;
private int HELP_MESSASGE_MAX_DELAY = 15;
private int GATHER_MESSASGE_MAX_DELAY = 15;
private LinkedList<MapLocation> densLocations = new LinkedList<>();
private LinkedList<MapLocation> neutralArchonLocations = new LinkedList<>();
private Signal[] IncomingSignals;
static int[] tryDirections = {0, -1, 1, -2, 2};
private final static int MAX_RADIUS = GameConstants.MAP_MAX_HEIGHT
* GameConstants.MAP_MAX_HEIGHT
+ GameConstants.MAP_MAX_WIDTH * GameConstants.MAP_MAX_WIDTH;
private MapLocation enemyBaseLocation = null;
private int lastBlitzkriegNotification = -1000;
private final EnemyLocationModel elm;
private int lastDenGatherTurn = -1000;
private boolean isTopArchon = false;
public enum GameMode {
FREEPLAY, GATHER, ACTIVATE, ATTACK, DEFENSE
}
private GameMode myMode = GameMode.FREEPLAY;
private boolean reachedTarget;
private static int emptyMessage = EncodedMessage.makeMessage(
MessageType.EMPTY_MESSAGE, new MapLocation(0, 0));
int modeMessage;
//private boolean defenseMode = false;
//private boolean gatherMode = false;
//private boolean activationMode = false;
//private boolean attackMode = false;
//private MapLocation gatherLocation = null;
//private MapLocation attackLocation = null;
public Archon(PotentialField field, MotionController mc,
RobotController rc) {
this.field = field;
this.mc = mc;
this.rcWrapper = new RCWrapper(rc);
this.elm = new EnemyLocationModel();
}
private boolean attemptBuild(RobotController rc)
throws GameActionException {
Direction proposedBuildDirection = null;
if (rc.isCoreReady()) {
if (myMode.equals(GameMode.DEFENSE)) {
toBuild = RobotType.TURRET;
for (int i = 0; i < 4; i++) {
proposedBuildDirection = Grid.mainDirections[i]
.rotateRight();
if (rc.canBuild(proposedBuildDirection, RobotType.TURRET)) {
break;
}
}
}
if (toBuild == null) {
toBuild = (new Probability<RobotType>())
.getRandomSample(buildDistribution);
if (toBuild == null) {
return false;
}
}
if (rc.hasBuildRequirements(toBuild)) {
if (proposedBuildDirection == null) {
proposedBuildDirection = RobotPlayer.randomDirection();
}
Direction buildDirection = closestToForwardToBuild(rc,
proposedBuildDirection, toBuild);
final double acceptProbability = 1.0
/ (healthyArchonCount - archonRank + 1);
// will equal to 1.0 if healthyArchonCount = 0 and archonRank =
// 0 (not assigned).
if (buildDirection != null
&& rc.canBuild(buildDirection, toBuild)) {
boolean isFairResourcesDistribution = Probability
.acceptWithProbability(acceptProbability)
|| rc.getTeamParts() > 120;
if (!isFairResourcesDistribution) {
return false;
}
rc.build(buildDirection, toBuild);
// lastBuilt = toBuild;
toBuild = null;
if(!myMode.equals(GameMode.FREEPLAY)){
addNextTurnMessage(modeMessage, emptyMessage, 2);
}
return true;
}
}
}
return false;
}
/**
* Broadcasts all messages that are on the queue.
*/
private void broadcastLateMessages(RobotController rc)
throws GameActionException {
for (ArrayList<Integer> message : toBroadcastNextTurnList) {
if (message.get(0) == null) {
rc.broadcastSignal(message.get(2));
} else {
rc.broadcastMessageSignal(message.get(0), message.get(1),
message.get(2));
}
}
toBroadcastNextTurnList.clear();
}
private void seekHelpIfNeeded(RobotController rc)
throws GameActionException {
boolean isAttacked = rcWrapper.isUnderAttack();
boolean canBeAttacked = false;
RobotInfo[] enemiesSensed = rc.senseHostileRobots(myCurrentLocation,
RobotType.ARCHON.sensorRadiusSquared);
if (!isAttacked) {
for (RobotInfo enemy : enemiesSensed) {
/*
* if (myCurrentLocation.distanceSquaredTo( enemy.location) <=
* enemy.type.attackRadiusSquared) { canBeAttacked = true;
* break; }
*/
if (enemy.type != RobotType.ARCHON
&& enemy.type != RobotType.SCOUT) {
canBeAttacked = true;
break;
}
}
}
if (isAttacked || canBeAttacked) {
inDanger = true;
if (helpMessageDelay == 0 && rc.getRobotCount() > 1) {
int message = EncodedMessage.makeMessage(
MessageType.MESSAGE_HELP_ARCHON,
rcWrapper.getCurrentLocation());
rc.broadcastMessageSignal(message, emptyMessage, 1000);
helpMessageDelay = this.HELP_MESSASGE_MAX_DELAY;
}
}
isDying = rc.getHealth() < ARCHON_UNHEALTHY_HP_THRESHOLD;
// TODO fix this:
/*
* if (isDying && !isAttacked && !canBeAttacked) {
* rc.broadcastMessageSignal(RobotPlayer.MESSAGE_BYE_ARCHON, archonRank,
* MAX_RADIUS); archonRank = -1; healthyArchonCount--; }
*/
}
public void figureOutDistribution() {
if (Turn.currentTurn() == 1) {
buildDistribution.clear();
// buildDistribution.put(RobotType.GUARD, 5.0);
buildDistribution.put(RobotType.SCOUT, 10.0);
buildDistribution.put(RobotType.SOLDIER, 90.0);
}
}
/**
* Returns the build direction closest to a given direction Returns null if
* it can't build anywhere.
*/
private Direction closestToForwardToBuild(RobotController rc,
Direction forward, RobotType toBuild) {
for (int deltaD : tryDirections) {
Direction currentDirection = Direction
.values()[(forward.ordinal() + deltaD + 8) % 8];
if (rc.canBuild(currentDirection, toBuild)) {
return currentDirection;
}
}
return null;
}
private void attemptRepairingWeakest(RobotController rc)
throws GameActionException {
RobotInfo[] alliesToHelp = rc.senseNearbyRobots(
RobotType.ARCHON.attackRadiusSquared, rcWrapper.myTeam);
MapLocation weakestOneLocation = null;
double weakestWeakness = -(1e9);
for (RobotInfo ally : alliesToHelp) {
if (!ally.type.equals(RobotType.ARCHON)
&& Battle.weakness(ally) > weakestWeakness
&& ally.health < ally.maxHealth) {
weakestOneLocation = ally.location;
weakestWeakness = Battle.weakness(ally);
}
}
if (weakestOneLocation != null) {
rc.repair(weakestOneLocation);
}
}
private void figureOutRank(RobotController rc) throws GameActionException {
// Get all incoming archon signals who were initialized before me.
for (Signal s : IncomingSignals) {
if (s.getTeam().equals(rcWrapper.myTeam)
&& s.getMessage() != null) {
if (EncodedMessage.getMessageType(s.getMessage()[0])
.equals(MessageType.MESSAGE_HELLO_ARCHON)) {
archonRank++;
if (archonRank == 1) {
leaderID = s.getID();
}
}
}
}
archonRank++;
// Find farthest archon from me and broadcast that I'm initialized.
MapLocation[] archonLocations = rc
.getInitialArchonLocations(rcWrapper.myTeam);
int furthestArchonDistance = 0;
if (Turn.currentTurn() == 1) {
for (MapLocation location : archonLocations) {
int distance = myCurrentLocation.distanceSquaredTo(location);
if (distance > furthestArchonDistance) {
furthestArchonDistance = distance;
}
}
} else {
furthestArchonDistance = MAX_RADIUS;
}
// TODO furthestArchonDistance doesn't work.
int message = EncodedMessage.makeMessage(
MessageType.MESSAGE_HELLO_ARCHON,
rcWrapper.getCurrentLocation());
rc.broadcastMessageSignal(message, 0, MAX_RADIUS);
rc.setIndicatorString(0, "My archon rank is: " + archonRank);
if (archonRank == 1) {
leaderID = rc.getID();
}
}
private void startGather(MapLocation location) {
myMode = GameMode.GATHER;
targetLocation = location;
}
private boolean processMessage(int message) throws GameActionException {
MapLocation location = EncodedMessage.getMessageLocation(message);
boolean success = false;
switch (EncodedMessage.getMessageType(message)) {
case EMPTY_MESSAGE :
break;
case ZOMBIE_DEN_LOCATION :
elm.addZombieDenLocation(location);
//field.addParticle(ParticleType.DEN, location, 100);
if (!densLocations.contains(location)) {
densLocations.add(location);
}
// field.addParticle(ParticleType.DEN, location, 100);
break;
case MESSAGE_HELP_ARCHON :
field.addParticle(ParticleType.ARCHON_ATTACKED, location, 5);
break;
case NEUTRAL_ARCHON_LOCATION :
neutralArchonLocations.add(location);
// field.addParticle(new ChargedParticle(1000, location, 500));
break;
case NEUTRAL_NON_ARCHON_LOCATION :
field.addParticle(new ChargedParticle(30, location, 100));
break;
case Y_BORDER :
int coordinateY = location.y;
if (coordinateY <= rcWrapper.getCurrentLocation().y) {
rcWrapper.setMaxCoordinate(Direction.NORTH, coordinateY);
} else {
rcWrapper.setMaxCoordinate(Direction.SOUTH, coordinateY);
}
break;
case X_BORDER :
int coordinateX = location.x;
if (coordinateX <= rcWrapper.getCurrentLocation().x) {
rcWrapper.setMaxCoordinate(Direction.WEST, coordinateX);
} else {
rcWrapper.setMaxCoordinate(Direction.EAST, coordinateX);
}
break;
case DEFENSE_MODE_ON :
myMode = GameMode.DEFENSE;
targetLocation = location;
// isTopArchon = false;
break;
case ACTIVATE :
myMode = GameMode.ACTIVATE;
targetLocation = location;
// isTopArchon = false;
break;
case ATTACK :
myMode = GameMode.ATTACK;
targetLocation = location;
// isTopArchon = false;
break;
case GATHER :
System.out.println("Gather Message received!");
if (elm.knownZombieDens.contains(location)) {
lastDenGatherTurn = Turn.currentTurn();
elm.knownZombieDens.remove(location);
}
startGather(location);
// isTopArchon = false;
break;
case ENEMY_BASE_LOCATION :
System.out.println("Enemy base location received: " + location);
enemyBaseLocation = location;
break;
default :
success = false;
break;
}
return success;
}
private void checkInbox(RobotController rc) throws GameActionException {
for (Signal s : IncomingSignals) {
if (s.getTeam() == rcWrapper.myTeam && s.getMessage() != null) {
processMessage(s.getMessage()[0]);
processMessage(s.getMessage()[1]);
/*
* if (!processMessage(s.getMessage()[0]) &&
* processMessage(s.getMessage()[1])) { /// switch
* (s.getMessage()[0]) { case RobotPlayer.MESSAGE_BYE_ARCHON :
* if (archonRank > s.getMessage()[1]) { archonRank--; if
* (archonRank == 1) { rc.broadcastMessageSignal(
* RobotPlayer.MESSAGE_DECLARE_LEADER, 0, MAX_RADIUS); } }
* healthyArchonCount--; break; case
* RobotPlayer.MESSAGE_WELCOME_ACTIVATED_ARCHON : if
* (healthyArchonCount == 0) { healthyArchonCount =
* s.getMessage()[1]; archonRank = healthyArchonCount; } else {
* healthyArchonCount++; } break; case
* RobotPlayer.MESSAGE_DECLARE_LEADER : leaderID = s.getID();
* break; default : break; } /// }
*/
}
}
}
private int activationProfit(RobotType type) {
switch (type) {
case ARCHON :
return 100;
case GUARD :
return 5;
case SOLDIER :
return 50;
case SCOUT :
return 1;
case VIPER :
return 20;
case TTM :
return 10;
case TURRET :
return 11;
default :
throw new RuntimeException("UNKNOWN ROBOT TYPE!");
}
}
private void attemptActivateRobots(RobotController rc)
throws GameActionException {
if (!rc.isCoreReady())
return;
RobotInfo[] neutralRobots = rc.senseNearbyRobots(2, Team.NEUTRAL);
int bestProfit = 0;
RobotInfo neutralRobotToActivate = null;
for (RobotInfo neutralRobot : neutralRobots) {
if (activationProfit(neutralRobot.type) > bestProfit
&& myCurrentLocation.isAdjacentTo(neutralRobot.location)) {
neutralRobotToActivate = neutralRobot;
bestProfit = activationProfit(neutralRobot.type);
}
}
if (neutralRobotToActivate != null) {
rc.activate(neutralRobotToActivate.location);
/*
* if (neutralRobotToActivate.type.equals(RobotType.ARCHON)) { int
* distanceToRobot = myCurrentLocation
* .distanceSquaredTo(neutralRobotToActivate.location);
* addNextTurnMessage(RobotPlayer.MESSAGE_WELCOME_ACTIVATED_ARCHON,
* healthyArchonCount + 1, distanceToRobot); }
*/
}
}
private void switchModes(RobotController rc) throws GameActionException {
MapLocation closestArchonLocation = rcWrapper
.getClosestLocation(neutralArchonLocations);
int emptyMessage = EncodedMessage.makeMessage(MessageType.EMPTY_MESSAGE,
new MapLocation(0, 0));
if (closestArchonLocation != null) {
targetLocation = closestArchonLocation;
myMode = GameMode.ACTIVATE;
int activateMessage = EncodedMessage
.makeMessage(MessageType.ACTIVATE, targetLocation);
// rc.broadcastMessageSignal(activateMessage, emptyMessage,
// MAX_RADIUS);
return;
}
MapLocation closestDenLocation = rcWrapper
.getClosestLocation(densLocations);
if (closestDenLocation != null && Turn.currentTurn() > 600) {
targetLocation = closestDenLocation;
myMode = GameMode.ATTACK;
int attackMessage = EncodedMessage.makeMessage(MessageType.ATTACK,
targetLocation);
System.out.println("Den message!");
// rc.broadcastMessageSignal(attackMessage, emptyMessage,
// MAX_RADIUS);
return;
}
if (Turn.currentTurn() > 1000) {
targetLocation = rcWrapper.getCurrentLocation();
int defenseMessage = EncodedMessage
.makeMessage(MessageType.DEFENSE_MODE_ON, targetLocation);
myMode = GameMode.DEFENSE;
System.out.println("Defense message!");
// rc.broadcastMessageSignal(defenseMessage, emptyMessage,
// MAX_RADIUS);
}
}
// High level logic here.
private void checkMode(RobotController rc) throws GameActionException {
boolean finishedMission = false;
reachedTarget = false;
Integer distance = null;
if (targetLocation != null) {
distance = rcWrapper.getCurrentLocation()
.distanceSquaredTo(targetLocation);
}
MessageType messageType = null;
switch (myMode) {
case FREEPLAY :
rc.setIndicatorString(1, "FreePlay");
reachedTarget = true;
// finishedMission = Turn.currentTurn() > 200;
break;
case GATHER :
rc.setIndicatorString(1, "Gather");
if (distance <= 10) {
reachedTarget = true;
finishedMission = true;
}
messageType = MessageType.GATHER;
break;
case ACTIVATE :
rc.setIndicatorString(1, "Activate");
if (distance <= 1) {
reachedTarget = true;
}
if (rc.senseNearbyRobots(targetLocation, 0,
Team.NEUTRAL).length == 0) {
finishedMission = true;
}
messageType = MessageType.ACTIVATE;
break;
case ATTACK :
rc.setIndicatorString(1, "Attack: " + densLocations);
if (distance <= 35) {
reachedTarget = true;
if (rc.senseNearbyRobots(targetLocation, 0,
Team.ZOMBIE).length == 0) {
finishedMission = true;
densLocations.remove(targetLocation);
}
}
messageType = MessageType.ATTACK;
break;
case DEFENSE :
rc.setIndicatorString(1, "Defense");
reachedTarget = true;
messageType = MessageType.DEFENSE_MODE_ON;
break;
default :
break;
}
if (finishedMission && Turn.currentTurn() > 500) {
switchModes(rc);
}
if(!myMode.equals(GameMode.FREEPLAY)){
modeMessage = EncodedMessage.makeMessage(messageType, targetLocation);
}
if(!myMode.equals(GameMode.FREEPLAY) && gatherMessageDelay == 0 && !inDanger){
int message = modeMessage;
rc.broadcastMessageSignal(message, emptyMessage, 1000);
gatherMessageDelay = GATHER_MESSASGE_MAX_DELAY;
}
if (!reachedTarget && !inDanger) {
field.addParticle(new ChargedParticle(1000, targetLocation, 1));
return;
}
}
private void initializeArchon(RobotController rc)
throws GameActionException {
rcWrapper.initOnNewTurn();
myCurrentLocation = rcWrapper.getCurrentLocation();
inDanger = false;
IncomingSignals = rc.emptySignalQueue();
if (helpMessageDelay > 0) {
helpMessageDelay
}
// if (gatherMode) { // TODO
// field.addParticle(new ChargedParticle(1000, gatherLocation, 1));
if (gatherMessageDelay > 0) {
gatherMessageDelay
}
checkInbox(rc);
seekHelpIfNeeded(rc);
checkMode(rc);
if (Turn.currentTurn() == 1) {
figureOutRank(rc);
healthyArchonCount = rc
.getInitialArchonLocations(rcWrapper.myTeam).length;
}
// if (Turn.currentTurn() - lastDenGatherTurn >= DEN_GATHER_PERIOD_TURNS
// && !elm.knownZombieDens.isEmpty()) {
// lastDenGatherTurn = Turn.currentTurn();
// MapLocation closestDen = null;
// for (MapLocation l : elm.knownZombieDens) {
// if (closestDen == null
// || closestDen.distanceSquaredTo(rc.getLocation()) > l
// .distanceSquaredTo(rc.getLocation())) {
// closestDen = l;
// elm.knownZombieDens.remove(closestDen);
// rc.broadcastMessageSignal(
// EncodedMessage.makeMessage(MessageType.GATHER, closestDen),
// 0, MAX_RADIUS);
// Start producing vipers if 1/3 of the game has passed. Getting ready
// for ambush.
if (enemyBaseLocation != null) {
field.addParticle(new ChargedParticle(-0.1, enemyBaseLocation, 1));
if (Turn.currentTurn() >= 2000) {
buildDistribution.clear();
buildDistribution.put(RobotType.VIPER, 100.0);
buildDistribution.put(RobotType.SOLDIER, 2.0);
}
if (Turn.currentTurn() >= 2500 && Turn.currentTurn()
- lastBlitzkriegNotification >= BLITZKRIEG_NOTIFICATION_PERIOD_TURNS) {
lastBlitzkriegNotification = Turn.currentTurn();
rc.broadcastMessageSignal(EncodedMessage
.makeMessage(MessageType.BLITZKRIEG, enemyBaseLocation),
0, MAX_RADIUS);
}
}
rc.setIndicatorString(1, "Zombie den locations known: ");
}
@Override
public void play(RobotController rc) throws GameActionException {
initializeArchon(rc);
broadcastLateMessages(rc);
figureOutDistribution();
attemptActivateRobots(rc);
if (!inDanger) {
attemptBuild(rc);
}
attemptRepairingWeakest(rc);
adjustBattle(rc);
// If not necessary move with a probability.
if (inDanger || myMode.equals(GameMode.GATHER)
|| (Probability.acceptWithProbability(.10)
&& !myMode.equals(GameMode.DEFENSE))) {
attempMoving(rc);
}
if (!inDanger && myMode.equals(GameMode.FREEPLAY)
&& Turn.currentTurn() > 200) {
int gatherMessage = EncodedMessage.makeMessage(MessageType.GATHER,
rcWrapper.getCurrentLocation());
int emptyMessage = EncodedMessage.makeMessage(
MessageType.EMPTY_MESSAGE, new MapLocation(0, 0));
rc.broadcastMessageSignal(gatherMessage, emptyMessage, MAX_RADIUS);
// System.out.println("Gather Message sent");
startGather(rcWrapper.getCurrentLocation());
}
}
private void attempMoving(RobotController rc) throws GameActionException {
if (rc.isCoreReady()) {
mc.tryToMove(rc);
}
}
private void adjustBattle(RobotController rc) throws GameActionException {
RobotInfo[] enemyArray = rc.senseHostileRobots(myCurrentLocation,
RobotType.ARCHON.sensorRadiusSquared);
Battle.addEnemyParticles(enemyArray, field, 1);
RobotInfo[] allyArray = rc.senseNearbyRobots(
RobotType.ARCHON.sensorRadiusSquared, rcWrapper.myTeam);
Battle.addAllyParticles(allyArray, field, 1);
// if (!consideredPartsBeforeFrom.contains(myCurrentLocation)) {
MapLocation[] partsLocations = rc
.sensePartLocations(RobotType.ARCHON.sensorRadiusSquared);
for (MapLocation partsLocation : partsLocations) {
// if (!partsAdded.contains(partsLocations)) {
double amount = rc.senseParts(partsLocation);
field.addParticle(
new ChargedParticle(amount / 100.0, partsLocation, 1));
// partsAdded.add(partsLocation);
}
// consideredPartsBeforeFrom.add(myCurrentLocation);
if (inDanger) {
Battle.addBorderParticles(rcWrapper, field);
}
}
}
|
package org.exist.xquery.functions.xmldb;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xmldb.UserManagementService;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.AnyURIValue;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
/**
* @author Wolfgang Meier (wolfgang@exist-db.org)
*
*/
public class XMLDBHasLock extends XMLDBAbstractCollectionManipulator {
protected static final Logger logger = LogManager.getLogger(XMLDBHasLock.class);
public final static FunctionSignature signature[] = {
new FunctionSignature(
new QName("document-has-lock", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
"Returns the user-id of the user that holds a write lock on the " +
"resource $resource in the collection $collection-uri. " +
"If no lock is in place, the empty sequence is returned. " +
XMLDBModule.COLLECTION_URI,
new SequenceType[] {
new FunctionParameterSequenceType("collection-uri", Type.STRING, Cardinality.EXACTLY_ONE, "The collection URI"),
new FunctionParameterSequenceType("resource", Type.STRING, Cardinality.EXACTLY_ONE, "The resource")
},
new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_ONE, "the user id of the lock owner, otherwise if not locked the empty sequence")
),
new FunctionSignature(
new QName("clear-lock", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
"Removes the user lock on the " +
"resource $resource in the collection $collection-uri. " +
"If no lock is in place, the empty sequence is returned. " +
XMLDBModule.COLLECTION_URI,
new SequenceType[] {
new FunctionParameterSequenceType("collection-uri", Type.STRING, Cardinality.EXACTLY_ONE, "The collection URI"),
new FunctionParameterSequenceType("resource", Type.STRING, Cardinality.EXACTLY_ONE, "The resource")
},
new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_ONE, "the user id of the previous lock owner, otherwise if not locked the empty sequence")
)
};
public XMLDBHasLock(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
/**
*
* @param contextSequence
* @param collection
* @param args
* @throws XPathException
*/
public Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence)
throws XPathException {
try {
final UserManagementService ums = (UserManagementService) collection.getService("UserManagementService", "1.0");
final Resource res = collection.getResource(new AnyURIValue(args[1].getStringValue()).toXmldbURI().toString());
if (res != null) {
final String lockUser = ums.hasUserLock(res);
if (lockUser != null && isCalledAs("clear-lock")) {
ums.unlockResource(res);
}
return lockUser == null ? Sequence.EMPTY_SEQUENCE : new StringValue(lockUser);
} else {
logger.error("Unable to locate resource " + args[1].getStringValue());
throw new XPathException(this, "Unable to locate resource " + args[1].getStringValue());
}
} catch (final XMLDBException e) {
logger.error("Failed to retrieve user lock");
throw new XPathException(this, "Failed to retrieve user lock", e);
}
}
}
|
package org.fusfoundation.kranion;
import java.beans.PropertyChangeEvent;
import java.io.ByteArrayOutputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observer;
import javax.swing.JFileChooser;
import org.fusfoundation.kranion.model.image.ImageVolume;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.Display;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.glBindBufferBase;
import static org.lwjgl.opengl.GL43.GL_COMPUTE_SHADER;
import static org.lwjgl.opengl.GL43.GL_SHADER_STORAGE_BUFFER;
import org.lwjgl.util.vector.*;
import org.fusfoundation.kranion.model.image.*;
/**
*
* @author john
*/
public class TransducerRayTracer extends Renderable implements Pickable {
private Vector3f steering = new Vector3f(0f, 0f, 0f);
private float boneThreshold = /*1024f +*/ 700f; // 700 HU threshold for bone
private static ShaderProgram refractShader;
private static ShaderProgram sdrShader;
private static ShaderProgram pressureShader;
private static ShaderProgram pickShader;
private int posSSBo=0; // buffer of element starting center points
private int colSSBo=0; // buffer of color data per element
private int outSSBo=0; // buffer of 6 vertices per element indicating beam path (3 line segments)
private int distSSBo=0; // buffer containing minimum distance from focal spot per element
private int outDiscSSBo = 0; // buffer of triangle vertices for 'discs' on skull surface
private int outRaysSSBo = 0; // buffer of lines from element start point to outside of skull
// skull floor strike data
private int skullFloorRaysSSBo = 0;
private int skullFloorDiscSSBo = 0;
private int envSSBo = 0; // buffer for treatment envelope data (21x21x21 volume of active element counts)
private int sdrSSBo = 0; // buffer of houdsfield values along the path between outside and inside of skull per element
private int pressureSSBo = 0; // buffer of pressure contributions per ray to a given sample point
private int phaseSSBo =0;
private Trackball trackball = null;
private Vector3f centerOfRotation;
private ImageVolume CTimage = null;
public FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16);
public Matrix4f ctTexMatrix = new Matrix4f();
public FloatBuffer normMatrixBuf = BufferUtils.createFloatBuffer(16);
private int selectedElement = -1;
private ImageVolume4D envelopeImage = null;
private boolean showEnvelope = false;
private int elementCount = 0;
private int activeElementCount = 0;
private float sdr = 0f;
// Observable pattern
private List<Observer> observers = new ArrayList<Observer>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void removeAllObservers() {
observers.clear();
}
private void updateObservers(PropertyChangeEvent e) {
Iterator<Observer> i = observers.iterator();
while(i.hasNext()) {
Observer o = i.next();
o.update(null, e);
}
}
public int getActiveElementCount() { return activeElementCount; }
public boolean getShowEnvelope() { return showEnvelope; }
public void setShowEnvelope(boolean f) {
if (showEnvelope != f) {
setIsDirty(true);
}
showEnvelope = f;
}
private boolean clipRays = true;
public void setClipRays(boolean clip) {
if (clipRays != clip) {
setIsDirty(true);
}
clipRays = clip;
}
private float rescaleIntercept = 0f;
private float rescaleSlope = 1f;
private float colormap_min, colormap_max;
public void setImage(ImageVolume image) {
// if (CTimage != image) {
setIsDirty(true);
CTimage = image;
Float value = (Float) image.getAttribute("RescaleIntercept");
if (value != null) rescaleIntercept = value;
value = (Float) image.getAttribute("RescaleSlope");
if (value != null) rescaleSlope = value;
}
public void setTextureRotatation(Vector3f rotationOffset, Trackball tb) {
if (trackball == null || !centerOfRotation.equals(rotationOffset) || trackball.getCurrent() != tb.getCurrent()) {
setIsDirty(true);
}
centerOfRotation = rotationOffset;
trackball = tb;
}
public float getSDR() { return sdr; }
private float transducerTilt = 0f;
// set tilt around x axis in degrees
public void setTransducerTilt(float tilt) {
if (transducerTilt != tilt) {
setIsDirty(true);
}
transducerTilt = tilt;
}
private float boneSpeed = 2652f;//3500f;
private float boneRefractionSpeed = 2900f;
public void setTargetSteering(float x, float y, float z) { // (0, 0, 0) = no steering
if (steering.x != x || steering.y != y || steering.z != z) {
setIsDirty(true);
}
steering.set(x, y, z);
}
public Vector3f getTargetSteering() {
return steering;
}
public void setBoneSpeed(float speed) {
if (boneSpeed != speed) {
setIsDirty(true);
}
boneSpeed = Math.min(3500, Math.max(1482, speed));
}
public void setBoneRefractionSpeed(float speed) {
if (boneRefractionSpeed != speed) {
setIsDirty(true);
}
boneRefractionSpeed = Math.min(3500, Math.max(1482, speed));
}
public float getBoneSpeed() { return boneSpeed; }
public float getBoneRefractionSpeed() { return boneRefractionSpeed; }
public void setBoneThreshold(float v) {
if (boneThreshold != v) {
setIsDirty(true);
}
boneThreshold = v;
}
public float getBoneThreshold() { return boneThreshold; }
public ImageVolume getEnvelopeImage() { return envelopeImage; }
public void setSelectedElement(int nelement) {
selectedElement = nelement;
}
public int getSelectedElement() {
return selectedElement;
}
private void initShader() {
if (refractShader == null) {
refractShader = new ShaderProgram();
refractShader.addShader(GL_COMPUTE_SHADER, "shaders/TransducerRayTracer5x5skullfloor.cs.glsl");
refractShader.compileShaderProgram();
}
if (pickShader == null) {
pickShader = new ShaderProgram();
pickShader.addShader(GL_COMPUTE_SHADER, "shaders/TransducerRayTracerPick.cs.glsl");
pickShader.compileShaderProgram();
}
if (sdrShader == null) {
sdrShader = new ShaderProgram();
sdrShader.addShader(GL_COMPUTE_SHADER, "shaders/sdrAreaShader2.cs.glsl"); // no refraction, only outer skull peak used
sdrShader.compileShaderProgram();
}
if (pressureShader == null) {
pressureShader = new ShaderProgram();
pressureShader.addShader(GL_COMPUTE_SHADER, "shaders/pressureShader.cs.glsl");
pressureShader.compileShaderProgram();
}
}
public void init(Transducer trans) {
setIsDirty(true);
release();
initShader();
elementCount = trans.getElementCount();
FloatBuffer floatPosBuffer = ByteBuffer.allocateDirect(1024*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer();
int maxElemCount = elementCount > 1024 ? elementCount : 1024;
for (int i=0; i<maxElemCount; i++) {
Vector4f pos = new Vector4f(trans.getElement(i));
pos.w = 1f;
if (!trans.getElementActive(i)) {
pos.w = -1f;
}
floatPosBuffer.put(pos.x);
floatPosBuffer.put(pos.y);
floatPosBuffer.put(pos.z);
floatPosBuffer.put(pos.w);
Vector3f norm = new Vector3f(pos.x, pos.y, pos.z);
norm.negate(norm);
norm.normalise();
floatPosBuffer.put(norm.x);
floatPosBuffer.put(norm.y);
floatPosBuffer.put(norm.z);
floatPosBuffer.put(0f);
}
floatPosBuffer.flip();
posSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, posSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_STATIC_DRAW);
floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*12 * 20*3).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024*3*20; i++) {
//positions
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
Vector3f norm = new Vector3f(1f, 1f, 1f);
norm.normalise();
//normals
floatPosBuffer.put(norm.x);
floatPosBuffer.put(norm.y);
floatPosBuffer.put(norm.z);
floatPosBuffer.put(0f);
//colors
floatPosBuffer.put(1f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
}
floatPosBuffer.flip();
outDiscSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW);
// Rays between transducer surface and skull
floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*8 * 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024*2; i++) {
//positions
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
//colors
floatPosBuffer.put(1f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
}
floatPosBuffer.flip();
outRaysSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW);
// Envelope survey data
floatPosBuffer = ByteBuffer.allocateDirect(/*11x11x11*/1331 * 4*8).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1331; i++) {
//positions
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
//colors
floatPosBuffer.put(1f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
}
floatPosBuffer.flip();
envSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW);
// // Create a buffer of vertices to hold the output of the raytrace procedure
// FloatBuffer floatOutBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer();
// for (int i=0; i<1024 * 2; i++) {
// //color
// floatOutBuffer.put(0f);
// floatOutBuffer.put(0f);
// floatOutBuffer.put(0f);
// floatOutBuffer.put(1f);
// floatOutBuffer.flip();
// outSSBo = glGenBuffers();
// glBindBuffer(GL_SHADER_STORAGE_BUFFER, outSSBo);
// glBufferData(GL_SHADER_STORAGE_BUFFER, floatOutBuffer, GL_STATIC_DRAW);
// Create a buffer of vertices to hold the output of the raytrace procedure
FloatBuffer floatOutBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024 * 6; i++) {
//color
floatOutBuffer.put(0f);
floatOutBuffer.put(0f);
floatOutBuffer.put(0f);
floatOutBuffer.put(1f);
}
floatOutBuffer.flip();
outSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glBufferData(GL_ARRAY_BUFFER, floatOutBuffer, GL_STATIC_DRAW);
FloatBuffer floatColBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024 * 6; i++) {
//color
floatColBuffer.put(1f);
floatColBuffer.put(1f);
floatColBuffer.put(1f);
floatColBuffer.put(0.4f);
}
floatColBuffer.flip();
colSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glBufferData(GL_ARRAY_BUFFER, floatColBuffer, GL_STATIC_DRAW);
distSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, distSSBo);
FloatBuffer distBuffer = ByteBuffer.allocateDirect(1024*4 *6).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024; i++) {
//distance from focus
distBuffer.put(0f);
// SDR value
distBuffer.put(0f);
// Incident angle value
distBuffer.put(0f);
// Skull path length value
distBuffer.put(0f);
// SDR 2 value
distBuffer.put(0f);
// Normal skull thickness value
distBuffer.put(0f);
}
distBuffer.flip();
glBufferData(GL_ARRAY_BUFFER,distBuffer,GL_STATIC_DRAW);
sdrSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, sdrSSBo);
FloatBuffer sdrBuffer = ByteBuffer.allocateDirect(1024*4 *(60 + 3)).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024; i++) {
for (int j=0; j<60; j++) {
//ct values along transit of skull per element
sdrBuffer.put(0f);
}
// extrema values
sdrBuffer.put(0f);
sdrBuffer.put(0f);
sdrBuffer.put(0f);
}
sdrBuffer.flip();
glBufferData(GL_ARRAY_BUFFER,sdrBuffer,GL_STATIC_DRAW);
pressureSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, pressureSSBo);
FloatBuffer pressureBuffer = ByteBuffer.allocateDirect(1024*4 * 1).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024; i++) {
//ct values along transit of skull per element
pressureBuffer.put(0f);
}
pressureBuffer.flip();
glBufferData(GL_ARRAY_BUFFER, pressureBuffer, GL_STATIC_DRAW);
phaseSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, phaseSSBo);
FloatBuffer phaseBuffer = ByteBuffer.allocateDirect(1024*4 * 1).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024; i++) {
//ct values along transit of skull per element
phaseBuffer.put(0f);
}
phaseBuffer.flip();
glBufferData(GL_ARRAY_BUFFER,phaseBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Skull floor strike geometry data
floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*12 * 20*3).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024*3*20; i++) {
//positions
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
Vector3f norm = new Vector3f(1f, 1f, 1f);
norm.normalise();
//normals
floatPosBuffer.put(norm.x);
floatPosBuffer.put(norm.y);
floatPosBuffer.put(norm.z);
floatPosBuffer.put(0f);
//colors
floatPosBuffer.put(1f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
}
floatPosBuffer.flip();
skullFloorDiscSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW);
// Rays between final beam point and skull floor
floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*8 * 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i=0; i<1024*2; i++) {
//positions
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
//colors
floatPosBuffer.put(1f);
floatPosBuffer.put(0f);
floatPosBuffer.put(0f);
floatPosBuffer.put(1f);
}
floatPosBuffer.flip();
this.skullFloorRaysSSBo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, skullFloorRaysSSBo);
glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
private void doCalc() {
refractShader.start();
int shaderProgID = refractShader.getShaderProgramID();
int texLoc = glGetUniformLocation(shaderProgID, "ct_tex");
glUniform1i(texLoc, 0);
int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix");
glUniformMatrix4(texMatLoc, false, this.matrixBuf);
int boneLoc = glGetUniformLocation(shaderProgID, "boneSpeed");
glUniform1f(boneLoc, boneRefractionSpeed);
int waterLoc = glGetUniformLocation(shaderProgID, "waterSpeed");
glUniform1f(waterLoc, 1482f);
int boneThreshLoc = glGetUniformLocation(shaderProgID, "ct_bone_threshold");
glUniform1f(boneThreshLoc, boneThreshold);
int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept");
glUniform1f(rescaleLoc, this.rescaleIntercept);
rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope");
glUniform1f(rescaleLoc, this.rescaleSlope);
int targetLoc = glGetUniformLocation(shaderProgID, "target");
glUniform3f(targetLoc, steering.x, steering.y, steering.z);
texLoc = glGetUniformLocation(shaderProgID, "selectedElement");
glUniform1i(texLoc, this.selectedElement);
// int targetLoc = glGetUniformLocation(shaderprogram, "target");
// glUniform3f(targetLoc, 0f, 0f, 300f);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, colSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, distSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, outDiscSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, outRaysSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, phaseSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, skullFloorRaysSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, skullFloorDiscSSBo);
// run compute shader
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1);
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, 0);
refractShader.stop();
this.updateObservers(new PropertyChangeEvent(this, "rayCalc", null, null));
}
private void doPickCalc() {
pickShader.start();
int shaderProgID = pickShader.getShaderProgramID();
int texLoc = glGetUniformLocation(shaderProgID, "ct_tex");
glUniform1i(texLoc, 0);
int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix");
glUniformMatrix4(texMatLoc, false, this.matrixBuf);
int boneLoc = glGetUniformLocation(shaderProgID, "boneSpeed");
glUniform1f(boneLoc, boneRefractionSpeed);
int waterLoc = glGetUniformLocation(shaderProgID, "waterSpeed");
glUniform1f(waterLoc, 1482f);
int boneThreshLoc = glGetUniformLocation(shaderProgID, "ct_bone_threshold");
glUniform1f(boneThreshLoc, boneThreshold);
int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept");
glUniform1f(rescaleLoc, this.rescaleIntercept);
rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope");
glUniform1f(rescaleLoc, this.rescaleSlope);
int targetLoc = glGetUniformLocation(shaderProgID, "target");
glUniform3f(targetLoc, steering.x, steering.y, steering.z);
// int targetLoc = glGetUniformLocation(shaderprogram, "target");
// glUniform3f(targetLoc, 0f, 0f, 300f);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, colSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, distSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, outDiscSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, outRaysSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, phaseSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, skullFloorRaysSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, skullFloorDiscSSBo);
// run compute shader
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1);
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, 0);
pickShader.stop();
// this.updateObservers(new PropertyChangeEvent(this, "rayCalc", null, null));
}
public void doSDRCalc() {
// Calculate per element SDR data
// doCalc() must be called first to compute the per element ray segments
sdrShader.start();
int shaderProgID = sdrShader.getShaderProgramID();
int texLoc = glGetUniformLocation(shaderProgID, "ct_tex");
glUniform1i(texLoc, 0);
int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix");
glUniformMatrix4(texMatLoc, false, this.matrixBuf);
int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept");
glUniform1f(rescaleLoc, this.rescaleIntercept);
rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope");
glUniform1f(rescaleLoc, this.rescaleSlope);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, outSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, distSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, sdrSSBo);
// run compute shader
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1);
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
sdrShader.stop();
this.updateObservers(new PropertyChangeEvent(this, "sdrCalc", null, null));
}
public void doPressureCalc(Vector4f samplePoint) {
// Calculate per element SDR data
// doCalc() must be called first to compute the per element ray segments
pressureShader.start();
int shaderProgID = pressureShader.getShaderProgramID();
int uniformLoc = glGetUniformLocation(shaderProgID, "sample_point");
glUniform3f(uniformLoc, samplePoint.x, samplePoint.y, samplePoint.z);// + 150f);
uniformLoc = glGetUniformLocation(shaderProgID, "boneSpeed");
glUniform1f(uniformLoc, this.boneSpeed);
//TEST glUniform1f(uniformLoc, 2640f);
uniformLoc = glGetUniformLocation(shaderProgID, "waterSpeed");
glUniform1f(uniformLoc, 1482f);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, distSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, pressureSSBo);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, phaseSSBo);
// run compute shader
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1);
org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0);
pressureShader.stop();
}
public void calcEnvelope() {
calcEnvelope(null);
}
public void calcSkullFloorDensity() {
if (this.CTimage == null) return;
int xsize = CTimage.getDimension(0).getSize() / 2;
int ysize = CTimage.getDimension(1).getSize() / 2;
int zsize = CTimage.getDimension(2).getSize() / 2;
float xres = CTimage.getDimension(0).getSampleWidth(0) * 2f;
float yres = CTimage.getDimension(1).getSampleWidth(1) * 2f;
float zres = CTimage.getDimension(2).getSampleWidth(2) * 2f;
Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
Quaternion imageRotation = (Quaternion)CTimage.getAttribute("ImageOrientationQ");
if (envelopeImage != null) {
ImageVolumeUtil.releaseTexture(envelopeImage);
}
envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, xsize, ysize, zsize, 1);
envelopeImage.getDimension(0).setSampleWidth(xres);
envelopeImage.getDimension(1).setSampleWidth(yres);
envelopeImage.getDimension(2).setSampleWidth(zres);
envelopeImage.getDimension(0).setSampleSpacing(xres);
envelopeImage.getDimension(1).setSampleSpacing(yres);
envelopeImage.getDimension(2).setSampleSpacing(zres);
envelopeImage.setAttribute("ImageTranslation", new Vector3f(imageTranslation));
envelopeImage.setAttribute("ImageOrientationQ", new Quaternion(imageRotation));
// setup textures
// need to compile shader in init
// TODO: work on integration of skull floor footprints
// shader.start();
// int uloc = glGetUniformLocation(shader.getShaderProgramID(), "ct_rescale_intercept");
// glUniform1f(uloc, this.rescaleIntercept);
// uloc = glGetUniformLocation(shader.getShaderProgramID(), "ct_rescale_slope");
// glUniform1f(uloc, this.rescaleSlope);
// // run compute shader
// org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
// org.lwjgl.opengl.GL43.glDispatchCompute((xsize+7)/8, (ysize+7)/8, (zsize+7)/8);
// org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS);
// // Clean up
// shader.stop();
}
public void calcEnvelope(ProgressListener listener) {
// if (envelopeImage == null) {
if (envelopeImage != null) {
ImageVolumeUtil.releaseTexture(envelopeImage);
}
envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, 21, 21, 21, 1);
envelopeImage.getDimension(0).setSampleWidth(4f);
envelopeImage.getDimension(1).setSampleWidth(6f);
envelopeImage.getDimension(2).setSampleWidth(4f);
envelopeImage.getDimension(0).setSampleSpacing(4f);
envelopeImage.getDimension(1).setSampleSpacing(6f);
envelopeImage.getDimension(2).setSampleSpacing(4f);
Vector4f offset = new Vector4f();
Matrix4f transducerTiltMat = new Matrix4f();
transducerTiltMat.setIdentity();
Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat);
if (CTimage == null) return;
Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
envelopeImage.setAttribute("ImageTranslation", new Vector3f());
// 21x21x21 array of floats to hold sampled treatment envelope
FloatBuffer envFloats = ByteBuffer.allocateDirect(9261*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer();
float[] voxels = (float[])envelopeImage.getData();
for (int i = -10; i <= 10; i++) {
for (int j = -10; j <= 10; j++) {
if (listener != null) {
listener.percentDone("Treatment envelope", Math.round( ((i+10)*21f + (j+10))/440f*100f ) );
}
for (int k = -10; k <= 10; k++) {
offset.set(i * 4f, j * 6f, k * 4f, 1f);
int elemCount = calcElementsOn(new Vector3f(0f, 0f, 0f), offset);
voxels[(i+10) + (-j+10)*21 + (-k+10)*21*21] = (short)(elemCount & 0xffff);
// System.out.print("elemCount = " + elemCount + " ");
// envFloats.put(-centerOfRotation.x + imageTranslation.x + offset.x);
// envFloats.put(-centerOfRotation.x + imageTranslation.y + offset.y);
// envFloats.put(-centerOfRotation.x + imageTranslation.z + offset.z + 150f);
Matrix4f.transform(transducerTiltMat, offset, offset);
envFloats.put(offset.x);// + centerOfRotation.x);
envFloats.put(offset.y);// - centerOfRotation.y);
envFloats.put(-offset.z);// -centerOfRotation.z);
envFloats.put(1f);
if (elemCount >= 700) {
envFloats.put(0f);
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0.6f);
}
else if (elemCount >= 500) {
envFloats.put(1f);
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0.6f);
} else {
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0f);
envFloats.put(0.6f);
}
}
}
// System.out.println("");
}
if (listener != null) {
listener.percentDone("Ready", -1);
}
envFloats.flip();
if (envSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(envSSBo);
envSSBo = glGenBuffers();
}
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glBufferData(GL_ARRAY_BUFFER, envFloats, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
public float[] getChannelSkullSamples(int channel) {
glBindBuffer(GL_ARRAY_BUFFER, this.sdrSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatSamples = dists.asFloatBuffer();
int count = 0;
float[] huOut = new float[63];
for (int i=0; i<huOut.length; i++) {
huOut[i] = floatSamples.get(channel * 63 + i);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return huOut;
}
public void writeSkullMeasuresFile(File outFile) {
if (outFile != null) {
List<Double> speeds = getSpeeds();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(outFile));
writer.write("Skull parameters");
writer.newLine();
writer.write("NumberOfChannels = 1024");
writer.newLine();
writer.newLine();
writer.write("channel\tsdr\tsdr5x5\tincidentAngle\tskull_thickness\trefracted_skull_path_length\tSOS");
writer.newLine();
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
float speed = CTSoundSpeed.lookupSpeed(speeds.get(count).floatValue() + 1000f); // add 1000 to get apparent density
writer.write(count + "\t");
writer.write(String.format("%1.3f", sdr) + "\t");
writer.write(String.format("%1.3f", sdr2) + "\t");
writer.write(String.format("%3.3f", incidentAngle) + "\t");
writer.write(String.format("%3.3f", normSkullThickness) + "\t");
writer.write(String.format("%3.3f", skullThickness) + "\t");
writer.write(String.format("%3.3f", speed) + "\t");
writer.newLine();
count++;
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
public void writeACTFile(File outFile) {
if (outFile != null) {
doCalc();
doPressureCalc(new Vector4f());
glBindBuffer(GL_ARRAY_BUFFER, phaseSSBo);
ByteBuffer phases = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = phases.asFloatBuffer();
int count = 0, zeroCount = 0;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(outFile));
writer.write("[AMPLITUDE_AND_PHASE_CORRECTIONS]");
writer.newLine();
writer.write("NumberOfChannels = 1024");
writer.newLine();
writer.newLine();
while (floatPhases.hasRemaining()) {
double phase = (double) floatPhases.get() % (2.0 * Math.PI);
if (phase > Math.PI) {
phase -= 2.0 * Math.PI;
} else if (phase < -Math.PI) {
phase += 2.0 * Math.PI;
}
if (phase == 0.0) {
zeroCount++;
}
// phase = -phase;
//double phase = (double)floatPhases.get(); // for outputing skull thickness if set in pressure shader
// System.out.println("Channel " + count + " = " + phase);
writer.write("CH" + count + "\t=\t");
count++;
if (phase == 0.0) {
writer.write("0\t");
} else {
writer.write("1\t");
}
writer.write(String.format("%1.4f", phase));
writer.newLine();
}
System.out.println("zero phase channels = " + zeroCount);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
public List<Double> getIncidentAngles() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (incidentAngle >= 0f) {
result.add((double)incidentAngle);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getIncidentAnglesFull() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
result.add((double)incidentAngle);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getSDRs() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)sdr);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
// include -1 for all inactive elements
public List<Double> getSDRsFull() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)sdr);
}
else {
result.add(-1.0);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getSDR2s() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)sdr2);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getSkullThicknesses() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)skullThickness);
}
else {
result.add(-1.0);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getNormSkullThicknesses() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)normSkullThickness);
}
else {
result.add(-1.0);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
// this list will contain sdr = -1 for inactive elements
public List<Double> getSDR2sFull() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo);
ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPhases = dists.asFloatBuffer();
int count = 0;
while (floatPhases.hasRemaining()) {
float dist = floatPhases.get();
float sdr = floatPhases.get();
float incidentAngle = floatPhases.get();
float skullThickness = floatPhases.get();
float sdr2 = floatPhases.get();
float normSkullThickness = floatPhases.get();
if (dist >= 0f) {
result.add((double)sdr2);
}
else {
result.add(-1.0);
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return result;
}
public List<Double> getSpeeds() {
List<Double> result = new ArrayList<>();
glBindBuffer(GL_SHADER_STORAGE_BUFFER,sdrSSBo);
ByteBuffer sdrOutput = glMapBuffer(GL_SHADER_STORAGE_BUFFER,GL_READ_ONLY,null);
FloatBuffer huValues = sdrOutput.asFloatBuffer();
float[] huOut = new float[60];
float[] huIndices = new float[3];
for (int i=0; i<1024; i++) {
huValues.get(huOut);
huValues.get(huIndices);
int left = 0;
int right = 59;
for (int x=0; x<59; x++) {
if (huOut[x] >= 700f) {
left = x;
break;
}
}
for (int x=59; x>=0; x
if (huOut[x] >= 700f) {
right = x;
break;
}
}
int count = 0;
float sum = 0f;
for (int x=left; x<=right; x++) {
count++;
sum += huOut[x];
}
if (count > 0) {
result.add((double)sum/(double)count);
}
else {
result.add(-1.0);
}
}
glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
return result;
}
public void calcPressureEnvelope() {
// if (envelopeImage == null) {
float voxelsize = 0.5f;
int volumeHalfWidth = 10;
int volumeWidth = 2*volumeHalfWidth+1;
envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, volumeWidth, volumeWidth, volumeWidth, 1);
envelopeImage.getDimension(0).setSampleWidth(voxelsize);
envelopeImage.getDimension(1).setSampleWidth(voxelsize);
envelopeImage.getDimension(2).setSampleWidth(voxelsize);
envelopeImage.getDimension(0).setSampleSpacing(voxelsize);
envelopeImage.getDimension(1).setSampleSpacing(voxelsize);
envelopeImage.getDimension(2).setSampleSpacing(voxelsize);
Vector4f offset = new Vector4f();
// Matrix4f transducerTiltMat = new Matrix4f();
// transducerTiltMat.setIdentity();
// Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat);
if (CTimage == null) return;
// Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
// envelopeImage.setAttribute("ImageTranslation", new Vector3f(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z));
envelopeImage.setAttribute("ImageTranslation", new Vector3f(-centerOfRotation.x, -centerOfRotation.y, -centerOfRotation.z));
envelopeImage.setAttribute("ImageOrientationQ", new Quaternion());
float[] voxels = (float[])envelopeImage.getData();
this.colormap_min = Float.MAX_VALUE;
this.colormap_max = -Float.MAX_VALUE;
setupImageTexture(CTimage, 0, new Vector3f(centerOfRotation.x, centerOfRotation.y, centerOfRotation.z), new Vector4f(0f, 0f, 0f, 1f)/*offset*/);
doCalc();
glActiveTexture(GL_TEXTURE0 + 0);
glDisable(GL_TEXTURE_3D);
for (int i = -volumeHalfWidth; i <= volumeHalfWidth; i++) {
for (int j = -volumeHalfWidth; j <= volumeHalfWidth; j++) {
for (int k = -volumeHalfWidth; k <= volumeHalfWidth; k++) {
float pressure = 0f;
//if (k==0) {
offset.set(i * voxelsize, j * voxelsize, k * voxelsize, 1f);
pressure = calcSamplePressure(new Vector3f(), offset) * 10f;
pressure *= pressure;
if (i==0 && j==0 && k==0) {
//TODO: just for now, remove
///glMapBuffer
// glBindBuffer(GL_SHADER_STORAGE_BUFFER, phaseSSBo);
// ByteBuffer phases = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_WRITE, null);
// FloatBuffer floatPhases = phases.asFloatBuffer();
// int count = 0, zeroCount = 0;
// BufferedWriter writer=null;
// try {
// writer = new BufferedWriter(new FileWriter("ACT.ini"));
// writer.write("[AMPLITUDE_AND_PHASE_CORRECTIONS]");
// writer.newLine();
// writer.write("NumberOfChannels = 1024");
// writer.newLine();
// writer.newLine();
// while (floatPhases.hasRemaining()) {
// double phase = (double)floatPhases.get() % (2.0 * Math.PI);
// if (phase > Math.PI) {
// phase -= 2.0 * Math.PI;
// else if (phase < -Math.PI) {
// phase += 2.0 * Math.PI;
// if (phase == 0.0) {
// zeroCount++;
//// phase = -phase;
////double phase = (double)floatPhases.get(); // for outputing skull thickness if set in pressure shader
// System.out.println("Channel " + count + " = " + phase);
// writer.write("CH" + count + "\t=\t");
// count++;
// if (phase == 0.0) {
// writer.write("0\t");
// else {
// writer.write("1\t");
// writer.write(String.format("%1.4f", phase));
// writer.newLine();
// System.out.println("zero phase channels = " + zeroCount);
// writer.close();
// catch(IOException e) {
// e.printStackTrace();
// glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
// glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
if (pressure > colormap_max) {
colormap_max = pressure;
}
if (pressure < colormap_min) {
colormap_min = pressure;
}
voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (k + volumeHalfWidth) * volumeWidth * volumeWidth] = pressure;
// if (i==0) {
// if (k==-volumeHalfWidth) {
// System.out.println();
// System.out.print(pressure + " ");
// } // k == 0
}
}
}
// for (int i = -volumeHalfWidth; i <= volumeHalfWidth; i++) {
// for (int j = -volumeHalfWidth; j <= volumeHalfWidth; j++) {
// for (int k = -volumeHalfWidth; k <= volumeHalfWidth; k++) {
// float value = voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (-k + volumeHalfWidth) * volumeWidth * volumeWidth];
// voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (-k + volumeHalfWidth) * volumeWidth * volumeWidth] = (value - colormap_min) / (colormap_max - colormap_min);
System.out.println("Pressure max = " + colormap_max + ", min = " + colormap_min);
}
public void calc2DEnvelope() {
Vector4f offset = new Vector4f();
Matrix4f transducerTiltMat = new Matrix4f();
transducerTiltMat.setIdentity();
Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat);
if (CTimage == null) return;
Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
// 21x21x21 array of floats to hold sampled treatment envelope
FloatBuffer envFloats = ByteBuffer.allocateDirect(9261*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer();
for (int i = -10; i <= 10; i++) {
for (int j = -10; j <= 10; j++) {
offset.set(i * 6f, j * 6f, 0f, 1f);
Matrix4f rotMat = Trackball.toMatrix4f(trackball.getCurrent());
// rotMat.rotate((float)Math.PI, new Vector3f(0f, 0f, 1f), rotMat);
Matrix4f.transform(rotMat, offset, offset);
int elemCount = calcElementsOn(centerOfRotation, offset);
System.out.print("" + elemCount + " ");
// envFloats.put(-centerOfRotation.x + imageTranslation.x + offset.x);
// envFloats.put(-centerOfRotation.x + imageTranslation.y + offset.y);
// envFloats.put(-centerOfRotation.x + imageTranslation.z + offset.z + 150f);
//Matrix4f.transform(transducerTiltMat, offset, offset);
envFloats.put(offset.x);// + centerOfRotation.x);
envFloats.put(offset.y);// - centerOfRotation.y);
envFloats.put(-offset.z);// -centerOfRotation.z);
envFloats.put(1f);
if (elemCount >= 700) {
envFloats.put(0f);
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0.6f);
}
else if (elemCount >= 500) {
envFloats.put(1f);
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0.6f);
} else {
envFloats.put(1f);
envFloats.put(0f);
envFloats.put(0f);
envFloats.put(0.6f);
}
}
System.out.println("");
}
envFloats.flip();
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glBufferData(GL_ARRAY_BUFFER, envFloats, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
private int calcElementsOn(Vector4f offset) {
return calcElementsOn(centerOfRotation, offset);
}
private int calcElementsOn(Vector3f center, Vector4f offset) {
if (CTimage == null) {
return 0;
}
setupImageTexture(CTimage, 0, center, offset);
doCalc();
glActiveTexture(GL_TEXTURE0 + 0);
glDisable(GL_TEXTURE_3D);
///glMapBuffer
glBindBuffer(GL_ARRAY_BUFFER, distSSBo);
ByteBuffer distances = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatDistances = distances.asFloatBuffer();
int numberOn = 0;
// float sdrSum = 0f;
while (floatDistances.hasRemaining()) {
float value = floatDistances.get();
float sdrval = floatDistances.get(); // TODO
floatDistances.get(); // incidence angle
floatDistances.get(); // skull thickness
float sdrval2 = floatDistances.get(); // TODO
float normSkullThickness = floatDistances.get();
if (value > 0) {
numberOn++;
// sdrSum += sdr;
}
}
// System.out.println("SDR = " + sdrSum/numberOn);
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return numberOn;
}
private float calcSamplePressure(Vector3f center, Vector4f offset) {
if (CTimage == null) {
return 0;
}
// setupImageTexture(CTimage, 0, center, new Vector4f(0f, 0f, 0f, 1f)/*offset*/);
// doCalc();
doPressureCalc(offset);
// glActiveTexture(GL_TEXTURE0 + 0);
// glDisable(GL_TEXTURE_3D);
///glMapBuffer
glBindBuffer(GL_ARRAY_BUFFER, pressureSSBo);
ByteBuffer pressures = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null);
FloatBuffer floatPressures = pressures.asFloatBuffer();
float totalPressure = 0f;
while (floatPressures.hasRemaining()) {
totalPressure += floatPressures.get();
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return totalPressure;
}
@Override
public void render() {
if (!getVisible()) return;
setIsDirty(false);
if (CTimage == null) return;
setupImageTexture(CTimage, 0, centerOfRotation);
doCalc();
doSDRCalc();
glActiveTexture(GL_TEXTURE0 + 0);
glDisable(GL_TEXTURE_3D);
// Raytracer done, now render result
// glBindBuffer(GL_SHADER_STORAGE_BUFFER,sdrSSBo);
// ByteBuffer sdrOutput = glMapBuffer(GL_SHADER_STORAGE_BUFFER,GL_READ_ONLY,null);
// FloatBuffer sdrValues = sdrOutput.asFloatBuffer();
// float[][] tmpOut = new float[1024][60];
// float[][] tmpIndices = new float[1024][3];
// for (int i=0; i<1024; i++) {
// sdrValues.get(tmpOut[i]);
// sdrValues.get(tmpIndices[i]);
// glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
// glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
// System.out.println("///////////SDR data");
// for (int i=0; i<60; i++) {
// System.out.print(i);
// for (int j=0; j<1024; j++) {
// System.out.print(", " + tmpOut[j][i]);
// System.out.println();
// for (int i=0; i<3; i++) {
// switch(i) {
// case 0:
// System.out.print("LPk");
// break;
// case 1:
// System.out.print("RPk");
// break;
// case 2:
// System.out.print("Min");
// break;
// for (int j=0; j<1024; j++) {
// System.out.print(", " + tmpIndices[j][i]);
// System.out.println();
// System.out.print("CH, ");
// for (int i=0; i<1024; i++) {
// System.out.print(i);
// if (i<1023) {
// System.out.print(", ");
// System.out.println();
// System.out.println("/////////////");
///glMapBuffer
glBindBuffer(GL_ARRAY_BUFFER,distSSBo);
ByteBuffer distances = glMapBuffer(GL_ARRAY_BUFFER,GL_READ_WRITE,null);
FloatBuffer floatDistances = distances.asFloatBuffer();
float distanceSum = 0.0f;
int distanceNum = 0;
int numberOn = 0;
while (floatDistances.hasRemaining())
{
float value = floatDistances.get();
float sdr = floatDistances.get();
floatDistances.get(); // skip incidence angle
floatDistances.get(); // skip skull thickness
float sdr2 = floatDistances.get();
float normSkullThickness = floatDistances.get();
if (value > 0)
{
distanceNum++;
distanceSum += value;
numberOn++;
}
}
float percentOn = numberOn/1024.0f;
float mean = distanceSum/distanceNum;
floatDistances.rewind();
float diffSqSum = 0.0f;
float sdrSum = 0.0f;
float sdrCount = 0.0f;
while (floatDistances.hasRemaining())
{
float value = floatDistances.get();
float sdr = floatDistances.get();
floatDistances.get();
floatDistances.get();
float sdr2 = floatDistances.get();
float normSkullThickness = floatDistances.get();
if (value > 0)
{
diffSqSum += (float) Math.pow(value-mean,2);
sdrSum += sdr2;
sdrCount += 1.0f;
}
}
activeElementCount = numberOn;
this.sdr = sdrSum/sdrCount; //distanceNum;
float stDev = (float)Math.sqrt(diffSqSum/distanceNum);
// System.out.println("Average: "+mean);
// System.out.println("Std Dev: "+stDev);
// System.out.println("% Within 3 mm of focus: "+(percentOn*100) + "(" + numberOn + " of 1024)");
// System.out.println("SDR: " + sdrSum/distanceNum);
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// glTranslatef(0, 0, 150);
glTranslatef(-steering.x, -steering.y, -steering.z);
glRotatef(this.transducerTilt, 1, 0, 0);
// glTranslatef(0, 0, -150);
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16*6, 0);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16*6, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
Main.glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT);
glDisable(GL_LIGHTING);
if (clipRays) {
glEnable(GL_CLIP_PLANE0);
glEnable(GL_CLIP_PLANE1);
}
else {
glDisable(GL_CLIP_PLANE0);
glDisable(GL_CLIP_PLANE1);
}
//glEnable(GL_BLEND);
//glColor4f(1f, 0f, 0f, 1f);
glPointSize(6f);
// Draw outer skull points
if (clipRays) {
glDrawArrays(GL_POINTS, 0, 1024);
}
// Draw inner skull points
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16*6, 16*3);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16*6, 16*3);
if (clipRays) {
glDrawArrays(GL_POINTS, 0, 1024);
}
// Draw envelope
renderEnvelope();
// calc2DEnvelope(); // TODO: doesn't work yet
// render2DEnvelope();
if (clipRays) {
// Draw normal flags
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16, 0);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
org.lwjgl.opengl.GL11.glLineWidth(1.2f);
if (!showEnvelope) {
glDrawArrays(GL_LINES, 0, 1024*6);
}
}
// Draw skull strike discs
if (!clipRays) {
Main.glPushAttrib(GL_LIGHTING_BIT);
glEnable(GL_LIGHTING);
FloatBuffer matSpecular = BufferUtils.createFloatBuffer(4);
matSpecular.put(0.2f).put(0.2f).put(0.2f).put(1.0f).flip();
glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, matSpecular); // sets specular material color
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 30.0f); // sets shininess
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glVertexPointer(4, GL_FLOAT, 12*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glNormalPointer(GL_FLOAT, 12*4, 16);
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glColorPointer(4, GL_FLOAT, 12*4, 32);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 1024*3*20);
// skull floor normal discs
glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo);
glVertexPointer(4, GL_FLOAT, 12*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo);
glNormalPointer(GL_FLOAT, 12*4, 16);
glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo);
glColorPointer(4, GL_FLOAT, 12*4, 32);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 1024*3*20);
Main.glPopAttrib();
}
else {
Main.glPushAttrib(GL_COLOR_BUFFER_BIT);
org.lwjgl.opengl.GL11.glLineWidth(1.0f);
glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo);
glVertexPointer(4, GL_FLOAT, 8*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo);
glColorPointer(4, GL_FLOAT, 8*4, 16);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDrawArrays(GL_LINES, 0, 1024*2);
// skull floor strike rays
glBindBuffer(GL_ARRAY_BUFFER, this.skullFloorRaysSSBo);
glVertexPointer(4, GL_FLOAT, 8*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, skullFloorRaysSSBo);
glColorPointer(4, GL_FLOAT, 8*4, 16);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDrawArrays(GL_LINES, 0, 1024*2);
Main.glPopAttrib();
}
Main.glPopAttrib();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
private void renderEnvelope() {
Main.glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT);
glPointSize(8f);
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glVertexPointer(4, GL_FLOAT, 16*2, 0);
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glColorPointer(4, GL_FLOAT, 16*2, 16);
if (clipRays && showEnvelope) {
//glEnable(GL_BLEND);
glMatrixMode(GL_MODELVIEW);
Main.glPushMatrix();
// envFloats.put(offset.x + centerOfRotation.x);
// envFloats.put(offset.y - centerOfRotation.y);
// envFloats.put(150f - offset.z - centerOfRotation.z);
// Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
// glTranslatef(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z);
// glTranslatef(0f, 0f, 150f);
// glRotatef(-(float)Math.PI, 1f, 0f, 0f);
glRotatef(-transducerTilt, 1f, 0f, 0f);
glTranslatef(-centerOfRotation.x, centerOfRotation.y, centerOfRotation.z);
glDrawArrays(GL_POINTS, 0, 9261);
Main.glPopMatrix();
}
Main.glPopAttrib();
}
private void render2DEnvelope() {
Main.glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT);
glPointSize(8f);
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glVertexPointer(4, GL_FLOAT, 16*2, 0);
glBindBuffer(GL_ARRAY_BUFFER, envSSBo);
glColorPointer(4, GL_FLOAT, 16*2, 16);
if (clipRays && showEnvelope) {
//glEnable(GL_BLEND);
glMatrixMode(GL_MODELVIEW);
Main.glPushMatrix();
// envFloats.put(offset.x + centerOfRotation.x);
// envFloats.put(offset.y - centerOfRotation.y);
// envFloats.put(150f - offset.z - centerOfRotation.z);
// Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation");
// glTranslatef(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z);
// glTranslatef(0f, 0f, 150f);
// glRotatef(-(float)Math.PI, 1f, 0f, 0f);
// glRotatef(-transducerTilt, 1f, 0f, 0f);
// glTranslatef(-centerOfRotation.x, centerOfRotation.y, centerOfRotation.z);
glDrawArrays(GL_POINTS, 0, 9261);
Main.glPopMatrix();
}
Main.glPopAttrib();
}
private void setupImageTexture(ImageVolume image, int textureUnit, Vector3f center) {
setupImageTexture(image, textureUnit, center, new Vector4f(0f, 0f, 0f, 1f));
}
private void setupImageTexture(ImageVolume image, int textureUnit, Vector3f center, Vector4f offset) {
if (image == null) return;
Main.glPushAttrib(GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glActiveTexture(GL_TEXTURE0 + textureUnit);
glEnable(GL_TEXTURE_3D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
Integer tn = (Integer) image.getAttribute("textureName");
if (tn == null) return; // TODO: this should be handled when the 3D texture doesn't exist for some reason (i.e. after some image filter)
int textureName = tn.intValue();
glBindTexture(GL_TEXTURE_3D, textureName);
int iWidth = image.getDimension(0).getSize();
int iHeight = image.getDimension(1).getSize();
int idepth = image.getDimension(2).getSize();
int texWidth = iWidth;
int texHeight = iHeight;
int texDepth = idepth;
// Build transformation of Texture matrix
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
//System.out.println("mid z = " + (double)idepth/texDepth/2.0);
//fix voxel scaling
float xres = image.getDimension(0).getSampleWidth(0);
float yres = image.getDimension(1).getSampleWidth(1);
float zres = image.getDimension(2).getSampleWidth(2);
// Translation to the texture volume center (convert 0 -> 1 value range to -0.5 -> 0.5)
// glTranslated(0.5, 0.5, (double) idepth / texDepth / 2.0);
// float zscaleFactor = ((float) texWidth * xres) / ((float) texDepth * zres);
// // Scale for in-plane/out-of-plane ratio
//// glScaled(1.0f, 1.0f, -zscaleFactor); // this assumes in-plane pixel dimesions are the same! //HACK
// glScaled(1f /(texWidth * xres), 1f/(texWidth * xres), 1f/(texDepth * zres));
// // Translation of center of rotation to origin (mm to texture coord values (0 -> 1))
Vector3f imageTranslation = (Vector3f)image.getAttribute("ImageTranslation");
if (imageTranslation == null) {
imageTranslation = new Vector3f();
}
float[] imagePosition = (float[])image.getAttribute("ImagePosition");
if (imagePosition == null) {
imagePosition = new float[3];
}
// glTranslatef(
//// (imageTranslation.x)/ (xres * iWidth),
//// (imageTranslation.y) / (yres * iHeight),
//// (imageTranslation.z) / (zres * idepth * zscaleFactor));
// (-imageTranslation.x),
// (-imageTranslation.y),
// (-imageTranslation.z) - 150f);
Quaternion imageOrientation = (Quaternion)image.getAttribute("ImageOrientationQ");
if (imageOrientation == null) return;
FloatBuffer orientBuffer = BufferUtils.createFloatBuffer(16);
Trackball.toMatrix4f(imageOrientation).store(orientBuffer);
orientBuffer.flip();
// Rotation for image orientation
//glMultMatrix(orientBuffer);
// Rotation for camera view
// if (trackball != null) {
// trackball.renderOpposite();
// matrixBuf.rewind();
// glGetFloat(GL_TEXTURE_MATRIX, matrixBuf);
// ctTexMatrix.load(matrixBuf);
ctTexMatrix.setIdentity();
// Final translation to put origin in the center of texture space (0.5, 0.5, 0.5)
Matrix4f.translate(new Vector3f(0.5f, 0.5f, 0.5f), ctTexMatrix, ctTexMatrix);
// Scale for image resolution (normalize to texture coordinates 0-1
Matrix4f.scale(new Vector3f(1.0f/(texWidth*xres), 1.0f/(texHeight*yres), -1.0f/(texDepth*zres)), ctTexMatrix, ctTexMatrix);
// Rotation
Matrix4f rotMat = new Matrix4f();
rotMat.load(orientBuffer);
Matrix4f.mul(ctTexMatrix, rotMat, ctTexMatrix);
// Translation
Matrix4f.translate(new Vector3f(
(center.x + imageTranslation.x /* + imagePosition[0] */),
(center.y + imageTranslation.y /* + imagePosition[1] */),
(center.z + imageTranslation.z /* + imagePosition[2] */)
),
ctTexMatrix, ctTexMatrix);
Matrix4f.rotate((float)Math.PI, new Vector3f(1f, 0f, 0f), ctTexMatrix, ctTexMatrix);
//Matrix4f.rotate((float)Math.PI, new Vector3f(0f, 1f, 0f), ctTexMatrix, ctTexMatrix);
// add in transducer tilt
Matrix4f.rotate(transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), ctTexMatrix, ctTexMatrix);
// Translate transducer origin to the transducer face
// Matrix4f.translate(new Vector3f(0f, 0f, -150f), ctTexMatrix, ctTexMatrix);
Matrix4f.translate(new Vector3f(offset.x, offset.y, -offset.z), ctTexMatrix, ctTexMatrix);
// store matrix for use later
matrixBuf.rewind();
ctTexMatrix.store(matrixBuf);
matrixBuf.flip();
// System.out.println(ctTexMatrix);
// System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(0f, 0f, 150f, 1f), null));
// System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(0f, 0f, 0f, 1f), null));
// System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(150f, 0f, 0f, 1f), null));
glMatrixMode(GL_MODELVIEW);
Main.glPopAttrib();
}
@Override
public void release()
{
if (posSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(posSSBo);
posSSBo = 0;
}
if (colSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(colSSBo);
colSSBo = 0;
}
if (outSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(outSSBo);
outSSBo = 0;
}
if (distSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(distSSBo);
distSSBo = 0;
}
if (outDiscSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(outDiscSSBo);
outDiscSSBo = 0;
}
if (outRaysSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(outDiscSSBo);
outRaysSSBo = 0;
}
if (envSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(envSSBo);
envSSBo = 0;
}
if (sdrSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(sdrSSBo);
sdrSSBo = 0;
}
if (pressureSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(pressureSSBo);
pressureSSBo = 0;
}
if (phaseSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(phaseSSBo);
phaseSSBo = 0;
}
if (skullFloorDiscSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(skullFloorDiscSSBo);
skullFloorDiscSSBo = 0;
}
if (skullFloorRaysSSBo != 0) {
org.lwjgl.opengl.GL15.glDeleteBuffers(skullFloorRaysSSBo);
skullFloorRaysSSBo = 0;
}
if (refractShader != null) {
refractShader.release();
refractShader = null;
}
if (sdrShader != null) {
sdrShader.release();
sdrShader = null;
}
if (pressureShader != null) {
pressureShader.release();
pressureShader = null;
}
}
@Override
public void renderPickable() {
if (!getVisible()) return;
if (CTimage == null) return;
setupImageTexture(CTimage, 0, centerOfRotation);
doPickCalc();
glActiveTexture(GL_TEXTURE0 + 0);
glDisable(GL_TEXTURE_3D);
glTranslatef(-steering.x, -steering.y, -steering.z);
glRotatef(this.transducerTilt, 1, 0, 0);
// glTranslatef(0, 0, -150);
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16*6, 0);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16*6, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
Main.glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT);
glDisable(GL_LIGHTING);
if (clipRays) {
glEnable(GL_CLIP_PLANE0);
glEnable(GL_CLIP_PLANE1);
}
else {
glDisable(GL_CLIP_PLANE0);
glDisable(GL_CLIP_PLANE1);
}
//glEnable(GL_BLEND);
//glColor4f(1f, 0f, 0f, 1f);
glPointSize(6f);
// Draw outer skull points
if (clipRays) {
glDrawArrays(GL_POINTS, 0, 1024);
}
// Draw inner skull points
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16*6, 16*3);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16*6, 16*3);
if (clipRays) {
glDrawArrays(GL_POINTS, 0, 1024);
}
if (clipRays) {
// Draw normal flags
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, outSSBo);
glVertexPointer(4, GL_FLOAT, 16, 0);
glBindBuffer(GL_ARRAY_BUFFER, colSSBo);
glColorPointer(4, GL_FLOAT, 16, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
org.lwjgl.opengl.GL11.glLineWidth(1.2f);
if (!showEnvelope) {
glDrawArrays(GL_LINES, 0, 1024*6);
}
}
// Draw skull strike discs
if (!clipRays) {
Main.glPushAttrib(GL_LIGHTING_BIT);
glDisable(GL_LIGHTING);
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glVertexPointer(4, GL_FLOAT, 12*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glNormalPointer(GL_FLOAT, 12*4, 16);
glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo);
glColorPointer(4, GL_FLOAT, 12*4, 32);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 1024*3*20);
Main.glPopAttrib();
}
else {
Main.glPushAttrib(GL_COLOR_BUFFER_BIT);
org.lwjgl.opengl.GL11.glLineWidth(1.0f);
glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo);
glVertexPointer(4, GL_FLOAT, 8*4, 0);
glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo);
glColorPointer(4, GL_FLOAT, 8*4, 16);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDisable(GL_BLEND);
glDrawArrays(GL_LINES, 0, 1024*2);
Main.glPopAttrib();
}
Main.glPopAttrib();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
|
package beast.evolution.alignment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import beast.core.Description;
import beast.core.Input;
import beast.core.Input.Validate;
import beast.core.parameter.Map;
import beast.evolution.datatype.DataType;
import beast.util.AddOnManager;
import java.util.Collection;
import java.util.HashMap;
@Description("Class representing alignment data")
public class Alignment extends Map<String> {
protected Class<?> mapType() {return String.class;}
/**
* default data type *
*/
final static String NUCLEOTIDE = "nucleotide";
/**
* directory to pick up data types from *
*/
final static String[] IMPLEMENTATION_DIR = {"beast.evolution.datatype"};
/**
* Mapping from DataType descriptions to representative objects.
*/
static java.util.Map<String, DataType> dataTypeMap = new HashMap<String, DataType>();
static {
findDataTypes();
}
/**
* Collate available data types and store the result in a static field.
*
* Called by AddOnManager when the external jars are done loading.
*/
static public void findDataTypes() {
// build up list of data types
List<String> m_sDataTypes = AddOnManager.find(beast.evolution.datatype.DataType.class, IMPLEMENTATION_DIR);
for (String sDataType : m_sDataTypes) {
try {
DataType dataType = (DataType) Class.forName(sDataType).newInstance();
if (dataType.isStandard()) {
String sDescription = dataType.getDescription();
dataTypeMap.put(sDescription, dataType);
}
} catch (ClassNotFoundException e) {
// TODO: handle exception
} catch (IllegalAccessException e) {
// TODO: handle exception
} catch (InstantiationException e) {
// TODO: handle exception
}
}
}
/**
* Obtain data type object corresponding to data type description.
*
* @param dataTypeDesc description string (e.g. "nucleotide")
* @return DataType instance or null if no corresponding instance found
*/
public static DataType getDataTypeFromDesc(String dataTypeDesc) {
if (dataTypeMap.containsKey(dataTypeDesc))
return dataTypeMap.get(dataTypeDesc);
else
return null;
}
public Input<List<Sequence>> sequenceInput =
new Input<List<Sequence>>("sequence", "sequence and meta data for particular taxon", new ArrayList<Sequence>(), Validate.OPTIONAL);
public Input<Integer> stateCountInput = new Input<Integer>("statecount", "maximum number of states in all sequences");
public Input<String> dataTypeDescInput = new Input<String>("dataType", "data type, one of " + dataTypeMap.keySet(), NUCLEOTIDE, dataTypeMap.keySet().toArray(new String[0]));
public Input<DataType.Base> userDataTypeInput= new Input<DataType.Base>("userDataType", "non-standard, user specified data type, if specified 'dataType' is ignored");
public Input<Boolean> stripInvariantSitesInput = new Input<Boolean>("strip", "sets weight to zero for sites that are invariant (e.g. all 1, all A or all unkown)", false);
public Input<String> siteWeightsInput = new Input<String>("weights","comma separated list of weights, one for each site in the sequences. If not specified, each site has weight 1");
/**
* list of taxa names defined through the sequences in the alignment *
*/
protected List<String> taxaNames = new ArrayList<String>();
/**
* list of state counts for each of the sequences, typically these are
* constant throughout the whole alignment.
*/
protected List<Integer> stateCounts = new ArrayList<Integer>();
/**
* maximum of m_nStateCounts *
*/
protected int maxStateCount;
/**
* state codes for the sequences *
*/
protected List<List<Integer>> counts = new ArrayList<List<Integer>>();
/**
* data type, useful for converting String sequence to Code sequence, and back *
*/
protected DataType m_dataType;
/**
* weight over the columns of a matrix *
*/
protected int [] patternWeight;
/**
* weights of sites -- assumed 1 for each site if not specified
*/
protected int [] siteWeights = null;
/**
* pattern state encodings *
*/
protected int [][] sitePatterns; // #patters x #taxa
/**
* maps site nr to pattern nr *
*/
protected int [] patternIndex;
public Alignment() {
}
/**
* Constructor for testing purposes.
*
* @param sequences
* @param stateCount
* @param dataType
* @throws Exception when validation fails
*/
public Alignment(List<Sequence> sequences, Integer stateCount, String dataType) throws Exception {
for (Sequence sequence : sequences) {
sequenceInput.setValue(sequence, this);
}
//m_nStateCount.setValue(stateCount, this);
dataTypeDescInput.setValue(dataType, this);
initAndValidate();
}
@Override
public void initAndValidate() throws Exception {
if (sequenceInput.get().size() == 0 && defaultInput.get().size() == 0) {
throw new Exception("Either a sequence input must be specified, or a map of strings must be specified");
}
if (siteWeightsInput.get() != null) {
String sStr = siteWeightsInput.get().trim();
String [] strs = sStr.split(",");
siteWeights = new int[strs.length];
for (int i = 0; i< strs.length; i++) {
siteWeights[i] = Integer.parseInt(strs[i].trim());
}
}
// determine data type, either user defined or one of the standard ones
if (userDataTypeInput.get() != null) {
m_dataType = userDataTypeInput.get();
} else {
if (!dataTypeMap.containsKey(dataTypeDescInput.get())) {
throw new Exception("data type + '" + dataTypeDescInput.get() + "' cannot be found. " +
"Choose one of " + Arrays.toString(dataTypeMap.keySet().toArray(new String[0])));
}
m_dataType = dataTypeMap.get(dataTypeDescInput.get());
}
// grab data from child sequences
taxaNames.clear();
stateCounts.clear();
counts.clear();
if (sequenceInput.get().size() > 0) {
for (Sequence seq : sequenceInput.get()) {
//m_counts.add(seq.getSequence(getMap()));
counts.add(seq.getSequence(m_dataType));
if (taxaNames.indexOf(seq.taxonInput.get()) >= 0) {
throw new Exception("Duplicate taxon found in alignment: " + seq.taxonInput.get());
}
taxaNames.add(seq.taxonInput.get());
stateCounts.add(seq.totalCountInput.get());
}
if (counts.size() == 0) {
// no sequence data
throw new Exception("Sequence data expected, but none found");
}
} else {
for (String key : map.keySet()) {
String sequence = map.get(key);
List<Integer> list = m_dataType.string2state(sequence);
counts.add(list);
if (taxaNames.indexOf(key) >= 0) {
throw new Exception("Duplicate taxon found in alignment: " + key);
}
taxaNames.add(key);
stateCounts.add(m_dataType.getStateCount());
}
}
// Sanity check: make sure sequences are of same length
int nLength = counts.get(0).size();
for (List<Integer> seq : counts) {
if (seq.size() != nLength) {
throw new Exception("Two sequences with different length found: " + nLength + " != " + seq.size());
}
}
if (siteWeights != null && siteWeights.length != nLength) {
throw new RuntimeException("Number of weights (" + siteWeights.length + ") does not match sequence length (" + nLength +")");
}
calcPatterns();
} // initAndValidate
/*
* assorted getters and setters *
*/
public List<String> getTaxaNames() {
if (taxaNames.size() == 0) {
try {
initAndValidate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return taxaNames;
}
public List<Integer> getStateCounts() {
return stateCounts;
}
public List<List<Integer>> getCounts() {
return counts;
}
public DataType getDataType() {
return m_dataType;
}
public int getNrTaxa() {
return taxaNames.size();
}
public int getTaxonIndex(String sID) {
return taxaNames.indexOf(sID);
}
/**
* @return Number of unique character patterns in alignment.
*/
public int getPatternCount() {
return sitePatterns.length;
}
public int[] getPattern(int iPattern) {
return sitePatterns[iPattern];
}
public int getPattern(int iTaxon, int iPattern) {
return sitePatterns[iPattern][iTaxon];
}
/**
* Retrieve the "weight" of a particular pattern: the number of sites
* having that pattern.
*
* @param iPattern Index into pattern array.
* @return pattern weight
*/
public int getPatternWeight(int iPattern) {
return patternWeight[iPattern];
}
public int getMaxStateCount() {
return maxStateCount;
}
/**
* Retrieve index of pattern corresponding to a particular site.
*
* @param iSite Index of site.
* @return Index of pattern.
*/
public int getPatternIndex(int iSite) {
return patternIndex[iSite];
}
/**
* @return Total number of sites in alignment.
*/
public int getSiteCount() {
return patternIndex.length;
}
/**
* Retrieve an array containing the number of times each character pattern
* occurs in the alignment.
*
* @return Pattern weight array.
*/
public int[] getWeights() {
return patternWeight;
}
/**
* SiteComparator is used for ordering the sites,
* which makes it easy to identify patterns.
*/
class SiteComparator implements Comparator<int[]> {
public int compare(int[] o1, int[] o2) {
for (int i = 0; i < o1.length; i++) {
if (o1[i] > o2[i]) {
return 1;
}
if (o1[i] < o2[i]) {
return -1;
}
}
return 0;
}
} // class SiteComparator
/**
* calculate patterns from sequence data
* *
*/
protected void calcPatterns() {
int nTaxa = counts.size();
int nSites = counts.get(0).size();
// convert data to transposed int array
int[][] nData = new int[nSites][nTaxa];
for (int i = 0; i < nTaxa; i++) {
List<Integer> sites = counts.get(i);
for (int j = 0; j < nSites; j++) {
nData[j][i] = sites.get(j);
}
}
// sort data
SiteComparator comparator = new SiteComparator();
Arrays.sort(nData, comparator);
// count patterns in sorted data
// if (siteWeights != null) the weights are recalculated below
int nPatterns = 1;
int[] weights = new int[nSites];
weights[0] = 1;
for (int i = 1; i < nSites; i++) {
if (comparator.compare(nData[i - 1], nData[i]) != 0) {
nPatterns++;
nData[nPatterns - 1] = nData[i];
}
weights[nPatterns - 1]++;
}
// reserve memory for patterns
patternWeight = new int[nPatterns];
sitePatterns = new int[nPatterns][nTaxa];
for (int i = 0; i < nPatterns; i++) {
patternWeight[i] = weights[i];
sitePatterns[i] = nData[i];
}
// find patterns for the sites
patternIndex = new int[nSites];
for (int i = 0; i < nSites; i++) {
int[] sites = new int[nTaxa];
for (int j = 0; j < nTaxa; j++) {
sites[j] = counts.get(j).get(i);
}
patternIndex[i] = Arrays.binarySearch(sitePatterns, sites, comparator);
}
if (siteWeights != null) {
Arrays.fill(patternWeight, 0);
for (int i = 0; i < nSites; i++) {
patternWeight[patternIndex[i]] += siteWeights[i];
}
}
// determine maximum state count
// Usually, the state count is equal for all sites,
// though for SnAP analysis, this is typically not the case.
maxStateCount = 0;
for (int m_nStateCount1 : stateCounts) {
maxStateCount = Math.max(maxStateCount, m_nStateCount1);
}
// report some statistics
if (taxaNames.size() < 30) {
for (int i = 0; i < taxaNames.size(); i++) {
System.err.println(taxaNames.get(i) + ": " + counts.get(i).size() + " " + stateCounts.get(i));
}
}
if (stripInvariantSitesInput.get()) {
// don't add patterns that are invariant, e.g. all gaps
System.err.print("Stripping invariant sites");
int removedSites = 0;
for (int i = 0; i < nPatterns; i++) {
int[] nPattern = sitePatterns[i];
int iValue = nPattern[0];
boolean bIsInvariant = true;
for (int k = 1; k < nPattern.length; k++) {
if (nPattern[k] != iValue) {
bIsInvariant = false;
break;
}
}
if (bIsInvariant) {
removedSites += patternWeight[i];
patternWeight[i] = 0;
System.err.print(" <" + iValue + "> ");
}
}
System.err.println(" removed " + removedSites + " sites ");
}
int totalWeight = 0;
for (int weight : patternWeight) {
totalWeight += weight;
}
System.out.println(getNrTaxa() + " taxa");
System.out.println(getSiteCount() + " sites" + (totalWeight == getSiteCount() ? "" : " with weight " + totalWeight));
System.out.println(getPatternCount() + " patterns");
} // calcPatterns
/**
* returns an array containing the non-ambiguous states that this state represents.
*/
public boolean[] getStateSet(int iState) {
return m_dataType.getStateSet(iState);
// if (!isAmbiguousState(iState)) {
// boolean[] stateSet = new boolean[m_nMaxStateCount];
// stateSet[iState] = true;
// return stateSet;
// } else {
}
boolean isAmbiguousState(int state) {
return (state >= 0 && state < maxStateCount);
}
} // class Data
|
package com.google.sitebricks.mail;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.sitebricks.mail.imap.*;
import com.google.sitebricks.mail.oauth.OAuthConfig;
import com.google.sitebricks.mail.oauth.Protocol;
import com.google.sitebricks.mail.oauth.XoauthSasl;
import net.oauth.OAuthException;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.EnumSet;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
class NettyImapClient implements MailClient, Idler {
private static final Logger log = LoggerFactory.getLogger(NettyImapClient.class);
private final ExecutorService workerPool;
private final ExecutorService bossPool;
private final MailClientConfig config;
// Connection variables.
private volatile ClientBootstrap bootstrap;
private volatile MailClientHandler mailClientHandler;
// State variables:
private final AtomicLong sequence = new AtomicLong();
private volatile Channel channel;
private volatile Folder currentFolder = null;
private volatile boolean loggedIn = false;
private volatile DisconnectListener disconnectListener;
public NettyImapClient(MailClientConfig config,
ExecutorService bossPool,
ExecutorService workerPool) {
this.workerPool = workerPool;
this.bossPool = bossPool;
this.config = config;
}
static {
System.setProperty("mail.mime.decodetext.strict", "false");
}
public boolean isConnected() {
return channel != null && channel.isConnected() && channel.isOpen();
}
private void reset() {
Preconditions.checkState(!isConnected(),
"Cannot reset while mail client is still connected (call disconnect() first).");
// Just to be on the safe side.
if (mailClientHandler != null)
mailClientHandler.halt();
this.mailClientHandler = new MailClientHandler(this);
MailClientPipelineFactory pipelineFactory =
new MailClientPipelineFactory(mailClientHandler, config);
this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(bossPool, workerPool));
this.bootstrap.setPipelineFactory(pipelineFactory);
// Reset state (helps if this is a reconnect).
this.currentFolder = null;
this.sequence.set(0L);
mailClientHandler.idling.set(false);
}
@Override
public boolean connect() {
return connect(null);
}
/**
* Connects to the IMAP server logs in with the given credentials.
*/
@Override
public synchronized boolean connect(final DisconnectListener listener) {
reset();
ChannelFuture future = bootstrap.connect(new InetSocketAddress(config.getHost(),
config.getPort()));
Channel channel = future.awaitUninterruptibly().getChannel();
if (!future.isSuccess()) {
throw new RuntimeException("Could not connect channel", future.getCause());
}
this.channel = channel;
this.disconnectListener = listener;
if (null != listener) {
// https://issues.jboss.org/browse/NETTY-47?page=com.atlassian.jirafisheyeplugin%3Afisheye-issuepanel#issue-tabs
channel.getCloseFuture().addListener(new ChannelFutureListener() {
@Override public void operationComplete(ChannelFuture future) throws Exception {
mailClientHandler.idleAcknowledged.set(false);
listener.disconnected();
}
});
}
return login();
}
private boolean login() {
channel.write(". CAPABILITY\r\n");
if (config.getPassword() != null)
channel.write(". login " + config.getUsername() + " " + config.getPassword() + "\r\n");
else {
// Use xoauth login instead.
OAuthConfig oauth = config.getOAuthConfig();
Preconditions.checkArgument(oauth != null,
"Must specify a valid oauth config if not using password auth");
//noinspection ConstantConditions
try {
String oauthString = new XoauthSasl(config.getUsername(),
oauth.clientId,
oauth.clientSecret)
.build(Protocol.IMAP, oauth.accessToken, oauth.tokenSecret);
channel.write(". AUTHENTICATE XOAUTH " + oauthString + "\r\n");
} catch (IOException e) {
throw new RuntimeException("Login failure", e);
} catch (OAuthException e) {
throw new RuntimeException("Login failure", e);
} catch (URISyntaxException e) {
throw new RuntimeException("Login failure", e);
}
}
return loggedIn = mailClientHandler.awaitLogin();
}
@Override public String lastError() {
return mailClientHandler.lastError().error;
}
/**
* Logs out of the current IMAP session and releases all resources, including
* executor services.
*/
@Override
public synchronized void disconnect() {
try {
// If there is an error with the handler, dont bother logging out.
if (!mailClientHandler.isHalted()) {
if(mailClientHandler.idling.get()) {
log.warn("Disconnect called while IDLE, leaving idle and logging out.");
done();
}
// Log out of the IMAP Server.
channel.write(". logout\n");
}
currentFolder = null;
} finally {
// Shut down all channels and exit (leave threadpools as is--for reconnects).
// The Netty channel close listener will fire a disconnect event to our client,
// automatically. See connect() for details.
channel.close().awaitUninterruptibly(config.getTimeout(), TimeUnit.MILLISECONDS);
mailClientHandler.idleAcknowledged.set(false);
if (disconnectListener != null)
disconnectListener.disconnected();
}
}
<D> ChannelFuture send(Command command, String args, SettableFuture<D> valueFuture) {
Long seq = sequence.incrementAndGet();
String commandString = seq + " " + command.toString()
+ (null == args ? "" : " " + args)
+ "\r\n";
// Log the command but clip the \r\n
log.debug("Sending {} to server...", commandString.substring(0, commandString.length() - 2));
// Enqueue command.
mailClientHandler.enqueue(new CommandCompletion(command, seq, valueFuture, commandString));
return channel.write(commandString);
}
@Override
public List<String> capabilities() {
return mailClientHandler.getCapabilities();
}
@Override
// @Stateless
public ListenableFuture<List<String>> listFolders() {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
Preconditions.checkState(!mailClientHandler.idling.get(),
"Can't execute command while idling (are you watching a folder?)");
SettableFuture<List<String>> valueFuture = SettableFuture.create();
// TODO Should we use LIST "[Gmail]" % here instead? That will only fetch top-level folders.
send(Command.LIST_FOLDERS, "\"\" \"*\"", valueFuture);
return valueFuture;
}
@Override
// @Stateless
public ListenableFuture<FolderStatus> statusOf(String folder) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
SettableFuture<FolderStatus> valueFuture = SettableFuture.create();
String args = '"' + folder + "\" (UIDNEXT RECENT MESSAGES UNSEEN)";
send(Command.FOLDER_STATUS, args, valueFuture);
return valueFuture;
}
@Override
public ListenableFuture<Folder> open(String folder) {
return open(folder, false);
}
@Override
// @Stateless
public ListenableFuture<Folder> open(String folder, boolean readWrite) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
Preconditions.checkState(!mailClientHandler.idling.get(),
"Can't execute command while idling (are you watching a folder?)");
final SettableFuture<Folder> valueFuture = SettableFuture.create();
final SettableFuture<Folder> externalFuture = SettableFuture.create();
valueFuture.addListener(new Runnable() {
@Override
public void run() {
try {
// We do this to enforce a happens-before ordering between the time a folder is
// saved to currentFolder and a listener registered by the user may fire in a parallel
// executor service.
currentFolder = valueFuture.get();
externalFuture.set(currentFolder);
} catch (InterruptedException e) {
log.error("Interrupted while attempting to open a folder", e);
} catch (ExecutionException e) {
log.error("Execution exception while attempting to open a folder", e);
}
}
}, workerPool);
String args = '"' + folder + "\"";
send(readWrite ? Command.FOLDER_OPEN : Command.FOLDER_EXAMINE, args, valueFuture);
return externalFuture;
}
@Override
public ListenableFuture<List<MessageStatus>> list(Folder folder, int start, int end) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
Preconditions.checkState(!mailClientHandler.idling.get(),
"Can't execute command while idling (are you watching a folder?)");
checkCurrentFolder(folder);
checkRange(start, end);
Preconditions.checkArgument(start > 0, "Start must be greater than zero (IMAP uses 1-based " +
"indexing)");
SettableFuture<List<MessageStatus>> valueFuture = SettableFuture.create();
// -ve end range means get everything (*).
String extensions = config.useGmailExtensions() ? " X-GM-MSGID X-GM-THRID X-GM-LABELS UID" : "";
String args = start + ":" + toUpperBound(end) + " (RFC822.SIZE INTERNALDATE FLAGS ENVELOPE"
+ extensions + ")";
send(Command.FETCH_HEADERS, args, valueFuture);
return valueFuture;
}
private static void checkRange(int start, int end) {
Preconditions.checkArgument(start <= end || end == -1, "Start must be <= end");
}
private static String toUpperBound(int end) {
return (end > 0)
? Integer.toString(end)
: "*";
}
@Override
public ListenableFuture<List<EnumSet<Flag>>> addFlags(EnumSet<Flag> flags, int imapUid) {
return addOrRemoveFlags(flags, imapUid, true);
}
@Override
public ListenableFuture<List<EnumSet<Flag>>> removeFlags(EnumSet<Flag> flags, int imapUid) {
return addOrRemoveFlags(flags, imapUid, false);
}
private ListenableFuture<List<EnumSet<Flag>>> addOrRemoveFlags(EnumSet<Flag> flags, int imapUid, boolean add) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
SettableFuture<List<EnumSet<Flag>>> valueFuture = SettableFuture.create();
String args = imapUid + " " + (add ? "+" : "-") + Flag.toImap(flags);
send(Command.STORE_FLAGS, args, valueFuture);
return valueFuture;
}
@Override
public ListenableFuture<List<Message>> fetch(Folder folder, int start, int end) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
Preconditions.checkState(!mailClientHandler.idling.get(),
"Can't execute command while idling (are you watching a folder?)");
checkCurrentFolder(folder);
checkRange(start, end);
Preconditions.checkArgument(start > 0, "Start must be greater than zero (IMAP uses 1-based " +
"indexing)");
SettableFuture<List<Message>> valueFuture = SettableFuture.create();
String args = start + ":" + toUpperBound(end) + " (uid body[])";
send(Command.FETCH_BODY, args, valueFuture);
return valueFuture;
}
@Override
public synchronized void watch(Folder folder, FolderObserver observer) {
Preconditions.checkState(loggedIn, "Can't execute command because client is not logged in");
checkCurrentFolder(folder);
Preconditions.checkState(mailClientHandler.idling.compareAndSet(false, true), "Already idling...");
// This MUST happen in the following order, otherwise send() may trigger a new mail event
// before we've registered the folder observer.
mailClientHandler.observe(observer);
channel.write(sequence.incrementAndGet() + " idle\r\n");
}
@Override
public synchronized void unwatch() {
if (!mailClientHandler.idling.get())
return;
done();
}
@Override
public boolean isIdling() {
return mailClientHandler.idleAcknowledged.get();
}
@Override
public synchronized void updateOAuthAccessToken(String accessToken, String tokenSecret) {
config.getOAuthConfig().accessToken = accessToken;
config.getOAuthConfig().tokenSecret = accessToken;
}
public synchronized void done() {
log.trace("Dropping out of IDLE...");
channel.write("done\r\n");
}
@Override public void idleStart() {
disconnectListener.idled();
}
@Override public void idleEnd() {
disconnectListener.unidled();
}
private void checkCurrentFolder(Folder folder) {
Preconditions.checkState(folder.equals(currentFolder), "You must have opened folder %s" +
" before attempting to read from it (%s is currently open).", folder.getName(),
(currentFolder == null ? "No folder" : currentFolder.getName()));
}
}
|
package org.ligerbots.steamworks.commands;
import org.ligerbots.steamworks.Robot;
import org.ligerbots.steamworks.RobotMap;
import org.ligerbots.steamworks.subsystems.DriveTrain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This command turns the robot by a certain number of degrees. Clockwise is positive (NavX
* convention)
*/
public class TurnCommand extends AccessibleCommand {
private static final Logger logger = LoggerFactory.getLogger(TurnCommand.class);
double offsetDegrees;
double maxTime; // seconds
long startTime;
double startingRotation;
double targetRotation;
boolean isClockwise;
double error2;
double error1;
// did we end up where we want or was it aborted?
boolean succeeded;
boolean ended;
boolean isHighGear;
double autoTurnRampZone;
double autoTurnMaxSpeed;
double autoTurnMinSpeed;
/**
* Create a new TurnCommand.
*
* @param offsetDegrees The number of degrees to turn by. Clockwise is positive
*/
public TurnCommand(double offsetDegrees) {
super("TurnCommand_" + offsetDegrees);
requires(Robot.driveTrain);
offsetDegrees = DriveTrain.fixDegrees(offsetDegrees);
if (offsetDegrees > 180) {
offsetDegrees = offsetDegrees - 360;
}
this.offsetDegrees = offsetDegrees;
maxTime = 2.5 * (Math.abs(offsetDegrees) / 180);
// give at least 5 seconds for turning
if (maxTime < 5) {
maxTime = 5;
}
isClockwise = offsetDegrees > 0;
}
// Called just before this Command runs the first time
protected void initialize() {
startTime = System.nanoTime();
startingRotation = DriveTrain.fixDegrees(Robot.driveTrain.getYaw());
targetRotation = DriveTrain.fixDegrees(startingRotation + offsetDegrees);
logger.debug(String.format("Start %f, target %f", startingRotation, targetRotation));
succeeded = false;
ended = false;
Robot.driveTrain.shift(DriveTrain.ShiftType.DOWN);
isHighGear = false;
if (isHighGear) {
autoTurnRampZone = RobotMap.AUTO_TURN_RAMP_ZONE_HIGH;
autoTurnMaxSpeed = RobotMap.AUTO_TURN_MAX_SPEED_HIGH;
autoTurnMinSpeed = RobotMap.AUTO_TURN_MIN_SPEED_HIGH;
} else {
autoTurnRampZone = RobotMap.AUTO_TURN_RAMP_ZONE_LOW;
autoTurnMaxSpeed = RobotMap.AUTO_TURN_MAX_SPEED_LOW;
autoTurnMinSpeed = RobotMap.AUTO_TURN_MIN_SPEED_LOW;
}
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
double localTargetRotation = targetRotation;
double currentRotation = DriveTrain.fixDegrees(Robot.driveTrain.getYaw());
if (localTargetRotation < currentRotation) {
localTargetRotation += 360;
}
isClockwise = localTargetRotation - currentRotation <= 180;
// We could be turning clockwise or counterclockwise, so an "error" of 350deg for example, is
// actually an error of 10deg
error1 = Math.abs(targetRotation - currentRotation);
error2 = Math.abs(360 - error1);
double actualError = Math.min(error1, error2);
if (actualError <= autoTurnRampZone) {
double driveSpeed = autoTurnMaxSpeed * actualError / autoTurnRampZone;
if (driveSpeed < autoTurnMinSpeed) {
driveSpeed = autoTurnMinSpeed;
}
Robot.driveTrain.rawThrottleTurnDrive(0, isClockwise ? -driveSpeed : driveSpeed);
} else {
Robot.driveTrain.rawThrottleTurnDrive(0,
isClockwise ? -autoTurnMaxSpeed : autoTurnMaxSpeed);
}
}
protected boolean isFinished() {
boolean outOfTime = System.nanoTime() - startTime > (maxTime * RobotMap.NANOS_PER_SECOND);
logger.debug(
String.format("Error %f %f, absolute yaw %f", error1, error2, Robot.driveTrain.getYaw()));
boolean onTarget = error1 < RobotMap.AUTO_TURN_ACCEPTABLE_ERROR
|| error2 < RobotMap.AUTO_TURN_ACCEPTABLE_ERROR;
if (onTarget) {
succeeded = true;
}
ended = outOfTime || onTarget || Robot.operatorInterface.isCancelled();
return ended;
}
protected void end() {
logger.info("Finish");
Robot.driveTrain.rawThrottleTurnDrive(0, 0);
ended = true;
}
protected void interrupted() {
logger.warn("Interrupted");
Robot.driveTrain.rawThrottleTurnDrive(0, 0);
ended = true;
}
protected boolean isFailedToComplete() {
return ended && !succeeded;
}
}
|
package org.mbds.wolf.java.view;
import org.mbds.wolf.java.SeqlReaderTester;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TerminalAddUserJFrame extends JFrame implements ActionListener {
public static String title = "meCoin Terminal";
// form
private JPanel mainPanel = new JPanel();
private JTextField idAccountX = new JTextField();
private JLabel idAccountY = new JLabel("Id Account : ");
private JTextField loginX = new JTextField();
private JLabel loginY = new JLabel("Login : ");
private JTextField passwordX = new JTextField();
private JLabel passwordY = new JLabel("Password : ");
private JTextField balanceX = new JTextField();
private JLabel balanceY = new JLabel("balance : ");
private JButton btnInsert = new JButton("Insert");
private JButton btnBack = new JButton("Back");
private JButton btnExit = new JButton("Exit");
// query value
private String valueId = "";
private String valueLogin = "";
private String valuePassword = "";
private String valueBalance = "";
private String seql = "";
private SeqlReaderTester seqlReaderTester;
public TerminalAddUserJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setSize(500, 500);
setResizable(false);
setLocationRelativeTo(null);
add(mainPanel);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{30, 30, 30, 30, 30, 30, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{30, 0, 50, 30, 0, 30, 30, 30, 30, 30, 30};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, Double.MIN_VALUE, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
mainPanel.setLayout(gridBagLayout);
// id_user
GridBagConstraints gridBagConstraintsIdY = new GridBagConstraints();
gridBagConstraintsIdY.gridwidth = 200;
gridBagConstraintsIdY.insets = new Insets(0, 0, -60, 350);
gridBagConstraintsIdY.gridx = 16;
gridBagConstraintsIdY.gridy = 3;
mainPanel.add(idAccountY, gridBagConstraintsIdY);
GridBagConstraints gridBagConstraintsIdX = new GridBagConstraints();
gridBagConstraintsIdX.gridwidth = 50;
gridBagConstraintsIdX.gridheight = 1;
gridBagConstraintsIdX.insets = new Insets(0, 0, -60, 50);
gridBagConstraintsIdX.fill = GridBagConstraints.BOTH;
gridBagConstraintsIdX.gridx = 16;
gridBagConstraintsIdX.gridy = 3;
mainPanel.add(idAccountX, gridBagConstraintsIdX);
// Login
GridBagConstraints gridBagConstraintsLoginY = new GridBagConstraints();
gridBagConstraintsLoginY.gridwidth = 200;
gridBagConstraintsLoginY.insets = new Insets(0, 0, -160, 350);
gridBagConstraintsLoginY.gridx = 16;
gridBagConstraintsLoginY.gridy = 3;
mainPanel.add(loginY, gridBagConstraintsLoginY);
GridBagConstraints gridBagConstraintsLoginX = new GridBagConstraints();
gridBagConstraintsLoginX.gridwidth = 50;
gridBagConstraintsLoginX.gridheight = 1;
gridBagConstraintsLoginX.insets = new Insets(0, 0, -160, 50);
gridBagConstraintsLoginX.fill = GridBagConstraints.BOTH;
gridBagConstraintsLoginX.gridx = 16;
gridBagConstraintsLoginX.gridy = 3;
mainPanel.add(loginX, gridBagConstraintsLoginX);
// Password
GridBagConstraints gridBagConstraintsPasswordY = new GridBagConstraints();
gridBagConstraintsPasswordY.gridwidth = 200;
gridBagConstraintsPasswordY.insets = new Insets(0, 0, -260, 350);
gridBagConstraintsPasswordY.gridx = 16;
gridBagConstraintsPasswordY.gridy = 3;
mainPanel.add(passwordY, gridBagConstraintsPasswordY);
GridBagConstraints gridBagConstraintsPasswordX = new GridBagConstraints();
gridBagConstraintsPasswordX.gridwidth = 50;
gridBagConstraintsPasswordX.gridheight = 1;
gridBagConstraintsPasswordX.insets = new Insets(0, 0, -260, 50);
gridBagConstraintsPasswordX.fill = GridBagConstraints.BOTH;
gridBagConstraintsPasswordX.gridx = 16;
gridBagConstraintsPasswordX.gridy = 3;
mainPanel.add(passwordX, gridBagConstraintsPasswordX);
//balance
GridBagConstraints gridBagConstraintsBalanceY = new GridBagConstraints();
gridBagConstraintsBalanceY.gridwidth = 200;
gridBagConstraintsBalanceY.insets = new Insets(0, 0, -360, 350);
gridBagConstraintsBalanceY.gridx = 16;
gridBagConstraintsBalanceY.gridy = 3;
mainPanel.add(balanceY, gridBagConstraintsBalanceY);
GridBagConstraints gridBagConstraintsBalanceX = new GridBagConstraints();
gridBagConstraintsBalanceX.gridwidth = 50;
gridBagConstraintsBalanceX.gridheight = 1;
gridBagConstraintsBalanceX.insets = new Insets(0, 0, -360, 50);
gridBagConstraintsBalanceX.fill = GridBagConstraints.BOTH;
gridBagConstraintsBalanceX.gridx = 16;
gridBagConstraintsBalanceX.gridy = 3;
mainPanel.add(balanceX, gridBagConstraintsBalanceX);
// button insert
GridBagConstraints gridBagConstraintsButtonInsert = new GridBagConstraints();
gridBagConstraintsButtonInsert.gridwidth = 200;
gridBagConstraintsButtonInsert.insets = new Insets(0, 0, -460, 350);
gridBagConstraintsButtonInsert.gridx = 16;
gridBagConstraintsButtonInsert.gridy = 3;
mainPanel.add(btnInsert, gridBagConstraintsButtonInsert);
//back
GridBagConstraints gridBagConstraintsButtonBack = new GridBagConstraints();
gridBagConstraintsButtonBack.gridwidth = 200;
gridBagConstraintsButtonBack.insets = new Insets(0, 0, -460, 200);
gridBagConstraintsButtonBack.gridx = 16;
gridBagConstraintsButtonBack.gridy = 3;
mainPanel.add(btnBack, gridBagConstraintsButtonBack);
//back
GridBagConstraints gridBagConstraintsButtonExit = new GridBagConstraints();
gridBagConstraintsButtonExit.gridwidth = 200;
gridBagConstraintsButtonExit.insets = new Insets(0, 0, -460, 50);
gridBagConstraintsButtonExit.gridx = 16;
gridBagConstraintsButtonExit.gridy = 3;
mainPanel.add(btnExit, gridBagConstraintsButtonExit);
btnInsert.addActionListener(this);
this.setContentPane(mainPanel);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnInsert) {
valueId = idAccountX.getText();
valueLogin = loginX.getText();
valuePassword = passwordX.getText();
valueBalance = balanceX.getText();
seql = "insert into wolf_hce (idCompte, login, password, balance) values(" + valueId + valueLogin + valuePassword + valueBalance + ")";
}
if (seql != null && !seql.isEmpty()) {
Thread thread = new Thread() {
public void run() {
JOptionPane.showMessageDialog(null, SeqlReaderTester.MSG_PLACE_NFC_DEVICE);
JOptionPane.showMessageDialog(null, seql);
if (SeqlReaderTester.execute(seql, 0)) {
idAccountX.setText("");
idAccountX.invalidate();
loginX.setText("");
loginX.invalidate();
passwordX.setText("");
passwordX.invalidate();
balanceX.setText("");
balanceX.invalidate();
}
}
};
thread.start();
}
/*else {
JOptionPane.showMessageDialog(null, SeqlReaderTester.MSG_ERR_BAD_REQUEST);
}*/
else if (event.getSource() == btnBack) {
this.dispose();
// seqlReaderTester = new SeqlTesterJFrame();
} else if (event.getSource() == btnExit) {
System.exit(0);
}
}
}
|
package gov.nih.nci.camod.util;
import java.util.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* DuplicateUtil - Bean Deep-Copy Utility
* <p>
* This class provides a utility method for performing a deep-copy (duplicate) of
* domain bean objects. Domain classes that implement the Duplicatable interface
* will be deep-copied along with any sub-classes.
* <p>
* @author Marc Piparo
* @version 1.1
* @see Duplicatable
*/
public class DuplicateUtil {
private static Log log = LogFactory.getLog(DuplicateUtil.class);
/**
* Performs deep-copy "Duplicate" of the input parameter source bean object.
* Source Bean MUST implement Duplicatable interface.
* <p>
* Only public accessible Bean properties will be copied. (i.e properties
* with "public" set and get methods)
* <p>
* Associated property beans (including beans in a collection) will by default
* be copied by reference, unless they implement the Duplicatable interface
* as well, in which case they too will be deep-copied.
* <p>
* @param src source bean object to be duplicated
* @throws java.lang.Exception Exception
* @return Object duplicate bean
*/
public static Object duplicateBean(Duplicatable src) throws Exception {
return duplicateBeanImpl(src, null, null, null, null);
}
/**
* Performs deep-copy "Duplicate" of the input parameter source bean object.
* Source Bean MUST implement Duplicatable interface.
* <p>
* Similar functionality to duplicateBean(Duplicatable src) method, however
* accepts an additional collection parameter which defines properties
* that should NOT be copied.
* <p>
* excludedProperties parameter consists of a Collection of String objects
* that should not be copied. String objects should use dot-notation to
* identify properties.
* <p>
* example: to exclude zipcode from a model containing a person object
* with an address object property bean during a duplicate of the person object.
* <p>
* excludedProperties.add("address.zipcode");
*
* @param src source bean object to be duplicated
* @param excludedProperties collection of strings representing property names (in dot-notation) not be copied
* @throws java.lang.Exception Exception
* @return Object duplicate bean
*/
public static Object duplicateBean(Duplicatable src, Collection excludedProperties) throws Exception {
return duplicateBeanImpl(src, null, null, null, excludedProperties);
}
private static Object duplicateBeanImpl(Object src, List srcHistory, List dupHistory, String path, Collection excludedProperties) throws Exception {
Object duplicate = null;
if (src != null) {
try {
// reset history collections on root duplicate
if (srcHistory == null) {
srcHistory = new ArrayList();
}
if (dupHistory == null) {
dupHistory = new ArrayList();
}
// check if we've already duplicated this object
if (!srcHistory.contains(src)) {
// add this src object to the history
srcHistory.add(src);
// instantiate a new instance of this class
// check for virtual enahancer classes (i.e. hibernate lazy loaders)
Class duplicateClass = null;
if (src.getClass().getName().indexOf("$$Enhancer") > -1) {
duplicateClass = src.getClass().getSuperclass();
} else {
duplicateClass = src.getClass();
}
duplicate = (Object) duplicateClass.newInstance();
// add this new duplicate object to history
dupHistory.add(duplicate);
Map beanProps = PropertyUtils.describe(src);
Iterator props = beanProps.entrySet().iterator();
log.debug("***** DUPLICATE Deep-Copy of Class: "+duplicateClass.getName());
// loop thru bean properties
while (props.hasNext()) {
Map.Entry entry = (Map.Entry) props.next();
Object propValue = entry.getValue();
if (entry.getKey() != null) {
String propName = entry.getKey().toString();
// determine path name
String pathName = "";
if (path != null) {
pathName = path+".";
}
pathName += propName;
// do no copy property if it is in the excluded list
if (!(excludedProperties != null && excludedProperties.contains(pathName))) {
Class propertyType = PropertyUtils.getPropertyType(duplicate, propName);
log.debug("** processing copy of property: "+pathName);
// check if property is a collection
if (propValue instanceof java.util.Collection) {
Collection collectionProperty = (Collection) propValue;
if (!collectionProperty.isEmpty()) {
// get collection property -
// *note: bean class is responsible for instatiating collection on construction
Collection duplicateCollection = (Collection) PropertyUtils.getProperty(duplicate, propName);
if (duplicateCollection != null) {
// iterate thru collection, duplicate elements and add to collection
for (Iterator iter = collectionProperty.iterator(); iter.hasNext();) {
Object collectionEntry = iter.next();
duplicateCollection.add(duplicateProperty(collectionEntry, srcHistory, dupHistory, pathName, excludedProperties));
}
}
}
} else {
// set member property in duplicate object
try {
//log.debug("** copying property: "+pathName);
BeanUtils.copyProperty(duplicate, propName, duplicateProperty(propValue, srcHistory, dupHistory, pathName, excludedProperties));
} catch (Exception ex) {
// do nothing. skip and move on. property value may be null, or no set method found.
log.debug("** property '"+propName+"' not copied. Either no set method, or null.");
}
} // collection condition
}
} // key=null check
} // loop end
} else {
// this src object has already been duplicated, so return a reference
// to the duplicate created earlier rather than re-duplicate
duplicate = dupHistory.get(srcHistory.indexOf(src));
log.debug("** skipping - already duplicated: "+src.getClass().getName());
}
} catch (Exception ex) {
throw new Exception("Error during Bean Duplicate: "+ex);
}
} // src=null check
return duplicate;
}
private static Object duplicateProperty(Object obj, List srcHistory, List dupHistory, String path, Collection excludedProperties) throws Exception {
// if property implements Duplicatable, duplicate this object
// otherwise return a reference
if (obj instanceof Duplicatable) {
return duplicateBeanImpl(obj, srcHistory, dupHistory, path, excludedProperties);
} else {
return obj;
}
}
}
|
package org.nschmidt.ldparteditor.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow;
import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow;
import org.nschmidt.ldparteditor.text.StringHelper;
import org.nschmidt.ldparteditor.workbench.WorkbenchManager;
public class HistoryManager {
private static final Pattern pattern = Pattern.compile("\r?\n|\r"); //$NON-NLS-1$
private DatFile df;
private boolean hasNoThread = true;
private volatile AtomicBoolean isRunning = new AtomicBoolean(true);
private volatile AtomicInteger action = new AtomicInteger(0);
private final Lock lock = new ReentrantLock();
private volatile int mode = 0;
private volatile Queue<Object[]> workQueue = new ConcurrentLinkedQueue<Object[]>();
private volatile Queue<Object[]> answerQueue = new ConcurrentLinkedQueue<Object[]>();
public HistoryManager(DatFile df) {
this.df = df;
}
public void pushHistory(String text, int selectionStart, int selectionEnd, GData[] data, HashMap<String, ArrayList<Boolean>> selectedData, HashMap<String, ArrayList<Boolean>> hiddenData, Vertex[] selectedVertices, Vertex[] hiddenVertices, int topIndex) {
if (df.isReadOnly()) return;
if (hasNoThread) {
hasNoThread = false;
new Thread(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
final int MAX_ITEM_COUNT = 100; // default is 100
int pointer = 0;
int pointerMax = 0;
final ArrayList<Integer> historySelectionStart = new ArrayList<Integer>();
final ArrayList<Integer> historySelectionEnd = new ArrayList<Integer>();
final ArrayList<Integer> historyTopIndex = new ArrayList<Integer>();
final ArrayList<String> historyFullText = new ArrayList<String>();
final ArrayList<String[]> historyText = new ArrayList<String[]>();
final ArrayList<HashMap<String, ArrayList<Boolean>>> historySelectedData = new ArrayList<HashMap<String, ArrayList<Boolean>>>();
final ArrayList<HashMap<String, ArrayList<Boolean>>> historyHiddenData = new ArrayList<HashMap<String, ArrayList<Boolean>>>();
final ArrayList<Vertex[]> historySelectedVertices = new ArrayList<Vertex[]>();
final ArrayList<Vertex[]> historyHiddenVertices = new ArrayList<Vertex[]>();
while (isRunning.get() && Editor3DWindow.getAlive().get()) {
try {
Object[] newEntry = workQueue.poll();
if (newEntry != null) {
final String[] result;
final String resultFullText;
String text = (String) newEntry[0];
GData[] data = (GData[]) newEntry[3];
if (text != null) {
if (text.charAt(text.length() - 1) == '\r') {
text = text.substring(0, text.length() - 1);
}
if (text.length() > 0 && text.charAt(text.length() - 1) == '\n') {
text = text.substring(0, text.length() - 1);
}
if (text.length() > 0 && text.charAt(text.length() - 1) == '\r') {
text = text.substring(0, text.length() - 1);
}
if (text.length() > 0 && text.charAt(text.length() - 1) == '\n') {
text = text.substring(0, text.length() - 1);
}
String[] result2 = pattern.split(text);
if (result2.length == 0) {
result = new String[]{""}; //$NON-NLS-1$
} else {
result = result2;
}
resultFullText = text;
} else if (data != null) {
final int size = data.length;
if (size > 0) {
final String ld = StringHelper.getLineDelimiter();
final StringBuilder sb = new StringBuilder();
result = new String[size];
for (int i = 0; i < size; i++) {
if (i > 0) {
sb.append(ld);
}
result[i] = data[i].toString();
sb.append(result[i]);
}
resultFullText = sb.toString();
} else {
result = new String[]{""}; //$NON-NLS-1$
resultFullText = result[0];
}
} else {
// throw new AssertionError("There must be data to backup!"); //$NON-NLS-1$
continue;
}
NLogger.debug(getClass(), "Pointer : {0}", pointer); //$NON-NLS-1$
NLogger.debug(getClass(), "PointerMax: {0}", pointerMax); //$NON-NLS-1$
NLogger.debug(getClass(), "Item Count: {0}", historyText.size()); //$NON-NLS-1$
if (pointer != pointerMax) {
// Delete old entries
removeFromListAboveOrEqualIndex(historySelectionStart, pointer + 1);
removeFromListAboveOrEqualIndex(historySelectionEnd, pointer + 1);
removeFromListAboveOrEqualIndex(historySelectedData, pointer + 1);
removeFromListAboveOrEqualIndex(historyHiddenData, pointer + 1);
removeFromListAboveOrEqualIndex(historySelectedVertices, pointer + 1);
removeFromListAboveOrEqualIndex(historyHiddenVertices, pointer + 1);
removeFromListAboveOrEqualIndex(historyText, pointer + 1);
removeFromListAboveOrEqualIndex(historyFullText, pointer + 1);
removeFromListAboveOrEqualIndex(historyTopIndex, pointer + 1);
pointerMax = pointer + 1;
}
// Dont store more than MAX_ITEM_COUNT undo/redo entries
{
final int item_count = historyText.size();
if (item_count > MAX_ITEM_COUNT) {
int delta = item_count - MAX_ITEM_COUNT;
removeFromListLessIndex(historySelectionStart, delta + 1);
removeFromListLessIndex(historySelectionEnd, delta + 1);
removeFromListLessIndex(historySelectedData, delta + 1);
removeFromListLessIndex(historyHiddenData, delta + 1);
removeFromListLessIndex(historySelectedVertices, delta + 1);
removeFromListLessIndex(historyHiddenVertices, delta + 1);
removeFromListLessIndex(historyText, delta + 1);
removeFromListLessIndex(historyFullText, delta + 1);
removeFromListLessIndex(historyTopIndex, delta + 1);
pointerMax = pointerMax - delta;
if (pointer > MAX_ITEM_COUNT) {
pointer = pointer - delta;
}
}
}
historySelectionStart.add((Integer) newEntry[1]);
historySelectionEnd.add((Integer) newEntry[2]);
historySelectedData.add((HashMap<String, ArrayList<Boolean>>) newEntry[4]);
historySelectedVertices.add((Vertex[]) newEntry[5]);
historyTopIndex.add((Integer) newEntry[6]);
historyHiddenData.add((HashMap<String, ArrayList<Boolean>>) newEntry[7]);
historyHiddenVertices.add((Vertex[]) newEntry[8]);
historyText.add(result);
historyFullText.add(resultFullText);
// 1. Cleanup duplicated text entries
if (pointer > 0) {
int pStart = historySelectionStart.get(pointer - 1);
String[] previous = historyText.get(pointer - 1);
if (Arrays.equals(previous, result) && !Editor3DWindow.getWindow().isAddingSomething()) {
if (pStart != -1) {
if ((Integer) newEntry[2] == 0) {
// Skip saving this entry since only the cursor was moved
removeFromListAboveOrEqualIndex(historySelectionStart, pointer);
removeFromListAboveOrEqualIndex(historySelectionEnd, pointer);
removeFromListAboveOrEqualIndex(historySelectedData, pointer);
removeFromListAboveOrEqualIndex(historyHiddenData, pointer);
removeFromListAboveOrEqualIndex(historySelectedVertices, pointer);
removeFromListAboveOrEqualIndex(historyHiddenVertices, pointer);
removeFromListAboveOrEqualIndex(historyText, pointer);
removeFromListAboveOrEqualIndex(historyFullText, pointer);
removeFromListAboveOrEqualIndex(historyTopIndex, pointer);
} else {
// Remove the previous entry, because it only contains a new text selection
historySelectionStart.remove(pointer - 1);
historySelectionEnd.remove(pointer - 1);
historySelectedData.remove(pointer - 1);
historyHiddenData.remove(pointer - 1);
historySelectedVertices.remove(pointer - 1);
historyHiddenVertices.remove(pointer - 1);
historyText.remove(pointer - 1);
historyFullText.remove(pointer - 1);
historyTopIndex.remove(pointer - 1);
}
pointerMax
pointer
}
}
}
// FIXME 2. There is still more cleanup work to do
pointerMax++;
pointer++;
NLogger.debug(getClass(), "Added undo/redo data"); //$NON-NLS-1$
if (workQueue.isEmpty()) Thread.sleep(100);
} else {
final int action2 = action.get();
int delta = 0;
if (action2 > 0 && action2 < 3) {
boolean doRestore = false;
switch (action2) {
case 1:
// Undo
if (pointer > 0) {
if (pointerMax == pointer && pointer > 1) pointer
NLogger.debug(getClass(), "Requested undo."); //$NON-NLS-1$
pointer
delta = -1;
doRestore = true;
}
break;
case 2:
// Redo
if (pointer < pointerMax - 1 && pointer + 1 < historySelectionStart.size()) {
NLogger.debug(getClass(), "Requested redo."); //$NON-NLS-1$
pointer++;
delta = 1;
doRestore = true;
}
break;
}
if (doRestore) {
df.getVertexManager().setSkipSyncWithTextEditor(true);
final boolean openTextEditor = historySelectionStart.get(pointer) != -1;
boolean hasTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null && txtDat.equals(df)) {
hasTextEditor = true;
break;
}
}
if (hasTextEditor) break;
}
while (!hasTextEditor && pointer + delta > -1 && pointer + delta < historySelectionStart.size() && historySelectionStart.get(pointer) != -1 && pointer > 0 && pointer < pointerMax - 1) {
pointer += delta;
}
final int start = historySelectionStart.get(pointer);
final int end = historySelectionEnd.get(pointer);
final int topIndex = historyTopIndex.get(pointer);
final String fullText = historyFullText.get(pointer);
final String[] lines = historyText.get(pointer);
HashMap<String, ArrayList<Boolean>> selection = historySelectedData.get(pointer);
HashMap<String, ArrayList<Boolean>> hiddenSelection = historyHiddenData.get(pointer);
final Vertex[] verts = historySelectedVertices.get(pointer);
final Vertex[] verts2 = historyHiddenVertices.get(pointer);
while (!answerQueue.offer(new Object[]{
openTextEditor,
start,
end,
topIndex,
fullText,
lines,
selection,
hiddenSelection,
verts,
verts2,
false
})) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
} else {
while (!answerQueue.offer(new Object[]{
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
true
})) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
action.set(0);
} else {
if (workQueue.isEmpty()) Thread.sleep(100);
}
}
} catch (InterruptedException e) {
// We want to know what can go wrong here
// because it SHOULD be avoided!!
NLogger.error(getClass(), "The HistoryManager cycle was interruped [InterruptedException]! :("); //$NON-NLS-1$
NLogger.error(getClass(), e);
} catch (Exception e) {
NLogger.error(getClass(), "The HistoryManager cycle was throwing an exception :("); //$NON-NLS-1$
NLogger.error(getClass(), e);
}
}
action.set(0);
}
}).start();
}
while (!workQueue.offer(new Object[]{text, selectionStart, selectionEnd, data, selectedData, selectedVertices, topIndex, hiddenData, hiddenVertices})) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
public void deleteHistory() {
isRunning.set(false);
}
public void undo(final Shell sh) {
if (lock.tryLock()) {
try {
action(1, sh);
} finally {
lock.unlock();
}
} else {
NLogger.debug(getClass(), "Undo was skipped due to synchronisation."); //$NON-NLS-1$
}
}
public void redo(final Shell sh) {
if (lock.tryLock()) {
try {
action(2, sh);
} finally {
lock.unlock();
}
} else {
NLogger.debug(getClass(), "Redo was skipped due to synchronisation."); //$NON-NLS-1$
}
}
@SuppressWarnings("unchecked")
private void action(final int action_mode, final Shell sh) {
if (action.get() != 0 || df.isReadOnly() || !df.getVertexManager().isUpdated() && WorkbenchManager.getUserSettingState().getSyncWithTextEditor().get()) return;
mode = action_mode;
action.set(mode);
if (!isRunning.get()) {
hasNoThread = true;
isRunning.set(true);
pushHistory(null, -1, -1, null, null, null, null, null, -1);
NLogger.debug(getClass(), "Forked history thread..."); //$NON-NLS-1$
}
boolean openTextEditor = false;
int start = -1;
int end = -1;
int topIndex = -1;
String fullText = null;
String[] lines = null;
HashMap<String, ArrayList<Boolean>> selection = null;
HashMap<String, ArrayList<Boolean>> hiddenSelection = null;
Vertex[] verts = null;
Vertex[] verts2 = null;
while (true) {
Object[] newEntry = answerQueue.poll();
if (newEntry != null) {
if ((boolean) newEntry[10]) {
action.set(0);
return;
}
openTextEditor = (boolean) newEntry[0];
start = (int) newEntry[1];
end = (int) newEntry[2];
topIndex = (int) newEntry[3];
fullText = (String) newEntry[4];
lines = (String[]) newEntry[5];
selection = (HashMap<String, ArrayList<Boolean>>) newEntry[6];
hiddenSelection = (HashMap<String, ArrayList<Boolean>>) newEntry[7];
verts = (Vertex[]) newEntry[8];
verts2 = (Vertex[]) newEntry[9];
break;
}
if (answerQueue.isEmpty()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
df.parseForChanges(lines);
GDataCSG.resetCSG(df, false);
GDataCSG.forceRecompile(df);
Project.getUnsavedFiles().add(df);
df.setText(fullText);
boolean hasTextEditor = false;
try {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null && txtDat.equals(df)) {
int ti = ((CompositeTab) t).getTextComposite().getTopIndex();
Point r = ((CompositeTab) t).getTextComposite().getSelectionRange();
if (openTextEditor) {
r.x = start;
r.y = end;
ti = topIndex;
}
((CompositeTab) t).getState().setSync(true);
((CompositeTab) t).getTextComposite().setText(fullText);
((CompositeTab) t).getTextComposite().setTopIndex(ti);
((CompositeTab) t).getTextComposite().forceFocus();
try {
((CompositeTab) t).getTextComposite().setSelectionRange(r.x, r.y);
} catch (IllegalArgumentException consumed) {}
((CompositeTab) t).getTextComposite().redraw();
((CompositeTab) t).getControl().redraw();
((CompositeTab) t).getTextComposite().update();
((CompositeTab) t).getControl().update();
((CompositeTab) t).getState().setSync(false);
hasTextEditor = true;
break;
}
}
if (hasTextEditor) break;
}
} catch (Exception undoRedoException) {
// We want to know what can go wrong here
// because it SHOULD be avoided!!
switch (action_mode) {
case 1:
NLogger.error(getClass(), "Undo failed."); //$NON-NLS-1$
break;
case 2:
NLogger.error(getClass(), "Redo failed."); //$NON-NLS-1$
break;
default:
// Can't happen
break;
}
NLogger.error(getClass(), undoRedoException);
}
final VertexManager vm = df.getVertexManager();
vm.clearSelection2();
if (verts != null) {
for (Vertex vertex : verts) {
vm.getSelectedVertices().add(vertex);
}
}
if (verts2 != null) {
vm.getHiddenVertices().clear();
for (Vertex vertex : verts2) {
vm.getHiddenVertices().add(vertex);
}
}
if (hiddenSelection != null) {
vm.hiddenData.clear();
vm.restoreHideShowState(hiddenSelection);
}
if (selection != null) {
vm.restoreSelectedDataState(selection);
ThreadsafeHashMap<GData, Set<VertexInfo>> llv = vm.getLineLinkedToVertices();
for (GData1 g1 : vm.getSelectedSubfiles()) {
final Set<VertexInfo> vis = llv.get(g1);
if (vis != null) {
for (VertexInfo vi : vis) {
vm.getSelectedVertices().add(vi.vertex);
GData gd = vi.getLinkedData();
vm.getSelectedData().add(gd);
switch (gd.type()) {
case 2:
vm.getSelectedLines().add((GData2) gd);
break;
case 3:
vm.getSelectedTriangles().add((GData3) gd);
break;
case 4:
vm.getSelectedQuads().add((GData4) gd);
break;
case 5:
vm.getSelectedCondlines().add((GData5) gd);
break;
default:
break;
}
}
}
}
}
vm.updateUnsavedStatus();
// Redraw the content of the StyledText (to see the selection)
try {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
((CompositeTab) t).getTextComposite().redraw();
hasTextEditor = true;
break;
}
}
if (hasTextEditor) break;
}
} catch (Exception undoRedoException) {
// We want to know what can go wrong here
// because it SHOULD be avoided!!
switch (action_mode) {
case 1:
NLogger.error(getClass(), "Undo StyledText redraw failed."); //$NON-NLS-1$
break;
case 2:
NLogger.error(getClass(), "Redo StyledText redraw failed."); //$NON-NLS-1$
break;
default:
// Can't happen
break;
}
NLogger.error(getClass(), undoRedoException);
}
// Never ever call "vm.setModified_NoSync();" here. NEVER delete the following lines.
vm.setModified(false, false);
vm.setUpdated(true);
vm.setSkipSyncWithTextEditor(false);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
action.set(0);
df.getVertexManager().setSelectedBgPicture(null);
df.getVertexManager().setSelectedBgPictureIndex(0);
Editor3DWindow.getWindow().updateBgPictureTab();
NLogger.debug(getClass(), "done."); //$NON-NLS-1$
}
private void removeFromListAboveOrEqualIndex(List<?> l, int i) {
i
for (int j = l.size() - 1; j > i; j
l.remove(j);
}
}
private void removeFromListLessIndex(List<?> l, int i) {
i
for (int j = i - 1; j > -1; j
l.remove(j);
}
}
public void setDatFile(DatFile df) {
this.df = df;
}
public Lock getLock() {
return lock;
}
}
|
package org.unipop.structure;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.unipop.process.strategyregistrar.StandardStrategyProvider;
import org.unipop.process.strategyregistrar.StrategyProvider;
import org.unipop.query.controller.ConfigurationControllerManager;
import org.unipop.query.controller.ControllerManager;
import org.unipop.query.mutation.AddVertexQuery;
import org.unipop.query.predicates.PredicatesHolder;
import org.unipop.query.predicates.PredicatesHolderFactory;
import org.unipop.query.search.SearchQuery;
import org.unipop.schema.property.PropertySchema;
import org.unipop.schema.property.type.*;
import org.unipop.structure.traversalfilter.DefaultTraversalFilter;
import org.unipop.structure.traversalfilter.TraversalFilter;
import org.unipop.test.UnipopGraphProvider;
import org.unipop.util.ConversionUtils;
import org.unipop.util.PropertyTypeFactory;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_repeatXoutX_timesX5X_asXaX_outXwrittenByX_asXbX_selectXa_bX_count",
reason = "Takes too long.")
//@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_repeatXoutX_timesX3X_count",
// reason = "Takes too long.")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_repeatXoutX_timesX8X_count",
reason = "Takes too long.")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_VX1_2X_localXunionXoutE_count__inE_count__outE_weight_sumXX",
reason = "Need to investigate.")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.SubgraphTest", method = "g_V_withSideEffectXsgX_repeatXbothEXcreatedX_subgraphXsgX_outVX_timesX5X_name_dedup",
reason = "Need to investigate.")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.SubgraphTest", method = "g_V_withSideEffectXsgX_outEXknowsX_subgraphXsgX_name_capXsgX",
reason = "Need to investigate.")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.AddVertexTest", method = "g_addVXpersonX_propertyXsingle_name_stephenX_propertyXsingle_name_stephenm_since_2010X",
reason = "Missing feature requirement")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnGraphAddVWithGeneratedDefaultId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnGraphAddVWithGeneratedCustomId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldSetIdOnAddVWithIdPropertyKeySpecifiedAndNameSuppliedAsProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldSetIdOnAddVWithIdPropertyKeySpecifiedAndIdSuppliedAsProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnGraphAddVWithSpecifiedId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnAddVWithGeneratedDefaultId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnAddVWithGeneratedCustomId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnAddVWithSpecifiedId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnAddEWithSpecifiedId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldGenerateDefaultIdOnAddEWithGeneratedId", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldSetIdOnAddEWithIdPropertyKeySpecifiedAndNameSuppliedAsProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.ElementIdStrategyProcessTest", method = "shouldSetIdOnAddEWithNamePropertyKeySpecifiedAndNameSuppliedAsProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertex", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexFromStart", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddEdge", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddEdgeByPath", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexPropertyAdded", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexWithPropertyThenPropertyAdded", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexPropertyChanged", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexPropertyPropertyChanged", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddEdgePropertyAdded", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerEdgePropertyChanged", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerRemoveVertex", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerRemoveEdge", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerRemoveVertexProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerRemoveEdgeProperty", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAddVertexPropertyPropertyRemoved", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldTriggerAfterCommit", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldResetAfterRollback", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategyProcessTest", method = "shouldWriteToMultiplePartitions", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategyProcessTest", method = "shouldWriteVerticesToMultiplePartitions", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategyProcessTest", method = "shouldAppendPartitionToEdge", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategyProcessTest", method = "shouldThrowExceptionOnVInDifferentPartition", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategyProcessTest", method = "shouldThrowExceptionOnEInDifferentPartition", reason = "jdbc fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachPropertyOfEdgeWhenRemoved", reason = "fails should investigate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachVertexPropertyWhenChanged", reason = "not all features implemented")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachVertexPropertyWhenRemoved", reason = "not all features implemented")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachPropertyOfEdgeWhenChanged", reason = "not all features implemented")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachVertexPropertyWhenNew", reason = "not all features implemented")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategyProcessTest", method = "shouldDetachPropertyOfEdgeWhenNew", reason = "not all features implemented")
@Graph.OptIn(UnipopGraphProvider.OptIn.UnipopStructureSuite)
@Graph.OptIn(UnipopGraphProvider.OptIn.UnipopProcessSuite)
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD)
public class UniGraph implements Graph {
//for testSuite
public static UniGraph open(final Configuration configuration) throws Exception {
return new UniGraph(configuration);
}
private UniFeatures features = new UniFeatures();
private Configuration configuration;
protected TraversalStrategies strategies;
private ControllerManager controllerManager;
private List<SearchQuery.SearchController> queryControllers;
public UniGraph(Configuration configuration) throws Exception {
configuration.setProperty(Graph.GRAPH, UniGraph.class.getName());
this.configuration = configuration;
PropertyTypeFactory.init(Arrays.asList(TextType.class.getCanonicalName(),
DateType.class.getCanonicalName(),
NumberType.class.getCanonicalName(),
DoubleType.class.getCanonicalName(),
FloatType.class.getCanonicalName(),
IntType.class.getCanonicalName(),
LongType.class.getCanonicalName()));
List<PropertySchema.PropertySchemaBuilder> thirdPartyPropertySchemas = new ArrayList<>();
if(configuration.containsKey("propertySchemas")){
Stream.of(configuration.getStringArray("propertiesSchemas")).map(classString -> {
try {
return ((PropertySchema.PropertySchemaBuilder) Class.forName(classString).newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new IllegalArgumentException("class: " + classString + " not found");
}
}).forEach(thirdPartyPropertySchemas::add);
}
String traversalFilter = configuration.getString("traversalFilter", DefaultTraversalFilter.class.getCanonicalName());
TraversalFilter filter = Class.forName(traversalFilter).asSubclass(TraversalFilter.class).newInstance();
String configurationControllerManagerName = configuration.getString("controllerManager", ConfigurationControllerManager.class.getCanonicalName().toString());
ControllerManager configurationControllerManager = Class.forName(configurationControllerManagerName)
.asSubclass(ControllerManager.class)
.getConstructor(UniGraph.class, Configuration.class, List.class, TraversalFilter.class)
.newInstance(this, configuration,thirdPartyPropertySchemas, filter);
StrategyProvider strategyProvider = determineStrategyProvider(configuration);
init(configurationControllerManager, strategyProvider);
}
public UniGraph(ControllerManager controllerManager, StrategyProvider strategyProvider) throws Exception {
init(controllerManager, strategyProvider);
}
private void init(ControllerManager controllerManager, StrategyProvider strategyProvider) {
this.strategies = strategyProvider.get();
//TraversalStrategies.GlobalCache.registerStrategies(UniGraph.class, strategies);
this.controllerManager = controllerManager;
this.queryControllers = controllerManager.getControllers(SearchQuery.SearchController.class);
}
private StrategyProvider determineStrategyProvider(Configuration configuration) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
StrategyProvider strategyProvider = (StrategyProvider) configuration.getProperty("strategyProvider");
if (strategyProvider == null) {
String strategyRegistrarClass = configuration.getString("strategyRegistrarClass");
if (StringUtils.isNotBlank(strategyRegistrarClass)) {
strategyProvider = (StrategyProvider) Class.forName(strategyRegistrarClass).newInstance();
}
}
if (strategyProvider == null) {
strategyProvider = new StandardStrategyProvider();
}
return strategyProvider;
}
public ControllerManager getControllerManager() {
return controllerManager;
}
@Override
public GraphTraversalSource traversal() {
return new GraphTraversalSource(this, strategies);
}
@Override
public Configuration configuration() {
return this.configuration;
}
@Override
public String toString() {
return StringFactory.graphString(this, "UniGraph"/*, controllerManager.toString()*/);
}
@Override
public void close() {
controllerManager.close();
}
@Override
public Features features() {
return features;
}
@Override
public Transaction tx() {
throw Exceptions.transactionsNotSupported();
}
@Override
public Variables variables() {
throw Exceptions.variablesNotSupported();
}
@Override
public <C extends GraphComputer> C compute(Class<C> graphComputerClass) throws IllegalArgumentException {
throw Exceptions.graphComputerNotSupported();
}
@Override
public GraphComputer compute() throws IllegalArgumentException {
throw Exceptions.graphComputerNotSupported();
}
@Override
public Iterator<Vertex> vertices(Object... ids) {
return this.query(Vertex.class, ids);
}
@Override
public Iterator<Edge> edges(Object... ids) {
return this.query(Edge.class, ids);
}
private <E extends Element, C extends Comparable> Iterator<E> query(Class<E> returnType, Object[] ids) {
PredicatesHolder idPredicate = createIdPredicate(ids, returnType);
SearchQuery<E> uniQuery = new SearchQuery<>(returnType, idPredicate, -1, null, null, null, null);
return queryControllers.stream().<E>flatMap(controller -> ConversionUtils.asStream(controller.search(uniQuery))).iterator();
}
public static <E extends Element> PredicatesHolder createIdPredicate(Object[] ids, Class<E> returnType) {
ElementHelper.validateMixedElementIds(returnType, ids);
//if (ids.length > 0 && Vertex.class.isAssignableFrom(ids[0].getClass())) return new ArrayIterator<>(ids);
if (ids.length > 0) {
List<Object> collect = Stream.of(ids).map(id -> {
if (id instanceof Element)
return ((Element) id).id();
return id;
}).collect(Collectors.toList());
HasContainer idPredicate = new HasContainer(T.id.getAccessor(), P.within(collect));
return PredicatesHolderFactory.predicate(idPredicate);
}
return PredicatesHolderFactory.empty();
}
@Override
public Vertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Optional<String> labelValue = ElementHelper.getLabelValue(keyValues);
labelValue.ifPresent(ElementHelper::validateLabel);
return controllerManager.getControllers(AddVertexQuery.AddVertexController.class).stream()
.map(controller -> controller.addVertex(new AddVertexQuery(ConversionUtils.asMap(keyValues), null)))
.filter(Objects::nonNull)
.findFirst().get();
}
}
|
package org.ojalgo.optimisation.integer;
import static org.ojalgo.constant.PrimitiveMath.*;
import static org.ojalgo.function.PrimitiveFunction.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;
import org.ojalgo.access.Access1D;
import org.ojalgo.function.FunctionUtils;
import org.ojalgo.function.PrimitiveFunction;
import org.ojalgo.function.aggregator.Aggregator;
import org.ojalgo.function.multiary.MultiaryFunction;
import org.ojalgo.matrix.store.MatrixStore;
import org.ojalgo.matrix.store.PrimitiveDenseStore;
import org.ojalgo.netio.BasicLogger;
import org.ojalgo.netio.CharacterRing;
import org.ojalgo.netio.CharacterRing.PrinterBuffer;
import org.ojalgo.optimisation.ExpressionsBasedModel;
import org.ojalgo.optimisation.GenericSolver;
import org.ojalgo.optimisation.Optimisation;
import org.ojalgo.optimisation.Variable;
import org.ojalgo.type.TypeUtils;
public final class IntegerSolver extends GenericSolver {
public static final class ModelIntegration extends ExpressionsBasedModel.Integration<IntegerSolver> {
public IntegerSolver build(final ExpressionsBasedModel model) {
return IntegerSolver.make(model);
}
public boolean isCapable(final ExpressionsBasedModel model) {
return !model.isAnyConstraintQuadratic();
}
@Override
public Result toModelState(final Result solverState, final ExpressionsBasedModel model) {
return solverState;
}
@Override
public Result toSolverState(final Result modelState, final ExpressionsBasedModel model) {
return modelState;
}
@Override
protected boolean isSolutionMapped() {
return false;
}
}
final class BranchAndBoundNodeTask extends RecursiveTask<Boolean> implements Comparable<BranchAndBoundNodeTask> {
private final NodeKey myKey;
private final PrinterBuffer myPrinter = IntegerSolver.this.isDebug() ? new CharacterRing().asPrinter() : null;
private BranchAndBoundNodeTask(final NodeKey key) {
super();
myKey = key;
}
BranchAndBoundNodeTask() {
super();
myKey = new NodeKey(IntegerSolver.this.getIntegerModel());
}
public int compareTo(BranchAndBoundNodeTask o) {
return myKey.compareTo(o.getKey());
}
@Override
public String toString() {
return myKey.toString();
}
private void flush(final BasicLogger.Printer receiver) {
if ((myPrinter != null) && (receiver != null)) {
myPrinter.flush(receiver);
}
}
private boolean isNodeDebug() {
return (myPrinter != null) && IntegerSolver.this.isDebug();
}
@Override
protected Boolean compute() {
final ExpressionsBasedModel nodeModel = IntegerSolver.this.getRelaxedModel();
myKey.setNodeState(nodeModel, IntegerSolver.this.getIntegerIndices());
if (IntegerSolver.this.isIntegerSolutionFound()) {
final double mip_gap = IntegerSolver.this.options.mip_gap;
final double bestIntegerSolutionValue = IntegerSolver.this.getBestResultSoFar().getValue();
final double parentRelaxedSolutionValue = myKey.objective;
final double absoluteValue = ABS.invoke(bestIntegerSolutionValue);
final double absoluteGap = ABS.invoke(absoluteValue - parentRelaxedSolutionValue);
final double small = FunctionUtils.max(mip_gap, absoluteGap * mip_gap, absoluteValue * mip_gap);
if (nodeModel.isMinimisation()) {
final BigDecimal upperLimit = TypeUtils.toBigDecimal(bestIntegerSolutionValue - small, IntegerSolver.this.options.feasibility);
// final BigDecimal lowerLimit = TypeUtils.toBigDecimal(parentRelaxedSolutionValue, IntegerSolver.this.options.feasibility);
nodeModel.limitObjective(null, upperLimit);
} else {
final BigDecimal lowerLimit = TypeUtils.toBigDecimal(bestIntegerSolutionValue + small, IntegerSolver.this.options.feasibility);
// final BigDecimal upperLimit = TypeUtils.toBigDecimal(parentRelaxedSolutionValue, IntegerSolver.this.options.feasibility);
nodeModel.limitObjective(lowerLimit, null);
}
}
return this.compute(nodeModel.prepare());
}
protected Boolean compute(final ExpressionsBasedModel.Intermediate nodeModel) {
if (this.isNodeDebug()) {
myPrinter.println();
myPrinter.println("Branch&Bound Node");
myPrinter.println(myKey.toString());
myPrinter.println(IntegerSolver.this.toString());
}
if (!IntegerSolver.this.isIterationAllowed() || !IntegerSolver.this.isIterationNecessary()) {
if (this.isNodeDebug()) {
myPrinter.println("Reached iterations or time limit - stop!");
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
return false;
}
if (!IntegerSolver.this.isGoodEnoughToContinueBranching(myKey.objective)) {
if (this.isNodeDebug()) {
myPrinter.println("No longer a relevant node!");
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
return true;
}
if (myKey.index >= 0) {
myKey.enforceBounds(nodeModel, IntegerSolver.this.getIntegerIndices());
//myKey.setNodeState(nodeModel, IntegerSolver.this.getIntegerIndices());
}
final Result bestResultSoFar = IntegerSolver.this.getBestResultSoFar();
final Optimisation.Result nodeResult = nodeModel.solve(bestResultSoFar);
// Increment when/if an iteration was actually performed
IntegerSolver.this.incrementIterationsCount();
if (this.isNodeDebug()) {
myPrinter.println("Node Result: {}", nodeResult);
}
if (nodeResult.getState().isOptimal()) {
if (this.isNodeDebug()) {
myPrinter.println("Node solved to optimality!");
}
if (IntegerSolver.this.options.validate && !nodeModel.validate(nodeResult)) {
// This should not be possible. There is a bug somewhere.
myPrinter.println("Node solution marked as OPTIMAL, but is actually INVALID/INFEASIBLE/FAILED. Stop this branch!");
myPrinter.println("Lower bounds: {}", Arrays.toString(myKey.getLowerBounds()));
myPrinter.println("Upper bounds: {}", Arrays.toString(myKey.getUpperBounds()));
// nodeModel.validate(nodeResult, myPrinter);
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
return false;
}
final int branchIntegerIndex = IntegerSolver.this.identifyNonIntegerVariable(nodeResult, myKey);
final double tmpSolutionValue = IntegerSolver.this.evaluateFunction(nodeResult);
if (branchIntegerIndex == -1) {
if (this.isNodeDebug()) {
myPrinter.println("Integer solution! Store it among the others, and stop this branch!");
}
final Optimisation.Result tmpIntegerSolutionResult = new Optimisation.Result(Optimisation.State.FEASIBLE, tmpSolutionValue, nodeResult);
IntegerSolver.this.markInteger(myKey, null, tmpIntegerSolutionResult);
if (this.isNodeDebug()) {
myPrinter.println(IntegerSolver.this.getBestResultSoFar().toString());
BasicLogger.debug();
BasicLogger.debug(IntegerSolver.this.toString());
// BasicLogger.debug(DaemonPoolExecutor.INSTANCE.toString());
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
nodeModel.dispose();
return true;
} else {
if (this.isNodeDebug()) {
myPrinter.println("Not an Integer Solution: " + tmpSolutionValue);
}
final double tmpVariableValue = nodeResult.doubleValue(IntegerSolver.this.getGlobalIndex(branchIntegerIndex));
if (IntegerSolver.this.isGoodEnoughToContinueBranching(tmpSolutionValue)) {
if (this.isNodeDebug()) {
myPrinter.println("Still hope, branching on {} @ {} >>> {}", branchIntegerIndex, tmpVariableValue,
nodeModel.getVariable(IntegerSolver.this.getGlobalIndex(branchIntegerIndex)));
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
// IntegerSolver.this.generateCuts(nodeModel);
final BranchAndBoundNodeTask lowerBranch = this.createLowerBranch(branchIntegerIndex, tmpVariableValue, tmpSolutionValue);
final BranchAndBoundNodeTask upperBranch = this.createUpperBranch(branchIntegerIndex, tmpVariableValue, tmpSolutionValue);
final BranchAndBoundNodeTask nextTask;
final BranchAndBoundNodeTask forkedTask;
BranchAndBoundNodeTask deferredTask;
final double fractional = tmpVariableValue - Math.floor(tmpVariableValue);
if (fractional >= HALF) {
nextTask = upperBranch;
if (fractional > 0.95) {
forkedTask = null;
//deferredTask = lowerBranch;
deferred.offer(lowerBranch);
} else {
forkedTask = lowerBranch;
deferredTask = null;
}
} else {
nextTask = lowerBranch;
if (fractional < 0.05) {
forkedTask = null;
// deferredTask = upperBranch;
deferred.offer(upperBranch);
} else {
forkedTask = upperBranch;
deferredTask = null;
}
}
if (forkedTask != null) {
forkedTask.fork();
return nextTask.compute(nodeModel) && forkedTask.join();
} else {
Boolean tmpCompute = nextTask.compute(nodeModel);
deferredTask = deferred.poll();
if (tmpCompute.booleanValue() && (deferredTask != null)) {
tmpCompute = deferredTask.compute();
}
return tmpCompute;
}
} else {
if (this.isNodeDebug()) {
myPrinter.println("Can't find better integer solutions - stop this branch!");
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
nodeModel.dispose();
return true;
}
}
} else {
if (this.isNodeDebug()) {
myPrinter.println("Failed to solve node problem - stop this branch!");
this.flush(IntegerSolver.this.getIntegerModel().options.logger_appender);
}
nodeModel.dispose();
return true;
}
}
BranchAndBoundNodeTask createLowerBranch(final int branchIntegerIndex, final double nonIntegerValue, final double parentObjectiveValue) {
final NodeKey tmpKey = myKey.createLowerBranch(branchIntegerIndex, nonIntegerValue, parentObjectiveValue);
return new BranchAndBoundNodeTask(tmpKey);
}
BranchAndBoundNodeTask createUpperBranch(final int branchIntegerIndex, final double nonIntegerValue, final double parentObjectiveValue) {
final NodeKey tmpKey = myKey.createUpperBranch(branchIntegerIndex, nonIntegerValue, parentObjectiveValue);
return new BranchAndBoundNodeTask(tmpKey);
}
NodeKey getKey() {
return myKey;
}
}
static final class NodeStatistics {
private final AtomicInteger myAbandoned = new AtomicInteger();
/**
* Resulted in 2 new nodes
*/
private final AtomicInteger myBranched = new AtomicInteger();
/**
* Integer solution found and/or solution not good enough to continue
*/
private final AtomicInteger myExhausted = new AtomicInteger();
/**
* Failed to solve node problem (not because it was infeasible)
*/
private final AtomicInteger myFailed = new AtomicInteger();
/**
* Node problem infeasible
*/
private final AtomicInteger myInfeasible = new AtomicInteger();
/**
* Integer solution
*/
private final AtomicInteger myInteger = new AtomicInteger();
/**
* Noninteger solution
*/
private final AtomicInteger myTruncated = new AtomicInteger();
public int countCreated() {
return myTruncated.get() + myAbandoned.get() + this.countEvaluated();
}
public int countEvaluated() {
return myInfeasible.get() + myFailed.get() + myExhausted.get() + myBranched.get();
}
/**
* Node never evaluated (sub/node problem never solved)
*/
boolean abandoned() {
myAbandoned.incrementAndGet();
return true;
}
/**
* Node evaluated, but solution not integer. Estimate still possible to find better integer solution.
* Created 2 new branches.
*/
boolean branched() {
myBranched.incrementAndGet();
return true;
}
/**
* Node evaluated, but solution not integer. Estimate NOT possible to find better integer solution.
*/
boolean exhausted() {
myExhausted.incrementAndGet();
return true;
}
boolean failed(final boolean state) {
myFailed.incrementAndGet();
return state;
}
boolean infeasible() {
myInfeasible.incrementAndGet();
return true;
}
boolean infeasible(final boolean state) {
myInfeasible.incrementAndGet();
return state;
}
/**
* Integer solution found
*/
boolean integer() {
myInteger.incrementAndGet();
return true;
}
boolean truncated(final boolean state) {
myTruncated.incrementAndGet();
return state;
}
}
public static IntegerSolver make(final ExpressionsBasedModel model) {
return new IntegerSolver(model, model.options);
}
private volatile Optimisation.Result myBestResultSoFar = null;
private final MultiaryFunction.TwiceDifferentiable<Double> myFunction;
/**
* One entry per integer variable, the entry is the global index of that integer variable
*/
private final int[] myIntegerIndices;
private final ExpressionsBasedModel myIntegerModel;
private final double[] myIntegerSignificances;
private final AtomicInteger myIntegerSolutionsCount = new AtomicInteger();
private final boolean myMinimisation;
private final NodeStatistics myNodeStatistics = new NodeStatistics();
PriorityBlockingQueue<BranchAndBoundNodeTask> deferred = new PriorityBlockingQueue<BranchAndBoundNodeTask>();
protected IntegerSolver(final ExpressionsBasedModel model, final Options solverOptions) {
super(solverOptions);
myIntegerModel = model.simplify();
myFunction = myIntegerModel.objective().toFunction();
myMinimisation = myIntegerModel.isMinimisation();
final List<Variable> integerVariables = myIntegerModel.getIntegerVariables();
myIntegerIndices = new int[integerVariables.size()];
for (int i = 0, limit = myIntegerIndices.length; i < limit; i++) {
myIntegerIndices[i] = myIntegerModel.indexOf(integerVariables.get(i));
}
myIntegerSignificances = new double[myIntegerIndices.length];
Arrays.fill(myIntegerSignificances, ONE);
}
public Result solve(final Result kickStarter) {
// Must verify that it actually is an integer solution
// The kickStarter may be user-supplied
if ((kickStarter != null) && kickStarter.getState().isFeasible() && this.getIntegerModel().validate(kickStarter)) {
this.markInteger(null, null, kickStarter);
}
this.resetIterationsCount();
final BranchAndBoundNodeTask rootNodeTask = new BranchAndBoundNodeTask();
final boolean normalExit = ForkJoinPool.commonPool().invoke(rootNodeTask);
final Optimisation.Result bestSolutionFound = this.getBestResultSoFar();
if (bestSolutionFound.getState().isFeasible()) {
if (normalExit) {
return new Optimisation.Result(State.OPTIMAL, bestSolutionFound);
} else {
return new Optimisation.Result(State.FEASIBLE, bestSolutionFound);
}
} else {
if (normalExit) {
return new Optimisation.Result(State.INFEASIBLE, bestSolutionFound);
} else {
return new Optimisation.Result(State.FAILED, bestSolutionFound);
}
}
}
@Override
public String toString() {
return TypeUtils.format("Solutions={} Nodes/Iterations={} {}", this.countIntegerSolutions(), this.countExploredNodes(), this.getBestResultSoFar());
}
protected int countIntegerSolutions() {
return myIntegerSolutionsCount.intValue();
}
@Override
protected double evaluateFunction(final Access1D<?> solution) {
if ((myFunction != null) && (solution != null) && (myFunction.arity() == solution.count())) {
return myFunction.invoke(Access1D.asPrimitive1D(solution));
} else {
return Double.NaN;
}
}
@Override
protected MatrixStore<Double> extractSolution() {
return PrimitiveDenseStore.FACTORY.columns(this.getBestResultSoFar());
}
protected Optimisation.Result getBestResultSoFar() {
final Result currentlyTheBest = myBestResultSoFar;
if (currentlyTheBest != null) {
return currentlyTheBest;
} else {
final State tmpSate = State.INVALID;
final double tmpValue = myMinimisation ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
final MatrixStore<Double> tmpSolution = MatrixStore.PRIMITIVE.makeZero(this.getIntegerModel().countVariables(), 1).get();
return new Optimisation.Result(tmpSate, tmpValue, tmpSolution);
}
}
protected MatrixStore<Double> getGradient(final Access1D<Double> solution) {
return myFunction.getGradient(solution);
}
protected ExpressionsBasedModel getIntegerModel() {
return myIntegerModel;
}
protected ExpressionsBasedModel getRelaxedModel() {
return myIntegerModel.relax(false);
}
protected boolean initialise(final Result kickStarter) {
return true;
}
protected boolean isFunctionSet() {
return myFunction != null;
}
protected boolean isGoodEnoughToContinueBranching(final double relaxedNodeValue) {
final Result bestResultSoFar = myBestResultSoFar;
if ((bestResultSoFar == null) || Double.isNaN(relaxedNodeValue)) {
return true;
} else {
final double bestIntegerValue = bestResultSoFar.getValue();
final double absoluteGap = PrimitiveFunction.ABS.invoke(bestIntegerValue - relaxedNodeValue);
final double relativeGap = PrimitiveFunction.ABS.invoke(absoluteGap / bestIntegerValue);
if (myMinimisation) {
return (relaxedNodeValue < bestIntegerValue) && (relativeGap > options.mip_gap) && (absoluteGap > options.mip_gap);
} else {
return (relaxedNodeValue > bestIntegerValue) && (relativeGap > options.mip_gap) && (absoluteGap > options.mip_gap);
}
}
}
protected boolean isIntegerSolutionFound() {
return myBestResultSoFar != null;
}
protected boolean isIterationNecessary() {
if (myBestResultSoFar == null) {
return true;
} else {
return (this.countTime() < options.time_suffice) && (this.countIterations() < options.iterations_suffice);
}
}
protected boolean isModelSet() {
return myIntegerModel != null;
}
protected synchronized void markInteger(final NodeKey key, final ExpressionsBasedModel model, final Optimisation.Result result) {
if (this.isProgress()) {
this.log("New integer solution {}", result);
this.log("\t@ node {}", key);
}
final Optimisation.Result currentlyTheBest = myBestResultSoFar;
if (currentlyTheBest == null) {
myBestResultSoFar = result;
} else if (myMinimisation && (result.getValue() < currentlyTheBest.getValue())) {
myBestResultSoFar = result;
} else if (!myMinimisation && (result.getValue() > currentlyTheBest.getValue())) {
myBestResultSoFar = result;
} else {
if (this.isDebug()) {
this.log("Previously best {}", myBestResultSoFar);
}
}
if (currentlyTheBest != null) {
final double objDiff = ABS.invoke((result.getValue() - currentlyTheBest.getValue()) / currentlyTheBest.getValue());
for (int i = 0; i < myIntegerIndices.length; i++) {
final int globalIndex = myIntegerIndices[i];
final double varDiff = ABS.invoke(result.doubleValue(globalIndex) - currentlyTheBest.doubleValue(globalIndex));
if (!options.feasibility.isZero(varDiff)) {
this.addIntegerSignificance(i, objDiff / varDiff);
}
}
} else {
final MatrixStore<Double> gradient = this.getGradient(Access1D.asPrimitive1D(result));
final double largest = gradient.aggregateAll(Aggregator.LARGEST);
if (largest > ZERO) {
for (int i = 0; i < myIntegerIndices.length; i++) {
final int globalIndex = myIntegerIndices[i];
this.addIntegerSignificance(i, ABS.invoke(gradient.doubleValue(globalIndex)) / largest);
}
}
}
myIntegerSolutionsCount.incrementAndGet();
}
protected boolean needsAnotherIteration() {
return !this.getState().isOptimal();
}
/**
* Should validate the solver data/input/structue. Even "expensive" validation can be performed as the
* method should only be called if {@linkplain Optimisation.Options#validate} is set to true. In addition
* to returning true or false the implementation should set the state to either
* {@linkplain Optimisation.State#VALID} or {@linkplain Optimisation.State#INVALID} (or possibly
* {@linkplain Optimisation.State#FAILED}). Typically the method should be called at the very beginning of
* the solve-method.
*
* @return Is the solver instance valid?
*/
protected boolean validate() {
boolean retVal = true;
this.setState(State.VALID);
try {
if (!(retVal = this.getIntegerModel().validate())) {
retVal = false;
this.setState(State.INVALID);
}
} catch (final Exception ex) {
retVal = false;
this.setState(State.FAILED);
}
return retVal;
}
void addIntegerSignificance(final int index, final double significance) {
myIntegerSignificances[index] += significance;
}
int countExploredNodes() {
// return myExploredNodes.size();
return 0;
}
void generateCuts(final ExpressionsBasedModel nodeModel) {
// nodeModel.generateCuts(myPotentialCutExpressions);
}
int getGlobalIndex(final int integerIndex) {
return myIntegerIndices[integerIndex];
}
int[] getIntegerIndices() {
return myIntegerIndices;
}
double getIntegerSignificance(final int index) {
return myIntegerSignificances[index];
}
/**
* Should return the index of the (best) integer variable to branch on. Returning a negative index means
* an integer solution has been found (no further branching). Does NOT return a global variable index -
* it's the index among the ineteger variable.
*/
int identifyNonIntegerVariable(final Optimisation.Result nodeResult, final NodeKey nodeKey) {
int retVal = -1;
double fraction;
double compareFraction = ZERO;
double maxFraction = ZERO;
for (int i = 0, limit = myIntegerIndices.length; i < limit; i++) {
fraction = nodeKey.getFraction(i, nodeResult.doubleValue(myIntegerIndices[i]));
// [0, 0.5]
if (!options.feasibility.isZero(fraction)) {
if (this.isIntegerSolutionFound()) {
// If an integer solution is already found
// then scale the fraction by its significance
compareFraction = fraction * this.getIntegerSignificance(i);
} else {
// If not yet found integer solution
// then compare the remaining/reversed (larger) fraction
compareFraction = ONE - fraction;
// [0.5, 1.0)
}
if (compareFraction > maxFraction) {
retVal = i;
maxFraction = compareFraction;
}
}
}
return retVal;
}
}
|
package info.tregmine.api;
import info.tregmine.database.Mysql;
import java.sql.ResultSet;
import java.util.HashMap;
//import java.util.Map;
import org.bukkit.ChatColor;
//import org.bukkit.GameMode;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
public class TregminePlayer extends PlayerDelegate
{
private HashMap<String,String> settings = new HashMap<String,String>();
private HashMap<String,Block> block = new HashMap<String,Block>();
private HashMap<String,Integer> integer = new HashMap<String,Integer>();
// private HashMap<String,Location> location = new HashMap<String,Location>();
private int id = 0;
private String name;
private final Mysql mysql = new Mysql();
private Zone currentZone = null;
public TregminePlayer(Player player, String _name)
{
super(player);
this.name = _name;
}
public boolean exists()
{
this.mysql.connect();
if (this.mysql.connect != null) {
try {
String SQL = "SELECT COUNT(*) as count FROM user WHERE player = '"+ name +"';";
this.mysql.statement.executeQuery(SQL);
ResultSet rs = this.mysql.statement.getResultSet();
rs.first();
if ( rs.getInt("count") != 1 ) {
this.mysql.close();
return false;
} else {
this.mysql.close();
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
this.mysql.close();
return false;
}
public void load()
{
settings.clear();
// System.out.println("Loading settings for " + name);
mysql.connect();
if (this.mysql.connect != null) {
try {
this.mysql.connect();
this.mysql.statement.executeQuery("SELECT * FROM user JOIN (user_settings) WHERE uid=id and player = '" + name + "';");
ResultSet rs = this.mysql.statement.getResultSet();
while (rs.next()) {
//TODO: Make this much nicer, this is bad code
this.id = rs.getInt("uid");
settings.put("uid", rs.getString("uid"));
settings.put(rs.getString("key"), rs.getString("value"));
}
this.mysql.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
mysql.close();
this.setTemporaryChatName(getNameColor() + name);
}
public void create()
{
this.mysql.connect();
if (this.mysql.connect != null) {
try {
String SQL = "INSERT INTO user (player) VALUE ('"+ name +"')";
this.mysql.statement.execute(SQL);
} catch (Exception e) {
e.printStackTrace();
}
}
this.mysql.close();
}
private boolean getBoolean(String key)
{
String value = this.settings.get(key);
try {
if (value.contains("true")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public int getId()
{
return id;
}
public boolean isAdmin()
{
return getBoolean("admin");
}
public boolean isDonator()
{
return getBoolean("donator");
}
public boolean isBanned()
{
return getBoolean("banned");
}
public boolean isTrusted()
{
return getBoolean("trusted");
}
public boolean isChild()
{
return getBoolean("child");
}
public boolean isImmortal()
{
return getBoolean("immortal");
}
public boolean getMetaBoolean(String _key)
{
return getBoolean(_key);
}
public void setMetaString(String _key, String _value)
{
try {
this.mysql.connect();
String SQLD = "DELETE FROM `minecraft`.`user_settings` WHERE `user_settings`.`id` = "+ settings.get("uid") +" AND `user_settings`.`key` = '" + _key +"'";
System.console().printf(SQLD);
this.mysql.statement.execute(SQLD);
String SQLU = "INSERT INTO user_settings (id,`key`,`value`) VALUE ((SELECT uid FROM user WHERE player='" + this.getName() + "'),'"+ _key +"','"+ _value +"')";
this.settings.put(_key, _value);
this.mysql.statement.execute(SQLU);
this.mysql.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setTempMetaString(String _key, String _value)
{
try {
this.settings.put(_key, _value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getMetaString(String _key)
{
return this.settings.get(_key);
}
public String getTimezone()
{
String value = this.settings.get("timezone");
if (value == null) {
return "Europe/Stockholm";
} else {
return value;
}
}
public void setBlock(String _key, Block _block)
{
this.block.put(_key, _block);
}
public Block getBlock(String _key)
{
return this.block.get(_key);
}
public Integer getMetaInt(String _key)
{
return this.integer.get(_key);
}
public void setMetaInt(String _key, Integer _value)
{
this.integer.put(_key, _value);
}
public ChatColor getNameColor()
{
String color = this.settings.get("color");
if (this.settings.get("color") != null ) {
if (color.toLowerCase().matches("admin")) {
return ChatColor.RED;
}
if (color.toLowerCase().matches("broker")) {
return ChatColor.DARK_RED;
}
if (color.toLowerCase().matches("helper")) {
return ChatColor.YELLOW;
}
if (color.toLowerCase().matches("purle")) {
return ChatColor.DARK_PURPLE;
}
if (color.toLowerCase().matches("donator")) {
return ChatColor.GOLD;
}
if (color.toLowerCase().matches("trusted")) {
return ChatColor.DARK_GREEN;
}
if (color.toLowerCase().matches("warned")) {
return ChatColor.GRAY;
}
if (color.toLowerCase().matches("trial")) {
return ChatColor.GREEN;
}
if (color.toLowerCase().matches("vampire")) {
return ChatColor.DARK_RED;
}
if (color.toLowerCase().matches("hunter")) {
return ChatColor.BLUE;
}
if (color.toLowerCase().matches("pink")) {
return ChatColor.LIGHT_PURPLE;
}
if (color.toLowerCase().matches("child")) {
return ChatColor.AQUA;
}
if (color.toLowerCase().matches("mentor")) {
return ChatColor.DARK_AQUA;
}
if (color.toLowerCase().matches("police")) {
return ChatColor.BLUE;
}
}
return ChatColor.WHITE;
}
public String getChatName() {
return name;
}
public void setTemporaryChatName(String _name) {
name = _name;
if (getChatName().length() > 16) {
this.setPlayerListName(name.substring(0, 15));
} else {
this.setPlayerListName(name);
}
}
public void setCurrentZone(Zone zone)
{
this.currentZone = zone;
}
public Zone getCurrentZone()
{
return currentZone;
}
}
|
package info.tregmine.database.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.DAOException;
import info.tregmine.database.IBlockDAO;
public class DBBlockDAO implements IBlockDAO{
private Connection conn;
public DBBlockDAO(Connection conn)
{
this.conn = conn;
}
@Override
public boolean isPlaced(Block a) throws DAOException {
Location block = a.getLocation();
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
String pos = block.getX() + "," + block.getY() + "," + block.getZ();
crc32.update(pos.getBytes());
long checksum = crc32.getValue();
String sql = "SELECT * FROM stats_blocks WHERE checksum = ? AND status = '1'";
try(PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setLong(1, checksum);
stmt.execute();
ResultSet rs = stmt.getResultSet();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public int blockValue(Block a) throws DAOException {
String sql = "SELECT * FROM block_prices WHERE blockid = ?";
try(PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setDouble(1, a.getTypeId());
stmt.execute();
ResultSet rs = stmt.getResultSet();
return rs.getInt("price");
} catch (SQLException e) {
return 0;
}
}
}
|
package cn.updev.Message.Task;
import cn.updev.Database.HibernateSessionFactory;
import cn.updev.EventWeight.Weight.EventWeight;
import cn.updev.Events.Event.EventDAO;
import cn.updev.Events.Static.IEvent;
import cn.updev.Message.Email.MailSenderInfo;
import cn.updev.Message.Email.ThreadSenter;
import cn.updev.Message.Template.BasicTemplate;
import cn.updev.Message.Template.EmailCheckFinishTemplate;
import cn.updev.Message.Template.EventRemidTemplate;
import cn.updev.Users.Static.UserOrGroupDAO.UserOrGroupQuery;
import cn.updev.Users.Static.UserOrGroupInterface.IUser;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
import java.util.List;
public class EventCheckJob implements Job {
public static final long PERIOD_DAY = DateUtils.MILLIS_PER_DAY;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("");
Session session = HibernateSessionFactory.currentSession();
String hql = "FROM EventWeight WHERE 1=1";
Query query = session.createQuery(hql);
List<EventWeight> list = query.list();
HibernateSessionFactory.closeSession();
EventDAO eventDAO = new EventDAO();
Date now = new Date();
Long nowLong = now.getTime();
Integer sentNum = 0;
for (EventWeight eventWeight : list){
IEvent event = eventDAO.getEventById(eventWeight.getEventId());
if(!event.isFinish()){
Date eventExpect = eventWeight.getEventExpect();
Long expectLong = eventExpect.getTime();
Long subTime = expectLong - nowLong;
if(subTime >= 0 && subTime <= 2 * PERIOD_DAY){
sentNum++;
sentMassage(event, eventWeight);
}
}
}
checkFinish(list.size(), sentNum, now);
}
private void sentMassage(IEvent event, EventWeight eventWeight){
UserOrGroupQuery userDAO = new UserOrGroupQuery();
IUser user = userDAO.queryUserById(event.getDoerId());
try {
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setToAddress(user.geteMail());
BasicTemplate template = new EventRemidTemplate(user.getNickName(),event, eventWeight).getTemplate();
mailInfo.setSubject(template.getTitle());
mailInfo.setContent(template.getContent());
new Thread(new ThreadSenter(mailInfo)).start();
}catch (Exception e){
System.out.println("[] eventId=" + event.getEventId() + " userEmail=" + user.geteMail());
System.out.println(e.getMessage());
}
}
private void checkFinish(Integer checkNum, Integer setnNum, Date startTime){
try {
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setToAddress("i@ihypo.net");
BasicTemplate template = new EmailCheckFinishTemplate(startTime,checkNum,setnNum).getTemplate();
mailInfo.setSubject(template.getTitle());
mailInfo.setContent(template.getContent());
new Thread(new ThreadSenter(mailInfo)).start();
mailInfo.setToAddress("blf20822@qq.com");
new Thread(new ThreadSenter(mailInfo)).start();
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package it.unitn.disi.annotation;
import it.unitn.disi.annotation.pipelines.IBaseContextPipeline;
import it.unitn.disi.common.components.Configurable;
import it.unitn.disi.common.components.ConfigurableException;
import it.unitn.disi.common.utils.MiscUtils;
import it.unitn.disi.nlptools.components.PipelineComponentException;
import it.unitn.disi.smatch.SMatchException;
import it.unitn.disi.smatch.data.trees.IBaseContext;
import it.unitn.disi.smatch.loaders.context.IBaseContextLoader;
import it.unitn.disi.smatch.renderers.context.IBaseContextRenderer;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
public class DatasetTool extends Configurable {
static {
MiscUtils.configureLog4J();
}
private static final Logger log = Logger.getLogger(DatasetTool.class);
public static final String DEFAULT_CONFIG_FILE_NAME = ".." + File.separator + "conf" + File.separator + "d-tool.properties";
// usage string
private static final String USAGE = "Usage: DatasetTool <input> [output] [options]\n" +
" Options: \n" +
" -config=file.properties read configuration from file.properties\n" +
" -property=key=value supply the configuration key=value (overriding those in the config file)";
// config file command line key
public static final String configFileCmdLineKey = "-config=";
// property command line key
public static final String propCmdLineKey = "-property=";
// component configuration keys and component instance variables
private static final String CONTEXT_LOADER_KEY = "ContextLoader";
private IBaseContextLoader contextLoader = null;
private static final String CONTEXT_RENDERER_KEY = "ContextRenderer";
private IBaseContextRenderer contextRenderer = null;
private static final String PIPELINE_KEY = "Pipeline";
private IBaseContextPipeline pipeline;
@Override
public boolean setProperties(Properties newProperties) throws ConfigurableException {
if (log.isEnabledFor(Level.INFO)) {
log.info("Loading configuration...");
}
Properties oldProperties = new Properties();
oldProperties.putAll(properties);
boolean result = super.setProperties(newProperties);
if (result) {
contextLoader = (IBaseContextLoader) configureComponent(contextLoader, oldProperties, newProperties, "context loader", CONTEXT_LOADER_KEY, IBaseContextLoader.class);
contextRenderer = (IBaseContextRenderer) configureComponent(contextRenderer, oldProperties, newProperties, "context renderer", CONTEXT_RENDERER_KEY, IBaseContextRenderer.class);
if (newProperties.containsKey(PIPELINE_KEY)) {
pipeline = (IBaseContextPipeline) configureComponent(pipeline, oldProperties, newProperties, "pipeline", PIPELINE_KEY, IBaseContextPipeline.class);
} else {
pipeline = null;
}
}
return result;
}
private IBaseContext loadContext(String fileName) throws ConfigurableException {
if (null == contextLoader) {
throw new ConfigurableException("Context loader is not configured.");
}
log.info("Loading context from: " + fileName);
final IBaseContext result = contextLoader.loadContext(fileName);
log.info("Loading context finished");
return result;
}
@SuppressWarnings("unchecked")
private void renderContext(IBaseContext context, String fileName) throws SMatchException {
if (null == contextRenderer) {
throw new SMatchException("Context renderer is not configured.");
}
log.info("Rendering context to: " + fileName);
contextRenderer.render(context, fileName);
log.info("Rendering context finished");
}
private void process(IBaseContext context) {
try {
if (null != pipeline) {
log.info("Processing context...");
pipeline.process(context);
}
} catch (PipelineComponentException e) {
if (log.isEnabledFor(Level.ERROR)) {
log.error(e.getMessage(), e);
}
}
}
public static void main(String[] args) throws IOException, ConfigurableException {
// initialize property file
String configFileName = DEFAULT_CONFIG_FILE_NAME;
ArrayList<String> cleanArgs = new ArrayList<String>();
for (String arg : args) {
if (arg.startsWith(configFileCmdLineKey)) {
configFileName = arg.substring(configFileCmdLineKey.length());
} else {
cleanArgs.add(arg);
}
}
args = cleanArgs.toArray(new String[cleanArgs.size()]);
cleanArgs.clear();
// collect properties specified on the command line
Properties commandProperties = new Properties();
for (String arg : args) {
if (arg.startsWith(propCmdLineKey)) {
String[] props = arg.substring(propCmdLineKey.length()).split("=");
if (0 < props.length) {
String key = props[0];
String value = "";
if (1 < props.length) {
value = props[1];
}
commandProperties.put(key, value);
}
} else {
cleanArgs.add(arg);
}
}
args = cleanArgs.toArray(new String[cleanArgs.size()]);
// check input parameters
if (args.length < 1) {
System.out.println(USAGE);
} else {
DatasetTool dt = new DatasetTool();
Properties config = new Properties();
if (new File(configFileName).exists()) {
config.load(new FileInputStream(configFileName));
}
if (log.isEnabledFor(Level.DEBUG)) {
for (String k : commandProperties.stringPropertyNames()) {
log.debug("property override: " + k + "=" + commandProperties.getProperty(k));
}
}
// override from command line
config.putAll(commandProperties);
dt.setProperties(config);
if (!config.isEmpty()) {
if (1 == args.length) {
String inputFile = args[0];
IBaseContext context = dt.loadContext(inputFile);
dt.process(context);
} else if (2 == args.length) {
String inputFile = args[0];
String outputFile = args[1];
IBaseContext context = dt.loadContext(inputFile);
dt.process(context);
dt.renderContext(context, outputFile);
}
} else {
System.out.println("Not enough arguments.");
}
}
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.event.AncestorEvent;
import javax.swing.event.MouseInputAdapter;
import java.util.Arrays;
import com.samskivert.swing.Controller;
import com.samskivert.swing.Label;
import com.samskivert.swing.event.AncestorAdapter;
import com.samskivert.swing.event.CommandEvent;
import com.samskivert.util.IntListUtil;
import com.samskivert.util.RuntimeAdjust;
import com.samskivert.util.StringUtil;
import com.threerings.media.timer.MediaTimer;
import com.threerings.media.animation.Animation;
import com.threerings.media.animation.AnimationManager;
import com.threerings.media.sprite.ButtonSprite;
import com.threerings.media.sprite.Sprite;
import com.threerings.media.sprite.SpriteManager;
import com.threerings.media.sprite.action.ActionSprite;
import com.threerings.media.sprite.action.ArmingSprite;
import com.threerings.media.sprite.action.CommandSprite;
import com.threerings.media.sprite.action.DisableableSprite;
import com.threerings.media.sprite.action.HoverSprite;
public class MediaPanel extends JComponent
implements FrameParticipant, MediaConstants
{
/**
* Constructs a media panel.
*/
public MediaPanel (FrameManager framemgr)
{
// keep this for later
_framemgr = framemgr;
setOpaque(true); // our repaints shouldn't cause other jcomponents to
// create our region manager
_remgr = new RegionManager();
// create our animation and sprite managers
_animmgr = new AnimationManager(this);
_spritemgr = new SpriteManager(this);
// participate in the frame when we're visible
addAncestorListener(new AncestorAdapter() {
public void ancestorAdded (AncestorEvent event) {
_framemgr.registerFrameParticipant(MediaPanel.this);
}
public void ancestorRemoved (AncestorEvent event) {
_framemgr.removeFrameParticipant(MediaPanel.this);
}
});
}
/**
* Returns a reference to the animation manager used by this media
* panel.
*/
public AnimationManager getAnimationManager ()
{
return _animmgr;
}
/**
* Returns a reference to the sprite manager used by this media panel.
*/
public SpriteManager getSpriteManager ()
{
return _spritemgr;
}
/**
* Pauses the sprites and animations that are currently active on this
* media panel. Also stops listening to the frame tick while paused.
*/
public void setPaused (boolean paused)
{
// sanity check
if ((paused && (_pauseTime != 0)) ||
(!paused && (_pauseTime == 0))) {
Log.warning("Requested to pause when paused or vice-versa " +
"[paused=" + paused + "].");
return;
}
if (_paused = paused) {
// make a note of our pause time
_pauseTime = _framemgr.getTimeStamp();
} else {
// let the animation and sprite managers know that we just
// warped into the future
long delta = _framemgr.getTimeStamp() - _pauseTime;
_animmgr.fastForward(delta);
_spritemgr.fastForward(delta);
// clear out our pause time
_pauseTime = 0;
}
}
/**
* Returns a reference to the region manager that is used to
* accumulate dirty regions each frame.
*/
public RegionManager getRegionManager ()
{
return _remgr;
}
/**
* Returns a timestamp from the {@link MediaTimer} used to track time
* intervals for this media panel. <em>Note:</em> this should only be
* called from the AWT thread.
*/
public long getTimeStamp ()
{
return _framemgr.getTimeStamp();
}
// documentation inherited from interface
public void getPerformanceStatus (StringBuffer buf)
{
}
/**
* Adds a sprite to this panel.
*/
public void addSprite (Sprite sprite)
{
_spritemgr.addSprite(sprite);
if (((sprite instanceof ActionSprite) ||
(sprite instanceof HoverSprite)) && (_actionSpriteCount++ == 0)) {
if (_actionHandler == null) {
_actionHandler = new ActionSpriteHandler();
}
addMouseListener(_actionHandler);
addMouseMotionListener(_actionHandler);
}
}
/**
* @return true if the sprite is already added to this panel.
*/
public boolean isManaged (Sprite sprite)
{
return _spritemgr.isManaged(sprite);
}
/**
* Removes a sprite from this panel.
*/
public void removeSprite (Sprite sprite)
{
_spritemgr.removeSprite(sprite);
if (((sprite instanceof ActionSprite) ||
(sprite instanceof HoverSprite)) && (--_actionSpriteCount == 0)) {
removeMouseListener(_actionHandler);
removeMouseMotionListener(_actionHandler);
}
}
/**
* Removes all sprites from this panel.
*/
public void clearSprites ()
{
_spritemgr.clearMedia();
if (_actionHandler != null) {
removeMouseListener(_actionHandler);
removeMouseMotionListener(_actionHandler);
_actionSpriteCount = 0;
}
}
/**
* Adds an animation to this panel. Animations are automatically
* removed when they finish.
*/
public void addAnimation (Animation anim)
{
_animmgr.registerAnimation(anim);
}
/**
* @return true if the animation is already added to this panel.
*/
public boolean isManaged (Animation anim)
{
return _animmgr.isManaged(anim);
}
/**
* Aborts a currently running animation and removes it from this
* panel. Animations are normally automatically removed when they
* finish.
*/
public void abortAnimation (Animation anim)
{
_animmgr.unregisterAnimation(anim);
}
/**
* Removes all animations from this panel.
*/
public void clearAnimations ()
{
_animmgr.clearMedia();
}
// documentation inherited from interface
public void tick (long tickStamp)
{
// bail if ticking is currently disabled
if (_paused) {
return;
}
// let derived classes do their business
willTick(tickStamp);
// now tick our animations and sprites
_animmgr.tick(tickStamp);
_spritemgr.tick(tickStamp);
// if performance debugging is enabled,
if (_perfDebug.getValue()) {
if (_perfLabel == null) {
_perfLabel = new Label(
"", Label.OUTLINE, Color.white, Color.black,
new Font("Arial", Font.PLAIN, 10));
}
if (_perfRect == null) {
_perfRect = new Rectangle(5, 5, 0, 0);
}
StringBuffer perf = new StringBuffer();
perf.append("[FPS: ");
perf.append(_framemgr.getPerfTicks()).append("/");
perf.append(_framemgr.getPerfTries());
perf.append(" PM:");
StringUtil.toString(perf, _framemgr.getPerfMetrics());
// perf.append(" MP:").append(_dirtyPerTick);
perf.append("]");
String perfStatus = perf.toString();
if (!_perfStatus.equals(perfStatus)) {
_perfStatus = perfStatus;
_perfLabel.setText(perfStatus);
Graphics2D gfx = (Graphics2D)getGraphics();
if (gfx != null) {
_perfLabel.layout(gfx);
gfx.dispose();
// make sure the region we dirty contains the old and
// the new text (which we ensure by never letting the
// rect shrink)
Dimension psize = _perfLabel.getSize();
_perfRect.width = Math.max(_perfRect.width, psize.width);
_perfRect.height = Math.max(_perfRect.height, psize.height);
dirtyScreenRect(new Rectangle(_perfRect));
}
}
}
// let derived classes do their business
didTick(tickStamp);
// make a note that the next paint will correspond to a call to
// tick()
_tickPaintPending = true;
}
/**
* Derived classes can override this method and perform computation
* prior to the ticking of the sprite and animation managers.
*/
protected void willTick (long tickStamp)
{
}
/**
* Derived classes can override this method and perform computation
* subsequent to the ticking of the sprite and animation managers.
*/
protected void didTick (long tickStamp)
{
}
// documentation inherited from interface
public boolean needsPaint ()
{
// compute our average dirty regions per tick
if (_tick++ == 99) {
_tick = 0;
int dirty = IntListUtil.sum(_dirty);
Arrays.fill(_dirty, 0);
_dirtyPerTick = (float)dirty/100;
}
// if we have no dirty regions, clear our pending tick indicator
// because we're not going to get painted
boolean needsPaint = _remgr.haveDirtyRegions();
if (!needsPaint) {
_tickPaintPending = false;
}
// regardless of whether or not we paint, we need to let our
// abstract media managers know that we've gotten to the point of
// painting because they need to remain prepared to deal with
// media changes that happen any time between the tick() and the
// paint() and thus need to know when paint() happens
_animmgr.willPaint();
_spritemgr.willPaint();
return needsPaint;
}
// documentation inherited from interface
public Component getComponent ()
{
return this;
}
// documentation inherited
public void setOpaque (boolean opaque)
{
if (!opaque) {
Log.warning("Media panels shouldn't be setOpaque(false).");
Thread.dumpStack();
}
super.setOpaque(true);
}
// documentation inherited
public void repaint (long tm, int x, int y, int width, int height)
{
if (width > 0 && height > 0) {
dirtyScreenRect(new Rectangle(x, y, width, height));
}
}
// documentation inherited
public void paint (Graphics g)
{
Graphics2D gfx = (Graphics2D)g;
// no use in painting if we're not showing or if we've not yet
// been validated
if (!isValid() || !isShowing()) {
return;
}
// if this isn't a tick paint, then we need to grab the clipping
// rectangle and mark it as dirty
if (!_tickPaintPending) {
Shape clip = g.getClip();
if (clip == null) {
// mark the whole component as dirty
repaint();
} else {
dirtyScreenRect(clip.getBounds());
}
// we used to bail out here and not render until our next
// tick, but it turns out that we need to render here because
// Swing may have repainted our parent over us and expect that
// we're going to paint ourselves on top of whatever it just
// painted, so we go ahead and paint now to avoid flashing
} else {
_tickPaintPending = false;
}
// if we have no invalid rects, there's no need to repaint
if (!_remgr.haveDirtyRegions()) {
return;
}
// get our dirty rectangles and delegate the main painting to a
// method that can be more easily overridden
Rectangle[] dirty = _remgr.getDirtyRegions();
_dirty[_tick] = dirty.length;
try {
paint(gfx, dirty);
} catch (Throwable t) {
Log.warning(this + " choked in paint(" + dirty + ").");
Log.logStackTrace(t);
}
// render our performance debugging if it's enabled
if (_perfRect != null && _perfDebug.getValue()) {
gfx.setClip(null);
_perfLabel.render(gfx, _perfRect.x, _perfRect.y);
}
}
/**
* Performs the actual painting of the media panel. Derived methods
* can override this method if they wish to perform pre- and/or
* post-paint activities or if they wish to provide their own painting
* mechanism entirely.
*/
protected void paint (Graphics2D gfx, Rectangle[] dirty)
{
int dcount = dirty.length;
for (int ii = 0; ii < dcount; ii++) {
Rectangle clip = dirty[ii];
// sanity-check the dirty rectangle
if (clip == null) {
Log.warning("Found null dirty rect painting media panel?!");
Thread.dumpStack();
continue;
}
// constrain this dirty region to the bounds of the component
constrainToBounds(clip);
// ignore rectangles that were reduced to nothingness
if (clip.width == 0 || clip.height == 0) {
continue;
}
// clip to this dirty region
clipToDirtyRegion(gfx, clip);
// paint the region
paintDirtyRect(gfx, clip);
}
}
/**
* Paints all the layers of the specified dirty region.
*/
protected void paintDirtyRect (Graphics2D gfx, Rectangle rect)
{
// paint the behind the scenes stuff
paintBehind(gfx, rect);
// paint back sprites and animations
paintBits(gfx, AnimationManager.BACK, rect);
// paint the between the scenes stuff
paintBetween(gfx, rect);
// paint front sprites and animations
paintBits(gfx, AnimationManager.FRONT, rect);
// paint anything in front
paintInFront(gfx, rect);
}
/**
* Called by the main rendering code to constrain this dirty rectangle
* to the bounds of the media panel. If a derived class is using dirty
* rectangles that live in some sort of virtual coordinate system,
* they'll want to override this method and constraint the rectangles
* properly.
*/
protected void constrainToBounds (Rectangle dirty)
{
SwingUtilities.computeIntersection(
0, 0, getWidth(), getHeight(), dirty);
}
/**
* This is called to clip the rendering output to the supplied dirty
* region. This should use {@link Graphics#setClip} because the
* clipping region will need to be replaced as we iterate through our
* dirty regions. By default, a region is assumed to represent screen
* coordinates, but if a derived class wishes to maintain dirty
* regions in non-screen coordinates, it can override this method to
* properly clip to the dirty region.
*/
protected void clipToDirtyRegion (Graphics2D gfx, Rectangle dirty)
{
// Log.info("MP: Clipping to [clip=" + StringUtil.toString(dirty) + "].");
gfx.setClip(dirty);
}
/**
* Called to mark the specified rectangle (in screen coordinates) as
* dirty. The rectangle will be bent, folded and mutilated, so be sure
* you're not passing a rectangle into this method that is being used
* elsewhere.
*
* <p> If derived classes wish to convert from screen coordinates to
* some virtual coordinate system to be used by their repaint manager,
* this is the place to do it.
*/
protected void dirtyScreenRect (Rectangle rect)
{
_remgr.addDirtyRegion(rect);
}
/**
* Paints behind all sprites and animations. The supplied invalid
* rectangle should be redrawn in the supplied graphics context.
* Sub-classes should override this method to do the actual rendering
* for their display.
*/
protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect)
{
}
/**
* Paints between the front and back layer of sprites and animations.
* The supplied invalid rectangle should be redrawn in the supplied
* graphics context. Sub-classes should override this method to do the
* actual rendering for their display.
*/
protected void paintBetween (Graphics2D gfx, Rectangle dirtyRect)
{
}
/**
* Paints in front of all sprites and animations. The supplied invalid
* rectangle should be redrawn in the supplied graphics context.
* Sub-classes should override this method to do the actual rendering
* for their display.
*/
protected void paintInFront (Graphics2D gfx, Rectangle dirtyRect)
{
}
/**
* Renders the sprites and animations that intersect the supplied
* dirty region in the specified layer. Derived classes can override
* this method if they need to do custom sprite or animation rendering
* (if they need to do special sprite z-order handling, for example).
* The clipping region will already be set appropriately.
*/
protected void paintBits (Graphics2D gfx, int layer, Rectangle dirty)
{
if (layer == FRONT) {
_spritemgr.paint(gfx, layer, dirty);
_animmgr.paint(gfx, layer, dirty);
} else {
_animmgr.paint(gfx, layer, dirty);
_spritemgr.paint(gfx, layer, dirty);
}
}
/** The frame manager with whom we register. */
protected FrameManager _framemgr;
/** The animation manager in use by this panel. */
protected AnimationManager _animmgr;
/** The sprite manager in use by this panel. */
protected SpriteManager _spritemgr;
/** Used to accumulate and merge dirty regions on each tick. */
protected RegionManager _remgr;
/** Used to correlate tick()s with paint()s. */
protected boolean _tickPaintPending = false;
/** Whether we're currently paused. */
protected boolean _paused;
/** Used to track the clock time at which we were paused. */
protected long _pauseTime;
/** Used to keep metrics. */
protected int[] _dirty = new int[200];
/** Used to keep metrics. */
protected int _tick;
/** Used to keep metrics. */
protected float _dirtyPerTick;
/** Handles ActionSprite/HoverSprite/ArmingSprite manipulation. */
protected class ActionSpriteHandler extends MouseInputAdapter
{
// documentation inherited
public void mousePressed (MouseEvent me)
{
if (_activeSprite == null) {
// see if we can find one
Sprite s = getHit(me);
if (s instanceof ActionSprite) {
_activeSprite = s;
}
}
if (_activeSprite instanceof ArmingSprite) {
((ArmingSprite) _activeSprite).setArmed(true);
}
}
// documentation inherited
public void mouseReleased (MouseEvent me)
{
if (_activeSprite instanceof ArmingSprite) {
((ArmingSprite)_activeSprite).setArmed(false);
}
if ((_activeSprite instanceof ActionSprite) &&
_activeSprite.hitTest(me.getX(), me.getY())) {
ActionEvent event;
if (_activeSprite instanceof CommandSprite) {
CommandSprite cs = (CommandSprite) _activeSprite;
event = new CommandEvent(
MediaPanel.this, cs.getActionCommand(),
cs.getCommandArgument(), me.getWhen(),
me.getModifiers());
} else {
ActionSprite as = (ActionSprite) _activeSprite;
event = new ActionEvent(
MediaPanel.this, ActionEvent.ACTION_PERFORMED,
as.getActionCommand(), me.getWhen(), me.getModifiers());
}
Controller.postAction(event);
}
if (!(_activeSprite instanceof HoverSprite)) {
_activeSprite = null;
}
mouseMoved(me);
}
// documentation inherited
public void mouseDragged (MouseEvent me)
{
if (_activeSprite instanceof ArmingSprite) {
((ArmingSprite) _activeSprite).setArmed(
_activeSprite.hitTest(me.getX(), me.getY()));
}
}
// documentation inherited
public void mouseMoved (MouseEvent me)
{
if (_activeSprite instanceof HoverSprite) {
if (!_activeSprite.hitTest(me.getX(), me.getY())) {
((HoverSprite) _activeSprite).setHovered(false);
_activeSprite = null;
}
}
Sprite s = getHit(me);
if (s instanceof HoverSprite) {
((HoverSprite) s).setHovered(true);
}
_activeSprite = s;
}
/**
* Utility method, get the highest sprite, return it
* if it's enabled.
*/
protected Sprite getHit (MouseEvent me)
{
Sprite s = _spritemgr.getHighestHitSprite(me.getX(), me.getY());
if (!(s instanceof DisableableSprite) ||
((DisableableSprite) s).isEnabled()) {
return s;
} else {
return null;
}
}
/** The active hover sprite, or action sprite. */
protected Sprite _activeSprite;
}
/** The action sprite handler, or null for none. */
protected ActionSpriteHandler _actionHandler;
/** The number of action/hover sprites being managed. */
protected int _actionSpriteCount;
// used to render performance metrics
protected String _perfStatus = "";
protected Label _perfLabel;
protected static Rectangle _perfRect;
/** A debug hook that toggles FPS rendering. */
protected static RuntimeAdjust.BooleanAdjust _perfDebug =
new RuntimeAdjust.BooleanAdjust(
"Toggles frames per second and dirty regions per tick rendering.",
"narya.media.fps_display", MediaPrefs.config, false) {
protected void adjusted (boolean newValue) {
// clear out some things if we're turned off
if (!newValue) {
_perfRect = null;
}
}
};
}
|
package org.apache.log4j.chainsaw;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Priority;
import org.apache.log4j.UtilLoggingLevel;
import org.apache.log4j.chainsaw.help.Tutorial;
import org.apache.log4j.chainsaw.icons.ChainsawIcons;
import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SettingsListener;
import org.apache.log4j.chainsaw.prefs.SettingsManager;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.net.SocketNodeEventListener;
import org.apache.log4j.plugins.Plugin;
import org.apache.log4j.plugins.PluginEvent;
import org.apache.log4j.plugins.PluginListener;
import org.apache.log4j.plugins.PluginRegistry;
import org.apache.log4j.plugins.Receiver;
/**
* The main entry point for Chainsaw, this class represents the first frame
* that is used to display a Welcome panel, and any other panels that are
* generated because Logging Events are streamed via a Receiver, or other
* mechanism.
*
* If a system property 'chainsaw.usecyclicbuffer' is set to 'true', each panel
* will use a cyclic buffer for displaying events and once events reach the
* buffer limit, the oldest events are removed from the table.
*
* If the property is not provided, there is no limit on the table's buffer
* size.
*
* If 'chainsaw.usecyclicbuffer' is set to 'true' and a system property
* 'chainsaw.cyclicbuffersize' is set to some integer value, that value will be
* used as the buffer size - if the buffersize is not provided, a default size
* of 500 is used.
*
* @author Scott Deboy <sdeboy@apache.org>
* @author Paul Smith
* <psmith@apache.org>
*
*/
public class LogUI extends JFrame implements ChainsawViewer, SettingsListener {
private static final String CONFIG_FILE_TO_USE = "config.file";
static final String USE_CYCLIC_BUFFER_PROP_NAME = "chainsaw.usecyclicbuffer";
static final String CYCLIC_BUFFER_SIZE_PROP_NAME =
"chainsaw.cyclicbuffersize";
private static final String MAIN_WINDOW_HEIGHT = "main.window.height";
private static final String MAIN_WINDOW_WIDTH = "main.window.width";
private static final String MAIN_WINDOW_Y = "main.window.y";
private static final String MAIN_WINDOW_X = "main.window.x";
static final String TABLE_COLUMN_ORDER = "table.columns.order";
static final String TABLE_COLUMN_WIDTHS = "table.columns.widths";
private static final String LOOK_AND_FEEL = "LookAndFeel";
private static final String STATUS_BAR = "StatusBar";
static final String COLUMNS_EXTENSION = ".columns";
static final String COLORS_EXTENSION = ".colors";
private final JFrame preferencesFrame = new JFrame();
private static ChainsawSplash splash;
private URL configURLToUse;
private boolean noReceiversDefined;
private ReceiversPanel receiversPanel;
private ChainsawTabbedPane tabbedPane;
private JToolBar toolbar;
private final ChainsawStatusBar statusBar = new ChainsawStatusBar();
private final ApplicationPreferenceModel applicationPreferenceModel = new ApplicationPreferenceModel();
private final ApplicationPreferenceModelPanel applicationPreferenceModelPanel = new ApplicationPreferenceModelPanel(applicationPreferenceModel);
private final Map tableModelMap = new HashMap();
private final Map tableMap = new HashMap();
private final List filterableColumns = new ArrayList();
private final Map panelMap = new HashMap();
ChainsawAppenderHandler handler;
private ChainsawToolBarAndMenus tbms;
private ChainsawAbout aboutBox;
private final SettingsManager sm = SettingsManager.getInstance();
private String lookAndFeelClassName;
private final JFrame tutorialFrame = new JFrame("Chainsaw Tutorial");
/**
* Set to true, if and only if the GUI has completed it's full
* initialization. Any logging events that come in must wait until this is
* true, and if it is false, should wait on the initializationLock object
* until notified.
*/
private boolean isGUIFullyInitialized = false;
private Object initializationLock = new Object();
/**
* The shutdownAction is called when the user requests to exit Chainsaw, and
* by default this exits the VM, but a developer may replace this action with
* something that better suits their needs
*/
private Action shutdownAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
/**
* Clients can register a ShutdownListener to be notified when the user has
* requested Chainsaw to exit.
*/
private EventListenerList shutdownListenerList = new EventListenerList();
private WelcomePanel welcomePanel;
/**
* Constructor which builds up all the visual elements of the frame including
* the Menu bar
*/
public LogUI() {
super("Chainsaw v2 - Log Viewer");
if (ChainsawIcons.WINDOW_ICON != null) {
setIconImage(new ImageIcon(ChainsawIcons.WINDOW_ICON).getImage());
}
}
private static final void showSplash(Frame owner) {
splash = new ChainsawSplash(owner);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
splash.setLocation(
(screenSize.width / 2) - (splash.getWidth() / 2),
(screenSize.height / 2) - (splash.getHeight() / 2));
splash.setVisible(true);
}
private static final void removeSplash() {
if (splash != null) {
splash.setVisible(false);
splash.dispose();
}
}
/**
* Registers a ShutdownListener with this calss so that it can be notified
* when the user has requested that Chainsaw exit.
*
* @param l
*/
public void addShutdownListener(ShutdownListener l) {
shutdownListenerList.add(ShutdownListener.class, l);
}
/**
* Removes the registered ShutdownListener so that the listener will not be
* notified on a shutdown.
*
* @param l
*/
public void removeShutdownListener(ShutdownListener l) {
shutdownListenerList.remove(ShutdownListener.class, l);
}
/**
* Starts Chainsaw by attaching a new instance to the Log4J main root Logger
* via a ChainsawAppender, and activates itself
*
* @param args
*/
public static void main(String[] args) {
createChainsawGUI(true, null);
}
/**
* Creates, activates, and then shows the Chainsaw GUI, optionally showing
* the splash screen, and using the passed shutdown action when the user
* requests to exit the application (if null, then Chainsaw will exit the vm)
*
* @param showSplash
* @param shutdownAction
* DOCUMENT ME!
*/
public static void createChainsawGUI(
boolean showSplash, Action shutdownAction) {
LogUI logUI = new LogUI();
if (showSplash) {
showSplash(logUI);
}
logUI.handler = new ChainsawAppenderHandler();
logUI.handler.addEventBatchListener(logUI.new NewTabEventBatchReceiver());
LogManager.getRootLogger().addAppender(logUI.handler);
logUI.activateViewer();
if (shutdownAction != null) {
logUI.setShutdownAction(shutdownAction);
}
}
/**
* DOCUMENT ME!
*
* @param appender
* DOCUMENT ME!
*/
public void activateViewer(ChainsawAppender appender) {
handler = new ChainsawAppenderHandler(appender);
handler.addEventBatchListener(new NewTabEventBatchReceiver());
activateViewer();
}
/**
* Initialises the menu's and toolbars, but does not actually create any of
* the main panel components.
*
*/
private void initGUI() {
welcomePanel = new WelcomePanel(this);
receiversPanel = new ReceiversPanel(this);
setToolBarAndMenus(new ChainsawToolBarAndMenus(this));
toolbar = getToolBarAndMenus().getToolbar();
setJMenuBar(getToolBarAndMenus().getMenubar());
setTabbedPane(new ChainsawTabbedPane());
applicationPreferenceModelPanel.setOkCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferencesFrame.setVisible(false);
}
});
}
/**
* Given the load event, configures the size/location of the main window etc
* etc.
*
* @param event
* DOCUMENT ME!
*/
public void loadSettings(LoadSettingsEvent event) {
setLocation(
event.asInt(LogUI.MAIN_WINDOW_X), event.asInt(LogUI.MAIN_WINDOW_Y));
setSize(
event.asInt(LogUI.MAIN_WINDOW_WIDTH),
event.asInt(LogUI.MAIN_WINDOW_HEIGHT));
getToolBarAndMenus().stateChange();
}
/**
* Ensures the location/size of the main window is stored with the settings
*
* @param event
* DOCUMENT ME!
*/
public void saveSettings(SaveSettingsEvent event) {
event.saveSetting(LogUI.MAIN_WINDOW_X, (int) getLocation().getX());
event.saveSetting(LogUI.MAIN_WINDOW_Y, (int) getLocation().getY());
event.saveSetting(LogUI.MAIN_WINDOW_WIDTH, getWidth());
event.saveSetting(LogUI.MAIN_WINDOW_HEIGHT, getHeight());
if (lookAndFeelClassName != null) {
event.saveSetting(LogUI.LOOK_AND_FEEL, lookAndFeelClassName);
}
if (configURLToUse != null) {
event.saveSetting(LogUI.CONFIG_FILE_TO_USE, configURLToUse.toString());
}
}
/**
* Activates itself as a viewer by configuring Size, and location of itself,
* and configures the default Tabbed Pane elements with the correct layout,
* table columns, and sets itself viewable.
*/
public void activateViewer() {
initGUI();
applicationPreferenceModel.addPropertyChangeListener("identifierExpression", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
handler.setIdentifierExpression(evt.getNewValue().toString());
}
} );
applicationPreferenceModel.addPropertyChangeListener("responsiveness", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
int value = ((Integer)evt.getNewValue()).intValue();
handler.setQueueInterval((value*1000)-750);
}
} );
applicationPreferenceModel.addPropertyChangeListener("tabPlacement", new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int placement = ((Integer)evt.getNewValue()).intValue();
switch (placement) {
case SwingConstants.TOP :
case SwingConstants.BOTTOM:
tabbedPane.setTabPlacement(placement);
break;
default :
break;
}
}});
}});
applicationPreferenceModel.addPropertyChangeListener("statusBar", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean)evt.getNewValue()).booleanValue();
setStatusBarVisible(value);
}});
applicationPreferenceModel.addPropertyChangeListener("receivers", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean)evt.getNewValue()).booleanValue();
receiversPanel.setVisible(value);
}});
receiversPanel.setVisible(applicationPreferenceModel.isReceivers());
applicationPreferenceModel.addPropertyChangeListener("toolbar", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean)evt.getNewValue()).booleanValue();
toolbar.setVisible(value);
}});
toolbar.setVisible(applicationPreferenceModel.isToolbar());
setStatusBarVisible(applicationPreferenceModel.isStatusBar());
final SocketNodeEventListener socketListener =
new SocketNodeEventListener() {
public void socketOpened(String remoteInfo) {
statusBar.remoteConnectionReceived(remoteInfo);
}
public void socketClosedEvent(Exception e) {
statusBar.setMessage("Connection lost! :: " + e.getMessage());
}
};
PluginListener pluginListener =
new PluginListener() {
public void pluginStarted(PluginEvent e) {
statusBar.setMessage(e.getPlugin().getName() + " started!");
Method method = getAddListenerMethod(e.getPlugin());
if (method != null) {
try {
method.invoke(e.getPlugin(), new Object[] { socketListener });
} catch (Exception ex) {
LogLog.error("Failed to add a SocketNodeEventListener", ex);
}
}
}
Method getRemoveListenerMethod(Plugin p) {
try {
return p.getClass().getMethod(
"removeSocketNodeEventListener",
new Class[] { SocketNodeEventListener.class });
} catch (Exception e) {
return null;
}
}
Method getAddListenerMethod(Plugin p) {
try {
return p.getClass().getMethod(
"addSocketNodeEventListener",
new Class[] { SocketNodeEventListener.class });
} catch (Exception e) {
return null;
}
}
public void pluginStopped(PluginEvent e) {
Method method = getRemoveListenerMethod(e.getPlugin());
if (method != null) {
try {
method.invoke(e.getPlugin(), new Object[] { socketListener });
} catch (Exception ex) {
LogLog.error("Failed to remove SocketNodeEventListener", ex);
}
}
statusBar.setMessage(e.getPlugin().getName() + " stopped!");
}
};
PluginRegistry.addPluginListener(pluginListener);
getSettingsManager().configure(
new SettingsListener() {
public void loadSettings(LoadSettingsEvent event) {
String configFile = event.getSetting(LogUI.CONFIG_FILE_TO_USE);
//if both a config file are defined and a log4j.configuration property
// are set,
//don't use configFile's configuration
if (
(configFile != null) && !configFile.trim().equals("")
&& (System.getProperty("log4j.configuration") == null)) {
try {
URL url = new URL(configFile);
OptionConverter.selectAndConfigure(
url, null, LogManager.getLoggerRepository());
if (LogUI.this.getStatusBar() != null) {
LogUI.this.getStatusBar().setMessage(
"Configured Log4j using remembered URL :: " + url);
}
LogUI.this.configURLToUse = url;
} catch (Exception e) {
LogLog.error("error occurred initializing log4j", e);
}
}
}
public void saveSettings(SaveSettingsEvent event) {
//required because of SettingsListener interface..not used during load
}
});
if (
PluginRegistry.getPlugins(
LogManager.getLoggerRepository(), Receiver.class).size() == 0) {
noReceiversDefined = true;
}
List utilList = UtilLoggingLevel.getAllPossibleLevels();
// TODO: Replace the array list creating with the standard way of
// retreiving the Level set. (TBD)
Priority[] priorities =
new Level[] { Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG };
List priorityLevels = new ArrayList();
for (int i = 0; i < priorities.length; i++) {
priorityLevels.add(priorities[i].toString());
}
List utilLevels = new ArrayList();
for (Iterator iterator = utilLevels.iterator(); iterator.hasNext();) {
utilLevels.add(iterator.next().toString());
}
// getLevelMap().put(ChainsawConstants.UTIL_LOGGING_EVENT_TYPE,
// utilLevels);
// getLevelMap().put(ChainsawConstants.LOG4J_EVENT_TYPE, priorityLevels);
getFilterableColumns().add(ChainsawConstants.LEVEL_COL_NAME);
getFilterableColumns().add(ChainsawConstants.LOGGER_COL_NAME);
getFilterableColumns().add(ChainsawConstants.THREAD_COL_NAME);
getFilterableColumns().add(ChainsawConstants.NDC_COL_NAME);
getFilterableColumns().add(ChainsawConstants.MDC_COL_NAME);
getFilterableColumns().add(ChainsawConstants.CLASS_COL_NAME);
getFilterableColumns().add(ChainsawConstants.METHOD_COL_NAME);
getFilterableColumns().add(ChainsawConstants.FILE_COL_NAME);
getFilterableColumns().add(ChainsawConstants.NONE_COL_NAME);
JPanel panePanel = new JPanel();
panePanel.setLayout(new BorderLayout(2, 2));
getContentPane().setLayout(new BorderLayout());
getTabbedPane().addChangeListener(getToolBarAndMenus());
getTabbedPane().addChangeListener(
new ChangeListener() {
//received a statechange event - selection changed - remove icon from
// selected index
public void stateChanged(ChangeEvent e) {
if (
getTabbedPane().getSelectedComponent() instanceof ChainsawTabbedPane) {
if (getTabbedPane().getSelectedIndex() > -1) {
getTabbedPane().setIconAt(
getTabbedPane().getSelectedIndex(), null);
}
}
}
});
KeyStroke ksRight =
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.CTRL_MASK);
KeyStroke ksLeft =
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.CTRL_MASK);
getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
ksRight, "MoveRight");
getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
ksLeft, "MoveLeft");
Action moveRight =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
int temp = getTabbedPane().getSelectedIndex();
++temp;
if (temp != getTabbedPane().getTabCount()) {
getTabbedPane().setSelectedTab(temp);
}
}
};
Action moveLeft =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
int temp = getTabbedPane().getSelectedIndex();
--temp;
if (temp > -1) {
getTabbedPane().setSelectedTab(temp);
}
}
};
getTabbedPane().getActionMap().put("MoveRight", moveRight);
getTabbedPane().getActionMap().put("MoveLeft", moveLeft);
/**
* We listen for double clicks, and auto-undock currently selected Tab if
* the mouse event location matches the currently selected tab
*/
getTabbedPane().addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if (
(e.getClickCount() > 1)
&& ((e.getModifiers() & InputEvent.BUTTON1_MASK) > 0)) {
int tabIndex = getTabbedPane().getSelectedIndex();
if (
(tabIndex != -1)
&& (tabIndex == getTabbedPane().getSelectedIndex())) {
LogPanel logPanel = getCurrentLogPanel();
if (logPanel != null) {
logPanel.undock();
}
}
}
}
});
panePanel.add(getTabbedPane());
addWelcomePanel();
getContentPane().add(toolbar, BorderLayout.NORTH);
getContentPane().add(panePanel, BorderLayout.CENTER);
getContentPane().add(statusBar, BorderLayout.SOUTH);
receiversPanel.setVisible(false);
getContentPane().add(receiversPanel, BorderLayout.EAST);
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent event) {
exit();
}
});
preferencesFrame.setTitle("'Application-wide Preferences");
preferencesFrame.setIconImage(
((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
preferencesFrame.getContentPane().add(applicationPreferenceModelPanel);
preferencesFrame.setSize(640, 340);
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
preferencesFrame.setLocation(new Point((screenDimension.width/2)-(preferencesFrame.getSize().width/2), (screenDimension.height/2)-(preferencesFrame.getSize().height/2) ));
getSettingsManager().configure(
new SettingsListener() {
public void loadSettings(LoadSettingsEvent event) {
lookAndFeelClassName = event.getSetting(LogUI.LOOK_AND_FEEL);
if (lookAndFeelClassName != null) {
applyLookAndFeel(lookAndFeelClassName);
}
}
public void saveSettings(SaveSettingsEvent event) {
//required because of SettingsListener interface..not used during load
}
});
pack();
final JPopupMenu tabPopup = new JPopupMenu();
final Action hideCurrentTabAction =
new AbstractAction("Hide") {
public void actionPerformed(ActionEvent e) {
displayPanel(getCurrentLogPanel().getIdentifier(), false);
tbms.stateChange();
}
};
final Action hideOtherTabsAction =
new AbstractAction("Hide Others") {
public void actionPerformed(ActionEvent e) {
String currentName = getCurrentLogPanel().getIdentifier();
int count = getTabbedPane().getTabCount();
int index = 0;
for (int i = 0; i < count; i++) {
String name = getTabbedPane().getTitleAt(index);
if (
getPanelMap().keySet().contains(name)
&& !name.equals(currentName)) {
displayPanel(name, false);
tbms.stateChange();
} else {
index++;
}
}
}
};
Action showHiddenTabsAction =
new AbstractAction("Show All Hidden") {
public void actionPerformed(ActionEvent e) {
for (Iterator iter = getPanels().keySet().iterator();
iter.hasNext();) {
String identifier = (String) iter.next();
int count = getTabbedPane().getTabCount();
boolean found = false;
for (int i = 0; i < count; i++) {
String name = getTabbedPane().getTitleAt(i);
if (name.equals(identifier)) {
found = true;
break;
}
}
if (!found) {
displayPanel(identifier, true);
tbms.stateChange();
}
}
}
};
tabPopup.add(hideCurrentTabAction);
tabPopup.add(hideOtherTabsAction);
tabPopup.addSeparator();
tabPopup.add(showHiddenTabsAction);
final PopupListener tabPopupListener = new PopupListener(tabPopup);
getTabbedPane().addMouseListener(tabPopupListener);
final ChangeListener actionEnabler = new ChangeListener(){
public void stateChanged(ChangeEvent arg0) {
boolean enabled = getCurrentLogPanel()!=null;
hideCurrentTabAction.setEnabled(enabled);
hideOtherTabsAction.setEnabled(enabled);
}};
getTabbedPane().addChangeListener(actionEnabler);
getTabbedPane().addContainerListener(new ContainerListener(){
public void componentAdded(ContainerEvent arg0) {
actionEnabler.stateChanged(null);
}
public void componentRemoved(ContainerEvent arg0) {
actionEnabler.stateChanged(null);
}});
this.handler.addPropertyChangeListener(
"dataRate",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
double dataRate = ((Double) evt.getNewValue()).doubleValue();
statusBar.setDataRate(dataRate);
}
});
getSettingsManager().addSettingsListener(this);
getSettingsManager().addSettingsListener(applicationPreferenceModel);
getSettingsManager().loadSettings();
setVisible(true);
removeSplash();
synchronized (initializationLock) {
isGUIFullyInitialized = true;
initializationLock.notifyAll();
}
if (noReceiversDefined && applicationPreferenceModel.isShowNoReceiverWarning()) {
showNoReceiversWarningPanel();
}
Container container = tutorialFrame.getContentPane();
final JEditorPane tutorialArea = new JEditorPane();
tutorialArea.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
tutorialArea.setEditable(false);
container.setLayout(new BorderLayout());
try {
tutorialArea.setPage(getWelcomePanel().getTutorialURL());
container.add(new JScrollPane(tutorialArea), BorderLayout.CENTER);
} catch (Exception e) {
LogLog.error("Error occurred loading the Tutorial", e);
}
tutorialFrame.setIconImage(new ImageIcon(ChainsawIcons.HELP).getImage());
tutorialFrame.setSize(new Dimension(640, 480));
final Action startTutorial =
new AbstractAction(
"Start Tutorial", new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER)) {
public void actionPerformed(ActionEvent e) {
if (
JOptionPane.showConfirmDialog(
null,
"This will start 3 \"Generator\" receivers for use in the Tutorial. Is that ok?",
"Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
new Thread(new Tutorial()).start();
putValue("TutorialStarted", Boolean.TRUE);
} else {
putValue("TutorialStarted", Boolean.FALSE);
}
}
};
final Action stopTutorial =
new AbstractAction(
"Stop Tutorial", new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER)) {
public void actionPerformed(ActionEvent e) {
if (
JOptionPane.showConfirmDialog(
null,
"This will stop all of the \"Generator\" receivers used in the Tutorial, but leave any other Receiver untouched. Is that ok?",
"Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
new Thread(
new Runnable() {
public void run() {
List list =
PluginRegistry.getPlugins(
LogManager.getLoggerRepository(), Generator.class);
for (Iterator iter = list.iterator(); iter.hasNext();) {
Plugin plugin = (Plugin) iter.next();
PluginRegistry.stopPlugin(plugin);
}
}
}).start();
setEnabled(false);
startTutorial.putValue("TutorialStarted", Boolean.FALSE);
}
}
};
stopTutorial.putValue(
Action.SHORT_DESCRIPTION,
"Removes all of the Tutorials Generator Receivers, leaving all other Receivers untouched");
startTutorial.putValue(
Action.SHORT_DESCRIPTION,
"Begins the Tutorial, starting up some Generator Receivers so you can see Chainsaw in action");
stopTutorial.setEnabled(false);
final SmallToggleButton startButton = new SmallToggleButton(startTutorial);
PropertyChangeListener pcl =
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
stopTutorial.setEnabled(
((Boolean) startTutorial.getValue("TutorialStarted")) == Boolean.TRUE);
startButton.setSelected(stopTutorial.isEnabled());
}
};
startTutorial.addPropertyChangeListener(pcl);
stopTutorial.addPropertyChangeListener(pcl);
PluginRegistry.addPluginListener(new PluginListener(){
public void pluginStarted(PluginEvent e) {
}
public void pluginStopped(PluginEvent e) {
List list = PluginRegistry.getPlugins(LogManager.getLoggerRepository(), Generator.class);
if (list.size() == 0) {
startTutorial.putValue("TutorialStarted", Boolean.FALSE);
}
}});
final SmallButton stopButton = new SmallButton(stopTutorial);
final JToolBar tutorialToolbar = new JToolBar();
tutorialToolbar.setFloatable(false);
tutorialToolbar.add(startButton);
tutorialToolbar.add(stopButton);
container.add(tutorialToolbar, BorderLayout.NORTH);
tutorialArea.addHyperlinkListener(
new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e.getDescription().equals("StartTutorial")) {
startTutorial.actionPerformed(null);
} else if (e.getDescription().equals("StopTutorial")) {
stopTutorial.actionPerformed(null);
} else {
try {
tutorialArea.setPage(e.getURL());
} catch (IOException e1) {
LogLog.error("Failed to change the URL for the Tutorial", e1);
}
}
}
}
});
}
/**
* Displays a warning dialog about having no Receivers defined and allows the
* user to choose some options for configuration
*/
private void showNoReceiversWarningPanel() {
final NoReceiversWarningPanel noReceiversWarningPanel =
new NoReceiversWarningPanel();
final SettingsListener sl =
new SettingsListener() {
public void loadSettings(LoadSettingsEvent event) {
int size = event.asInt("SavedConfigs.Size");
Object[] configs = new Object[size];
for (int i = 0; i < size; i++) {
configs[i] = event.getSetting("SavedConfigs." + i);
}
noReceiversWarningPanel.getModel().setRememberedConfigs(configs);
}
public void saveSettings(SaveSettingsEvent event) {
Object[] configs =
noReceiversWarningPanel.getModel().getRememberedConfigs();
event.saveSetting("SavedConfigs.Size", configs.length);
for (int i = 0; i < configs.length; i++) {
event.saveSetting("SavedConfigs." + i, configs[i].toString());
}
}
};
/**
* This listener sets up the NoReciversWarningPanel and loads saves the
* configs/logfiles
*/
getSettingsManager().addSettingsListener(sl);
getSettingsManager().configure(sl);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
final JDialog dialog = new JDialog(LogUI.this, true);
dialog.setTitle("Warning: You have no Receivers defined...");
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setResizable(false);
noReceiversWarningPanel.setOkActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
dialog.getContentPane().add(noReceiversWarningPanel);
dialog.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(
(screenSize.width / 2) - (dialog.getWidth() / 2),
(screenSize.height / 2) - (dialog.getHeight() / 2));
dialog.show();
dialog.dispose();
applicationPreferenceModel.setShowNoReceiverWarning(!noReceiversWarningPanel.isDontWarnMeAgain());
if (noReceiversWarningPanel.getModel().isManualMode() ) {
applicationPreferenceModel.setReceivers(true);
} else if (noReceiversWarningPanel.getModel().isSimpleReceiverMode()) {
int port = noReceiversWarningPanel.getModel().getSimplePort();
Class receiverClass =
noReceiversWarningPanel.getModel().getSimpleReceiverClass();
try {
Receiver simpleReceiver = (Receiver) receiverClass.newInstance();
simpleReceiver.setName("Simple Receiver");
Method portMethod =
simpleReceiver.getClass().getMethod(
"setPort", new Class[] { int.class });
portMethod.invoke(
simpleReceiver, new Object[] { new Integer(port) });
simpleReceiver.setThreshold(Level.DEBUG);
PluginRegistry.startPlugin(simpleReceiver);
receiversPanel.updateReceiverTreeInDispatchThread();
} catch (Exception e) {
LogLog.error("Error creating Receiver", e);
getStatusBar().setMessage(
"An error occurred creating your Receiver");
}
} else if (noReceiversWarningPanel.getModel().isLoadConfig()) {
final URL url =
noReceiversWarningPanel.getModel().getConfigToLoad();
if (url != null) {
LogLog.debug("Initialiazing Log4j with " + url.toExternalForm());
new Thread(
new Runnable() {
public void run() {
try {
OptionConverter.selectAndConfigure(
url, null, LogManager.getLoggerRepository());
} catch (Exception e) {
LogLog.error("Error initializing Log4j", e);
}
LogManager.getLoggerRepository().getRootLogger()
.addAppender(handler);
receiversPanel.updateReceiverTreeInDispatchThread();
}
}).start();
}
}
}
});
}
/**
* Exits the application, ensuring Settings are saved.
*
*/
void exit() {
// TODO Ask the user if they want to save the settings via a dialog.
getSettingsManager().saveSettings();
shutdown();
}
void addWelcomePanel() {
getTabbedPane().addANewTab(
"Welcome", welcomePanel, new ImageIcon(ChainsawIcons.ABOUT),
"Welcome/Help");
}
void removeWelcomePanel() {
if (getTabbedPane().containsWelcomePanel()) {
getTabbedPane().remove(
getTabbedPane().getComponentAt(getTabbedPane().indexOfTab("Welcome")));
}
}
boolean isReceiverPanelVisible() {
return receiversPanel.isVisible();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ChainsawStatusBar getStatusBar() {
return statusBar;
}
void showApplicationPreferences() {
applicationPreferenceModelPanel.updateModel();
preferencesFrame.show();
}
void showAboutBox() {
if (aboutBox == null) {
aboutBox = new ChainsawAbout(this);
}
aboutBox.setVisible(true);
}
Map getPanels() {
Map m = new HashMap();
Set panelSet = getPanelMap().entrySet();
Iterator iter = panelSet.iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
m.put(
entry.getKey(),
new Boolean(((DockablePanel) entry.getValue()).isDocked()));
}
return m;
}
void displayPanel(String panelName, boolean display) {
Object o = getPanelMap().get(panelName);
if (o instanceof LogPanel) {
LogPanel p = (LogPanel) o;
int index = getTabbedPane().indexOfTab(panelName);
if ((index == -1) && display) {
getTabbedPane().addTab(panelName, p);
}
if ((index > -1) && !display) {
getTabbedPane().removeTabAt(index);
}
}
}
/**
* Shutsdown by ensuring the Appender gets a chance to close.
*/
private void shutdown() {
JWindow progress = new JWindow();
final ProgressPanel panel = new ProgressPanel(1, 3, "Shutting down");
progress.getContentPane().add(panel);
progress.pack();
Point p = new Point(getLocation());
p.move((int) getSize().getWidth() >> 1, (int) getSize().getHeight() >> 1);
progress.setLocation(p);
progress.setVisible(true);
Runnable runnable =
new Runnable() {
public void run() {
try {
int progress = 1;
final int delay = 25;
handler.close();
panel.setProgress(progress++);
Thread.sleep(delay);
PluginRegistry.stopAllPlugins();
panel.setProgress(progress++);
Thread.sleep(delay);
panel.setProgress(progress++);
Thread.sleep(delay);
} catch (Exception e) {
e.printStackTrace();
}
fireShutdownEvent();
performShutdownAction();
}
};
new Thread(runnable).start();
}
/**
* Ensures all the registered ShutdownListeners are notified.
*/
private void fireShutdownEvent() {
ShutdownListener[] listeners =
(ShutdownListener[]) shutdownListenerList.getListeners(
ShutdownListener.class);
for (int i = 0; i < listeners.length; i++) {
listeners[i].shuttingDown();
}
}
/**
* Configures LogUI's with an action to execute when the user requests to
* exit the application, the default action is to exit the VM. This Action is
* called AFTER all the ShutdownListeners have been notified
*
* @param shutdownAction
*/
public final void setShutdownAction(Action shutdownAction) {
this.shutdownAction = shutdownAction;
}
/**
* Using the current thread, calls the registed Shutdown action's
* actionPerformed(...) method.
*
*/
private void performShutdownAction() {
LogLog.debug("Calling the shutdown Action. Goodbye!");
shutdownAction.actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Shutting Down"));
}
/**
* Returns the currently selected LogPanel, if there is one, otherwise null
*
* @return
*/
LogPanel getCurrentLogPanel() {
Component selectedTab = getTabbedPane().getSelectedComponent();
if (selectedTab instanceof LogPanel) {
return (LogPanel) selectedTab;
} else {
// System.out.println(selectedTab);
}
return null;
}
/**
* @param b
*/
private void setStatusBarVisible(final boolean visible) {
LogLog.debug("Setting StatusBar to " + visible);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
statusBar.setVisible(visible);
}
});
}
boolean isStatusBarVisible() {
return statusBar.isVisible();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getActiveTabName() {
int index = getTabbedPane().getSelectedIndex();
if (index == -1) {
return null;
} else {
return getTabbedPane().getTitleAt(index);
}
}
/**
* Formats the individual elements of an LoggingEvent by ensuring that there
* are no null bits, replacing them with EMPTY_STRING
*
* @param v
* @return
*/
private Vector formatFields(Vector v) {
for (int i = 0; i < v.size(); i++) {
if (v.get(i) == null) {
v.set(i, ChainsawConstants.EMPTY_STRING);
}
}
return v;
}
/**
* Modify the saved Look And Feel - does not update the currently used Look
* And Feel
*
* @param lookAndFeelClassName
* The FQN of the LookAndFeel
*/
public void setLookAndFeel(String lookAndFeelClassName) {
this.lookAndFeelClassName = lookAndFeelClassName;
JOptionPane.showMessageDialog(
getContentPane(),
"Restart application for the new Look and Feel to take effect.",
"Look and Feel Updated", JOptionPane.INFORMATION_MESSAGE);
}
/**
* Changes the currently used Look And Feel of the App
*
* @param lookAndFeelClassName
* The FQN of the LookANdFeel
*/
private void applyLookAndFeel(String lookAndFeelClassName) {
if (
UIManager.getLookAndFeel().getClass().getName().equals(
lookAndFeelClassName)) {
LogLog.debug("No need to change L&F, already the same");
return;
}
LogLog.debug("Setting L&F -> " + lookAndFeelClassName);
try {
UIManager.setLookAndFeel(lookAndFeelClassName);
SwingUtilities.updateComponentTreeUI(this);
SwingUtilities.updateComponentTreeUI(preferencesFrame);
applicationPreferenceModelPanel.notifyOfLookAndFeelChange();
} catch (Exception e) {
LogLog.error("Failed to change L&F", e);
}
}
/**
* Causes the Welcome Panel to become visible, and shows the URL specified as
* it's contents
*
* @param url
* for content to show
*/
void showHelp(URL url) {
removeWelcomePanel();
addWelcomePanel();
// TODO ensure the Welcome Panel is the selected tab
getWelcomePanel().setURL(url);
}
/**
* DOCUMENT ME!
*
* @return
*/
private WelcomePanel getWelcomePanel() {
return welcomePanel;
}
/**
* DOCUMENT ME!
*
* @return
*/
public boolean isLogTreePanelVisible() {
if (getCurrentLogPanel() == null) {
return false;
}
return getCurrentLogPanel().isLogTreePanelVisible();
}
/*
* (non-Javadoc)
*
* @see org.apache.log4j.chainsaw.EventBatchListener#getInterestedIdentifier()
*/
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getInterestedIdentifier() {
// this instance is interested in ALL event batches, as we determine how to
// route things
return null;
}
// public Map getEntryMap() {
// return entryMap;
// public Map getScrollMap() {
// return scrollMap;
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map getPanelMap() {
return panelMap;
}
// public Map getLevelMap() {
// return levelMap;
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public SettingsManager getSettingsManager() {
return sm;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public List getFilterableColumns() {
return filterableColumns;
}
/**
* DOCUMENT ME!
*
* @param tbms
* DOCUMENT ME!
*/
public void setToolBarAndMenus(ChainsawToolBarAndMenus tbms) {
this.tbms = tbms;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ChainsawToolBarAndMenus getToolBarAndMenus() {
return tbms;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map getTableMap() {
return tableMap;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Map getTableModelMap() {
return tableModelMap;
}
/**
* DOCUMENT ME!
*
* @param tabbedPane
* DOCUMENT ME!
*/
public void setTabbedPane(ChainsawTabbedPane tabbedPane) {
this.tabbedPane = tabbedPane;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ChainsawTabbedPane getTabbedPane() {
return tabbedPane;
}
/**
* DOCUMENT ME!
*/
public void setupTutorial() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(0, getLocation().y);
double chainsawwidth = 0.7;
double tutorialwidth = 1 - chainsawwidth;
setSize((int) (screen.width * chainsawwidth), getSize().height);
invalidate();
validate();
Dimension size = getSize();
Point loc = getLocation();
tutorialFrame.setSize(
(int) (screen.width * tutorialwidth), size.height);
tutorialFrame.setLocation(loc.x + size.width, loc.y);
tutorialFrame.setVisible(true);
}
});
}
/**
* This class handles the recption of the Event batches and creates new
* LogPanels if the identifier is not in use otherwise it ignores the event
* batch.
*
* @author Paul Smith
* <psmith@apache.org>
*
*/
private class NewTabEventBatchReceiver implements EventBatchListener {
/**
* DOCUMENT ME!
*
* @param ident
* DOCUMENT ME!
* @param eventBatchEntrys
* DOCUMENT ME!
*/
public void receiveEventBatch(
final String ident, final List eventBatchEntrys) {
if (eventBatchEntrys.size() == 0) {
return;
}
EventContainer tableModel;
JSortTable table;
HashMap map = null;
if (!isGUIFullyInitialized) {
synchronized (initializationLock) {
while (!isGUIFullyInitialized) {
System.out.println(
"Wanting to add a row, but GUI not initialized, waiting...");
/**
* Lets wait 1 seconds and recheck.
*/
try {
initializationLock.wait(1000);
} catch (InterruptedException e) {
}
}
}
}
if (!getPanelMap().containsKey(ident)) {
final String eventType =
((ChainsawEventBatchEntry) eventBatchEntrys.get(0)).getEventType();
final LogPanel thisPanel =
new LogPanel(getStatusBar(), ident, eventType);
thisPanel.addEventCountListener(new TabIconHandler(ident));
PropertyChangeListener toolbarMenuUpdateListener =
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
tbms.stateChange();
}
};
thisPanel.addPropertyChangeListener(toolbarMenuUpdateListener);
thisPanel.getPreferenceModel().addPropertyChangeListener(
toolbarMenuUpdateListener);
thisPanel.addPropertyChangeListener(
"docked",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogPanel logPanel = (LogPanel) evt.getSource();
if (logPanel.isDocked()) {
getPanelMap().put(logPanel.getIdentifier(), logPanel);
getTabbedPane().addANewTab(
logPanel.getIdentifier(), logPanel, null);
} else {
getTabbedPane().remove(logPanel);
}
}
});
getTabbedPane().add(ident, thisPanel);
getPanelMap().put(ident, thisPanel);
getSettingsManager().addSettingsListener(thisPanel);
getSettingsManager().configure(thisPanel);
/**
* Let the new LogPanel receive this batch
*/
thisPanel.receiveEventBatch(ident, eventBatchEntrys);
/**
* Now add the panel as a batch listener so it can handle it's own
* batchs
*/
handler.addEventBatchListener(thisPanel);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
getTabbedPane().addANewTab(
ident, thisPanel, new ImageIcon(
ChainsawIcons.ANIM_RADIO_TOWER));
}
});
String msg = "added tab " + ident;
LogLog.debug(msg);
statusBar.setMessage(msg);
}
}
/*
* (non-Javadoc)
*
* @see org.apache.log4j.chainsaw.EventBatchListener#getInterestedIdentifier()
*/
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getInterestedIdentifier() {
// we are interested in all batches so we can detect new identifiers
return null;
}
}
class TabIconHandler implements EventCountListener {
private final String ident;
private int lastCount;
private int currentCount;
//the tabIconHandler is associated with a new tab, and a new tab always
//has new events
private boolean hasNewEvents = true;
ImageIcon NEW_EVENTS = new ImageIcon(ChainsawIcons.ANIM_RADIO_TOWER);
ImageIcon HAS_EVENTS = new ImageIcon(ChainsawIcons.INFO);
public TabIconHandler(final String ident) {
this.ident = ident;
new Thread(
new Runnable() {
public void run() {
while (true) {
//if this tab is active, remove the icon
if (
(getTabbedPane().getSelectedIndex() > -1)
&& (getTabbedPane().getSelectedIndex() == getTabbedPane()
.indexOfTab(
ident))) {
getTabbedPane().setIconAt(
getTabbedPane().indexOfTab(ident), null);
//reset fields so no icon will display
lastCount = currentCount;
hasNewEvents = false;
} else {
//don't process undocked tabs
if (getTabbedPane().indexOfTab(ident) > -1) {
//if the tab is not active and the counts don't match, set the
// new events icon
if (lastCount != currentCount) {
getTabbedPane().setIconAt(
getTabbedPane().indexOfTab(ident), NEW_EVENTS);
lastCount = currentCount;
hasNewEvents = true;
} else {
if (hasNewEvents) {
getTabbedPane().setIconAt(
getTabbedPane().indexOfTab(ident), HAS_EVENTS);
}
}
}
}
try {
Thread.sleep(handler.getQueueInterval() + 1000);
} catch (InterruptedException ie) {
}
}
}
}).start();
}
/**
* DOCUMENT ME!
*
* @param currentCount
* DOCUMENT ME!
* @param totalCount
* DOCUMENT ME!
*/
public void eventCountChanged(int currentCount, int totalCount) {
this.currentCount = currentCount;
}
}
/**
* @return Returns the applicationPreferenceModel.
*/
public final ApplicationPreferenceModel getApplicationPreferenceModel()
{
return applicationPreferenceModel;
}
}
|
package org.jaxen.dom4j;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jaxen.Navigator;
import org.jaxen.FunctionCallException;
import org.jaxen.UnsupportedAxisException;
import java.util.Iterator;
/**
* <p>
* Collect Jaxen's dom4j tests.
* </p>
*
* @author Elliotte Rusty Harold
* @version 1.1b4
*
*/
public class DOM4JTests extends TestCase {
public DOM4JTests(String name) {
super(name);
}
public static Test suite() {
TestSuite result = new TestSuite();
result.addTest(new TestSuite(DocumentNavigatorTest.class));
result.addTest(new TestSuite(XPathTest.class));
return result;
}
/**
* reported as JAXEN-104.
* @throws FunctionCallException
* @throws UnsupportedAxisException
*/
public void testConcurrentModification() throws FunctionCallException, UnsupportedAxisException
{
Navigator nav = new DocumentNavigator();
Object document = nav.getDocument("xml/testNamespaces.xml");
Iterator descendantOrSelfAxisIterator = nav.getDescendantOrSelfAxisIterator(document);
while (descendantOrSelfAxisIterator.hasNext()) {
Object node = descendantOrSelfAxisIterator.next();
Iterator namespaceAxisIterator = nav.getNamespaceAxisIterator(node);
while (namespaceAxisIterator.hasNext()) {
namespaceAxisIterator.next();
}
}
}
}
|
package com.ra4king.circuitsimulator.gui;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.ra4king.circuitsimulator.gui.ComponentManager.ComponentCreator;
import com.ra4king.circuitsimulator.gui.Connection.PortConnection;
import com.ra4king.circuitsimulator.gui.LinkWires.Wire;
import com.ra4king.circuitsimulator.gui.peers.ClockPeer;
import com.ra4king.circuitsimulator.gui.peers.PinPeer;
import com.ra4king.circuitsimulator.gui.peers.SubcircuitPeer;
import com.ra4king.circuitsimulator.simulator.Circuit;
import com.ra4king.circuitsimulator.simulator.ShortCircuitException;
import com.ra4king.circuitsimulator.simulator.Simulator;
import com.ra4king.circuitsimulator.simulator.WireValue;
import com.ra4king.circuitsimulator.simulator.WireValue.State;
import com.ra4king.circuitsimulator.simulator.components.Clock;
import com.ra4king.circuitsimulator.simulator.components.Pin;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
/**
* @author Roi Atalla
*/
public class CircuitManager {
private enum SelectingState {
IDLE,
HIGHLIGHT_DRAGGED,
ELEMENT_SELECTED,
CONNECTION_SELECTED,
ELEMENT_DRAGGED,
CONNECTION_DRAGGED,
PLACING_COMPONENT,
}
private SelectingState currentState = SelectingState.IDLE;
private final CircuitSimulator simulatorWindow;
private final ScrollPane canvasScrollPane;
private final CircuitBoard circuitBoard;
private ContextMenu menu;
private Point2D lastMousePosition = new Point2D(0, 0);
private Point2D lastMousePressed = new Point2D(0, 0);
private boolean isMouseInsideCanvas;
private boolean isDraggedHorizontally;
private boolean ctrlDown;
private Circuit dummyCircuit = new Circuit(new Simulator());
private ComponentPeer<?> potentialComponent;
private ComponentCreator componentCreator;
private Properties properties;
private Connection startConnection, endConnection;
private Map<GuiElement, Point2D> selectedElementsMap = new HashMap<>();
private String lastErrorMessage;
public CircuitManager(CircuitSimulator simulatorWindow, ScrollPane canvasScrollPane, Simulator simulator) {
this.simulatorWindow = simulatorWindow;
this.canvasScrollPane = canvasScrollPane;
circuitBoard = new CircuitBoard(this, simulator, simulatorWindow.getEditHistory());
getCanvas().setOnContextMenuRequested(event -> {
menu = new ContextMenu();
MenuItem delete = new MenuItem("Delete");
delete.setOnAction(event1 -> {
mayThrow(() -> circuitBoard.removeElements(selectedElementsMap.keySet()));
setSelectedElements(Collections.emptySet());
reset();
});
if(selectedElementsMap.size() == 0) {
Optional<ComponentPeer<?>> any = circuitBoard.getComponents().stream().filter(
component -> component.containsScreenCoord((int)event.getX(), (int)event.getY())).findAny();
if(any.isPresent()) {
menu.getItems().add(delete);
menu.getItems().addAll(any.get().getContextMenuItems(this));
}
} else if(selectedElementsMap.size() == 1) {
menu.getItems().add(delete);
menu.getItems().addAll(selectedElementsMap.keySet().iterator().next().getContextMenuItems(this));
} else {
menu.getItems().add(delete);
}
if(menu.getItems().size() > 0) {
menu.show(getCanvas(), event.getScreenX(), event.getScreenY());
}
});
}
private void reset() {
currentState = SelectingState.IDLE;
setSelectedElements(Collections.emptySet());
simulatorWindow.clearSelection();
dummyCircuit.clearComponents();
potentialComponent = null;
isDraggedHorizontally = false;
startConnection = null;
endConnection = null;
}
public void destroy() {
circuitBoard.destroy();
}
public CircuitSimulator getSimulatorWindow() {
return simulatorWindow;
}
public ScrollPane getCanvasScrollPane() {
return canvasScrollPane;
}
public Canvas getCanvas() {
return (Canvas)canvasScrollPane.getContent();
}
public Circuit getCircuit() {
return circuitBoard.getCircuit();
}
public CircuitBoard getCircuitBoard() {
return circuitBoard;
}
public String getCurrentError() {
if(circuitBoard.getLastException() != null) {
return lastErrorMessage;
}
return "";
}
public Point2D getLastMousePosition() {
return lastMousePosition;
}
public void setLastMousePosition(Point2D lastMousePosition) {
this.lastMousePosition = lastMousePosition;
}
public Set<GuiElement> getSelectedElements() {
return selectedElementsMap.keySet();
}
public void setSelectedElements(Set<GuiElement> elements) {
mayThrow(circuitBoard::finalizeMove);
selectedElementsMap = elements.stream().collect(
Collectors.toMap(peer -> peer,
peer -> new Point2D(peer.getX(),
peer.getY())));
updateSelectedProperties();
}
private Properties getCommonSelectedProperties() {
return selectedElementsMap.keySet().stream()
.filter(element -> element instanceof ComponentPeer<?>)
.map(element -> ((ComponentPeer<?>)element).getProperties())
.reduce(Properties::intersect).orElse(null);
}
private void updateSelectedProperties() {
long componentCount = selectedElementsMap.keySet().stream()
.filter(element -> element instanceof ComponentPeer<?>)
.count();
if(componentCount == 1) {
Optional<? extends ComponentPeer<?>> peer = selectedElementsMap
.keySet().stream()
.filter(element -> element instanceof ComponentPeer<?>)
.map(element -> ((ComponentPeer<?>)element))
.findAny();
peer.ifPresent(simulatorWindow::setProperties);
} else {
simulatorWindow.setProperties("Multiple selections", getCommonSelectedProperties());
}
}
public void modifiedSelection(ComponentCreator componentCreator, Properties properties) {
this.componentCreator = componentCreator;
this.properties = properties;
if(currentState != SelectingState.IDLE && currentState != SelectingState.PLACING_COMPONENT) {
reset();
}
if(componentCreator != null) {
currentState = SelectingState.PLACING_COMPONENT;
potentialComponent = componentCreator.createComponent(properties,
GuiUtils.getCircuitCoord(lastMousePosition.getX()),
GuiUtils.getCircuitCoord(lastMousePosition.getY()));
mayThrow(() -> dummyCircuit.addComponent(potentialComponent.getComponent()));
potentialComponent.setX(potentialComponent.getX() - potentialComponent.getWidth() / 2);
potentialComponent.setY(potentialComponent.getY() - potentialComponent.getHeight() / 2);
simulatorWindow.setProperties(potentialComponent);
return;
}
if(properties != null && !properties.isEmpty() && !selectedElementsMap.isEmpty()) {
Map<ComponentPeer<?>, ComponentPeer<?>> newComponents =
selectedElementsMap
.keySet().stream()
.filter(element -> element instanceof ComponentPeer<?>)
.map(element -> (ComponentPeer<?>)element)
.collect(Collectors.toMap(
component -> component,
component -> (ComponentPeer<?>)ComponentManager
.forClass(component.getClass())
.createComponent(
component.getProperties()
.mergeIfExists(properties),
component.getX(),
component.getY())));
newComponents.forEach((oldComponent, newComponent) ->
mayThrow(() -> circuitBoard.updateComponent(oldComponent, newComponent)));
setSelectedElements(Stream.concat(
selectedElementsMap.keySet().stream().filter(element -> !(element instanceof ComponentPeer<?>)),
newComponents.values().stream())
.collect(Collectors.toSet()));
return;
}
setSelectedElements(Collections.emptySet());
}
public void paint() {
GraphicsContext graphics = getCanvas().getGraphicsContext2D();
graphics.save();
graphics.setFont(Font.font("monospace", 13));
graphics.save();
graphics.setFill(Color.LIGHTGRAY);
graphics.fillRect(0, 0, getCanvas().getWidth(), getCanvas().getHeight());
graphics.setFill(Color.BLACK);
for(int i = 0; i < getCanvas().getWidth(); i += GuiUtils.BLOCK_SIZE) {
for(int j = 0; j < getCanvas().getHeight(); j += GuiUtils.BLOCK_SIZE) {
graphics.fillRect(i, j, 1, 1);
}
}
graphics.restore();
circuitBoard.paint(graphics);
switch(currentState) {
case IDLE:
case CONNECTION_SELECTED:
if(startConnection != null) {
graphics.save();
graphics.setLineWidth(2);
graphics.setStroke(Color.GREEN);
graphics.strokeOval(startConnection.getScreenX() - 2, startConnection.getScreenY() - 2, 10, 10);
if(endConnection != null) {
graphics.strokeOval(endConnection.getScreenX() - 2, endConnection.getScreenY() - 2, 10, 10);
}
if(startConnection instanceof PortConnection) {
PortConnection portConnection = (PortConnection)startConnection;
String name = portConnection.getName();
if(!name.isEmpty()) {
Text text = new Text(name);
text.setFont(graphics.getFont());
Bounds bounds = text.getLayoutBounds();
double x = startConnection.getScreenX() - bounds.getWidth() / 2 - 3;
double y = startConnection.getScreenY() + 30;
double width = bounds.getWidth() + 6;
double height = bounds.getHeight() + 3;
graphics.setLineWidth(1);
graphics.setStroke(Color.BLACK);
graphics.setFill(Color.ORANGE.brighter());
graphics.fillRect(x, y, width, height);
graphics.strokeRect(x, y, width, height);
graphics.strokeText(name, x + 3, y + height - 5);
}
}
graphics.restore();
}
break;
case CONNECTION_DRAGGED: {
graphics.save();
graphics.setLineWidth(2);
graphics.setStroke(Color.GREEN);
graphics.strokeOval(startConnection.getScreenX() - 2, startConnection.getScreenY() - 2, 10, 10);
if(endConnection != null) {
graphics.strokeOval(endConnection.getScreenX() - 2, endConnection.getScreenY() - 2, 10, 10);
}
int startX = startConnection.getScreenX() + startConnection.getScreenWidth() / 2;
int startY = startConnection.getScreenY() + startConnection.getScreenHeight() / 2;
int pointX = GuiUtils.getScreenCircuitCoord(lastMousePosition.getX());
int pointY = GuiUtils.getScreenCircuitCoord(lastMousePosition.getY());
graphics.setStroke(Color.BLACK);
if(isDraggedHorizontally) {
graphics.strokeLine(startX, startY, pointX, startY);
graphics.strokeLine(pointX, startY, pointX, pointY);
} else {
graphics.strokeLine(startX, startY, startX, pointY);
graphics.strokeLine(startX, pointY, pointX, pointY);
}
graphics.restore();
break;
}
case PLACING_COMPONENT: {
if(potentialComponent != null && isMouseInsideCanvas) {
graphics.save();
potentialComponent.paint(graphics, dummyCircuit.getTopLevelState());
graphics.restore();
for(Connection connection : potentialComponent.getConnections()) {
graphics.save();
connection.paint(graphics, dummyCircuit.getTopLevelState());
graphics.restore();
}
}
break;
}
case HIGHLIGHT_DRAGGED: {
double startX = lastMousePressed.getX() < lastMousePosition.getX()
? lastMousePressed.getX()
: lastMousePosition.getX();
double startY = lastMousePressed.getY() < lastMousePosition.getY()
? lastMousePressed.getY()
: lastMousePosition.getY();
double width = Math.abs(lastMousePosition.getX() - lastMousePressed.getX());
double height = Math.abs(lastMousePosition.getY() - lastMousePressed.getY());
graphics.setStroke(Color.GREEN.darker());
graphics.strokeRect(startX, startY, width, height);
break;
}
}
for(GuiElement selectedElement : selectedElementsMap.keySet()) {
graphics.setStroke(Color.RED);
if(selectedElement instanceof Wire) {
graphics.strokeRect(selectedElement.getScreenX() - 1, selectedElement.getScreenY() - 1,
selectedElement.getScreenWidth() + 2, selectedElement.getScreenHeight() + 2);
} else {
GuiUtils.drawShape(graphics::strokeRect, selectedElement);
}
}
graphics.restore();
}
private interface ThrowableRunnable {
void run() throws Exception;
}
private void mayThrow(ThrowableRunnable runnable) {
try {
runnable.run();
} catch(Exception exc) {
// exc.printStackTrace();
lastErrorMessage = exc instanceof ShortCircuitException ? "Short circuit detected" : exc.getMessage();
}
}
public void keyPressed(KeyEvent e) {
switch(e.getCode()) {
case CONTROL:
ctrlDown = true;
break;
case NUMPAD0:
case NUMPAD1:
case DIGIT0:
case DIGIT1:
int value = e.getText().charAt(0) - '0';
GuiElement selectedElem;
if(selectedElementsMap.size() == 1
&& (selectedElem = selectedElementsMap.keySet().iterator().next()) instanceof PinPeer
&& ((PinPeer)selectedElem).isInput()) {
PinPeer selectedPin = (PinPeer)selectedElem;
WireValue currentValue =
new WireValue(circuitBoard.getCurrentState()
.getLastPushedValue(
selectedPin.getComponent().getPort(Pin.PORT)));
for(int i = currentValue.getBitSize() - 1; i > 0; i
currentValue.setBit(i, currentValue.getBit(i - 1));
}
currentValue.setBit(0, value == 1 ? State.ONE : State.ZERO);
selectedPin.getComponent().setValue(circuitBoard.getCurrentState(), currentValue);
mayThrow(circuitBoard::runSim);
}
break;
case BACK_SPACE:
case DELETE:
mayThrow(() -> circuitBoard.removeElements(selectedElementsMap.keySet()));
case ESCAPE:
if(currentState == SelectingState.ELEMENT_DRAGGED) {
mayThrow(() -> circuitBoard.moveElements(0, 0));
}
reset();
break;
}
}
public void keyReleased(KeyEvent e) {
switch(e.getCode()) {
case CONTROL:
ctrlDown = false;
break;
}
}
public void mousePressed(MouseEvent e) {
if(menu != null) {
menu.hide();
}
if(e.getButton() != MouseButton.PRIMARY) {
return;
}
lastMousePosition = new Point2D(e.getX(), e.getY());
lastMousePressed = new Point2D(e.getX(), e.getY());
System.out.println("Mouse Pressed before: " + currentState);
switch(currentState) {
case ELEMENT_DRAGGED:
case CONNECTION_SELECTED:
case CONNECTION_DRAGGED:
case HIGHLIGHT_DRAGGED:
throw new IllegalStateException("How?!");
case IDLE:
case ELEMENT_SELECTED:
if(startConnection != null) {
currentState = SelectingState.CONNECTION_SELECTED;
} else {
Optional<GuiElement> clickedComponent =
Stream.concat(Stream.concat(circuitBoard.getComponents().stream(),
circuitBoard.getLinks()
.stream()
.flatMap(link -> link.getWires().stream())),
getSelectedElements().stream())
.filter(peer -> peer.containsScreenCoord((int)e.getX(), (int)e.getY()))
.findAny();
if(clickedComponent.isPresent()) {
GuiElement selectedElement = clickedComponent.get();
if(e.getClickCount() == 2 && selectedElement instanceof SubcircuitPeer) {
reset();
((SubcircuitPeer)selectedElement).switchToSubcircuit(this);
} else if(ctrlDown) {
Set<GuiElement> elements = new HashSet<>(getSelectedElements());
elements.add(selectedElement);
setSelectedElements(elements);
} else if(!getSelectedElements().contains(selectedElement)) {
setSelectedElements(Collections.singleton(selectedElement));
}
if(currentState == SelectingState.IDLE) {
currentState = SelectingState.ELEMENT_SELECTED;
}
} else if(!ctrlDown) {
reset();
}
}
break;
case PLACING_COMPONENT:
ComponentPeer<?> newComponent = componentCreator.createComponent(properties,
potentialComponent.getX(),
potentialComponent.getY());
mayThrow(() -> circuitBoard.addComponent(newComponent));
reset();
setSelectedElements(Collections.singleton(newComponent));
currentState = SelectingState.PLACING_COMPONENT;
break;
}
System.out.println("Mouse Pressed after: " + currentState);
}
public void mouseReleased(MouseEvent e) {
if(e.getButton() != MouseButton.PRIMARY) {
return;
}
lastMousePosition = new Point2D(e.getX(), e.getY());
System.out.println("Mouse Released before: " + currentState);
switch(currentState) {
case IDLE:
case ELEMENT_SELECTED:
Optional<GuiElement> clickedComponent =
Stream.concat(circuitBoard.getComponents().stream(),
circuitBoard.getLinks()
.stream()
.flatMap(link -> link.getWires().stream()))
.filter(peer -> peer.containsScreenCoord((int)e.getX(), (int)e.getY()))
.findAny();
if(clickedComponent.isPresent()) {
GuiElement selectedElement = clickedComponent.get();
if(circuitBoard.getCurrentState() == getCircuit().getTopLevelState() &&
selectedElement instanceof PinPeer && ((PinPeer)selectedElement).isInput()) {
((PinPeer)selectedElement).clicked(circuitBoard.getCurrentState(),
(int)lastMousePosition.getX(),
(int)lastMousePosition.getY());
mayThrow(circuitBoard::runSim);
} else if(selectedElement instanceof ClockPeer) {
Clock.tick();
}
}
case ELEMENT_DRAGGED:
mayThrow(circuitBoard::finalizeMove);
currentState = SelectingState.IDLE;
break;
case CONNECTION_SELECTED: {
Set<Connection> connections = circuitBoard.getConnections(startConnection.getX(),
startConnection.getY());
setSelectedElements(Stream.concat(ctrlDown ? getSelectedElements().stream() : Stream.empty(),
connections.stream().map(Connection::getParent))
.collect(Collectors.toSet()));
currentState = SelectingState.IDLE;
break;
}
case CONNECTION_DRAGGED: {
int endMidX = endConnection == null
? GuiUtils.getCircuitCoord(lastMousePosition.getX())
: endConnection.getX();
int endMidY = endConnection == null
? GuiUtils.getCircuitCoord(lastMousePosition.getY())
: endConnection.getY();
if(endMidX - startConnection.getX() != 0 && endMidY - startConnection.getY() != 0) {
simulatorWindow.getEditHistory().beginGroup();
if(isDraggedHorizontally) {
mayThrow(() -> circuitBoard.addWire(startConnection.getX(), startConnection.getY(),
endMidX - startConnection.getX(), true));
mayThrow(() -> circuitBoard.addWire(endMidX, startConnection.getY(),
endMidY - startConnection.getY(),
false));
} else {
mayThrow(() -> circuitBoard.addWire(startConnection.getX(), startConnection.getY(),
endMidY - startConnection.getY(), false));
mayThrow(() -> circuitBoard.addWire(startConnection.getX(), endMidY,
endMidX - startConnection.getX(), true));
}
simulatorWindow.getEditHistory().endGroup();
} else if(endMidX - startConnection.getX() != 0) {
mayThrow(() -> circuitBoard.addWire(startConnection.getX(), startConnection.getY(),
endMidX - startConnection.getX(), true));
} else if(endMidY - startConnection.getY() != 0) {
mayThrow(() -> circuitBoard.addWire(endMidX, startConnection.getY(),
endMidY - startConnection.getY(),
false));
} else {
Set<Connection> connections = circuitBoard.getConnections(startConnection.getX(),
startConnection.getY());
setSelectedElements(Stream.concat(ctrlDown ? getSelectedElements().stream() : Stream.empty(),
connections.stream().map(Connection::getParent))
.collect(Collectors.toSet()));
}
currentState = SelectingState.IDLE;
startConnection = null;
endConnection = null;
break;
}
case HIGHLIGHT_DRAGGED:
case PLACING_COMPONENT:
currentState = SelectingState.IDLE;
break;
}
System.out.println("Mouse Released after: " + currentState);
mouseMoved(e);
}
public void mouseDragged(MouseEvent e) {
if(e.getButton() != MouseButton.PRIMARY) {
return;
}
Point2D prevMousePosition = lastMousePosition;
lastMousePosition = new Point2D(e.getX(), e.getY());
System.out.println("Mouse Dragged before: " + currentState);
switch(currentState) {
case IDLE:
case HIGHLIGHT_DRAGGED:
currentState = SelectingState.HIGHLIGHT_DRAGGED;
int startX = (int)(lastMousePressed.getX() < lastMousePosition.getX() ? lastMousePressed.getX()
: lastMousePosition.getX());
int startY = (int)(lastMousePressed.getY() < lastMousePosition.getY() ? lastMousePressed.getY()
: lastMousePosition.getY());
int width = (int)Math.abs(lastMousePosition.getX() - lastMousePressed.getX());
int height = (int)Math.abs(lastMousePosition.getY() - lastMousePressed.getY());
if(!ctrlDown) {
selectedElementsMap.clear();
mayThrow(circuitBoard::finalizeMove);
}
setSelectedElements(Stream.concat(circuitBoard.getComponents().stream(),
circuitBoard.getLinks().stream()
.flatMap(link -> link.getWires().stream()))
.filter(peer -> peer.isWithinScreenCoord(startX, startY, width, height))
.collect(Collectors.toSet()));
break;
case ELEMENT_SELECTED:
case ELEMENT_DRAGGED:
case PLACING_COMPONENT:
currentState = SelectingState.ELEMENT_DRAGGED;
int dx = GuiUtils.getCircuitCoord(lastMousePosition.getX() - lastMousePressed.getX());
int dy = GuiUtils.getCircuitCoord(lastMousePosition.getY() - lastMousePressed.getY());
if(!circuitBoard.isMoving()) {
mayThrow(() -> circuitBoard.initMove(getSelectedElements()));
}
mayThrow(() -> circuitBoard.moveElements(dx, dy));
break;
case CONNECTION_SELECTED:
case CONNECTION_DRAGGED:
currentState = SelectingState.CONNECTION_DRAGGED;
if(startConnection != null) {
int currDiffX = GuiUtils.getCircuitCoord(e.getX()) - startConnection.getX();
int prevDiffX = GuiUtils.getCircuitCoord(prevMousePosition.getX()) - startConnection.getX();
int currDiffY = GuiUtils.getCircuitCoord(e.getY()) - startConnection.getY();
int prevDiffY = GuiUtils.getCircuitCoord(prevMousePosition.getY()) - startConnection.getY();
if(currDiffX == 0 || prevDiffX == 0 ||
currDiffX / Math.abs(currDiffX) != prevDiffX / Math.abs(prevDiffX)) {
isDraggedHorizontally = false;
}
if(currDiffY == 0 || prevDiffY == 0 ||
currDiffY / Math.abs(currDiffY) != prevDiffY / Math.abs(prevDiffY)) {
isDraggedHorizontally = true;
}
}
endConnection = circuitBoard.findConnection(GuiUtils.getCircuitCoord(lastMousePosition.getX()),
GuiUtils.getCircuitCoord(lastMousePosition.getY()));
break;
}
System.out.println("Mouse Dragged after: " + currentState);
mouseMoved(e);
}
public void mouseMoved(MouseEvent e) {
lastMousePosition = new Point2D(e.getX(), e.getY());
if(potentialComponent != null) {
potentialComponent.setX(GuiUtils.getCircuitCoord(e.getX()) - potentialComponent.getWidth() / 2);
potentialComponent.setY(GuiUtils.getCircuitCoord(e.getY()) - potentialComponent.getHeight() / 2);
}
if(currentState != SelectingState.CONNECTION_DRAGGED) {
Set<Connection> selectedConns = circuitBoard.getConnections(GuiUtils.getCircuitCoord(e.getX()),
GuiUtils.getCircuitCoord(e.getY()));
Connection selected = null;
for(Connection connection : selectedConns) {
if(connection instanceof PortConnection) {
selected = connection;
break;
}
}
if(selected == null && !selectedConns.isEmpty()) {
selected = selectedConns.iterator().next();
}
startConnection = selected;
}
}
public void mouseEntered(MouseEvent e) {
isMouseInsideCanvas = true;
}
public void mouseExited(MouseEvent e) {
isMouseInsideCanvas = false;
ctrlDown = false;
}
}
|
package com.redhat.ceylon.compiler.js;
import static java.lang.Character.toUpperCase;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.*;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.*;
public class GenerateJsVisitor extends Visitor
implements NaturalVisitor {
private boolean sequencedParameter=false;
private int tmpvarCount = 0;
private final class SuperVisitor extends Visitor {
private final List<Declaration> decs;
private SuperVisitor(List<Declaration> decs) {
this.decs = decs;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Super) {
decs.add(qe.getDeclaration());
}
super.visit(qe);
}
public void visit(com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassOrInterface qe) {
//don't recurse
}
}
private final class OuterVisitor extends Visitor {
boolean found = false;
private Declaration dec;
private OuterVisitor(Declaration dec) {
this.dec = dec;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Outer ||
qe.getPrimary() instanceof This) {
if ( qe.getDeclaration().equals(dec) ) {
found = true;
}
}
super.visit(qe);
}
}
private final Writer out;
private boolean prototypeStyle;
private CompilationUnit root;
@Override
public void handleException(Exception e, Node that) {
that.addUnexpectedError(that.getMessage(e, this));
}
public GenerateJsVisitor(Writer out, boolean prototypeStyle) {
this.out = out;
this.prototypeStyle=prototypeStyle;
}
/** Print generated code to the Writer specified at creation time.
* @param code The main code
* @param codez Optional additional strings to print after the main code. */
private void out(String code, String... codez) {
try {
out.write(code);
for (String s : codez) {
out.write(s);
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
int indentLevel = 0;
/** Print out 4 spaces per indentation level. */
private void indent() {
for (int i=0;i<indentLevel;i++) {
out(" ");
}
}
/** Prints a newline and the necessary spaces to reach current indentation level. */
private void endLine() {
out("\n");
indent();
}
/** Increases indentation level, prints opening brace, newline and necessary spaces to reach new indentation level. */
private void beginBlock() {
indentLevel++;
out("{");
endLine();
}
/** Decreases indentation level, prints closing brace in new line and necessary spaces to reach new indentation level. */
private void endBlock() {
endBlock(true);
}
private void endBlock(boolean newline) {
indentLevel
endLine();
out("}");
if (newline) {
endLine();
}
}
/** Prints source code location in the form "at [filename] ([location])" */
private void location(Node node) {
out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")");
}
@Override
public void visit(CompilationUnit that) {
root = that;
Module clm = that.getUnit().getPackage().getModule()
.getLanguageModule();
require(clm.getPackage(clm.getNameAsString()));
super.visit(that);
}
@Override
public void visit(Import that) {
require(that.getImportList().getImportedPackage());
}
private void require(Package pkg) {
out("var ");
packageAlias(pkg);
out("=require('");
scriptPath(pkg);
out("');");
endLine();
}
private void packageAlias(Package pkg) {
out(packageAliasString(pkg));
}
private String packageAliasString(Package pkg) {
StringBuilder sb = new StringBuilder("$$$");
//out(pkg.getNameAsString().replace('.', '$'));
for (String s: pkg.getName()) {
sb.append(s.substring(0,1));
}
sb.append(pkg.getQualifiedNameString().length());
return sb.toString();
}
private void scriptPath(Package pkg) {
out(pkg.getModule().getNameAsString().replace('.', '/'));
out("/");
if (!pkg.getModule().isDefault()) {
out(pkg.getModule().getVersion());
out("/");
}
out(pkg.getNameAsString());
}
@Override
public void visit(Parameter that) {
memberName(that.getDeclarationModel());
}
@Override
public void visit(ParameterList that) {
out("(");
boolean first=true;
for (Parameter param: that.getParameters()) {
if (!first) out(",");
memberName(param.getDeclarationModel());
first = false;
}
out(")");
}
private void visitStatements(List<Statement> statements, boolean endLastLine) {
for (int i=0; i<statements.size(); i++) {
Statement s = statements.get(i);
s.visit(this);
if ((endLastLine || (i<statements.size()-1)) &&
s instanceof ExecutableStatement) {
endLine();
}
}
}
@Override
public void visit(Body that) {
visitStatements(that.getStatements(), true);
}
@Override
public void visit(Block that) {
List<Statement> stmnts = that.getStatements();
if (stmnts.isEmpty()) {
out("{}");
endLine();
}
else {
beginBlock();
initSelf(that);
visitStatements(stmnts, false);
endBlock();
}
}
private void initSelf(Block block) {
if ((prototypeOwner!=null) && (block.getScope() instanceof MethodOrValue)) {
/*out("var ");
self();
out("=this;");
endLine();*/
out("var ");
self(prototypeOwner);
out("=this;");
endLine();
}
}
private void comment(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration that) {
endLine();
out("//", that.getNodeType(), " ", that.getDeclarationModel().getName());
location(that);
endLine();
}
private void var(Declaration d) {
out("var ");
memberName(d);
out("=");
}
private void share(Declaration d) {
if (isCaptured(d) && !(prototypeStyle && d.isClassOrInterfaceMember())) {
outerSelf(d);
out(".");
memberName(d);
out("=");
memberName(d);
out(";");
endLine();
}
}
@Override
public void visit(ClassDeclaration that) {
Class d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
memberName(dec);
out(";");
endLine();
share(d);
}
@Override
public void visit(InterfaceDeclaration that) {
Interface d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
out(";");
share(d);
}
private void function() {
out("function ");
}
private void addInterfaceToPrototype(ClassOrInterface type, InterfaceDefinition interfaceDef) {
interfaceDefinition(interfaceDef);
Interface d = interfaceDef.getDeclarationModel();
out("$proto$.", memberNameString(d, false), "=", d.getName(), ";");
endLine();
}
@Override
public void visit(InterfaceDefinition that) {
if (!(prototypeStyle && that.getDeclarationModel().isClassOrInterfaceMember())) {
interfaceDefinition(that);
}
}
private void interfaceDefinition(InterfaceDefinition that) {
Interface d = that.getDeclarationModel();
comment(that);
function();
out(d.getName(), "(");
self(d);
out(")");
beginBlock();
//declareSelf(d);
referenceOuter(d);
that.getInterfaceBody().visit(this);
//returnSelf(d);
endBlock();
share(d);
addTypeInfo(that);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
addToPrototype(d, that.getInterfaceBody().getStatements());
}
/** Add a comment to the generated code with info about the type parameters. */
private void comment(TypeParameter tp) {
out("<");
if (tp.isCovariant()) {
out("out ");
} else if (tp.isContravariant()) {
out("in ");
}
out(tp.getQualifiedNameString());
for (TypeParameter st : tp.getTypeParameters()) {
comment(st);
}
out("> ");
}
/** Add a comment to the generated code with info about the produced type parameters. */
private void comment(ProducedType pt) {
out("<");
out(pt.getProducedTypeQualifiedName());
//This is useful to iterate into the types of this type
//but for comment it's unnecessary
/*for (ProducedType spt : pt.getTypeArgumentList()) {
comment(spt);
}*/
out("> ");
}
private void addClassToPrototype(ClassOrInterface type, ClassDefinition classDef) {
classDefinition(classDef);
Class d = classDef.getDeclarationModel();
out("$proto$.", memberNameString(d, false), "=", d.getName(), ";");
endLine();
}
@Override
public void visit(ClassDefinition that) {
if (!(prototypeStyle && that.getDeclarationModel().isClassOrInterfaceMember())) {
classDefinition(that);
}
}
private void classDefinition(ClassDefinition that) {
Class d = that.getDeclarationModel();
comment(that);
function();
out(d.getName(), "(");
for (Parameter p: that.getParameterList().getParameters()) {
p.visit(this);
out(", ");
}
self(d);
out(")");
beginBlock();
if (!d.getTypeParameters().isEmpty()) {
//out(",");
//selfTypeParameters(d);
out("/* REIFIED GENERICS SOON! ");
for (TypeParameter tp : d.getTypeParameters()) {
comment(tp);
}
out("*/");
endLine();
}
declareSelf(d);
referenceOuter(d);
initParameters(that.getParameterList(), d);
callSuperclass(that.getExtendedType(), d, that);
copySuperMembers(that.getExtendedType(), that.getClassBody(), d);
callInterfaces(that.getSatisfiedTypes(), d, that);
that.getClassBody().visit(this);
returnSelf(d);
endBlock();
share(d);
addTypeInfo(that);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
addToPrototype(d, that.getClassBody().getStatements());
}
private void referenceOuter(TypeDeclaration d) {
if (prototypeStyle && d.isClassOrInterfaceMember()) {
self(d);
out(".");
outerSelf(d);
out("=this;");
endLine();
}
}
private void copySuperMembers(ExtendedType extType, ClassBody body, Class d) {
if (!prototypeStyle) {
String parentName = "";
if (extType != null) {
TypeDeclaration parentTypeDecl = extType.getType().getDeclarationModel();
if (declaredInCL(parentTypeDecl)) {
return;
}
parentName = parentTypeDecl.getName();
}
final List<Declaration> decs = new ArrayList<Declaration>();
new SuperVisitor(decs).visit(body);
for (Declaration dec: decs) {
if (dec instanceof Value) {
superGetterRef(dec,d,parentName);
if (((Value) dec).isVariable()) {
superSetterRef(dec,d,parentName);
}
}
else if (dec instanceof Getter) {
superGetterRef(dec,d,parentName);
if (((Getter) dec).isVariable()) {
superSetterRef(dec,d,parentName);
}
}
else {
superRef(dec,d,parentName);
}
}
}
}
private void callSuperclass(ExtendedType extendedType, Class d, Node that) {
if (extendedType!=null) {
qualify(that, extendedType.getType().getDeclarationModel());
memberName(extendedType.getType().getDeclarationModel());
out("(");
for (PositionalArgument arg: extendedType.getInvocationExpression()
.getPositionalArgumentList().getPositionalArguments()) {
arg.visit(this);
out(",");
}
self(d);
out(")");
out(";");
endLine();
}
}
private void callInterfaces(SatisfiedTypes satisfiedTypes, Class d, Node that) {
if (satisfiedTypes!=null)
for (SimpleType st: satisfiedTypes.getTypes()) {
qualify(that, st.getDeclarationModel());
memberName(st.getDeclarationModel());
out("(");
self(d);
out(")");
out(";");
endLine();
}
}
private void addTypeInfo(
com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration type) {
ExtendedType extendedType = null;
SatisfiedTypes satisfiedTypes = null;
if (type instanceof ClassDefinition) {
ClassDefinition classDef = (ClassDefinition) type;
extendedType = classDef.getExtendedType();
satisfiedTypes = classDef.getSatisfiedTypes();
} else if (type instanceof InterfaceDefinition) {
satisfiedTypes = ((InterfaceDefinition) type).getSatisfiedTypes();
} else if (type instanceof ObjectDefinition) {
ObjectDefinition objectDef = (ObjectDefinition) type;
extendedType = objectDef.getExtendedType();
satisfiedTypes = objectDef.getSatisfiedTypes();
}
clAlias();
out(".initType(", type.getDeclarationModel().getName(), ",'",
type.getDeclarationModel().getQualifiedNameString(), "'");
if (extendedType != null) {
out(",", constructorFunctionName(extendedType.getType()));
} else if (!(type instanceof InterfaceDefinition)) {
out(",");
clAlias();
out(".IdentifiableObject");
}
if (satisfiedTypes != null) {
for (SimpleType satType : satisfiedTypes.getTypes()) {
out(",", constructorFunctionName(satType));
}
}
out(");");
endLine();
}
private String constructorFunctionName(SimpleType type) {
String constr = qualifiedPath(type, type.getDeclarationModel());
if (constr.length() > 0) {
constr += '.';
}
constr += type.getDeclarationModel().getName();
return constr;
}
private void addToPrototype(ClassOrInterface d, List<Statement> statements) {
if (prototypeStyle && !statements.isEmpty()) {
out(";(function($proto$)");
beginBlock();
for (Statement s: statements) {
addToPrototype(d, s);
}
endBlock(false);
out(")(", d.getName(), ".$$.prototype);");
endLine();
}
}
private ClassOrInterface prototypeOwner;
private void addToPrototype(ClassOrInterface d, Statement s) {
ClassOrInterface oldPrototypeOwner = prototypeOwner;
prototypeOwner = d;
if (s instanceof MethodDefinition) {
addMethodToPrototype(d, (MethodDefinition)s);
} else if (s instanceof AttributeGetterDefinition) {
addGetterToPrototype(d, (AttributeGetterDefinition)s);
} else if (s instanceof AttributeSetterDefinition) {
addSetterToPrototype(d, (AttributeSetterDefinition)s);
} else if (s instanceof AttributeDeclaration) {
addGetterAndSetterToPrototype(d, (AttributeDeclaration)s);
} else if (s instanceof ClassDefinition) {
addClassToPrototype(d, (ClassDefinition) s);
} else if (s instanceof InterfaceDefinition) {
addInterfaceToPrototype(d, (InterfaceDefinition) s);
} else if (s instanceof ObjectDefinition) {
addObjectToPrototype(d, (ObjectDefinition) s);
}
prototypeOwner = oldPrototypeOwner;
}
private void declareSelf(ClassOrInterface d) {
out("if (");
self(d);
out("===undefined)");
self(d);
out("=new ");
if (prototypeStyle && d.isClassOrInterfaceMember()) {
out("this.");
}
out(memberNameString(d, false), ".$$;");
endLine();
/*out("var ");
self(d);
out("=");
self();
out(";");
endLine();*/
}
private void instantiateSelf(ClassOrInterface d) {
out("var ");
self(d);
out("=new ");
if (prototypeStyle && d.isClassOrInterfaceMember()) {
out("this.");
}
memberName(d);
out(".$$;");
endLine();
}
private void returnSelf(ClassOrInterface d) {
out("return ");
self(d);
out(";");
}
private void copyMembersToPrototype(SimpleType that, Declaration d) {
String thatName = that.getDeclarationModel().getName();
String path = qualifiedPath(that, that.getDeclarationModel());
String suffix = null;
if (!((d instanceof Interface)
|| (that.getDeclarationModel() instanceof Interface))) {
suffix = path + '$' + thatName + '$';
}
if (path.length() > 0) {
path += '.';
}
copyMembersToPrototype(path+thatName, d, suffix);
}
private void copyMembersToPrototype(String from, Declaration d, String suffix) {
clAlias();
out(".inheritProto(", d.getName(), ",", from);
if ((suffix != null) && (suffix.length() > 0)) {
out(",'", suffix, "'");
}
out(");");
endLine();
}
private void copySuperclassPrototype(ExtendedType that, Declaration d) {
if (that==null) {
String suffix = (d instanceof Interface) ? null : "$$$cl15$IdentifiableObject$";
copyMembersToPrototype("$$$cl15.IdentifiableObject", d, suffix);
}
else if (prototypeStyle || declaredInCL(that.getType().getDeclarationModel())) {
copyMembersToPrototype(that.getType(), d);
}
}
private void copyInterfacePrototypes(SatisfiedTypes that, Declaration d) {
if (that!=null) {
for (Tree.SimpleType st: that.getTypes()) {
if (prototypeStyle || declaredInCL(st.getDeclarationModel())) {
copyMembersToPrototype(st, d);
}
}
}
}
private void addObjectToPrototype(ClassOrInterface type, ObjectDefinition objDef) {
objectDefinition(objDef);
Value d = objDef.getDeclarationModel();
out("$proto$.", memberNameString(d, false), "=", d.getName(), ";");
endLine();
}
@Override
public void visit(ObjectDefinition that) {
Value d = that.getDeclarationModel();
if (!(prototypeStyle && d.isClassOrInterfaceMember())) {
objectDefinition(that);
} else {
String name = memberNameString(d, false);
comment(that);
outerSelf(d);
out(".o$", name, "=");
outerSelf(d);
out(".", name, "();");
endLine();
}
}
private void objectDefinition(ObjectDefinition that) {
Value d = that.getDeclarationModel();
boolean addToPrototype = prototypeStyle && d.isClassOrInterfaceMember();
Class c = (Class) d.getTypeDeclaration();
comment(that);
function();
out(d.getName(), "()");
beginBlock();
instantiateSelf(c);
referenceOuter(c);
callSuperclass(that.getExtendedType(), c, that);
copySuperMembers(that.getExtendedType(), that.getClassBody(), c);
callInterfaces(that.getSatisfiedTypes(), c, that);
that.getClassBody().visit(this);
returnSelf(c);
indentLevel
endLine();
out("}");
endLine();
addTypeInfo(that);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(),d);
if (!addToPrototype) {
out("var o$", memberNameString(d, false), "=",
d.getName(), "(new ", d.getName(), ".$$);");
endLine();
}
if (addToPrototype) {
out("$proto$.", getter(d), "=");
} else if (d.isShared()) {
outerSelf(d);
out(".", getter(d), "=");
}
function();
out(getter(d), "()");
beginBlock();
out("return ");
if (addToPrototype) {
out("this.");
}
out("o$", memberNameString(d, false), ";");
endBlock();
addToPrototype(c, that.getClassBody().getStatements());
}
private void superRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".");
memberName(d);
out("$", parent, "$=");
self(sub);
out(".");
memberName(d);
out(";");
endLine();
}
private void superGetterRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".", getter(d), "$", parent, "$=");
self(sub);
out(".", getter(d), ";");
endLine();
}
private void superSetterRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".", setter(d), "$", parent, "$=");
self(sub);
out(".", setter(d), ";");
endLine();
}
@Override
public void visit(MethodDeclaration that) {}
@Override
public void visit(MethodDefinition that) {
Method d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
memberName(d);
//TODO: if there are multiple parameter lists
// do the inner function declarations
ParameterList paramList = that.getParameterLists().get(0);
paramList.visit(this);
beginBlock();
initSelf(that.getBlock());
initParameters(paramList, null);
visitStatements(that.getBlock().getStatements(), false);
endBlock();
share(d);
}
private void initParameters(ParameterList params, TypeDeclaration typeDecl) {
for (Parameter param : params.getParameters()) {
String paramName = memberNameString(param.getDeclarationModel(), false);
if (param.getDefaultArgument() != null) {
out("if(", paramName, "===undefined){", paramName, "=");
param.getDefaultArgument().getSpecifierExpression().getExpression().visit(this);
out("}");
endLine();
}
if ((typeDecl != null) && param.getDeclarationModel().isCaptured()) {
self(typeDecl);
out(".", paramName, "=", paramName, ";");
endLine();
}
}
}
private void addMethodToPrototype(Declaration outer,
MethodDefinition that) {
Method d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$proto$.");
memberName(d);
out("=");
function();
memberName(d);
//TODO: if there are multiple parameter lists
// do the inner function declarations
super.visit(that);
}
@Override
public void visit(AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(getter(d), "()");
super.visit(that);
shareGetter(d);
}
private void addGetterToPrototype(Declaration outer,
AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$proto$.", getter(d), "=");
function();
out(getter(d), "()");
super.visit(that);
}
private void shareGetter(MethodOrValue d) {
if (isCaptured(d)) {
outerSelf(d);
out(".", getter(d), "=", getter(d), ";");
endLine();
}
}
@Override
public void visit(AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(setter(d), "(");
memberName(d);
out(")");
super.visit(that);
shareSetter(d);
}
private void addSetterToPrototype(Declaration outer,
AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (!prototypeStyle || !d.isClassOrInterfaceMember()) return;
comment(that);
out("$proto$.", setter(d), "=");
function();
out(setter(d), "(");
memberName(d);
out(")");
super.visit(that);
}
private boolean isCaptured(Declaration d) {
if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures
if (d.isShared() || d.isCaptured() ) {
return true;
}
else {
OuterVisitor ov = new OuterVisitor(d);
ov.visit(root);
return ov.found;
}
}
else {
return false;
}
}
private void shareSetter(MethodOrValue d) {
if (isCaptured(d)) {
outerSelf(d);
out(".", setter(d), "=", setter(d), ";");
endLine();
}
}
@Override
public void visit(AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!d.isFormal()) {
comment(that);
if (prototypeStyle&&d.isClassOrInterfaceMember()) {
if (that.getSpecifierOrInitializerExpression()!=null) {
outerSelf(d);
out(".");
memberName(d);
out("=");
super.visit(that);
out(";");
endLine();
}
}
else {
out("var $", d.getName());
if (that.getSpecifierOrInitializerExpression()!=null) {
out("=");
}
super.visit(that);
out(";");
endLine();
function();
out(getter(d));
out("()");
beginBlock();
out("return $", d.getName(), ";");
endBlock();
shareGetter(d);
if (d.isVariable()) {
function();
out(setter(d), "(", d.getName(), ")");
beginBlock();
out("$", d.getName(), "=", d.getName(), "; return ", d.getName(), ";");
endBlock();
shareSetter(d);
}
}
}
}
private void addGetterAndSetterToPrototype(Declaration outer,
AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!prototypeStyle||d.isToplevel()) return;
if (!d.isFormal()) {
comment(that);
out("$proto$.", getter(d), "=");
function();
out(getter(d), "()");
beginBlock();
out("return this.");
memberName(d);
out(";");
endBlock();
if (d.isVariable()) {
out("$proto$.", setter(d), "=");
function();
out(setter(d), "(", d.getName(), ")");
beginBlock();
out("this.");
memberName(d);
out("=", d.getName(), "; return ", d.getName(), ";");
endBlock();
}
}
}
private void clAlias() {
out("$$$cl15");
}
@Override
public void visit(CharLiteral that) {
clAlias();
out(".Character(");
//out(that.getText().replace('`', '"'));
//TODO: what about escape sequences?
out(String.valueOf(that.getText().codePointAt(1)));
out(")");
}
@Override
public void visit(StringLiteral that) {
clAlias();
out(".String(");
String text = that.getText();
out(text);
// pre-calculate string length
// TODO: also for strings that contain escape sequences
if (text.indexOf('\\') < 0) {
out(",");
out(String.valueOf(text.codePointCount(0, text.length()) - 2));
}
out(")");
}
@Override
public void visit(StringTemplate that) {
List<StringLiteral> literals = that.getStringLiterals();
List<Expression> exprs = that.getExpressions();
clAlias();
out(".StringBuilder().appendAll(");
clAlias();
out(".ArraySequence([");
for (int i = 0; i < literals.size(); i++) {
literals.get(i).visit(this);
if (i < exprs.size()) {
out(",");
exprs.get(i).visit(this);
out(".getString()");
out(",");
}
}
out("])).getString()");
}
@Override
public void visit(FloatLiteral that) {
clAlias();
out(".Float(", that.getText(), ")");
}
@Override
public void visit(NaturalLiteral that) {
clAlias();
out(".Integer(", that.getText(), ")");
}
@Override
public void visit(This that) {
self(Util.getContainingClassOrInterface(that.getScope()));
}
@Override
public void visit(Super that) {
self(Util.getContainingClassOrInterface(that.getScope()));
}
@Override
public void visit(Outer that) {
if (prototypeStyle) {
Scope scope = that.getScope();
while ((scope != null) && !(scope instanceof TypeDeclaration)) {
scope = scope.getContainer();
}
if (scope != null) {
self((TypeDeclaration) scope);
out(".");
}
}
self(that.getTypeModel().getDeclaration());
}
@Override
public void visit(BaseMemberExpression that) {
Declaration decl = that.getDeclaration();
qualify(that, decl);
if (!accessThroughGetter(decl)) {
memberName(decl);
}
else {
out(getter(decl));
out("()");
}
}
private boolean accessThroughGetter(Declaration d) {
return !((d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter)
|| (d instanceof Method));
}
@Override
public void visit(QualifiedMemberExpression that) {
//Big TODO: make sure the member is actually
// refined by the current class!
if (that.getMemberOperator() instanceof SafeMemberOp) {
out("(function($){return $===null?");
if (that.getDeclaration() instanceof Method) {
clAlias();
out(".nullsafe:$.");
} else {
out("null:$.");
}
qualifiedMemberRHS(that);
out("}(");
super.visit(that);
out("))");
} else {
super.visit(that);
out(".");
qualifiedMemberRHS(that);
}
}
private void qualifiedMemberRHS(QualifiedMemberExpression that) {
boolean sup = that.getPrimary() instanceof Super;
String postfix = "";
if (sup) {
ClassOrInterface type = Util.getContainingClassOrInterface(that.getScope());
ClassOrInterface parentType = type.getExtendedTypeDeclaration();
if (parentType != null) {
postfix = '$' + parentType.getName() + '$';
}
}
if (!accessThroughGetter(that.getDeclaration())) {
memberName(that.getDeclaration());
out(postfix);
}
else {
out(getter(that.getDeclaration()));
out(postfix);
out("()");
}
}
@Override
public void visit(BaseTypeExpression that) {
qualify(that, that.getDeclaration());
memberName(that.getDeclaration());
if (!that.getTypeArguments().getTypeModels().isEmpty()) {
out("/* REIFIED GENERICS SOON!! ");
for (ProducedType pt : that.getTypeArguments().getTypeModels()) {
comment(pt);
}
out("*/");
}
}
@Override
public void visit(QualifiedTypeExpression that) {
super.visit(that);
out(".");
memberName(that.getDeclaration());
}
@Override
public void visit(InvocationExpression that) {
sequencedParameter=false;
if (that.getNamedArgumentList()!=null) {
out("(function (){");
that.getNamedArgumentList().visit(this);
out("return ");
that.getPrimary().visit(this);
out("(");
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
if (!f.getParameterLists().isEmpty()) {
List<String> argNames = that.getNamedArgumentList().getNamedArgumentList().getArgumentNames();
boolean first=true;
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p:
f.getParameterLists().get(0).getParameters()) {
if (!first) out(",");
if (p.isSequenced() && that.getNamedArgumentList().getSequencedArgument()==null && that.getNamedArgumentList().getNamedArguments().isEmpty()) {
clAlias();
out(".empty");
} else if (p.isSequenced() || argNames.contains(p.getName())) {
out("$");
out(p.getName());
} else {
out("undefined");
}
first = false;
}
}
}
}
out(")}())");
}
else {
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
if (!f.getParameterLists().isEmpty()) {
com.redhat.ceylon.compiler.typechecker.model.ParameterList plist = f.getParameterLists().get(0);
if (!plist.getParameters().isEmpty() && plist.getParameters().get(plist.getParameters().size()-1).isSequenced()) {
sequencedParameter=true;
}
}
}
}
super.visit(that);
}
}
@Override
public void visit(PositionalArgumentList that) {
out("(");
if (that.getPositionalArguments().isEmpty() && sequencedParameter) {
clAlias();
out(".empty");
} else {
boolean first=true;
boolean sequenced=false;
for (PositionalArgument arg: that.getPositionalArguments()) {
if (!first) out(",");
if (!sequenced && arg.getParameter().isSequenced() && that.getEllipsis() == null) {
sequenced=true;
clAlias();
out(".ArraySequence([");
}
arg.visit(this);
first = false;
}
if (sequenced) {
out("])");
}
}
out(")");
}
@Override
public void visit(NamedArgumentList that) {
for (NamedArgument arg: that.getNamedArguments()) {
out("var $", arg.getParameter().getName(), "=");
arg.visit(this);
out(";");
}
SequencedArgument sarg = that.getSequencedArgument();
if (sarg!=null) {
out("var $", sarg.getParameter().getName(), "=");
sarg.visit(this);
out(";");
}
}
@Override
public void visit(SequencedArgument that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
out("])");
}
@Override
public void visit(SequenceEnumeration that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
if (that.getExpressionList() != null) {
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
}
out("])");
}
@Override
public void visit(SpecifierStatement that) {
BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getBaseMemberExpression();
qualify(that, bme.getDeclaration());
if (!(prototypeStyle && bme.getDeclaration().isClassOrInterfaceMember())) {
out("$");
}
memberName(bme.getDeclaration());
out("=");
that.getSpecifierExpression().visit(this);
}
@Override
public void visit(AssignOp that) {
boolean paren=false;
if (that.getLeftTerm() instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm();
qualify(that, bme.getDeclaration());
out(setter(bme.getDeclaration()));
out("(");
paren = !(bme.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter);
} else if (that.getLeftTerm() instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm();
out(setter(qme.getDeclaration()));
out("(");
paren = true;
}
that.getRightTerm().visit(this);
if (paren) {
out(")");
}
}
private void qualify(Node that, Declaration d) {
String path = qualifiedPath(that, d);
out(path);
if (path.length() > 0) {
out(".");
}
}
private String qualifiedPath(Node that, Declaration d) {
if (isImported(that, d)) {
return packageAliasString(d.getUnit().getPackage());
}
else if (prototypeStyle) {
if (d.isClassOrInterfaceMember() &&
!(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter &&
!d.isCaptured())) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (id == null) {
//a local declaration of some kind,
//perhaps in an outer scope
id = (TypeDeclaration) d.getContainer();
} //else {
//an inherited declaration that might be
//inherited by an outer scope
String path = "";
Scope scope = that.getScope();
while (scope != null) {
if (scope instanceof TypeDeclaration) {
if (path.length() > 0) {
path += '.';
}
path += selfString((TypeDeclaration) scope);
} else {
path = "";
}
if (scope == id) {
break;
}
scope = scope.getContainer();
}
return path;
}
}
else {
if (d.isShared() && d.isClassOrInterfaceMember()) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (id==null) {
//a shared local declaration
return selfString((TypeDeclaration)d.getContainer());
}
else {
//an inherited declaration that might be
//inherited by an outer scope
return selfString(id);
}
}
}
return "";
}
private boolean isImported(Node that, Declaration d) {
return !d.getUnit().getPackage()
.equals(that.getUnit().getPackage());
}
@Override
public void visit(ExecutableStatement that) {
super.visit(that);
out(";");
}
@Override
public void visit(Expression that) {
if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) {
QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm();
// references to methods of types from ceylon.language always need
// special treatment, even if prototypeStyle==false
if ((term.getDeclaration() instanceof Functional)
&& (prototypeStyle || declaredInCL(term.getDeclaration()))) {
out("function(){var $=");
term.getPrimary().visit(this);
if (term.getMemberOperator() instanceof SafeMemberOp) {
out(";return $===null?null:$.");
} else {
out(";return $.");
}
memberName(term.getDeclaration());
out(".apply($,arguments)}");
return;
}
}
super.visit(that);
}
@Override
public void visit(Return that) {
out("return ");
super.visit(that);
}
@Override
public void visit(AnnotationList that) {}
private void self(TypeDeclaration d) {
out(selfString(d));
}
private String selfString(TypeDeclaration d) {
return "$$" + d.getName().substring(0,1).toLowerCase()
+ d.getName().substring(1);
}
/* * Output the name of a variable that receives the type parameter info, usually in the class constructor. * /
private void selfTypeParameters(TypeDeclaration d) {
out(selfTypeParametersString(d));
}
private String selfTypeParametersString(TypeDeclaration d) {
return "$$typeParms" + d.getName();
}*/
/*private void self() {
out("$$");
}*/
private void outerSelf(Declaration d) {
if (d.isToplevel()) {
out("exports");
}
else if (d.isClassOrInterfaceMember()) {
self((TypeDeclaration)d.getContainer());
}
}
private String setter(Declaration d) {
String name = memberNameString(d, true);
return "set" + toUpperCase(name.charAt(0)) + name.substring(1);
}
private String getter(Declaration d) {
String name = memberNameString(d, true);
return "get" + toUpperCase(name.charAt(0)) + name.substring(1);
}
private void memberName(Declaration d) {
out(memberNameString(d, false));
}
private String memberNameString(Declaration d, Boolean forGetterSetter) {
String name = d.getName();
Scope container = d.getContainer();
if (prototypeStyle && !d.isShared() && d.isMember()
&& (container instanceof ClassOrInterface)) {
ClassOrInterface parentType = (ClassOrInterface) container;
name += '$' + parentType.getName();
if (forGetterSetter || (d instanceof Method)) {
name += '$';
}
}
return name;
}
private boolean declaredInCL(Declaration typeDecl) {
return typeDecl.getUnit().getPackage().getQualifiedNameString()
.startsWith("ceylon.language");
}
@Override
public void visit(SumOp that) {
that.getLeftTerm().visit(this);
out(".plus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(DifferenceOp that) {
that.getLeftTerm().visit(this);
out(".minus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(ProductOp that) {
that.getLeftTerm().visit(this);
out(".times(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(QuotientOp that) {
that.getLeftTerm().visit(this);
out(".divided(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(RemainderOp that) {
that.getLeftTerm().visit(this);
out(".remainder(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(PowerOp that) {
that.getLeftTerm().visit(this);
out(".power(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(AddAssignOp that) {
arithmeticAssignOp(that, "plus");
}
@Override public void visit(SubtractAssignOp that) {
arithmeticAssignOp(that, "minus");
}
@Override public void visit(MultiplyAssignOp that) {
arithmeticAssignOp(that, "times");
}
@Override public void visit(DivideAssignOp that) {
arithmeticAssignOp(that, "divided");
}
@Override public void visit(RemainderAssignOp that) {
arithmeticAssignOp(that, "remainder");
}
private void arithmeticAssignOp(ArithmeticAssignmentOp that,
String functionName) {
Term lhs = that.getLeftTerm();
if (lhs instanceof BaseMemberExpression) {
BaseMemberExpression lhsBME = (BaseMemberExpression) lhs;
String lhsPath = qualifiedPath(lhsBME, lhsBME.getDeclaration());
if (lhsPath.length() > 0) {
lhsPath += '.';
}
out("(", lhsPath, setter(lhsBME.getDeclaration()), "(", lhsPath,
getter(lhsBME.getDeclaration()), "().", functionName, "(");
that.getRightTerm().visit(this);
out(")),", lhsPath, getter(lhsBME.getDeclaration()), "())");
} else if (lhs instanceof QualifiedMemberExpression) {
QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs;
out("(function($1,$2){var $=$1.", getter(lhsQME.getDeclaration()), "().",
functionName, "($2);$1.", setter(lhsQME.getDeclaration()), "($);return $}(");
lhsQME.getPrimary().visit(this);
out(",");
that.getRightTerm().visit(this);
out("))");
}
}
@Override public void visit(NegativeOp that) {
that.getTerm().visit(this);
out(".getNegativeValue()");
}
@Override public void visit(PositiveOp that) {
that.getTerm().visit(this);
out(".getPositiveValue()");
}
@Override public void visit(EqualOp that) {
leftEqualsRight(that);
}
@Override public void visit(NotEqualOp that) {
leftEqualsRight(that);
equalsFalse();
}
@Override public void visit(NotOp that) {
that.getTerm().visit(this);
equalsFalse();
}
@Override public void visit(IdenticalOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
that.getRightTerm().visit(this);
thenTrueElseFalse();
out(")");
}
@Override public void visit(CompareOp that) {
leftCompareRight(that);
}
@Override public void visit(SmallerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getSmaller())");
}
@Override public void visit(LargerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getLarger())");
}
@Override public void visit(SmallAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getLarger()");
thenTrueElseFalse();
out(")");
}
@Override public void visit(LargeAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getSmaller()");
thenTrueElseFalse();
out(")");
}
private void leftEqualsRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".equals(");
that.getRightTerm().visit(this);
out(")");
}
private void clTrue() {
clAlias();
out(".getTrue()");
}
private void clFalse() {
clAlias();
out(".getFalse()");
}
private void equalsFalse() {
out(".equals(");
clFalse();
out(")");
}
private void thenTrueElseFalse() {
out("?");
clTrue();
out(":");
clFalse();
}
private void leftCompareRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".compare(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(AndOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
that.getRightTerm().visit(this);
out(":");
clFalse();
out(")");
}
@Override public void visit(OrOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
clTrue();
out(":");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(EntryOp that) {
clAlias();
out(".Entry(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(Element that) {
out(".item(");
that.getExpression().visit(this);
out(")");
}
@Override public void visit(DefaultOp that) {
out("function($){return $!==null?$:");
that.getRightTerm().visit(this);
out("}(");
that.getLeftTerm().visit(this);
out(")");
}
@Override public void visit(ThenOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
that.getRightTerm().visit(this);
out(":null)");
}
@Override public void visit(IncrementOp that) {
prefixIncrementOrDecrement(that.getTerm(), "getSuccessor");
}
@Override public void visit(DecrementOp that) {
prefixIncrementOrDecrement(that.getTerm(), "getPredecessor");
}
private void prefixIncrementOrDecrement(Term term, String functionName) {
if (term instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) term;
String path = qualifiedPath(bme, bme.getDeclaration());
if (path.length() > 0) {
path += '.';
}
out("(", path, setter(bme.getDeclaration()), "(", path);
String bmeGetter = getter(bme.getDeclaration());
out(bmeGetter, "().", functionName, "()),", path, bmeGetter, "())");
} else if (term instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression) term;
out("function($){var $2=$.", getter(qme.getDeclaration()), "().",
functionName, "();$.", setter(qme.getDeclaration()), "($2);return $2}(");
qme.getPrimary().visit(this);
out(")");
}
}
@Override public void visit(PostfixIncrementOp that) {
postfixIncrementOrDecrement(that.getTerm(), "getSuccessor");
}
@Override public void visit(PostfixDecrementOp that) {
postfixIncrementOrDecrement(that.getTerm(), "getPredecessor");
}
private void postfixIncrementOrDecrement(Term term, String functionName) {
if (term instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) term;
String path = qualifiedPath(bme, bme.getDeclaration());
if (path.length() > 0) {
path += '.';
}
out("(function($){", path, setter(bme.getDeclaration()), "($.", functionName,
"());return $}(", path, getter(bme.getDeclaration()), "()))");
} else if (term instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression) term;
out("function($){var $2=$.", getter(qme.getDeclaration()), "();$.",
setter(qme.getDeclaration()), "($2.", functionName, "());return $2}(");
qme.getPrimary().visit(this);
out(")");
}
}
@Override public void visit(Exists that) {
clAlias();
out(".exists(");
that.getTerm().visit(this);
out(")");
}
@Override public void visit(Nonempty that) {
clAlias();
out(".nonempty(");
that.getTerm().visit(this);
out(")");
}
@Override public void visit(IfStatement that) {
IfClause ifClause = that.getIfClause();
Block ifBlock = ifClause.getBlock();
Condition condition = ifClause.getCondition();
if ((condition instanceof ExistsOrNonemptyCondition)
|| (condition instanceof IsCondition)) {
// if (is/exists/nonempty ...)
specialConditionAndBlock(condition, ifBlock, "if");
} else {
out("if ((");
condition.visit(this);
out(")===");
clAlias();
out(".getTrue())");
if (ifBlock != null) {
ifBlock.visit(this);
}
}
if (that.getElseClause() != null) {
out("else ");
that.getElseClause().visit(this);
}
}
@Override public void visit(WhileStatement that) {
WhileClause whileClause = that.getWhileClause();
Condition condition = whileClause.getCondition();
if ((condition instanceof ExistsOrNonemptyCondition)
|| (condition instanceof IsCondition)) {
// while (is/exists/nonempty...)
specialConditionAndBlock(condition, whileClause.getBlock(), "while");
} else {
out("while ((");
condition.visit(this);
out(")===");
clAlias();
out(".getTrue())");
whileClause.getBlock().visit(this);
}
}
// handles an "is", "exists" or "nonempty" condition
private void specialConditionAndBlock(Condition condition,
Block block, String keyword) {
Variable variable = null;
if (condition instanceof ExistsOrNonemptyCondition) {
variable = ((ExistsOrNonemptyCondition) condition).getVariable();
} else if (condition instanceof IsCondition) {
variable = ((IsCondition) condition).getVariable();
} else {
condition.addUnexpectedError("No support for conditions of type " + condition.getClass().getSimpleName());
return;
}
String varName = variable.getDeclarationModel().getName();
boolean simpleCheck = false;
Term variableRHS = variable.getSpecifierExpression().getExpression().getTerm();
if (variableRHS instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) variableRHS;
if (bme.getDeclaration().getName().equals(varName)) {
// the simple case: if/while (is/exists/nonempty x)
simpleCheck = true;
}
}
if (simpleCheck) {
BaseMemberExpression bme = (BaseMemberExpression) variableRHS;
out(keyword);
out("(");
specialConditionCheck(condition, variableRHS, simpleCheck);
out(")");
if (accessThroughGetter(bme.getDeclaration())) {
// a getter for the variable already exists
block.visit(this);
} else {
// no getter exists yet, so define one
beginBlock();
function();
out(getter(variable.getDeclarationModel()));
out("(){");
out("return ");
memberName(bme.getDeclaration());
out("}");
endLine();
visitStatements(block.getStatements(), false);
endBlock();
}
} else {
// if/while (is/exists/nonempty x=...)
out("var $cond$;");
endLine();
out(keyword);
out("(");
specialConditionCheck(condition, variableRHS, simpleCheck);
out(")");
if (block.getStatements().isEmpty()) {
out("{}");
} else {
beginBlock();
out("var $");
out(varName);
out("=$cond$;");
endLine();
function();
out(getter(variable.getDeclarationModel()));
out("(){");
out("return $");
out(varName);
out("}");
endLine();
visitStatements(block.getStatements(), false);
endBlock();
}
}
}
private void specialConditionCheck(Condition condition, Term variableRHS,
boolean simpleCheck) {
if (condition instanceof ExistsOrNonemptyCondition) {
specialConditionRHS(variableRHS, simpleCheck);
if (condition instanceof NonemptyCondition) {
out(".getEmpty()===");
clAlias();
out(".getFalse()");
} else {
out("!==null");
}
} else {
Type type = ((IsCondition) condition).getType();
generateIsOfType(variableRHS, null, type, simpleCheck);
out("===");
clAlias();
out(".getTrue()");
}
}
private void specialConditionRHS(Term variableRHS, boolean simple) {
if (simple) {
variableRHS.visit(this);
} else {
out("($cond$=");
variableRHS.visit(this);
out(")");
}
}
private void specialConditionRHS(String variableRHS, boolean simple) {
if (simple) {
out(variableRHS);
} else {
out("($cond$=");
out(variableRHS);
out(")");
}
}
/** Appends an object with the type's type and list of union/instersection types. */
private void getTypeList(StaticType type) {
out("{ t:'");
if (type instanceof UnionType) {
out("u");
} else {
out("i");
}
out("', l:[");
List<StaticType> types = type instanceof UnionType ? ((UnionType)type).getStaticTypes() : ((IntersectionType)type).getStaticTypes();
boolean first = true;
for (StaticType t : types) {
if (!first) out(",");
if (t instanceof SimpleType) {
out("'");
out(((SimpleType)t).getDeclarationModel().getQualifiedNameString());
out("'");
} else {
getTypeList(t);
}
first = false;
}
out("]}");
}
/** Generates js code to check if a term is of a certain type. We solve this in JS by
* checking against all types that Type satisfies (in the case of union types, matching any
* type will do, and in case of intersection types, all types must be matched). */
private void generateIsOfType(Term term, String termString, Type type, boolean simpleCheck) {
clAlias();
if (type instanceof SimpleType) {
out(".isOfType(");
} else {
out(".Boolean(");
clAlias();
out(".isOfTypes(");
}
if (term != null) {
specialConditionRHS(term, simpleCheck);
} else {
specialConditionRHS(termString, simpleCheck);
}
out(",");
if (type instanceof SimpleType) {
out("'");
out(((SimpleType) type).getDeclarationModel().getQualifiedNameString());
out("')");
if (term != null && term.getTypeModel() != null && !term.getTypeModel().getTypeArguments().isEmpty()) {
out("/* REIFIED GENERICS SOON!!! ");
out(" term " + term.getTypeModel());
out(" model " + term.getTypeModel().getTypeArguments());
for (ProducedType pt : term.getTypeModel().getTypeArgumentList()) {
comment(pt);
}
out("*/");
}
} else {
getTypeList((StaticType)type);
out("))");
}
}
@Override
public void visit(IsOp that) {
generateIsOfType(that.getTerm(), null, that.getType(), true); //TODO is it always simple?
}
@Override public void visit(Break that) {
out("break;");
}
@Override public void visit(Continue that) {
out("continue;");
}
@Override public void visit(RangeOp that) {
clAlias();
out(".Range(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(ForStatement that) {
ForIterator foriter = that.getForClause().getForIterator();
SpecifierExpression iterable = foriter.getSpecifierExpression();
boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty();
//First we need to enclose this inside an anonymous function,
//to avoid problems with repeated iterator variables
out("(function(){"); indentLevel++;
endLine();
final String iterVar = createTempVariable();
final String itemVar = createTempVariable();
out("var ", iterVar, " = ");
iterable.visit(this);
out(".getIterator();");
endLine();
out("var ", itemVar, ";");
endLine();
out("while (");
out("(", itemVar, "=", iterVar, ".next()) !== ");
clAlias();
out(".getExhausted())");
List<Statement> stmnts = that.getForClause().getBlock().getStatements();
if (stmnts.isEmpty()) {
out("{}");
endLine();
} else {
beginBlock();
if (foriter instanceof ValueIterator) {
Value model = ((ValueIterator)foriter).getVariable().getDeclarationModel();
function();
out(getter(model), "(){ return ", itemVar, "; }");
} else if (foriter instanceof KeyValueIterator) {
Value keyModel = ((KeyValueIterator)foriter).getKeyVariable().getDeclarationModel();
Value valModel = ((KeyValueIterator)foriter).getValueVariable().getDeclarationModel();
function();
out(getter(keyModel), "(){ return ", itemVar, ".getKey(); }");
endLine();
function();
out(getter(valModel), "(){ return ", itemVar, ".getItem(); }");
}
endLine();
for (int i=0; i<stmnts.size(); i++) {
Statement s = stmnts.get(i);
s.visit(this);
if (i<stmnts.size()-1 && s instanceof ExecutableStatement) {
endLine();
}
}
}
//If there's an else block, check for normal termination
indentLevel
endLine();
out("}");
if (hasElse) {
endLine();
out("if (");
clAlias();
out(".getExhausted() === ", itemVar, ")");
that.getElseClause().getBlock().visit(this);
}
indentLevel
endLine();
out("}());");
}
public void visit(InOp that) {
that.getRightTerm().visit(this);
out(".contains(");
that.getLeftTerm().visit(this);
out(")");
}
@Override public void visit(TryCatchStatement that) {
out("try");
that.getTryClause().getBlock().visit(this);
if (!that.getCatchClauses().isEmpty()) {
out("catch($ex0$)");
beginBlock();
out("var $ex$=$ex0$;");
endLine();
boolean firstCatch = true;
for (CatchClause catchClause : that.getCatchClauses()) {
Variable variable = catchClause.getCatchVariable().getVariable();
if (!firstCatch) {
out("else ");
}
firstCatch = false;
out("if(");
generateIsOfType(null, "$ex$", variable.getType(), true);
out("===");
clAlias();
out(".getTrue())");
if (catchClause.getBlock().getStatements().isEmpty()) {
out("{}");
} else {
beginBlock();
function();
out(getter(variable.getDeclarationModel()));
out("(){return $ex$}");
endLine();
visitStatements(catchClause.getBlock().getStatements(), false);
endBlock();
}
}
out("else{throw $ex$}");
endBlock();
}
if (that.getFinallyClause() != null) {
out("finally");
that.getFinallyClause().getBlock().visit(this);
}
}
@Override public void visit(Throw that) {
out("throw ");
if (that.getExpression() != null) {
that.getExpression().visit(this);
} else {
clAlias();
out(".Exception()");
}
out(";");
}
private void visitIndex(IndexExpression that) {
that.getPrimary().visit(this);
ElementOrRange eor = that.getElementOrRange();
if (eor instanceof Element) {
out(".item(");
((Element)eor).getExpression().visit(this);
out(")");
} else {//range, or spread?
out(".span(");
((ElementRange)eor).getLowerBound().visit(this);
if (((ElementRange)eor).getUpperBound() != null) {
out(",");
((ElementRange)eor).getUpperBound().visit(this);
}
out(")");
}
}
public void visit(IndexExpression that) {
IndexOperator op = that.getIndexOperator();
if (op instanceof SafeIndexOp) {
clAlias();
out(".exists(");
that.getPrimary().visit(this);
out(")===");
clAlias();
out(".getTrue()?");
}
visitIndex(that);
if (op instanceof SafeIndexOp) {
out(":");
clAlias();
out(".getNull()");
}
}
/** Creates and returns a name for a tmp var. */
private String createTempVariable() {
tmpvarCount++;
return "tmpvar$" + tmpvarCount;
}
private void caseClause(CaseClause cc, String expvar) {
out("if (");
final CaseItem item = cc.getCaseItem();
if (item instanceof IsCase) {
generateIsOfType(null, expvar, ((IsCase)item).getType(), true);
out("===");
clAlias(); out(".getTrue()");
/*} else if (item instanceof SatisfiesCase) {
out("true");*/
} else if (item instanceof MatchCase){
boolean first = true;
for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) {
if (!first) out(" || ");
out(expvar);
out("==="); //TODO equality?
/*out(".equals(");*/
exp.visit(this);
first = false;
}
} else {
cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented");
}
out(") ");
cc.getBlock().visit(this);
}
@Override
public void visit(SwitchStatement that) {
out("//Switch"); endLine();
//Put the expression in a tmp var
//TODO is this really necessary?
final String expvar = createTempVariable();
out("var ", expvar, "=");
that.getSwitchClause().getExpression().visit(this);
out(";"); endLine();
//For each case, do an if
boolean first = true;
for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) {
if (!first) out("else ");
caseClause(cc, expvar);
first = false;
}
if (that.getSwitchCaseList().getElseClause() != null) {
out("else ");
that.getSwitchCaseList().getElseClause().visit(this);
}
}
}
|
package com.redhat.ceylon.compiler.js;
import static java.lang.Character.toUpperCase;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.*;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.*;
public class GenerateJsVisitor extends Visitor
implements NaturalVisitor {
private boolean sequencedParameter=false;
private int tmpvarCount = 0;
private final class SuperVisitor extends Visitor {
private final List<Declaration> decs;
private SuperVisitor(List<Declaration> decs) {
this.decs = decs;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Super) {
decs.add(qe.getDeclaration());
}
super.visit(qe);
}
public void visit(com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassOrInterface qe) {
//don't recurse
}
}
private final class OuterVisitor extends Visitor {
boolean found = false;
private Declaration dec;
private OuterVisitor(Declaration dec) {
this.dec = dec;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Outer ||
qe.getPrimary() instanceof This) {
if ( qe.getDeclaration().equals(dec) ) {
found = true;
}
}
super.visit(qe);
}
}
private final Writer out;
private boolean prototypeStyle;
private CompilationUnit root;
@Override
public void handleException(Exception e, Node that) {
that.addUnexpectedError(that.getMessage(e, this));
}
public GenerateJsVisitor(Writer out, boolean prototypeStyle) {
this.out = out;
this.prototypeStyle=prototypeStyle;
}
private void out(String code) {
try {
out.write(code);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
int indentLevel = 0;
private void indent() {
for (int i=0;i<indentLevel;i++) {
out(" ");
}
}
private void endLine() {
out("\n");
indent();
}
private void beginBlock() {
indentLevel++;
out("{");
endLine();
}
private void endBlock() {
indentLevel
endLine();
out("}");
endLine();
}
private void location(Node node) {
out(" at ");
out(node.getUnit().getFilename());
out(" (");
out(node.getLocation());
out(")");
}
@Override
public void visit(CompilationUnit that) {
root = that;
Module clm = that.getUnit().getPackage().getModule()
.getLanguageModule();
require(clm.getPackage(clm.getNameAsString()));
super.visit(that);
}
@Override
public void visit(Import that) {
require(that.getImportList().getImportedPackage());
}
private void require(Package pkg) {
out("var ");
packageAlias(pkg);
out("=require('");
scriptPath(pkg);
out("');");
endLine();
}
private void packageAlias(Package pkg) {
out(packageAliasString(pkg));
}
private String packageAliasString(Package pkg) {
StringBuilder sb = new StringBuilder("$$$");
//out(pkg.getNameAsString().replace('.', '$'));
for (String s: pkg.getName()) {
sb.append(s.substring(0,1));
}
sb.append(pkg.getQualifiedNameString().length());
return sb.toString();
}
private void scriptPath(Package pkg) {
out(pkg.getModule().getNameAsString().replace('.', '/'));
out("/");
if (!pkg.getModule().isDefault()) {
out(pkg.getModule().getVersion());
out("/");
}
out(pkg.getNameAsString());
}
@Override
public void visit(Parameter that) {
memberName(that.getDeclarationModel());
}
@Override
public void visit(ParameterList that) {
out("(");
boolean first=true;
for (Parameter param: that.getParameters()) {
if (!first) out(",");
memberName(param.getDeclarationModel());
first = false;
}
out(")");
}
private void visitStatements(List<Statement> statements, boolean endLastLine) {
for (int i=0; i<statements.size(); i++) {
Statement s = statements.get(i);
s.visit(this);
if ((endLastLine || (i<statements.size()-1)) &&
s instanceof ExecutableStatement) {
endLine();
}
}
}
@Override
public void visit(Body that) {
visitStatements(that.getStatements(), true);
}
@Override
public void visit(Block that) {
List<Statement> stmnts = that.getStatements();
if (stmnts.isEmpty()) {
out("{}");
endLine();
}
else {
beginBlock();
if ((prototypeOwner!=null) && (that.getScope() instanceof MethodOrValue)) {
/*out("var ");
self();
out("=this;");
endLine();*/
out("var ");
self(prototypeOwner);
out("=this;");
endLine();
}
visitStatements(stmnts, false);
endBlock();
}
}
private void comment(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration that) {
endLine();
out("
out(that.getNodeType());
out(" ");
out(that.getDeclarationModel().getName());
location(that);
endLine();
}
private void var(Declaration d) {
out("var ");
memberName(d);
out("=");
}
private void share(Declaration d) {
if (isCaptured(d)) {
outerSelf(d);
out(".");
memberName(d);
out("=");
memberName(d);
out(";");
endLine();
}
}
@Override
public void visit(ClassDeclaration that) {
Class d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
memberName(dec);
out(";");
endLine();
share(d);
}
@Override
public void visit(InterfaceDeclaration that) {
Interface d = that.getDeclarationModel();
comment(that);
var(d);
TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel()
.getDeclaration();
qualify(that,dec);
out(";");
share(d);
}
private void function() {
out("function ");
}
@Override
public void visit(InterfaceDefinition that) {
Interface d = that.getDeclarationModel();
comment(that);
defineType(d);
addTypeInfo(that);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
for (Statement s: that.getInterfaceBody().getStatements()) {
addToPrototype(d, s);
}
function();
memberName(d);
out("(");
self(d);
out(")");
beginBlock();
declareSelf(d);
that.getInterfaceBody().visit(this);
returnSelf(d);
endBlock();
share(d);
}
/** Add a comment to the generated code with info about the type parameters. */
private void comment(TypeParameter tp) {
out("<");
if (tp.isCovariant()) {
out("out ");
} else if (tp.isContravariant()) {
out("in ");
}
out(tp.getQualifiedNameString());
for (TypeParameter st : tp.getTypeParameters()) {
comment(st);
}
out("> ");
}
/** Add a comment to the generated code with info about the produced type parameters. */
private void comment(ProducedType pt) {
out("<");
out(pt.getProducedTypeQualifiedName());
//This is useful to iterate into the types of this type
//but for comment it's unnecessary
/*for (ProducedType spt : pt.getTypeArgumentList()) {
comment(spt);
}*/
out("> ");
}
@Override
public void visit(ClassDefinition that) {
Class d = that.getDeclarationModel();
comment(that);
defineType(d);
addTypeInfo(that);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(), d);
for (Statement s: that.getClassBody().getStatements()) {
addToPrototype(d, s);
}
function();
memberName(d);
out("(");
for (Parameter p: that.getParameterList().getParameters()) {
p.visit(this);
out(", ");
}
self(d);
out(")");
beginBlock();
if (!d.getTypeParameters().isEmpty()) {
//out(",");
//selfTypeParameters(d);
out("/* REIFIED GENERICS SOON! ");
for (TypeParameter tp : d.getTypeParameters()) {
comment(tp);
}
out("*/");
endLine();
}
declareSelf(d);
for (Parameter p: that.getParameterList().getParameters()) {
if (p.getDeclarationModel().isCaptured()) {
self(d);
out(".");
memberName(p.getDeclarationModel());
out("=");
memberName(p.getDeclarationModel());
out(";");
endLine();
}
}
callSuperclass(that.getExtendedType(), d);
copySuperMembers(that.getExtendedType(), that.getClassBody(), d);
callInterfaces(that.getSatisfiedTypes(), d);
that.getClassBody().visit(this);
returnSelf(d);
endBlock();
share(d);
}
private void copySuperMembers(ExtendedType extType, ClassBody body, Class d) {
if (!prototypeStyle) {
String parentName = "";
if (extType != null) {
TypeDeclaration parentTypeDecl = extType.getType().getDeclarationModel();
if (declaredInCL(parentTypeDecl)) {
return;
}
parentName = parentTypeDecl.getName();
}
final List<Declaration> decs = new ArrayList<Declaration>();
new SuperVisitor(decs).visit(body);
for (Declaration dec: decs) {
if (dec instanceof Value) {
superGetterRef(dec,d,parentName);
if (((Value) dec).isVariable()) {
superSetterRef(dec,d,parentName);
}
}
else if (dec instanceof Getter) {
superGetterRef(dec,d,parentName);
if (((Getter) dec).isVariable()) {
superSetterRef(dec,d,parentName);
}
}
else {
superRef(dec,d,parentName);
}
}
}
}
private void callSuperclass(ExtendedType extendedType, Class d) {
if (extendedType!=null) {
qualify(extendedType.getType(), extendedType.getType().getDeclarationModel());
out(extendedType.getType().getDeclarationModel().getName());
out("(");
for (PositionalArgument arg: extendedType.getInvocationExpression()
.getPositionalArgumentList().getPositionalArguments()) {
arg.visit(this);
out(",");
}
self(d);
out(")");
out(";");
endLine();
}
}
private void callInterfaces(SatisfiedTypes satisfiedTypes, Class d) {
if (satisfiedTypes!=null)
for (SimpleType st: satisfiedTypes.getTypes()) {
qualify(st, st.getDeclarationModel());
out(st.getDeclarationModel().getName());
out("(");
self(d);
out(")");
out(";");
endLine();
}
}
private void defineType(ClassOrInterface d) {
function();
out("$");
out(d.getName());
out("(){}");
endLine();
}
private void addTypeInfo(
com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration type) {
ExtendedType extendedType = null;
SatisfiedTypes satisfiedTypes = null;
if (type instanceof ClassDefinition) {
ClassDefinition classDef = (ClassDefinition) type;
extendedType = classDef.getExtendedType();
satisfiedTypes = classDef.getSatisfiedTypes();
} else if (type instanceof InterfaceDefinition) {
satisfiedTypes = ((InterfaceDefinition) type).getSatisfiedTypes();
} else if (type instanceof ObjectDefinition) {
ObjectDefinition objectDef = (ObjectDefinition) type;
extendedType = objectDef.getExtendedType();
satisfiedTypes = objectDef.getSatisfiedTypes();
}
clAlias();
out(".initType($");
out(type.getDeclarationModel().getName());
out(",'");
out(type.getDeclarationModel().getQualifiedNameString());
out("'");
if (extendedType != null) {
out(",");
out(constructorFunctionName(extendedType.getType()));
} else if (!(type instanceof InterfaceDefinition)) {
out(",");
clAlias();
out(".$IdentifiableObject");
}
if (satisfiedTypes != null) {
for (SimpleType satType : satisfiedTypes.getTypes()) {
out(",");
out(constructorFunctionName(satType));
}
}
out(");");
endLine();
}
private String constructorFunctionName(SimpleType type) {
String constr = qualifiedPath(type, type.getDeclarationModel());
if (constr.length() > 0) {
constr += '.';
}
constr += "$";
constr += type.getDeclarationModel().getName();
return constr;
}
private ClassOrInterface prototypeOwner;
private void addToPrototype(ClassOrInterface d, Statement s) {
prototypeOwner = d;
if (s instanceof MethodDefinition) {
addMethodToPrototype(d, (MethodDefinition)s);
}
if (s instanceof AttributeGetterDefinition) {
addGetterToPrototype(d, (AttributeGetterDefinition)s);
}
if (s instanceof AttributeSetterDefinition) {
addSetterToPrototype(d, (AttributeSetterDefinition)s);
}
if (s instanceof AttributeDeclaration) {
addGetterAndSetterToPrototype(d, (AttributeDeclaration)s);
}
prototypeOwner = null;
}
private void declareSelf(ClassOrInterface d) {
out("if (");
self(d);
out("===undefined)");
self(d);
out("=");
out("new $");
out(d.getName());
out(";");
endLine();
/*out("var ");
self(d);
out("=");
self();
out(";");
endLine();*/
}
private void instantiateSelf(ClassOrInterface d) {
out("var ");
self(d);
out("=");
out("new $");
out(d.getName());
out(";");
endLine();
}
private void returnSelf(ClassOrInterface d) {
out("return ");
self(d);
out(";");
}
private void copyMembersToPrototype(SimpleType that, Declaration d) {
String thatName = that.getDeclarationModel().getName();
String path = qualifiedPath(that, that.getDeclarationModel());
String suffix = path + '$' + thatName + '$';
if (path.length() > 0) {
path += '.';
}
copyMembersToPrototype(path+'$'+thatName, d, suffix);
}
private void copyMembersToPrototype(String from, Declaration d, String suffix) {
clAlias();
out(".inheritProto($");
out(d.getName());
out(",");
out(from);
if ((suffix != null) && (suffix.length() > 0)) {
out(",'");
out(suffix);
out("'");
}
out(");");
endLine();
}
private void copySuperclassPrototype(ExtendedType that, Declaration d) {
if (that==null) {
String suffix = (d instanceof Interface) ? null : "$$$cl15$IdentifiableObject$";
copyMembersToPrototype("$$$cl15.$IdentifiableObject", d, suffix);
}
else if (prototypeStyle || declaredInCL(that.getType().getDeclarationModel())) {
copyMembersToPrototype(that.getType(), d);
}
}
private void copyInterfacePrototypes(SatisfiedTypes that, Declaration d) {
if (that!=null) {
for (Tree.SimpleType st: that.getTypes()) {
if (prototypeStyle || declaredInCL(st.getDeclarationModel())) {
copyMembersToPrototype(st, d);
}
}
}
}
@Override
public void visit(ObjectDefinition that) {
Value d = that.getDeclarationModel();
Class c = (Class) d.getTypeDeclaration();
comment(that);
defineType(c);
addTypeInfo(that);
copySuperclassPrototype(that.getExtendedType(),d);
copyInterfacePrototypes(that.getSatisfiedTypes(),d);
for (Statement s: that.getClassBody().getStatements()) {
addToPrototype(c, s);
}
out("var o$");
out(d.getName());
out("=");
function();
memberName(d);
out("()");
beginBlock();
instantiateSelf(c);
callSuperclass(that.getExtendedType(), c);
copySuperMembers(that.getExtendedType(), that.getClassBody(), c);
callInterfaces(that.getSatisfiedTypes(), c);
that.getClassBody().visit(this);
returnSelf(c);
indentLevel
endLine();
out("}();");
endLine();
if (d.isShared()) {
outerSelf(d);
out(".");
out(getter(d));
out("=");
}
function();
out(getter(d));
out("()");
beginBlock();
out("return o$");
out(d.getName());
out(";");
endBlock();
}
private void superRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".");
memberName(d);
out("$");
out(parent);
out("$=");
self(sub);
out(".");
memberName(d);
out(";");
endLine();
}
private void superGetterRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".");
out(getter(d));
out("$");
out(parent);
out("$=");
self(sub);
out(".");
out(getter(d));
out(";");
endLine();
}
private void superSetterRef(Declaration d, Class sub, String parent) {
//if (d.isActual()) {
self(sub);
out(".");
out(setter(d));
out("$");
out(parent);
out("$=");
self(sub);
out(".");
out(setter(d));
out(";");
endLine();
}
@Override
public void visit(MethodDeclaration that) {}
@Override
public void visit(MethodDefinition that) {
Method d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
memberName(d);
//TODO: if there are multiple parameter lists
// do the inner function declarations
super.visit(that);
share(d);
}
private void addMethodToPrototype(Declaration outer,
MethodDefinition that) {
Method d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
memberName(d);
out("=");
function();
memberName(d);
//TODO: if there are multiple parameter lists
// do the inner function declarations
super.visit(that);
}
@Override
public void visit(AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(getter(d));
out("()");
super.visit(that);
shareGetter(d);
}
private void addGetterToPrototype(Declaration outer,
AttributeGetterDefinition that) {
Getter d = that.getDeclarationModel();
if (!prototypeStyle||!d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(getter(d));
out("=");
function();
out(getter(d));
out("()");
super.visit(that);
}
private void shareGetter(MethodOrValue d) {
if (isCaptured(d)) {
outerSelf(d);
out(".");
out(getter(d));
out("=");
out(getter(d));
out(";");
endLine();
}
}
@Override
public void visit(AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (prototypeStyle&&d.isClassOrInterfaceMember()) return;
comment(that);
function();
out(setter(d));
out("(");
memberName(d);
out(")");
super.visit(that);
shareSetter(d);
}
private void addSetterToPrototype(Declaration outer,
AttributeSetterDefinition that) {
Setter d = that.getDeclarationModel();
if (!prototypeStyle || !d.isClassOrInterfaceMember()) return;
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(setter(d));
out("=");
function();
out(setter(d));
out("(");
memberName(d);
out(")");
super.visit(that);
}
private boolean isCaptured(Declaration d) {
if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures
if (d.isShared() || d.isCaptured() ) {
return true;
}
else {
OuterVisitor ov = new OuterVisitor(d);
ov.visit(root);
return ov.found;
}
}
else {
return false;
}
}
private void shareSetter(MethodOrValue d) {
if (isCaptured(d)) {
outerSelf(d);
out(".");
out(setter(d));
out("=");
out(setter(d));
out(";");
endLine();
}
}
@Override
public void visit(AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!d.isFormal()) {
comment(that);
if (prototypeStyle&&d.isClassOrInterfaceMember()) {
if (that.getSpecifierOrInitializerExpression()!=null) {
outerSelf(d);
out(".");
memberName(d);
out("=");
super.visit(that);
out(";");
endLine();
}
}
else {
out("var $");
out(d.getName());
if (that.getSpecifierOrInitializerExpression()!=null) {
out("=");
}
super.visit(that);
out(";");
endLine();
function();
out(getter(d));
out("()");
beginBlock();
out("return $");
out(d.getName());
out(";");
endBlock();
shareGetter(d);
if (d.isVariable()) {
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
beginBlock();
out("$");
out(d.getName());
out("=");
out(d.getName());
out("; return ");
out(d.getName());
out(";");
endBlock();
shareSetter(d);
}
}
}
}
private void addGetterAndSetterToPrototype(Declaration outer,
AttributeDeclaration that) {
Value d = that.getDeclarationModel();
if (!prototypeStyle||d.isToplevel()) return;
if (!d.isFormal()) {
comment(that);
out("$");
out(outer.getName());
out(".prototype.");
out(getter(d));
out("=");
function();
out(getter(d));
out("()");
beginBlock();
out("return this.");
memberName(d);
out(";");
endBlock();
if (d.isVariable()) {
out("$");
out(outer.getName());
out(".prototype.");
out(setter(d));
out("=");
function();
out(setter(d));
out("(");
out(d.getName());
out(")");
beginBlock();
out("this.");
memberName(d);
out("=");
out(d.getName());
out("; return ");
out(d.getName());
out(";");
endBlock();
}
}
}
private void clAlias() {
out("$$$cl15");
}
@Override
public void visit(CharLiteral that) {
clAlias();
out(".Character(");
//out(that.getText().replace('`', '"'));
//TODO: what about escape sequences?
out(String.valueOf(that.getText().codePointAt(1)));
out(")");
}
@Override
public void visit(StringLiteral that) {
clAlias();
out(".String(");
String text = that.getText();
out(text);
// pre-calculate string length
// TODO: also for strings that contain escape sequences
if (text.indexOf('\\') < 0) {
out(",");
out(String.valueOf(text.codePointCount(0, text.length()) - 2));
}
out(")");
}
@Override
public void visit(StringTemplate that) {
List<StringLiteral> literals = that.getStringLiterals();
List<Expression> exprs = that.getExpressions();
clAlias();
out(".StringBuilder().appendAll(");
clAlias();
out(".ArraySequence([");
for (int i = 0; i < literals.size(); i++) {
literals.get(i).visit(this);
if (i < exprs.size()) {
out(",");
exprs.get(i).visit(this);
out(".getString()");
out(",");
}
}
out("])).getString()");
}
@Override
public void visit(FloatLiteral that) {
clAlias();
out(".Float(");
out(that.getText());
out(")");
}
@Override
public void visit(NaturalLiteral that) {
clAlias();
out(".Integer(");
out(that.getText());
out(")");
}
@Override
public void visit(This that) {
self(Util.getContainingClassOrInterface(that.getScope()));
}
@Override
public void visit(Super that) {
self(Util.getContainingClassOrInterface(that.getScope()));
}
@Override
public void visit(Outer that) {
self(that.getTypeModel().getDeclaration());
}
@Override
public void visit(BaseMemberExpression that) {
Declaration decl = that.getDeclaration();
qualify(that, decl);
if (!accessThroughGetter(decl)) {
memberName(decl);
}
else {
out(getter(decl));
out("()");
}
}
private boolean accessThroughGetter(Declaration d) {
return !((d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter)
|| (d instanceof Method));
}
@Override
public void visit(QualifiedMemberExpression that) {
//Big TODO: make sure the member is actually
// refined by the current class!
if (that.getMemberOperator() instanceof SafeMemberOp) {
out("(function($){return $===null?");
if (that.getDeclaration() instanceof Method) {
clAlias();
out(".nullsafe:$.");
} else {
out("null:$.");
}
qualifiedMemberRHS(that);
out("}(");
super.visit(that);
out("))");
} else {
super.visit(that);
out(".");
qualifiedMemberRHS(that);
}
}
private void qualifiedMemberRHS(QualifiedMemberExpression that) {
boolean sup = that.getPrimary() instanceof Super;
String postfix = "";
if (sup) {
ClassOrInterface type = Util.getContainingClassOrInterface(that.getScope());
ClassOrInterface parentType = type.getExtendedTypeDeclaration();
if (parentType != null) {
postfix = '$' + parentType.getName() + '$';
}
}
if (!accessThroughGetter(that.getDeclaration())) {
memberName(that.getDeclaration());
out(postfix);
}
else {
out(getter(that.getDeclaration()));
out(postfix);
out("()");
}
}
@Override
public void visit(BaseTypeExpression that) {
qualify(that, that.getDeclaration());
memberName(that.getDeclaration());
if (!that.getTypeArguments().getTypeModels().isEmpty()) {
out("/* REIFIED GENERICS SOON!! ");
for (ProducedType pt : that.getTypeArguments().getTypeModels()) {
comment(pt);
}
out("*/");
}
}
@Override
public void visit(QualifiedTypeExpression that) {
super.visit(that);
out(".");
memberName(that.getDeclaration());
}
@Override
public void visit(InvocationExpression that) {
sequencedParameter=false;
if (that.getNamedArgumentList()!=null) {
out("(function (){");
that.getNamedArgumentList().visit(this);
out("return ");
that.getPrimary().visit(this);
out("(");
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
if (!f.getParameterLists().isEmpty()) {
boolean first=true;
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p:
f.getParameterLists().get(0).getParameters()) {
if (!first) out(",");
if (p.isSequenced() && that.getNamedArgumentList().getSequencedArgument()==null && that.getNamedArgumentList().getNamedArguments().isEmpty()) {
clAlias();
out(".empty");
} else {
out("$");
out(p.getName());
}
first = false;
}
}
}
}
out(")}())");
}
else {
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
if (!f.getParameterLists().isEmpty()) {
com.redhat.ceylon.compiler.typechecker.model.ParameterList plist = f.getParameterLists().get(0);
if (!plist.getParameters().isEmpty() && plist.getParameters().get(plist.getParameters().size()-1).isSequenced()) {
sequencedParameter=true;
}
}
}
}
super.visit(that);
}
}
@Override
public void visit(PositionalArgumentList that) {
out("(");
if (that.getPositionalArguments().isEmpty() && sequencedParameter) {
clAlias();
out(".empty");
} else {
boolean first=true;
boolean sequenced=false;
for (PositionalArgument arg: that.getPositionalArguments()) {
if (!first) out(",");
if (!sequenced && arg.getParameter().isSequenced() && that.getEllipsis() == null) {
sequenced=true;
clAlias();
out(".ArraySequence([");
}
arg.visit(this);
first = false;
}
if (sequenced) {
out("])");
}
}
out(")");
}
@Override
public void visit(NamedArgumentList that) {
for (NamedArgument arg: that.getNamedArguments()) {
out("var $");
out(arg.getParameter().getName());
out("=");
arg.visit(this);
out(";");
}
SequencedArgument sarg = that.getSequencedArgument();
if (sarg!=null) {
out("var $");
out(sarg.getParameter().getName());
out("=");
sarg.visit(this);
out(";");
}
}
@Override
public void visit(SequencedArgument that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
out("])");
}
@Override
public void visit(SequenceEnumeration that) {
clAlias();
out(".ArraySequence([");
boolean first=true;
if (that.getExpressionList() != null) {
for (Expression arg: that.getExpressionList().getExpressions()) {
if (!first) out(",");
arg.visit(this);
first = false;
}
}
out("])");
}
@Override
public void visit(SpecifierStatement that) {
BaseMemberExpression bme = (Tree.BaseMemberExpression) that.getBaseMemberExpression();
qualify(that, bme.getDeclaration());
if (!(prototypeStyle && bme.getDeclaration().isClassOrInterfaceMember())) {
out("$");
}
memberName(bme.getDeclaration());
out("=");
that.getSpecifierExpression().visit(this);
}
@Override
public void visit(AssignOp that) {
boolean paren=false;
if (that.getLeftTerm() instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm();
qualify(that, bme.getDeclaration());
out(setter(bme.getDeclaration()));
out("(");
paren = !(bme.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter);
} else if (that.getLeftTerm() instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm();
out(setter(qme.getDeclaration()));
out("(");
paren = true;
}
that.getRightTerm().visit(this);
if (paren) {
out(")");
}
}
private void qualify(Node that, Declaration d) {
String path = qualifiedPath(that, d);
out(path);
if (path.length() > 0) {
out(".");
}
}
private String qualifiedPath(Node that, Declaration d) {
if (isImported(that, d)) {
return packageAliasString(d.getUnit().getPackage());
}
else if (prototypeStyle) {
if (d.isClassOrInterfaceMember() &&
!(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter &&
!d.isCaptured())) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
/*if (d.getContainer().equals(prototypeOwner)) {
out("this");
}
else*/
if (id==null) {
//a local declaration of some kind,
//perhaps in an outer scope
if (!(d instanceof TypeDeclaration)) {
return selfString((TypeDeclaration)d.getContainer());
}
else {
//a local type declaration: for now,
//we don't flatten out nested types
//onto the prototype
return "";
}
}
else {
//an inherited declaration that might be
//inherited by an outer scope
return selfString(id);
}
}
}
else {
if (d.isShared() && d.isClassOrInterfaceMember()) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (id==null) {
//a shared local declaration
return selfString((TypeDeclaration)d.getContainer());
}
else {
//an inherited declaration that might be
//inherited by an outer scope
return selfString(id);
}
}
}
return "";
}
private boolean isImported(Node that, Declaration d) {
return !d.getUnit().getPackage()
.equals(that.getUnit().getPackage());
}
@Override
public void visit(ExecutableStatement that) {
super.visit(that);
out(";");
}
@Override
public void visit(Expression that) {
if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) {
QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm();
// references to methods of types from ceylon.language always need
// special treatment, even if prototypeStyle==false
if ((term.getDeclaration() instanceof Functional)
&& (prototypeStyle || declaredInCL(term.getDeclaration()))) {
out("function(){var $=");
term.getPrimary().visit(this);
if (term.getMemberOperator() instanceof SafeMemberOp) {
out(";return $===null?null:$.");
} else {
out(";return $.");
}
memberName(term.getDeclaration());
out(".apply($,arguments)}");
return;
}
}
super.visit(that);
}
@Override
public void visit(Return that) {
out("return ");
super.visit(that);
}
@Override
public void visit(AnnotationList that) {}
private void self(TypeDeclaration d) {
out(selfString(d));
}
private String selfString(TypeDeclaration d) {
return "$$" + d.getName().substring(0,1).toLowerCase()
+ d.getName().substring(1);
}
/* * Output the name of a variable that receives the type parameter info, usually in the class constructor. * /
private void selfTypeParameters(TypeDeclaration d) {
out(selfTypeParametersString(d));
}
private String selfTypeParametersString(TypeDeclaration d) {
return "$$typeParms" + d.getName();
}*/
/*private void self() {
out("$$");
}*/
private void outerSelf(Declaration d) {
if (d.isToplevel()) {
out("this");
}
else if (d.isClassOrInterfaceMember()) {
self((TypeDeclaration)d.getContainer());
}
}
private String setter(Declaration d) {
String name = memberNameString(d, true);
return "set" + toUpperCase(name.charAt(0)) + name.substring(1);
}
private String getter(Declaration d) {
String name = memberNameString(d, true);
return "get" + toUpperCase(name.charAt(0)) + name.substring(1);
}
private void memberName(Declaration d) {
out(memberNameString(d, false));
}
private String memberNameString(Declaration d, Boolean forGetterSetter) {
String name = d.getName();
Scope container = d.getContainer();
if (prototypeStyle && !d.isShared() && d.isMember() && (container != null)
&& (container instanceof ClassOrInterface)) {
ClassOrInterface parentType = (ClassOrInterface) container;
name += '$' + parentType.getName();
if (forGetterSetter || (d instanceof Method)) {
name += '$';
}
}
return name;
}
private boolean declaredInCL(Declaration typeDecl) {
return typeDecl.getUnit().getPackage().getQualifiedNameString()
.startsWith("ceylon.language");
}
@Override
public void visit(SumOp that) {
that.getLeftTerm().visit(this);
out(".plus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(DifferenceOp that) {
that.getLeftTerm().visit(this);
out(".minus(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(ProductOp that) {
that.getLeftTerm().visit(this);
out(".times(");
that.getRightTerm().visit(this);
out(")");
}
@Override
public void visit(QuotientOp that) {
that.getLeftTerm().visit(this);
out(".divided(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(RemainderOp that) {
that.getLeftTerm().visit(this);
out(".remainder(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(PowerOp that) {
that.getLeftTerm().visit(this);
out(".power(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(AddAssignOp that) {
arithmeticAssignOp(that, "plus");
}
@Override public void visit(SubtractAssignOp that) {
arithmeticAssignOp(that, "minus");
}
@Override public void visit(MultiplyAssignOp that) {
arithmeticAssignOp(that, "times");
}
@Override public void visit(DivideAssignOp that) {
arithmeticAssignOp(that, "divided");
}
@Override public void visit(RemainderAssignOp that) {
arithmeticAssignOp(that, "remainder");
}
private void arithmeticAssignOp(ArithmeticAssignmentOp that,
String functionName) {
Term lhs = that.getLeftTerm();
if (lhs instanceof BaseMemberExpression) {
BaseMemberExpression lhsBME = (BaseMemberExpression) lhs;
String lhsPath = qualifiedPath(lhsBME, lhsBME.getDeclaration());
if (lhsPath.length() > 0) {
lhsPath += '.';
}
out("(");
out(lhsPath);
out(setter(lhsBME.getDeclaration()));
out("(");
out(lhsPath);
out(getter(lhsBME.getDeclaration()));
out("()." + functionName + "(");
that.getRightTerm().visit(this);
out(")),");
out(lhsPath);
out(getter(lhsBME.getDeclaration()));
out("())");
} else if (lhs instanceof QualifiedMemberExpression) {
QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs;
out("(function($1,$2){var $=$1.");
out(getter(lhsQME.getDeclaration()));
out("()." + functionName + "($2);$1.");
out(setter(lhsQME.getDeclaration()));
out("($);return $}(");
lhsQME.getPrimary().visit(this);
out(",");
that.getRightTerm().visit(this);
out("))");
}
}
@Override public void visit(NegativeOp that) {
that.getTerm().visit(this);
out(".getNegativeValue()");
}
@Override public void visit(PositiveOp that) {
that.getTerm().visit(this);
out(".getPositiveValue()");
}
@Override public void visit(EqualOp that) {
leftEqualsRight(that);
}
@Override public void visit(NotEqualOp that) {
leftEqualsRight(that);
equalsFalse();
}
@Override public void visit(NotOp that) {
that.getTerm().visit(this);
equalsFalse();
}
@Override public void visit(IdenticalOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
that.getRightTerm().visit(this);
thenTrueElseFalse();
out(")");
}
@Override public void visit(CompareOp that) {
leftCompareRight(that);
}
@Override public void visit(SmallerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getSmaller())");
}
@Override public void visit(LargerOp that) {
leftCompareRight(that);
out(".equals(");
clAlias();
out(".getLarger())");
}
@Override public void visit(SmallAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getLarger()");
thenTrueElseFalse();
out(")");
}
@Override public void visit(LargeAsOp that) {
out("(");
leftCompareRight(that);
out("!==");
clAlias();
out(".getSmaller()");
thenTrueElseFalse();
out(")");
}
private void leftEqualsRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".equals(");
that.getRightTerm().visit(this);
out(")");
}
private void clTrue() {
clAlias();
out(".getTrue()");
}
private void clFalse() {
clAlias();
out(".getFalse()");
}
private void equalsFalse() {
out(".equals(");
clFalse();
out(")");
}
private void thenTrueElseFalse() {
out("?");
clTrue();
out(":");
clFalse();
}
private void leftCompareRight(BinaryOperatorExpression that) {
that.getLeftTerm().visit(this);
out(".compare(");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(AndOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
that.getRightTerm().visit(this);
out(":");
clFalse();
out(")");
}
@Override public void visit(OrOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
clTrue();
out(":");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(EntryOp that) {
clAlias();
out(".Entry(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(Element that) {
out(".item(");
that.getExpression().visit(this);
out(")");
}
@Override public void visit(DefaultOp that) {
out("function($){return $!==null?$:");
that.getRightTerm().visit(this);
out("}(");
that.getLeftTerm().visit(this);
out(")");
}
@Override public void visit(ThenOp that) {
out("(");
that.getLeftTerm().visit(this);
out("===");
clTrue();
out("?");
that.getRightTerm().visit(this);
out(":null)");
}
@Override public void visit(IncrementOp that) {
prefixIncrementOrDecrement(that.getTerm(), "getSuccessor");
}
@Override public void visit(DecrementOp that) {
prefixIncrementOrDecrement(that.getTerm(), "getPredecessor");
}
private void prefixIncrementOrDecrement(Term term, String functionName) {
if (term instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) term;
String path = qualifiedPath(bme, bme.getDeclaration());
if (path.length() > 0) {
path += '.';
}
out("(");
out(path);
out(setter(bme.getDeclaration()));
out("(");
out(path);
String bmeGetter = getter(bme.getDeclaration());
out(bmeGetter);
out("()." + functionName + "()),");
out(path);
out(bmeGetter);
out("())");
} else if (term instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression) term;
out("function($){var $2=$.");
out(getter(qme.getDeclaration()));
out("()." + functionName + "();$.");
out(setter(qme.getDeclaration()));
out("($2);return $2}(");
qme.getPrimary().visit(this);
out(")");
}
}
@Override public void visit(PostfixIncrementOp that) {
postfixIncrementOrDecrement(that.getTerm(), "getSuccessor");
}
@Override public void visit(PostfixDecrementOp that) {
postfixIncrementOrDecrement(that.getTerm(), "getPredecessor");
}
private void postfixIncrementOrDecrement(Term term, String functionName) {
if (term instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) term;
String path = qualifiedPath(bme, bme.getDeclaration());
if (path.length() > 0) {
path += '.';
}
out("(function($){");
out(path);
out(setter(bme.getDeclaration()));
out("($." + functionName + "());return $}(");
out(path);
out(getter(bme.getDeclaration()));
out("()))");
} else if (term instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression) term;
out("function($){var $2=$.");
out(getter(qme.getDeclaration()));
out("();$.");
out(setter(qme.getDeclaration()));
out("($2." + functionName + "());return $2}(");
qme.getPrimary().visit(this);
out(")");
}
}
@Override public void visit(Exists that) {
clAlias();
out(".exists(");
that.getTerm().visit(this);
out(")");
}
@Override public void visit(Nonempty that) {
clAlias();
out(".nonempty(");
that.getTerm().visit(this);
out(")");
}
@Override public void visit(IfStatement that) {
IfClause ifClause = that.getIfClause();
Block ifBlock = ifClause.getBlock();
Condition condition = ifClause.getCondition();
if ((condition instanceof ExistsOrNonemptyCondition)
|| (condition instanceof IsCondition)) {
// if (is/exists/nonempty ...)
specialConditionAndBlock(condition, ifBlock, "if");
} else {
out("if ((");
condition.visit(this);
out(")===");
clAlias();
out(".getTrue())");
if (ifBlock != null) {
ifBlock.visit(this);
}
}
if (that.getElseClause() != null) {
out("else ");
that.getElseClause().visit(this);
}
}
@Override public void visit(WhileStatement that) {
WhileClause whileClause = that.getWhileClause();
Condition condition = whileClause.getCondition();
if ((condition instanceof ExistsOrNonemptyCondition)
|| (condition instanceof IsCondition)) {
// while (is/exists/nonempty...)
specialConditionAndBlock(condition, whileClause.getBlock(), "while");
} else {
out("while ((");
condition.visit(this);
out(")===");
clAlias();
out(".getTrue())");
whileClause.getBlock().visit(this);
}
}
// handles an "is", "exists" or "nonempty" condition
private void specialConditionAndBlock(Condition condition,
Block block, String keyword) {
Variable variable = null;
if (condition instanceof ExistsOrNonemptyCondition) {
variable = ((ExistsOrNonemptyCondition) condition).getVariable();
} else if (condition instanceof IsCondition) {
variable = ((IsCondition) condition).getVariable();
} else {
return;
}
String varName = variable.getDeclarationModel().getName();
boolean simpleCheck = false;
Term variableRHS = variable.getSpecifierExpression().getExpression().getTerm();
if (variableRHS instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) variableRHS;
if (bme.getDeclaration().getName().equals(varName)) {
// the simple case: if/while (is/exists/nonempty x)
simpleCheck = true;
}
}
if (simpleCheck) {
BaseMemberExpression bme = (BaseMemberExpression) variableRHS;
out(keyword);
out("(");
specialConditionCheck(condition, variableRHS, simpleCheck);
out(")");
if (accessThroughGetter(bme.getDeclaration())) {
// a getter for the variable already exists
block.visit(this);
} else {
// no getter exists yet, so define one
beginBlock();
function();
out(getter(variable.getDeclarationModel()));
out("(){");
out("return ");
memberName(bme.getDeclaration());
out("}");
endLine();
visitStatements(block.getStatements(), false);
endBlock();
}
} else {
// if/while (is/exists/nonempty x=...)
out("var $cond$;");
endLine();
out(keyword);
out("(");
specialConditionCheck(condition, variableRHS, simpleCheck);
out(")");
if (block.getStatements().isEmpty()) {
out("{}");
} else {
beginBlock();
out("var $");
out(varName);
out("=$cond$;");
endLine();
function();
out(getter(variable.getDeclarationModel()));
out("(){");
out("return $");
out(varName);
out("}");
endLine();
visitStatements(block.getStatements(), false);
endBlock();
}
}
}
private void specialConditionCheck(Condition condition, Term variableRHS,
boolean simpleCheck) {
if (condition instanceof ExistsOrNonemptyCondition) {
specialConditionRHS(variableRHS, simpleCheck);
if (condition instanceof NonemptyCondition) {
out(".getEmpty()===");
clAlias();
out(".getFalse()");
} else {
out("!==null");
}
} else {
Type type = ((IsCondition) condition).getType();
generateIsOfType(variableRHS, null, type, simpleCheck);
out("===");
clAlias();
out(".getTrue()");
}
}
private void specialConditionRHS(Term variableRHS, boolean simple) {
if (simple) {
variableRHS.visit(this);
} else {
out("($cond$=");
variableRHS.visit(this);
out(")");
}
}
private void specialConditionRHS(String variableRHS, boolean simple) {
if (simple) {
out(variableRHS);
} else {
out("($cond$=");
out(variableRHS);
out(")");
}
}
/** Appends an object with the type's type and list of union/instersection types. */
private void getTypeList(StaticType type) {
out("{ t:'");
if (type instanceof UnionType) {
out("u");
} else {
out("i");
}
out("', l:[");
List<StaticType> types = type instanceof UnionType ? ((UnionType)type).getStaticTypes() : ((IntersectionType)type).getStaticTypes();
boolean first = true;
for (StaticType t : types) {
if (!first) out(",");
if (t instanceof SimpleType) {
out("'");
out(((SimpleType)t).getDeclarationModel().getQualifiedNameString());
out("'");
} else {
getTypeList(t);
}
first = false;
}
out("]}");
}
/** Generates js code to check if a term is of a certain type. We solve this in JS by
* checking against all types that Type satisfies (in the case of union types, matching any
* type will do, and in case of intersection types, all types must be matched). */
private void generateIsOfType(Term term, String termString, Type type, boolean simpleCheck) {
clAlias();
if (type instanceof SimpleType) {
out(".isOfType(");
} else {
out(".Boolean(");
clAlias();
out(".isOfTypes(");
}
if (term != null) {
specialConditionRHS(term, simpleCheck);
} else {
specialConditionRHS(termString, simpleCheck);
}
out(",");
if (type instanceof SimpleType) {
out("'");
out(((SimpleType) type).getDeclarationModel().getQualifiedNameString());
out("')");
if (term != null && !term.getTypeModel().getTypeArguments().isEmpty()) {
out("/* REIFIED GENERICS SOON!!! ");
out(" term " + term.getTypeModel());
out(" model " + term.getTypeModel().getTypeArguments());
for (ProducedType pt : term.getTypeModel().getTypeArgumentList()) {
comment(pt);
}
out("*/");
}
} else {
getTypeList((StaticType)type);
out("))");
}
}
@Override
public void visit(IsOp that) {
generateIsOfType(that.getTerm(), null, that.getType(), true); //TODO is it always simple?
}
@Override public void visit(Break that) {
out("break;");
}
@Override public void visit(Continue that) {
out("continue;");
}
@Override public void visit(RangeOp that) {
clAlias();
out(".Range(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(")");
}
@Override public void visit(ForStatement that) {
ForIterator foriter = that.getForClause().getForIterator();
SpecifierExpression iterable = foriter.getSpecifierExpression();
boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty();
//First we need to enclose this inside an anonymous function,
//to avoid problems with repeated iterator variables
out("(function(){"); indentLevel++;
endLine();
final String iterVar = createTempVariable();
final String itemVar = createTempVariable();
out("var "); out(iterVar); out(" = ");
iterable.visit(this);
out(".getIterator();");
endLine();
out("var "); out(itemVar); out(";");
endLine();
out("while (");
out("("); out(itemVar); out("="); out(iterVar); out(".next()) !== ");
clAlias();
out(".getExhausted())");
List<Statement> stmnts = that.getForClause().getBlock().getStatements();
if (stmnts.isEmpty()) {
out("{}");
endLine();
} else {
beginBlock();
if (foriter instanceof ValueIterator) {
Value model = ((ValueIterator)foriter).getVariable().getDeclarationModel();
function();
out(getter(model));
out("(){ return "); out(itemVar); out("; }");
} else if (foriter instanceof KeyValueIterator) {
Value keyModel = ((KeyValueIterator)foriter).getKeyVariable().getDeclarationModel();
Value valModel = ((KeyValueIterator)foriter).getValueVariable().getDeclarationModel();
function();
out(getter(keyModel));
out("(){ return "); out(itemVar); out(".getKey(); }");
endLine();
function();
out(getter(valModel));
out("(){ return "); out(itemVar); out(".getItem(); }");
}
endLine();
for (int i=0; i<stmnts.size(); i++) {
Statement s = stmnts.get(i);
s.visit(this);
if (i<stmnts.size()-1 && s instanceof ExecutableStatement) {
endLine();
}
}
}
//If there's an else block, check for normal termination
indentLevel
endLine();
out("}");
if (hasElse) {
endLine();
out("if (");
clAlias();
out(".getExhausted() === "); out(itemVar); out(")");
that.getElseClause().getBlock().visit(this);
}
indentLevel
endLine();
out("}());");
}
public void visit(InOp that) {
that.getRightTerm().visit(this);
out(".contains(");
that.getLeftTerm().visit(this);
out(")");
}
@Override public void visit(TryCatchStatement that) {
out("try");
that.getTryClause().getBlock().visit(this);
if (!that.getCatchClauses().isEmpty()) {
out("catch($ex0$)");
beginBlock();
out("var $ex$=$ex0$;");
endLine();
boolean firstCatch = true;
for (CatchClause catchClause : that.getCatchClauses()) {
Variable variable = catchClause.getCatchVariable().getVariable();
if (!firstCatch) {
out("else ");
}
firstCatch = false;
out("if(");
generateIsOfType(null, "$ex$", variable.getType(), true);
out("===");
clAlias();
out(".getTrue())");
if (catchClause.getBlock().getStatements().isEmpty()) {
out("{}");
} else {
beginBlock();
function();
out(getter(variable.getDeclarationModel()));
out("(){return $ex$}");
endLine();
visitStatements(catchClause.getBlock().getStatements(), false);
endBlock();
}
}
out("else{throw $ex$}");
endBlock();
}
if (that.getFinallyClause() != null) {
out("finally");
that.getFinallyClause().getBlock().visit(this);
}
}
@Override public void visit(Throw that) {
out("throw ");
if (that.getExpression() != null) {
that.getExpression().visit(this);
} else {
clAlias();
out(".Exception()");
}
out(";");
}
private void visitIndex(IndexExpression that) {
that.getPrimary().visit(this);
ElementOrRange eor = that.getElementOrRange();
if (eor instanceof Element) {
out(".item(");
((Element)eor).getExpression().visit(this);
out(")");
} else {//range, or spread?
out(".span(");
((ElementRange)eor).getLowerBound().visit(this);
if (((ElementRange)eor).getUpperBound() != null) {
out(",");
((ElementRange)eor).getUpperBound().visit(this);
}
out(")");
}
}
public void visit(IndexExpression that) {
IndexOperator op = that.getIndexOperator();
if (op instanceof SafeIndexOp) {
clAlias();
out(".exists(");
that.getPrimary().visit(this);
out(")===");
clAlias();
out(".getTrue()?");
}
visitIndex(that);
if (op instanceof SafeIndexOp) {
out(":");
clAlias();
out(".getNull()");
}
}
/** Creates and returns a name for a tmp var. */
private String createTempVariable() {
tmpvarCount++;
return "tmpvar$" + tmpvarCount;
}
private void caseClause(CaseClause cc, String expvar) {
out("if (");
final CaseItem item = cc.getCaseItem();
if (item instanceof IsCase) {
generateIsOfType(null, expvar, ((IsCase)item).getType(), true);
out("===");
clAlias(); out(".getTrue()");
} else if (item instanceof SatisfiesCase) {
out("true");
} else if (item instanceof MatchCase){
boolean first = true;
for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) {
if (!first) out(" || ");
out(expvar);
out("==="); //TODO equality?
/*out(".equals(");*/
exp.visit(this);
first = false;
}
} else {
out("WARNING!!! JS COMPILER OUT OF WHACK WITH TYPECHECKER");
}
out(") ");
//TODO code inside block makes wrong refs sometimes, need to fix that (similar to what happened with if (is)
cc.getBlock().visit(this);
}
@Override
public void visit(SwitchStatement that) {
out("//Switch"); endLine();
//Put the expression in a tmp var
//TODO is this really necessary?
final String expvar = createTempVariable();
out("var "); out(expvar); out("=");
that.getSwitchClause().getExpression().visit(this);
out(";"); endLine();
//For each case, do an if
boolean first = true;
for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) {
if (!first) out("else ");
caseClause(cc, expvar);
first = false;
}
if (that.getSwitchCaseList().getElseClause() != null) {
out("else ");
that.getSwitchCaseList().getElseClause().visit(this);
}
}
}
|
package com.syncleus.dann.genetics.wavelets;
import com.syncleus.dann.genetics.Gene;
import com.syncleus.dann.math.MathFunction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public abstract class WaveletGene implements Gene
{
private double currentActivity;
private double pendingActivity;
private ExpressionFunction expressionFunction;
private HashSet<SignalKeyConcentration> signalConcentrations;
private double mutability;
private static Random random = new Random();
protected WaveletGene(ReceptorKey initialReceptor)
{
this.expressionFunction = new ExpressionFunction(initialReceptor);
this.mutability = 1d;
this.signalConcentrations = new HashSet<SignalKeyConcentration>();
}
protected WaveletGene(WaveletGene copy)
{
this.currentActivity = copy.currentActivity;
this.pendingActivity = copy.pendingActivity;
this.expressionFunction = copy.expressionFunction;
this.mutability = copy.mutability;
this.signalConcentrations = new HashSet<SignalKeyConcentration>(copy.signalConcentrations);
}
protected Random getRandom()
{
return random;
}
protected double getMutability()
{
return this.mutability;
}
public MathFunction getExpressionActivityMathFunction()
{
return this.expressionFunction.getWaveletMathFunction();
}
public double expressionActivity()
{
return this.currentActivity;
}
public boolean bind(SignalKeyConcentration concentration, boolean isExternal)
{
if( this.expressionFunction.receives(concentration.getSignal()))
{
this.signalConcentrations.add(concentration);
return true;
}
return false;
}
public void preTick()
{
this.pendingActivity = this.expressionFunction.calculate(signalConcentrations);
}
public void tick()
{
this.currentActivity = this.pendingActivity;
}
public void mutate(Set<Key> keyPool)
{
this.currentActivity = 0.0;
this.pendingActivity = 0.0;
if(keyPool != null)
{
ReceptorKey newReceptor = new ReceptorKey(new ArrayList<Key>(keyPool).get(random.nextInt(keyPool.size())));
this.expressionFunction.mutate(mutability, newReceptor);
}
else
this.expressionFunction.mutate(mutability);
this.mutability = Mutation.mutabilityMutation(mutability);
}
@Override
public abstract WaveletGene clone();
}
|
package com.vaadin.demo.featurebrowser;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
/**
* Accordion is a derivative of TabSheet, a vertical tabbed layout that places
* the tab contents between the vertical tabs.
*/
@SuppressWarnings("serial")
public class AccordionExample extends CustomComponent {
public AccordionExample() {
// Create a new accordion
final Accordion accordion = new Accordion();
setCompositionRoot(accordion);
// Add a few tabs to the accordion.
for (int i = 0; i < 5; i++) {
// Create a root component for a accordion tab
VerticalLayout layout = new VerticalLayout();
// The accordion tab label is taken from the caption of the root
// component. Notice that layouts can have a caption too.
layout.setCaption("Tab " + (i + 1));
accordion.addComponent(layout);
// Add some components in each accordion tab
Label label = new Label("These are the contents of Tab " + (i + 1)
+ ".");
layout.addComponent(label);
TextField textfield = new TextField("Some text field");
layout.addComponent(textfield);
}
}
}
|
package backtype.storm.scheduler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Cluster {
/**
* key: supervisor id, value: supervisor details
*/
private Map<String, SupervisorDetails> supervisors;
/**
* key: topologyId, value: topology's current assignments.
*/
private Map<String, SchedulerAssignmentImpl> assignments;
/**
* a map from hostname to supervisor id.
*/
private Map<String, List<String>> hostToId;
public Cluster(Map<String, SupervisorDetails> supervisors, Map<String, SchedulerAssignmentImpl> assignments){
this.supervisors = new HashMap<String, SupervisorDetails>(supervisors.size());
this.supervisors.putAll(supervisors);
this.assignments = new HashMap<String, SchedulerAssignmentImpl>(assignments.size());
this.assignments.putAll(assignments);
this.hostToId = new HashMap<String, List<String>>();
for (String nodeId : supervisors.keySet()) {
SupervisorDetails supervisor = supervisors.get(nodeId);
String host = supervisor.getHost();
if (!this.supervisors.containsKey(host)) {
this.hostToId.put(host, new ArrayList<String>());
}
this.hostToId.get(host).add(nodeId);
}
}
/**
* Gets all the topologies which needs scheduling.
*
* @param topologies
* @return
*/
public List<TopologyDetails> needsSchedulingTopologies(Topologies topologies) {
List<TopologyDetails> ret = new ArrayList<TopologyDetails>();
for (TopologyDetails topology : topologies.getTopologies()) {
if (needsScheduling(topology)) {
ret.add(topology);
}
}
return ret;
}
/**
* Does the topology need scheduling?
*
* A topology needs scheduling if one of the following conditions holds:
* <ul>
* <li>Although the topology is assigned slots, but is squeezed. i.e. the topology is assigned less slots than desired.</li>
* <li>There are unassigned executors in this topology</li>
* </ul>
*/
public boolean needsScheduling(TopologyDetails topology) {
int desiredNumWorkers = topology.getNumWorkers();
int assignedNumWorkers = this.getAssignedNumWorkers(topology);
if (desiredNumWorkers > assignedNumWorkers) {
return true;
}
return this.getUnassignedExecutors(topology).size() > 0;
}
/**
* Gets a executor -> component-id map which needs scheduling in this topology.
*
* @param topology
* @return
*/
public Map<ExecutorDetails, String> getNeedsSchedulingExecutorToComponents(TopologyDetails topology) {
Collection<ExecutorDetails> allExecutors = new HashSet(topology.getExecutors());
SchedulerAssignment assignment = this.assignments.get(topology.getId());
if (assignment != null) {
Collection<ExecutorDetails> assignedExecutors = assignment.getExecutors();
allExecutors.removeAll(assignedExecutors);
}
return topology.selectExecutorToComponent(allExecutors);
}
/**
* Gets a component-id -> executors map which needs scheduling in this topology.
*
* @param topology
* @return
*/
public Map<String, List<ExecutorDetails>> getNeedsSchedulingComponentToExecutors(TopologyDetails topology) {
Map<ExecutorDetails, String> executorToComponents = this.getNeedsSchedulingExecutorToComponents(topology);
Map<String, List<ExecutorDetails>> componentToExecutors = new HashMap<String, List<ExecutorDetails>>();
for (ExecutorDetails executor : executorToComponents.keySet()) {
String component = executorToComponents.get(executor);
if (!componentToExecutors.containsKey(component)) {
componentToExecutors.put(component, new ArrayList<ExecutorDetails>());
}
componentToExecutors.get(component).add(executor);
}
return componentToExecutors;
}
/**
* Get all the used ports of this supervisor.
*
* @param cluster
* @return
*/
public List<Integer> getUsedPorts(SupervisorDetails supervisor) {
Map<String, SchedulerAssignment> assignments = this.getAssignments();
List<Integer> usedPorts = new ArrayList<Integer>();
for (SchedulerAssignment assignment : assignments.values()) {
for (WorkerSlot slot : assignment.getExecutorToSlot().values()) {
if (slot.getNodeId().equals(supervisor.getId())) {
usedPorts.add(slot.getPort());
}
}
}
return usedPorts;
}
/**
* Return the available ports of this supervisor.
*
* @param cluster
* @return
*/
public List<Integer> getAvailablePorts(SupervisorDetails supervisor) {
List<Integer> usedPorts = this.getUsedPorts(supervisor);
List<Integer> ret = new ArrayList<Integer>();
ret.addAll(supervisor.allPorts);
ret.removeAll(usedPorts);
return ret;
}
/**
* Return all the available slots on this supervisor.
*
* @param cluster
* @return
*/
public List<WorkerSlot> getAvailableSlots(SupervisorDetails supervisor) {
List<Integer> ports = this.getAvailablePorts(supervisor);
List<WorkerSlot> slots = new ArrayList<WorkerSlot>(ports.size());
for (Integer port : ports) {
slots.add(new WorkerSlot(supervisor.getId(), port));
}
return slots;
}
/**
* get the unassigned executors of the topology.
*/
public Collection<ExecutorDetails> getUnassignedExecutors(TopologyDetails topology) {
if (topology == null) {
return new ArrayList<ExecutorDetails>(0);
}
Collection<ExecutorDetails> ret = new HashSet(topology.getExecutors());
SchedulerAssignment assignment = this.getAssignmentById(topology.getId());
if (assignment != null) {
Set<ExecutorDetails> assignedExecutors = assignment.getExecutors();
ret.removeAll(assignedExecutors);
}
return ret;
}
/**
* Gets the number of workers assigned to this topology.
*
* @param topology
* @return
*/
public int getAssignedNumWorkers(TopologyDetails topology) {
SchedulerAssignment assignment = this.getAssignmentById(topology.getId());
if (topology == null || assignment == null) {
return 0;
}
Set<WorkerSlot> slots = new HashSet<WorkerSlot>();
slots.addAll(assignment.getExecutorToSlot().values());
return slots.size();
}
/**
* Assign the slot to the executors for this topology.
*
* @throws RuntimeException if the specified slot is already occupied.
*/
public void assign(WorkerSlot slot, String topologyId, Collection<ExecutorDetails> executors) {
if (this.isSlotOccupied(slot)) {
throw new RuntimeException("slot: [" + slot.getNodeId() + ", " + slot.getPort() + "] is already occupied.");
}
SchedulerAssignmentImpl assignment = (SchedulerAssignmentImpl)this.getAssignmentById(topologyId);
if (assignment == null) {
assignment = new SchedulerAssignmentImpl(topologyId, new HashMap<ExecutorDetails, WorkerSlot>());
this.assignments.put(topologyId, assignment);
} else {
for (ExecutorDetails executor : executors) {
if (assignment.isExecutorAssigned(executor)) {
throw new RuntimeException("the executor is already assigned, you should unassign it before assign it to another slot.");
}
}
}
assignment.assign(slot, executors);
}
/**
* Gets all the available slots in the cluster.
*
* @return
*/
public List<WorkerSlot> getAvailableSlots() {
List<WorkerSlot> slots = new ArrayList<WorkerSlot>();
for (SupervisorDetails supervisor : this.supervisors.values()) {
slots.addAll(this.getAvailableSlots(supervisor));
}
return slots;
}
/**
* Free the specified slot.
*
* @param slot
*/
public void freeSlot(WorkerSlot slot) {
// remove the slot from the existing assignments
for (SchedulerAssignmentImpl assignment : this.assignments.values()) {
if (assignment.isSlotOccupied(slot)) {
assignment.unassignBySlot(slot);
}
}
}
/**
* free the slots.
*
* @param slots
*/
public void freeSlots(Collection<WorkerSlot> slots) {
for (WorkerSlot slot : slots) {
this.freeSlot(slot);
}
}
/**
* Checks the specified slot is occupied.
*
* @param slot the slot be to checked.
* @return
*/
public boolean isSlotOccupied(WorkerSlot slot) {
for (SchedulerAssignment assignment : this.assignments.values()) {
if (assignment.isSlotOccupied(slot)) {
return true;
}
}
return false;
}
/**
* get the current assignment for the topology.
*/
public SchedulerAssignment getAssignmentById(String topologyId) {
if (this.assignments.containsKey(topologyId)) {
return this.assignments.get(topologyId);
}
return null;
}
/**
* Get a specific supervisor with the <code>nodeId</code>
*/
public SupervisorDetails getSupervisorById(String nodeId) {
if (this.supervisors.containsKey(nodeId)) {
return this.supervisors.get(nodeId);
}
return null;
}
/**
* Get all the supervisors on the specified <code>host</code>.
*
* @param host hostname of the supervisor
* @return the <code>SupervisorDetails</code> object.
*/
public List<SupervisorDetails> getSupervisorsByHost(String host) {
List<String> nodeIds = this.hostToId.get(host);
List<SupervisorDetails> ret = new ArrayList<SupervisorDetails>();
if (nodeIds != null) {
for (String nodeId : nodeIds) {
ret.add(this.getSupervisorById(nodeId));
}
}
return ret;
}
/**
* Get all the assignments.
*/
public Map<String, SchedulerAssignment> getAssignments() {
Map<String, SchedulerAssignment> ret = new HashMap<String, SchedulerAssignment>(this.assignments.size());
for (String topologyId : this.assignments.keySet()) {
ret.put(topologyId, this.assignments.get(topologyId));
}
return ret;
}
/**
* Get all the supervisors.
*/
public Map<String, SupervisorDetails> getSupervisors() {
return this.supervisors;
}
}
|
package com.valkryst.VTerminal.printer;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.component.Screen;
import lombok.Getter;
import lombok.Setter;
import java.util.Optional;
public class RectanglePrinter {
/** The width of the rectangle to print. */
@Getter private int width = 2;
/** The height of the rectangle to print. */
@Getter private int height = 2;
/** The title string. */
@Getter @Setter private String title;
/** The type of rectangle to print. */
@Getter @Setter private RectangleType rectangleType = RectangleType.HEAVY;
/**
* Prints a rectangle on the screen of a panel.
*
* @param panel
* The panel.
*
* @param column
* The x-axis (column) coordinate of the top-left character.
*
* @param row
* The y-axis (row) coordinate of the top-left character.
*/
public void print(final Panel panel, final int column, final int row) {
print(panel.getScreen(), column, row);
}
/**
* Prints a rectangle on a screen and attempts to connect the new
* rectangle with existing similar rectangles within the draw area.
*
* @param screen
* The screen.
*
* @param column
* The x-axis (column) coordinate of the top-left character.
*
* @param row
* The y-axis (row) coordinate of the top-left character.
*/
public void print(final Screen screen, final int column, final int row) {
print(screen, column, row, true);
}
/**
* Prints a rectangle on a screen.
*
* If the function is set to perform connections, then it will attempt
* to connect the new rectangle with existing similar rectangles in
* the draw area.
*
* @param screen
* The screen.
*
* @param column
* The x-axis (column) coordinate of the top-left character.
*
* @param row
* The y-axis (row) coordinate of the top-left character.
*
* @param performConnections
* Whether or not to perform connections.
*/
public void print(final Screen screen, final int column, final int row, final boolean performConnections) {
final int lastRow = row + height - 1;
final int lastColumn = column + width - 1;
// Draw Corners:
screen.write(rectangleType.getTopLeft(), column, row);
screen.write(rectangleType.getTopRight(), lastColumn, row);
screen.write(rectangleType.getBottomLeft(), column, lastRow);
screen.write(rectangleType.getBottomRight(), lastColumn, lastRow);
// Draw Left/Right Sides:
for (int i = 1 ; i < height - 1 ; i++) {
screen.write(rectangleType.getVertical(), column, row + i);
screen.write(rectangleType.getVertical(), lastColumn, row + i);
}
// Draw Top/Bottom Sides:
for (int i = 1 ; i < width - 1 ; i++) {
screen.write(rectangleType.getHorizontal(), column + i, row);
screen.write(rectangleType.getHorizontal(), column + i, lastRow);
}
// Draw title on Top Side:
if (title != null && title.isEmpty() == false) {
final char[] titleChars = title.toCharArray();
for (int i = 2; i < width - 1 && i <= titleChars.length + 1; i++) {
screen.write(titleChars[i - 2], column + i, row);
}
}
// Handle Connectors:
if (performConnections) {
setConnectors(screen, column, row);
}
}
/**
* Checks for, and sets, all positions of the printed rectangle where a
* connector character is required.
*
* @param screen
* The screen.
*
* @param column
* The x-axis (column) coordinate of the top-left character.
*
* @param row
* The y-axis (row) coordinate of the top-left character.
*/
private void setConnectors(final Screen screen, final int column, final int row) {
final int lastRow = row + height - 1;
final int lastColumn = column + width - 1;
// Check Corners:
setConnector(screen, column, row);
setConnector(screen, lastColumn, row);
setConnector(screen, column, lastRow);
setConnector(screen, lastColumn, lastRow);
// Check Left/Right Sides:
for (int i = 1 ; i < height - 1 ; i++) {
setConnector(screen, column, row + i);
setConnector(screen, lastColumn, row + i);
}
// Check Top/Bottom Sides:
for (int i = 1 ; i < width - 1 ; i++) {
setConnector(screen, column + i, row);
setConnector(screen, column + i, lastRow);
}
}
/**
* Checks if a character should be a connector and changes it to the
* appropriate connector character if it should be.
*
* @param screen
* The screen.
*
* @param column
* The x-axis (column) coordinate of the character.
*
* @param row
* The y-axis (row) coordinate of the character
*/
private void setConnector(final Screen screen, final int column, final int row) {
final boolean validTop = hasValidTopNeighbour(screen, column, row);
final boolean validBottom = hasValidBottomNeighbour(screen, column, row);
final boolean validLeft = hasValidLeftNeighbour(screen, column, row);
final boolean validRight = hasValidRightNeighbour(screen, column, row);
final boolean[] neighbourPattern = new boolean[]{validRight, validTop, validLeft, validBottom};
final Optional<Character> optChar = rectangleType.getCharacterByNeighbourPattern(neighbourPattern);
optChar.ifPresent(character -> screen.write(character, column, row));
}
/**
* Determines if the top-neighbour of a cell is both of the correct
* RectangleType and that the character of the top-neighbour can be
* connected to.
*
* @param column
* The x-axis (column) coordinate of the cell.
*
* @param row
* The y-axis (row) coordinate of the cell
*
* @return
* If the top-neighbour is valid.
*/
private boolean hasValidTopNeighbour(final Screen screen, final int column, final int row) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(column, row - 1);
return optChar.filter(asciiCharacter -> rectangleType.isValidTopCharacter(asciiCharacter)).isPresent();
}
/**
* Determines if the bottom-neighbour of a cell is both of the correct
* RectangleType and that the character of the bottom-neighbour can be
* connected to.
*
* @param column
* The x-axis (column) coordinate of the cell.
*
* @param row
* The y-axis (row) coordinate of the cell
*
* @return
* If the bottom-neighbour is valid.
*/
private boolean hasValidBottomNeighbour(final Screen screen, final int column, final int row) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(column, row + 1);
return optChar.filter(asciiCharacter -> rectangleType.isValidBottomCharacter(asciiCharacter)).isPresent();
}
/**
* Determines if the left-neighbour of a cell is both of the correct
* RectangleType and that the character of the left-neighbour can be
* connected to.
*
* @param column
* The x-axis (column) coordinate of the cell.
*
* @param row
* The y-axis (row) coordinate of the cell
*
* @return
* If the left-neighbour is valid.
*/
private boolean hasValidLeftNeighbour(final Screen screen, final int column, final int row) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(column - 1, row);
return optChar.filter(asciiCharacter -> rectangleType.isValidLeftCharacter(asciiCharacter)).isPresent();
}
/**
* Determines if the right-neighbour of a cell is both of the correct
* RectangleType and that the character of the right-neighbour can be
* connected to.
*
* @param column
* The x-axis (column) coordinate of the cell.
*
* @param row
* The y-axis (row) coordinate of the cell
*
* @return
* If the right-neighbour is valid.
*/
private boolean hasValidRightNeighbour(final Screen screen, final int column, final int row) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(column + 1, row);
return optChar.filter(asciiCharacter -> rectangleType.isValidRightCharacter(asciiCharacter)).isPresent();
}
/**
* Sets the width.
*
* @param width
* The new width.
*
* @return
* This.
*/
public RectanglePrinter setWidth(final int width) {
if (width > 0) {
this.width = width;
}
return this;
}
/**
* Sets the height.
*
* @param height
* The new height.
*
* @return
* This.
*/
public RectanglePrinter setHeight(final int height) {
if (height > 0) {
this.height = height;
}
return this;
}
}
|
package org.apache.hadoop.spatial;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
public class GridRecordWriter implements TigerShapeRecordWriter {
public static final Log LOG = LogFactory.getLog(GridRecordWriter.class);
/**An output stream for each grid cell*/
private CellInfo[] cells;
private OutputStream[] cellStreams;
private final Path outFile;
private final FileSystem fileSystem;
private Text text;
/**
* New line marker
*/
private static final byte[] NEW_LINE = {'\n'};
/**
* Store all information associated with a cell file
* @author eldawy
*
*/
class CellFileInfo extends CellInfo {
OutputStream output;
}
public GridRecordWriter(FileSystem outFileSystem, Path outFile,
CellInfo[] cells, boolean overwrite) throws IOException {
LOG.info("Writing without RTree");
this.fileSystem = outFileSystem;
this.outFile = outFile;
this.cells = cells;
// Prepare arrays that hold streams
cellStreams = new OutputStream[cells.length];
Vector<Path> filesToOverwrite = new Vector<Path>();
if (outFileSystem.exists(outFile)) {
filesToOverwrite.add(outFile);
}
for (int cellIndex = 0; cellIndex < cells.length; cellIndex++) {
Path cellFilePath = getCellFilePath(cellIndex);
if (outFileSystem.exists(cellFilePath) && overwrite)
filesToOverwrite.add(cellFilePath);
LOG.info("Partitioning according to cell: " + cells[cellIndex]);
}
if (!overwrite && !filesToOverwrite.isEmpty()) {
throw new RuntimeException("Cannot overwrite existing files: "+filesToOverwrite);
}
for (Path fileToOverwrite : filesToOverwrite)
outFileSystem.delete(fileToOverwrite, true);
text = new Text();
}
public synchronized void write(LongWritable dummyId, TigerShape shape) throws IOException {
text.clear();
shape.toText(text);
write(dummyId, shape, text);
}
/**
* Writes the given shape to the current grid file. The text representation that need
* to be written is passed for two reasons.
* 1 - Avoid converting the shape to text. (Performance)
* 2 - Some information may have been lost from the original line when converted to shape
* The text is assumed not to have a new line. This method writes a new line to the output
* after the given text is written.
* @param dummyId
* @param shape
* @param text
* @throws IOException
*/
public synchronized void write(LongWritable dummyId, TigerShape shape, Text text) throws IOException {
// Write to all possible grid cells
Rectangle mbr = shape.getMBR();
for (int cellIndex = 0; cellIndex < cells.length; cellIndex++) {
if (mbr.isIntersected(cells[cellIndex])) {
writeToCell(cellIndex, text);
}
}
}
/**
* A low level method to write a text to a specified cell.
*
* @param cellIndex
* @param text
* @throws IOException
*/
private synchronized void writeToCell(int cellIndex, Text text) throws IOException {
OutputStream cellStream = getCellStream(cellIndex);
cellStream.write(text.getBytes(), 0, text.getLength());
cellStream.write(NEW_LINE);
}
// Get a stream that writes to the given cell
private OutputStream getCellStream(int cellIndex) {
if (cellStreams[cellIndex] == null) {
try {
// Try to get a stream that writes directly to the file
cellStreams[cellIndex] = createCellFileStream(cellIndex);
} catch (IOException e) {
LOG.info("Cannot get a file handle. Using a temporary in memory stream instead");
// Cannot open more files. May be out of handles.
// Create a temporary memory-resident stream
cellStreams[cellIndex] = new ByteArrayOutputStream();
}
}
return cellStreams[cellIndex];
}
private OutputStream createCellFileStream(int cellIndex) throws IOException {
OutputStream cellStream;
Path cellFilePath = getCellFilePath(cellIndex);
if (!fileSystem.exists(cellFilePath)) {
// Create new file
cellStream = fileSystem.create(cellFilePath, cells[cellIndex]);
} else {
// Append to existing file
cellStream = fileSystem.append(cellFilePath);
}
return cellStream;
}
/**
* Write the given shape to a specific cell. The shape is not replicated to any other cells.
* It's just written to the given cell. This is useful when shapes are already assigned
* and replicated to grid cells another way, e.g. from a map phase that partitions.
* @param cellInfo
* @param rect
* @throws IOException
*/
public synchronized void write(CellInfo cellInfo, TigerShape rect) throws IOException {
if (rect == null) {
closeCell(cellInfo);
return;
}
text.clear();
rect.toText(text);
write(cellInfo, rect, text);
}
public synchronized void write(CellInfo cellInfo, TigerShape rect, Text text) throws IOException {
// Write to the cell given
int cellIndex = locateCell(cellInfo);
writeToCell(cellIndex, text);
}
public synchronized void write(CellInfo cellInfo, Text text) throws IOException {
if (text == null) {
closeCell(cellInfo);
return;
}
// Write to the cell given
int cellIndex = locateCell(cellInfo);
writeToCell(cellIndex, text);
}
private int locateCell(CellInfo cellInfo) {
// TODO use a hashtable for faster locating a cell
for (int cellIndex = 0; cellIndex < cells.length; cellIndex++)
if (cells[cellIndex].equals(cellInfo))
return cellIndex;
LOG.info("Could not find: "+cellInfo);
LOG.info("In this list");
for (int cellIndex = 0; cellIndex < cells.length; cellIndex++) {
LOG.info("#"+cellIndex+": " + cells[cellIndex]);
}
return -1;
}
public synchronized void close() throws IOException {
final Vector<Path> pathsToConcat = new Vector<Path>();
final int MaxConcurrentThreads = 10;
final Vector<Thread> closingThreads = new Vector<Thread>();
// Close all output files
for (int cellIndex = 0; cellIndex < cells.length; cellIndex++) {
if (cellStreams[cellIndex] != null || fileSystem.exists(getCellFilePath(cellIndex))) {
final int iCell = cellIndex;
closingThreads.add(new Thread() {
@Override
public void run() {
try {
flushCell(iCell);
finalizeCell(iCell);
Path cellPath = getCellFilePath(iCell);
if (fileSystem.exists(cellPath))
pathsToConcat.add(cellPath);
} catch (IOException e) {
e.printStackTrace();
}
}
});
closingThreads.lastElement().start();
// Limit number of concurrent threads to save memory
if (closingThreads.size() > MaxConcurrentThreads) {
try {
closingThreads.firstElement().join();
closingThreads.remove(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
for (Thread closingThread : closingThreads) {
try {
closingThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LOG.info("Closing... Merging "+pathsToConcat.size());
if (pathsToConcat.size() == 1) {
fileSystem.rename(pathsToConcat.firstElement(), outFile);
} else {
if (!pathsToConcat.isEmpty()) {
// Concat requires the target file to be a non-empty file with the same
// block size as source files
Path target = pathsToConcat.lastElement();
pathsToConcat.remove(pathsToConcat.size()-1);
Path[] paths = pathsToConcat.toArray(new Path[pathsToConcat.size()]);
fileSystem.concat(target, paths);
fileSystem.rename(target, outFile);
}
LOG.info("Concatenated files into: "+outFile);
}
LOG.info("Final file size: "+fileSystem.getFileStatus(outFile).getLen());
}
// Create a buffer filled with new lines
final static byte[] buffer = new byte[1024 * 1024];
static {
Arrays.fill(buffer, (byte)'\n');
}
/**
* Close the given cell freeing all memory reserved by it.
* Once a cell is closed, we should not write more data to it.
* @param cellInfo
* @throws IOException
*/
@Override
public void closeCell(CellInfo cellInfo) throws IOException {
int cellIndex = locateCell(cellInfo);
// Flush all outstanding writes to the file
flushCell(cellIndex);
if (fileSystem.getConf().getBoolean("dfs.support.append", false)) {
// Close the file. We can later append to it or finalize it
if (cellStreams[cellIndex] != null) {
cellStreams[cellIndex].close();
cellStreams[cellIndex] = null;
}
} else {
// File system doesn't support append. We need to finalize it right now
finalizeCell(cellIndex);
}
}
/**
* Flush current buffer to the given cell and reset buffer.
* @param cellIndex
* @throws IOException
*/
private void flushCell(int cellIndex) throws IOException {
OutputStream cellStream = cellStreams[cellIndex];
// Flush only needed for temporary byte array outputstream
if (cellStream == null || !(cellStream instanceof ByteArrayOutputStream))
return;
cellStream.close();
byte[] bytes = ((ByteArrayOutputStream) cellStream).toByteArray();
cellStreams[cellIndex] = createCellFileStream(cellIndex);
cellStreams[cellIndex].write(bytes);
}
/**
* Finalize the given cell file and makes it ready to be concatenated with
* other cell files. This function should be called at the very end. Once
* called, you should not append any more data to this cell.
* If a stream is open to the given file, we use it to write empty lines to
* the file to be a multiple of block size. If the file has been already
* closed, we open it for append (if supported) and write empty lines.
* If in the later case append is not supported, the method fails and an
* IOException is thrown.
* @param cellIndex - The index of the cell to be written
* @param buffer - A buffer used to fill the cell file until it reaches a
* size that is multiple of block size
* @throws IOException
*/
private void finalizeCell(int cellIndex) throws IOException {
if (!fileSystem.exists(getCellFilePath(cellIndex)))
return;
// Get current file size
OutputStream cellStream = cellStreams[cellIndex];
long cellSize;
// Check if the file was previously closed and need to be finalized
if (cellStream == null) {
cellSize = fileSystem.getFileStatus(getCellFilePath(cellIndex)).getLen();
} else {
// I don't want to use getFileSize here because the file might still be
cellSize = ((FSDataOutputStream)cellStream).getPos();
}
// Check if we need to write empty lines
long blockSize =
fileSystem.getFileStatus(getCellFilePath(cellIndex)).getBlockSize();
LOG.info("Current size: "+cellSize);
// Stuff all open streams with empty lines until each one is 64 MB
long remainingBytes = (blockSize - cellSize % blockSize) % blockSize;
if (remainingBytes > 0) {
LOG.info("Stuffing file " + cellIndex + " with new lines: " + remainingBytes);
if (cellStream == null) {
// Open for append. An exception is throws if FS doesn't support append
cellStream = createCellFileStream(cellIndex);
}
// Write some bytes so that remainingBytes is multiple of buffer.length
cellStream.write(buffer, 0, (int)(remainingBytes % buffer.length));
remainingBytes -= remainingBytes % buffer.length;
// Write chunks of size buffer.length
while (remainingBytes > 0) {
cellStream.write(buffer);
remainingBytes -= buffer.length;
}
}
if (cellStream != null) {
// Close stream
cellStream.close();
cellStreams[cellIndex] = null;
}
// Now getFileSize should work because the file is closed
LOG.info("Actual size: "+fileSystem.getFileStatus(getCellFilePath(cellIndex)).getLen());
}
/**
* Return path to a file that is used to write one grid cell
* @param column
* @param row
* @return
*/
private Path getCellFilePath(int cellIndex) {
return new Path(outFile.toUri().getPath() + '_' + cellIndex);
}
@Override
public void write(CellInfo cellInfo, BytesWritable buffer) throws IOException {
throw new RuntimeException("Not supported");
}
}
|
package dr.evomodel.substmodel;
import dr.math.matrixAlgebra.WrappedMatrix;
/**
* @author Marc A. Suchard
* @author Xiang Ji
*/
public interface DifferentialMassProvider {
double[] getDifferentialMassMatrix(double time);
class DifferentialWrapper implements DifferentialMassProvider {
private final DifferentiableSubstitutionModel baseModel;
private final WrtParameter wrt;
public DifferentialWrapper(DifferentiableSubstitutionModel baseModel,
WrtParameter wrt) {
this.baseModel = baseModel;
this.wrt = wrt;
}
@Override
public double[] getDifferentialMassMatrix(double time) {
WrappedMatrix infinitesimalDifferentialMatrix = baseModel.getInfinitesimalDifferentialMatrix(wrt);
return DifferentiableSubstitutionModelUtil.getDifferentialMassMatrix(time, baseModel.getDataType().getStateCount(),
infinitesimalDifferentialMatrix, baseModel.getEigenDecomposition());
}
public interface WrtParameter {
double getRate(int switchCase, double normalizingConstant,
DifferentiableSubstitutionModel substitutionModel);
}
}
}
|
package edu.brandeis.cs.steele.wn.browser;
import javax.swing.JApplet;
import java.util.logging.*;
import java.net.URL;
import edu.brandeis.cs.steele.wn.DictionaryDatabase;
import edu.brandeis.cs.steele.wn.FileBackedDictionary;
import edu.brandeis.cs.steele.wn.RemoteFileManager;
public class BrowserApplet extends JApplet {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(BrowserApplet.class.getName());
public void init() {
final URL url = getCodeBase();
if (log.isLoggable(Level.FINEST)) {
log.finest("url = "+url);
}
String hostname = url.getHost();
if (url.getPort() != -1) {
hostname += ":" + url.getPort();
}
if (log.isLoggable(Level.FINEST)) {
log.finest("hostname = "+hostname);
}
final DictionaryDatabase dictionary;
try {
dictionary = FileBackedDictionary.getInstance(RemoteFileManager.lookup(hostname));
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("dictionary = "+dictionary);
}
throw new UnsupportedOperationException("FIXME");
//FIXME add(new BrowserPanel(dictionary));
}
}
|
package edu.uw.easysrl.semantics.lexicon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableSet;
import edu.uw.easysrl.dependencies.Coindexation;
import edu.uw.easysrl.dependencies.ResolvedDependency;
import edu.uw.easysrl.dependencies.SRLFrame;
import edu.uw.easysrl.dependencies.SRLFrame.SRLLabel;
import edu.uw.easysrl.semantics.AtomicSentence;
import edu.uw.easysrl.semantics.ConnectiveSentence;
import edu.uw.easysrl.semantics.ConnectiveSentence.Connective;
import edu.uw.easysrl.semantics.Constant;
import edu.uw.easysrl.semantics.LambdaExpression;
import edu.uw.easysrl.semantics.Logic;
import edu.uw.easysrl.semantics.OperatorSentence;
import edu.uw.easysrl.semantics.OperatorSentence.Operator;
import edu.uw.easysrl.semantics.QuantifierSentence;
import edu.uw.easysrl.semantics.QuantifierSentence.Quantifier;
import edu.uw.easysrl.semantics.SemanticType;
import edu.uw.easysrl.semantics.Sentence;
import edu.uw.easysrl.semantics.SkolemTerm;
import edu.uw.easysrl.semantics.Variable;
import edu.uw.easysrl.syntax.grammar.Category;
import edu.uw.easysrl.syntax.grammar.Combinator.RuleType;
import edu.uw.easysrl.syntax.grammar.SyntaxTreeNode;
import edu.uw.easysrl.syntax.parser.SRLParser.CCGandSRLparse;
/**
* Automatically constructs a default semantics for a word based on its category
*
*/
public class DefaultLexicon extends Lexicon {
private static final Constant ANSWER = new Constant("ANSWER", SemanticType.E);
/**
* Useful to distinguish auxiliary and implicative verbs, which have the same category (S\NP)/(S\NP).
*/
private final ImmutableSet<String> auxiliaryVerbs = ImmutableSet.of("be", "do", "have", "go");
private final String ARG = "ARG";
// POS tags for content words.
private final static Set<String> contentPOS = ImmutableSet.of("NN", "VB", "JJ", "RB", "PR", "RP", "IN", "PO");
private final static List<SRLLabel> noLabels = Arrays.asList(SRLFrame.NONE, SRLFrame.NONE, SRLFrame.NONE,
SRLFrame.NONE, SRLFrame.NONE, SRLFrame.NONE);
@Override
Logic getEntry(final String word, final String pos, final Category category, final Coindexation coindexation,
final Optional<CCGandSRLparse> parse, final int wordIndex) {
final String lemma = getLemma(word, pos, parse, wordIndex);
if (Category.valueOf("conj|conj").matches(category)) {
// Special case, since we have other rules to deal with this non-compositionally.
return new Constant(lemma, SemanticType.E);
}
final List<SRLLabel> labels;
if (parse.isPresent()) {
final List<ResolvedDependency> deps = parse.get().getOrderedDependenciesAtPredicateIndex(wordIndex);
// Find the semantic role for each argument of the category.
labels = deps.stream().map(x -> x == null ? SRLFrame.NONE : x.getSemanticRole())
.collect(Collectors.toList());
} else {
labels = noLabels;
}
final HeadAndArguments headAndArguments = new HeadAndArguments(category, coindexation);
return LambdaExpression.make(
getEntry(lemma, category, coindexation, headAndArguments.argumentVariables,
headAndArguments.headVariable, null, headAndArguments.coindexationIDtoVariable,
isContentWord(lemma, pos, category), labels), headAndArguments.argumentVariables);
}
private boolean isContentWord(final String word, final String pos, final Category category) {
if (!(pos.length() > 1 && contentPOS.contains(pos.substring(0, 2)))) {
return false;
} else if (auxiliaryVerbs.contains(word)
&& (Category.valueOf("(S\\NP)/(S\\NP)").matches(category) || Category.valueOf("(S[q]/(S\\NP))/NP")
.matches(category))) {
// Auxiliary verbs
return false;
} else {
return true;
}
}
/**
* Recursively builds up logical form, add interpretations for arguments from right to left.
*/
private Logic getEntry(final String word, final Category category, final Coindexation coindexation,
final List<Variable> vars, final Variable head, final Sentence resultSoFar,
final Map<Coindexation.IDorHead, Variable> idToVar, final boolean isContentWord, final List<SRLLabel> labels) {
SRLLabel label = labels.size() == 0 ? SRLFrame.NONE : labels.get(labels.size() - 1);
if (category.getNumberOfArguments() > 0 && category.getLeft().isModifier() && labels.size() > 1
&& labels.get(labels.size() - 2) != SRLFrame.NONE) {
// For transitive modifier categories, like (S\S)/NP or ((S\NP)\(S\NP)/NP move the semantic role to the
// argument.
// Hacky, but simplifies things a lot.
label = labels.get(labels.size() - 2);
labels.set(labels.size() - 2, SRLFrame.NONE);
}
if (Category.valueOf("(NP|NP)|(NP|NP)").matches(category)
|| Category.valueOf("(PP|PP)|(PP|PP)").matches(category)) {
// Hate these categories soo much.
return head;
}
// A label for this argument, either a semantic role or "ARG".
final String argumentLabel = (label == SRLFrame.NONE) ? ARG : label.toString();
if (category.getNumberOfArguments() == 0) {
// Base case. N, S, NP etc.
if (Category.N.matches(category) || Category.S.matches(category.getArgument(0))) {
return ConnectiveSentence
.make(Connective.AND, resultSoFar != null && (word == null || !isContentWord) ? null
: new AtomicSentence(word, head), resultSoFar);
} else if (category == Category.NP || category == Category.PP) {
if (resultSoFar == null) {
// Pronouns, named-entities, etc. are just constants.
return new Constant(word, SemanticType.E);
}
// NP/N --> sk(#x . p(x))
return new SkolemTerm(new LambdaExpression(resultSoFar, head));
} else if (category == Category.PR) {
return new Constant(word, SemanticType.E);
} else {
return new Constant(word, SemanticType.E);
}
} else if (isFunctionIntoEntityModifier(category) && category.getNumberOfArguments() == 1) {
if (resultSoFar == null) {
// PP/NP --> #x . x
return head;
} else {
// Functions into NP\NP get special treatment.
// (NP\NP)/(S\NP) --> #p#x . sk(#y . p(y) & x=y)
final Variable y = new Variable(SemanticType.E);
return new SkolemTerm(new LambdaExpression(ConnectiveSentence.make(Connective.AND, new AtomicSentence(
equals, head, y), resultSoFar), y));
}
} else {
final Variable predicate = vars.get(0);
if (category.isModifier() && coindexation.isModifier()) {
// Modifier categories.
// (S\NP)/(S\NP) --> #p#x#e . lemma(e) & p(x,e)
// S/S --> #p#e . lemma(e) & p(e)
// (S/S)/(S/S) --> #p#q#e . lemma(e) & p(e) & q(p, e)
final Sentence modifier;
final AtomicSentence px = new AtomicSentence(predicate, vars.subList(1, vars.size()));
if (resultSoFar != null || word == null || !isContentWord) {
// Non-content word modifiers
modifier = null;
} else if (label == SRLFrame.NONE) {
// No semantic role: foo(e)
modifier = new AtomicSentence(word, head);
} else if (label == SRLFrame.NEG) {
// Special case negation
return ConnectiveSentence.make(Connective.AND, new OperatorSentence(Operator.NOT, px), resultSoFar);
} else {
// Semantic role: TMP(yesterday, e)
modifier = new AtomicSentence(argumentLabel, new Constant(word, SemanticType.E), head);
}
return ConnectiveSentence.make(Connective.AND, px, modifier, resultSoFar);
} else {
return getEntryComplexCategories(word, category, coindexation, vars, head, resultSoFar, idToVar,
isContentWord, labels, label, argumentLabel);
}
}
}
private Logic getEntryComplexCategories(final String word, final Category category,
final Coindexation coindexation, final List<Variable> vars, final Variable head,
final Sentence resultSoFar, final Map<Coindexation.IDorHead, Variable> idToVar,
final boolean isContentWord, final List<SRLLabel> labels, final SRLLabel label, final String argumentLabel) {
// Other complex categories.
final Category argument = category.getRight();
final Variable predicate = vars.get(0);
Sentence resultForArgument;
if (isWhQuestion(category) && (argument.equals(Category.NP) || argument.equals(Category.PP))) {
// wh-questions. The NP argument is the answer.
resultForArgument = ConnectiveSentence.make(Connective.AND, new AtomicSentence(equals, predicate, ANSWER),
resultSoFar);
} else if (isDuplicateArgument(coindexation)) {
// Avoid creating duplicate argument.
resultForArgument = resultSoFar;
} else if (argument.getNumberOfArguments() == 0) {
resultForArgument = getEntryComplexCategoriesWithAtomicArgument(word, category, head, resultSoFar,
isContentWord, label, argumentLabel, predicate);
} else if (Category.valueOf("NP|NP").matches(argument) || Category.valueOf("NP|N").matches(argument)
|| Category.valueOf("(N\\N)/NP").matches(argument)
|| Category.valueOf("(NP|NP)|(NP|NP)").matches(argument)) {
// Very rare and weird (NP/NP) arguments. Discard these.
resultForArgument = resultSoFar;
} else {
resultForArgument = getEntryComplexCategoryWithComplexArgument(category, coindexation, head, resultSoFar,
idToVar, argumentLabel, predicate);
}
// Recursively build up the next interpretation for the other arguments.
return getEntry(word, category.getLeft(), coindexation.getLeft(), vars.subList(1, vars.size()), head,
resultForArgument, idToVar, isContentWord, labels.subList(0, labels.size() - 1));
}
private Sentence getEntryComplexCategoryWithComplexArgument(final Category category,
final Coindexation coindexation, final Variable head, final Sentence resultSoFar,
final Map<Coindexation.IDorHead, Variable> idToVar, final String argumentLabel, final Variable predicate) {
final Category argument = category.getRight();
Sentence resultForArgument;
// Complex argument, e.g. ((S[dcl]\NP)/NP_1)/(S[to]\NP_1)
// Build up a list of the arguments of the argument. If these arguments aren't supplied elsewhere,
// need to quantify them.
final List<Logic> argumentsOfArgument = new ArrayList<>(argument.getNumberOfArguments());
final List<Variable> toQuantify = new ArrayList<>();
Coindexation coindexationOfArgument = coindexation.getRight();
for (int i = argument.getNumberOfArguments(); i > 0; i
// Iterate over arguments of argument.
Logic argumentSemantics;
final Coindexation.IDorHead id = coindexationOfArgument.getRight().getID();
if (idToVar.containsKey(id)) {
// Argument is co-indexed with another argument.
final Variable coindexedVar = idToVar.get(id);
final SemanticType variableType = coindexedVar.getType();
final SemanticType expectedType = SemanticType.makeFromCategory(argument.getArgument(i));
if (variableType == SemanticType.EtoT && expectedType == SemanticType.E) {
// NP argument coindexed with N
if (isWhQuestion(category)) {
// Question where the N is the answer, as in Which dog barks?
// sk(#x.p(x) & x=ANSWER)
final Variable x = new Variable(SemanticType.E);
argumentSemantics = new SkolemTerm(new LambdaExpression(ConnectiveSentence.make(Connective.AND,
new AtomicSentence(coindexedVar, x), new AtomicSentence(equals, x, ANSWER)), x));
} else {
// sk(#x.p(x))
argumentSemantics = makeSkolem(coindexedVar);
}
} else {
argumentSemantics = idToVar.get(id);
}
} else if (isWhQuestion(category) && argument.getArgument(i) == Category.NP && resultSoFar == null) {
// Categories like: S[wq]/(S[dcl\NP)
argumentSemantics = ANSWER;
} else {
// Not coindexed - make a new variable, and quantify it later.
final Category argumentOfArgument = argument.getArgument(i);
final Variable var = new Variable(SemanticType.makeFromCategory(argumentOfArgument));
toQuantify.add(var);
argumentSemantics = var;
}
argumentsOfArgument.add(argumentSemantics);
coindexationOfArgument = coindexationOfArgument.getLeft();
}
// We need to add an extra variable for functions into N and S
// e.g. an S\NP argument p needs arguments p(x, e)
if (argument.getArgument(0) == Category.N || Category.S.matches(argument.getArgument(0))) {
final Coindexation.IDorHead id = coindexationOfArgument.getID();
if (idToVar.containsKey(id)) {
argumentsOfArgument.add(idToVar.get(id));
} else {
final Variable var = new Variable(argument.getArgument(0) == Category.N ? SemanticType.E
: SemanticType.Ev);
toQuantify.add(var);
argumentsOfArgument.add(var);
}
}
Sentence argumentSemantics = new AtomicSentence(predicate, argumentsOfArgument);
if (toQuantify.contains(argumentsOfArgument.get(argumentsOfArgument.size() - 1))
&& !argumentsOfArgument.contains(head)) {
// Link the head of the argument back to the head of the construction.
argumentSemantics = ConnectiveSentence.make(Connective.AND, argumentSemantics, new AtomicSentence(
argumentLabel, argumentsOfArgument.get(argumentsOfArgument.size() - 1), head));
}
// Existentially quantify any missing variables
for (final Variable var : toQuantify) {
argumentSemantics = new QuantifierSentence(Quantifier.EXISTS, var, argumentSemantics);
}
resultForArgument = ConnectiveSentence.make(Connective.AND, argumentSemantics, resultSoFar);
return resultForArgument;
}
private Sentence getEntryComplexCategoriesWithAtomicArgument(final String word, final Category category,
final Variable head, final Sentence resultSoFar, final boolean isContentWord, final SRLLabel label,
final String argumentLabel, final Variable predicate) {
final Category argument = category.getRight();
Sentence resultForArgument;
// Atomic argument, e.g. S\NP
if (argument.equals(Category.NP) || argument.equals(Category.PP)) {
if (category.isFunctionIntoModifier()) {
// No semantic role --> on:(S\S)/NP --> #x#p#e . p(e) & on(x,e)
// With semantic role --> on:(S\S)/NP --> #x#p#e . p(e) & TMP(x,e)
resultForArgument = ConnectiveSentence.make(Connective.AND, new AtomicSentence(
label == SRLFrame.NONE ? word : argumentLabel, predicate, head), resultSoFar);
} else {
// (S\NP)/NP --> ... & arg(y, x)
resultForArgument = isContentWord ? ConnectiveSentence.make(Connective.AND, new AtomicSentence(
argumentLabel, predicate, head), resultSoFar) : resultSoFar;
}
} else if (Category.N.matches(argument)) {
if (head.getType() == SemanticType.Ev) {
// S/N --> #p#e . ARG(sk(#x.p(x)),e)
resultForArgument = ConnectiveSentence.make(Connective.AND, new AtomicSentence(argumentLabel,
makeSkolem(predicate), head), resultSoFar);
} else {
// NP/N --> ... & p(x)
resultForArgument = ConnectiveSentence.make(Connective.AND, new AtomicSentence(predicate, head),
resultSoFar);
}
} else if (argument.equals(Category.PR) || argument.equals(Category.NPthr) || argument.equals(Category.NPexpl)) {
// Semantically vacuous arguments
resultForArgument = resultSoFar;
} else if (Category.S.matches(argument)) {
// N/S --> ... & p(ev)
final Variable ev = new Variable(SemanticType.Ev);
resultForArgument = ConnectiveSentence.make(
Connective.AND,
new QuantifierSentence(Quantifier.EXISTS, ev, ConnectiveSentence.make(Connective.AND,
new AtomicSentence(predicate, ev), new AtomicSentence(argumentLabel, ev, head))),
resultSoFar);
} else {
throw new IllegalStateException();
}
return resultForArgument;
}
private boolean isWhQuestion(final Category category) {
return category.isFunctionInto(Category.valueOf("S[wq]"))
&& !category.isFunctionInto(Category.valueOf("S[dcl]")) // Hacky way of avoiding matches to S[X]
&& !category.isFunctionIntoModifier();
}
private SkolemTerm makeSkolem(final Logic predicate) {
final Variable x = new Variable(SemanticType.E);
return new SkolemTerm(new LambdaExpression(new AtomicSentence(predicate, x), x));
}
/*
* (non-Javadoc)
*
* @see
* edu.uw.easysrl.semantics.lexicon.AbstractLexicon#isMultiWordExpression(edu.uw.easysrl.syntax.grammar.SyntaxTreeNode
* )
*/
@Override
public boolean isMultiWordExpression(final SyntaxTreeNode node) {
if (node.getLeaves().stream().allMatch(x -> x.getPos().startsWith("NNP"))) {
// Analyze "Barack Obama" as barack_obama, not #x.barack(x)&obama(x)
return true;
} else if (node.getCategory() == Category.CONJ && node.getRuleType() != RuleType.LP
&& node.getRuleType() != RuleType.RP) {
// Don't bother trying to do multi-word conjunctions compositionally (e.g. "as well as").
return true;
}
return false;
}
/**
* Looks for cases like (S_1/(S_1\NP_2))/NP_2 or (NP_1/(N_1/PP_2))\NP_2 where we don't want to make _2 an argument
* of _1 twice.
*/
private boolean isDuplicateArgument(Coindexation indexation) {
final Coindexation argument = indexation.getRight();
while (indexation.getLeft() != null) {
indexation = indexation.getLeft();
Coindexation otherArgument = indexation.getRight();
if (otherArgument != null && indexation.getLeftMost().getID().equals(otherArgument.getLeftMost().getID())) {
while (otherArgument.getLeft() != null) {
if (argument.getID().equals(otherArgument.getRight().getID())) {
return true;
}
otherArgument = otherArgument.getLeft();
}
}
}
return false;
}
}
|
package emergencylanding.k.library.debug;
import java.util.HashMap;
import org.lwjgl.opengl.Display;
import emergencylanding.k.imported.Sync;
import emergencylanding.k.library.internalstate.ELEntity;
import emergencylanding.k.library.internalstate.world.World;
import emergencylanding.k.library.internalstate.world.WorldManager;
import emergencylanding.k.library.lwjgl.DisplayLayer;
import emergencylanding.k.library.lwjgl.render.*;
import emergencylanding.k.library.main.KMain;
public class CollisionsTest extends KMain {
private static Thread is;
private static boolean run = true;
private static Thread ip;
private static final int TICKS_PER_SECOND = 20;
private static final int FRAMES_PER_SECOND = 1200;
public static final int DISPLAY_FPS_INDEX = 0, IS_INDEX = FPS.genIndex(),
INTERPOLATE_INDEX = FPS.genIndex();
private static World w;
private static TestCollisionEntity e;
private static TestCollisionEntity e2;
private static TestCollisionEntity e3;
public static void main(String[] args) {
try {
DisplayLayer.initDisplay(false, 800, 500, "Testing Collisions",
false, false, args);
FPS.enable(CollisionsTest.DISPLAY_FPS_INDEX);
CollisionsTest.startISThreads();
while (CollisionsTest.run) {
CollisionsTest.run = !Display.isCloseRequested();
DisplayLayer.loop(CollisionsTest.FRAMES_PER_SECOND);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DisplayLayer.destroy();
System.exit(0);
}
}
private static void startISThreads() {
Runnable isr = new Runnable() {
Sync s = new Sync();
@Override
public void run() {
FPS.init(CollisionsTest.IS_INDEX);
while (CollisionsTest.run) {
e.setRelativeXYZ(0, 1, 0);
s.sync(CollisionsTest.TICKS_PER_SECOND);
int delta = FPS.update(CollisionsTest.IS_INDEX);
DisplayLayer.readDevices();
WorldManager.update(delta);
if (e.collidesWith(e2)) {
System.err.println("**BOOM**");
run = false;
}
}
}
};
CollisionsTest.is = new Thread(isr);
CollisionsTest.is.setName("Internal State Thread");
CollisionsTest.is.start();
Runnable ipr = new Runnable() {
Sync s = new Sync();
@Override
public void run() {
FPS.init(CollisionsTest.INTERPOLATE_INDEX);
while (CollisionsTest.run) {
s.sync(CollisionsTest.FRAMES_PER_SECOND);
int delta = FPS.update(CollisionsTest.INTERPOLATE_INDEX);
WorldManager.interpolate(delta);
}
}
};
CollisionsTest.ip = new Thread(ipr);
CollisionsTest.ip.setName("Interpolation Thread");
CollisionsTest.ip.setDaemon(true);
CollisionsTest.ip.start();
System.err.println("ISThreads running!");
}
@Override
public void onDisplayUpdate(int delta) {
RenderManager.render(delta);
}
@Override
public void init(String[] args) {
w = new World();
WorldManager.addWorldToSystem(w);
e = new TestCollisionEntity(w, 50, 250, 50);
e2 = new TestCollisionEntity(w, 50, 400, 50);
e3 = new TestCollisionEntity(w, 50, 50, 50);
e.setPitch(45);
e2.setPitch(0);
w.addEntity(e);
w.addEntity(e2);
w.addEntity(e3);
}
@Override
public void registerRenders(
HashMap<Class<? extends ELEntity>, Render<? extends ELEntity>> classToRender) {
classToRender.put(TestCollisionEntity.class, new TextureRender());
}
}
|
package uno.perwironegoro.boardgames.pawnrace;
import uno.perwironegoro.boardgames.Board;
import uno.perwironegoro.boardgames.Colour;
import uno.perwironegoro.boardgames.Symbols;
import uno.perwironegoro.boardgames.UtilsBoard;
public class BoardPR extends Board {
public static final char ARBCHAR = '@';
private static final Symbols sym = new SymbolsPR();
public BoardPR(BoardPR b) {
super(b.getWidth(), b.getHeight());
for (int x = 1; x <= b.getWidth(); x++) {
for (int y = 1; y <= b.getHeight(); y++) {
copyOntoBoard(b.getSquare(x, y));
}
}
}
public BoardPR(char blackGap, char whiteGap) {
this(8, 8, blackGap, whiteGap);
}
public BoardPR(int width, int height, char whiteGap, char blackGap) {
super(width, height);
assert (width >= 2) : "Min board width: 2";
assert (height >= 4) : "Max board height: 4";
for (int x = 0; x < width; x++) {
squares[x][height - 2].setOccupier(Colour.BLACK);
squares[x][1].setOccupier(Colour.WHITE);
}
if (blackGap != ARBCHAR) {
squares[UtilsBoard.alphaCharToIndex(blackGap) - 1][height - 2].setOccupier(Colour.NONE);
}
if (whiteGap != ARBCHAR) {
squares[UtilsBoard.alphaCharToIndex(whiteGap) - 1][1].setOccupier(Colour.NONE);
}
}
public void applyMove(MovePR move) {
super.applyMove(move);
if (move.isEnPassant()) {
UtilsPR.getBoardSquareBefore(move.getTo(), this).setOccupier(Colour.NONE);
}
}
public void unapplyMove(MovePR move) {
super.unapplyMove(move);
Colour movedPlayer = move.getTo().getOccupier();
if (move.isEnPassant()) {
getBoardSquare(UtilsPR.getBoardSquareBefore(move.getTo(), this)).setOccupier(movedPlayer.opposite());
} else if (move.isCapture()) {
getBoardSquare(move.getTo()).setOccupier(movedPlayer.opposite());
}
}
public void display() {
super.display(sym);
}
}
|
package protocolsupport.protocol.storage;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedEntity;
import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedPlayer;
import com.mojang.authlib.properties.Property;
public class LocalStorage {
private TIntObjectHashMap<WatchedEntity> watchedEntities = new TIntObjectHashMap<WatchedEntity>();
private WatchedPlayer player;
private HashMap<UUID, String> playersNames = new HashMap<UUID, String>();
@SuppressWarnings("serial")
private HashMap<UUID, PropertiesStorage> properties = new HashMap<UUID, PropertiesStorage>() {
@Override
public PropertiesStorage get(Object uuid) {
if (!super.containsKey(uuid)) {
super.put((UUID) uuid, new PropertiesStorage());
}
return super.get(uuid);
}
};
public void addWatchedEntity(WatchedEntity entity) {
watchedEntities.put(entity.getId(), entity);
}
public void addWatchedSelfPlayer(WatchedPlayer player) {
this.player = player;
addWatchedEntity(player);
}
private void readdSelfPlayer() {
if (player != null) {
addWatchedEntity(player);
}
}
public WatchedEntity getWatchedEntity(int entityId) {
return watchedEntities.get(entityId);
}
public void removeWatchedEntities(int[] entityIds) {
for (int entityId : entityIds) {
watchedEntities.remove(entityId);
}
readdSelfPlayer();
}
public void clearWatchedEntities() {
watchedEntities.clear();
readdSelfPlayer();
}
public void addPlayerListName(UUID uuid, String name) {
playersNames.put(uuid, name);
}
public String getPlayerListName(UUID uuid) {
String name = playersNames.get(uuid);
if (name == null) {
Player player = Bukkit.getPlayer(uuid);
if (player != null) {
return player.getName();
}
}
if (name == null) {
return "Unknown";
}
return name;
}
public void removePlayerListName(UUID uuid) {
playersNames.remove(uuid);
}
public void addPropertyData(UUID uuid, Property property) {
properties.get(uuid).addProperty(property);
}
public List<Property> getPropertyData(UUID uuid, boolean signedOnly) {
return properties.get(uuid).getProperties(signedOnly);
}
public void removePropertyData(UUID uuid) {
properties.remove(uuid);
}
private static class PropertiesStorage {
private final HashMap<String, Property> signed = new HashMap<String, Property>();
private final HashMap<String, Property> unsigned = new HashMap<String, Property>();
public void addProperty(Property property) {
if (property.hasSignature()) {
signed.put(property.getName(), property);
} else {
unsigned.put(property.getName(), property);
}
}
public List<Property> getProperties(boolean signedOnly) {
if (signedOnly) {
return new ArrayList<Property>(signed.values());
} else {
ArrayList<Property> properties = new ArrayList<>();
properties.addAll(signed.values());
properties.addAll(unsigned.values());
return properties;
}
}
}
}
|
package main.cli;
import core.Protocol;
import io.networkreaders.GraphvizReaderFactory;
import io.networkreaders.SimpleTopologyReaderFactory;
import io.networkreaders.TopologyReaderFactory;
import io.reporters.CSVReporterFactory;
import main.SimulatorParameters;
import org.apache.commons.cli.*;
import org.apache.commons.io.FilenameUtils;
import protocols.BGPProtocol;
import protocols.D1R1Protocol;
import protocols.D2R1Protocol;
import simulators.SimulatorFactory;
import simulators.basic.BasicSimulatorFactory;
import simulators.timeddeployment.TimedDeploymentSimulatorFactory;
import java.io.File;
/**
* Parses the command line arguments returning the necessary simulator parameters form it.
*/
public class ParametersCommandLineParser {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Long option names
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private static final String TOPOLOGY_FILE = "topology";
private static final String DESTINATION = "destination";
private static final String REPETITION_COUNT = "repetition_count";
private static final String ENABLED_DETECTION2 = "detection2";
private static final String ENABLED_BGP = "bgp";
private static final String DEPLOY_TIME = "deploy_time";
private static final String INPUT_FORMAT_GRAPHVIZ = "graphviz";
private static final String DEBUG = "debug";
private static final String ANYCAST_FILE = "anycast";
private static final String SEED = "seed";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Parser and options are static since they are global to all instances of the class
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private static final CommandLineParser parser = new DefaultParser();
private static final Options options = new Options();
static {
// setup the command options
options.addOption("n", TOPOLOGY_FILE, true, "topology to be simulated");
options.addOption("d", DESTINATION, true, "simulate with the given destination id");
options.addOption("c", REPETITION_COUNT, true, "number of repetitions");
options.addOption("d2", ENABLED_DETECTION2, false, "use detection 2 instead of detection 1");
options.addOption("t", DEPLOY_TIME, true, "time deploy detection");
options.addOption("gv", INPUT_FORMAT_GRAPHVIZ, false, "indicate the input network file is in Graphviz format");
options.addOption("debug", DEBUG, false, "activate debugging");
options.addOption("any", ANYCAST_FILE, true, "anycast file to be used");
options.addOption("bgp", ENABLED_BGP, false, "use the original BGP");
options.addOption("s", SEED, true, "seed value to force");
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Public Interface
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Parses the simulator parameters from the given array with string arguments.
*
* @param args arrays with the string arguments.
* @return simulator parameters instance with the parsed parameters.
* @throws ParseException if the arguments are not correct.
*/
public SimulatorParameters parse(String[] args) throws ParseException {
CommandLine commandLine = parser.parse(options, args);
int destinationId = getDestinationId(commandLine);
File topologyFile = getTopologyFile(commandLine);
// report file appends the destination to the topology file
File reportFile = new File(topologyFile.getParent(),
FilenameUtils.getBaseName(topologyFile.getName()) + String.format("-dest%02d", destinationId));
return new SimulatorParameters.Builder(topologyFile, reportFile)
.readerFactory(getReader(commandLine))
.destinationId(destinationId)
.repetitionCount(getRepetitionCount(commandLine))
.protocol(getProtocol(commandLine))
.simulatorFactory(getSimulatorFactory(commandLine))
.reporterFactory(new CSVReporterFactory())
.debugEnabled(isDebugEnabled(commandLine))
.anycastFile(getAnycastFile(commandLine))
.seed(getSeed(commandLine))
.build();
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Parsing methods for each parameter
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Obtains the input format of the topology file from the command line and returns the appropriate reader
* factory. This is an optional argument.
*
* @param commandLine command line containing the parsed options.
* @return reader factory instance.
*/
private TopologyReaderFactory getReader(CommandLine commandLine) {
if (commandLine.hasOption(INPUT_FORMAT_GRAPHVIZ)) {
return new GraphvizReaderFactory();
} else {
// by default use simple reader
return new SimpleTopologyReaderFactory();
}
}
/**
* Obtains the topology file from the command line. This is not an optional argument, which means that a
* ParseException is thrown when the argument is missing.
*
* @param commandLine command line containing the parsed options.
* @return file instance for the topology file.
* @throws ParseException if the topology file option is missing.
*/
private File getTopologyFile(CommandLine commandLine) throws ParseException {
if (!commandLine.hasOption(TOPOLOGY_FILE)) {
throw new ParseException(missingOptionMessage("topology file"));
}
return new File(commandLine.getOptionValue(TOPOLOGY_FILE));
}
/**
* Obtains the destination ID from the command line. This is not an optional argument, which means that a
* ParseException is thrown when the argument is missing.
*
* @param commandLine command line containing the parsed options.
* @return destination ID in integer format.
* @throws ParseException if the destination option is missing or is not an integer.
*/
private int getDestinationId(CommandLine commandLine) throws ParseException {
if (!commandLine.hasOption(DESTINATION)) {
throw new ParseException(missingOptionMessage("destination ID"));
}
try {
return Integer.parseInt(commandLine.getOptionValue(DESTINATION));
} catch (NumberFormatException e){
throw new ParseException(expectedIntegerMessage("destination ID"));
}
}
/**
* Obtains the destination ID from the command line. This is not an optional argument, which means that a
* ParseException is thrown when the argument is missing.
*
* @param commandLine command line containing the parsed options.
* @return destination ID in integer format.
* @throws ParseException if the repetitions count option is missing or is not an integer.
*/
private int getRepetitionCount(CommandLine commandLine) throws ParseException {
if (!commandLine.hasOption(REPETITION_COUNT)) {
throw new ParseException(missingOptionMessage("number of repetitions"));
}
try {
return Integer.parseInt(commandLine.getOptionValue(REPETITION_COUNT));
} catch (NumberFormatException e){
throw new ParseException(expectedIntegerMessage("number of repetitions"));
}
}
/**
* Obtains the protocol from the command line. This is an optional argument, if not specified by the user it
* returns the default protocol (instance of D1R1Protocol).
*
* @param commandLine command line containing the parsed options
* @return a new protocol instance.
*/
private Protocol getProtocol(CommandLine commandLine) {
if (commandLine.hasOption(ENABLED_BGP)) {
return new BGPProtocol();
} else if (commandLine.hasOption(ENABLED_DETECTION2)) {
return new D2R1Protocol();
} else {
return new D1R1Protocol();
}
}
/**
* Obtains the simulator factory implementation based on the available options in the command line.
*
* @param commandLine command line containing the parsed options.
* @return a new simulator factory instance.
* @throws ParseException if the deploy time is not an integer value.
*/
private SimulatorFactory getSimulatorFactory(CommandLine commandLine) throws ParseException {
if (commandLine.hasOption(DEPLOY_TIME)) {
return new TimedDeploymentSimulatorFactory(getProtocol(commandLine), getDeployTime(commandLine));
} else {
return new BasicSimulatorFactory(getProtocol(commandLine));
}
}
/**
* Obtains the deploy time argument from the command line in integer format.
*
* @param commandLine command line containing the parsed options.
* @return a new simulator factory instance.
* @throws ParseException if the deploy time is not an integer.
*/
private int getDeployTime(CommandLine commandLine) throws ParseException {
try {
return Integer.parseInt(commandLine.getOptionValue(DEPLOY_TIME));
} catch (NumberFormatException e) {
throw new ParseException(expectedIntegerMessage("deploy time"));
}
}
/**
* Checks if the command line contains the -debug option flag.
*
* @param commandLine command line containing the parsed options.
* @return true if the -debug is present and false otherwise
*/
private boolean isDebugEnabled(CommandLine commandLine) {
return commandLine.hasOption(DEBUG);
}
/**
* Obtains the anycast file from teh command line. This is an optional argument, in case it is missing null will
* be returned.
*
* @param commandLine command line containing the parsed options.
* @return the parsed anycast file or null if the argument does not exist.
*/
private File getAnycastFile(CommandLine commandLine) {
if (commandLine.hasOption(ANYCAST_FILE)) {
return new File(commandLine.getOptionValue(ANYCAST_FILE));
} else {
return null;
}
}
/**
* Obtains the seed value from the command line. This is an optional argument, in case it is missing null will
* be returned. It throws a parse exception if the option is available but the argument value is not a signed long.
*
* @param commandLine command line containing the parsed options.
* @return the parsed anycast file or null if the argument does not exist.
* @throws ParseException if the option is available but the argument value is not a signed long.
*/
private Long getSeed(CommandLine commandLine) throws ParseException {
if (commandLine.hasOption(SEED)) {
try {
return Long.parseLong(commandLine.getOptionValue(SEED));
} catch (NumberFormatException e) {
throw new ParseException(expectedIntegerMessage("seed"));
}
} else {
return null;
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Helper method to create common error messages
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Returns the formatted message for missing non-optional arguments.
*
* @param optionName name for the option to display in the message.
* @return the formatted message for missing non-optional arguments.
*/
private String missingOptionMessage(String optionName) {
return optionName + " is missing and it is not an optional argument";
}
/**
* Returns the formatted message for an argument was expected to be an integer value but it is not.
*
* @param optionName name for the option to display in the message.
* @return the formatted message error.
*/
private String expectedIntegerMessage(String optionName) {
return optionName + " must be an integer value";
}
}
|
package org.voltdb.utils;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TreeMap;
import com.google.common.base.Throwables;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.DBBPool.BBContainer;
import com.google.common.base.Joiner;
/**
* A deque that specializes in providing persistence of binary objects to disk. Any object placed
* in the deque will be persisted to disk asynchronously. Objects placed in the queue can
* be persisted synchronously by invoking sync. The files backing this deque all start with a nonce
* provided at construction time followed by a segment index that is stored in the filename. Files grow to
* a maximum size of 64 megabytes and then a new segment is created. The index starts at 0. Segments are deleted
* once all objects from the segment have been polled and all the containers returned by poll have been discarded.
* Push is implemented by creating new segments at the head of the queue containing the objects to be pushed.
*
*/
public class PersistentBinaryDeque implements BinaryDeque {
/**
* Processors also log using this facility.
*/
private static final VoltLogger exportLog = new VoltLogger("EXPORT");
private final File m_path;
private final String m_nonce;
private java.util.concurrent.atomic.AtomicLong m_sizeInBytes =
new java.util.concurrent.atomic.AtomicLong(0);
/**
* Objects placed in the deque are stored in file segments that are up to 64 megabytes.
* Segments only support appending objects. A segment will throw an IOException if an attempt
* to insert an object that exceeds the remaining space is made. A segment can be used
* for reading and writing, but not both at the same time.
*
*/
private class DequeSegment {
//Avoid unecessary sync with this flag
private boolean m_syncedSinceLastEdit = true;
private final File m_file;
private RandomAccessFile m_ras;
private FileChannel m_fc;
//Index of the next object to read, not an offset into the file
//The offset is maintained by the ByteBuffer. Used to determine if there is another object
private int m_objectReadIndex = 0;
//ID of this segment
private final Long m_index;
private static final int m_chunkSize = (1024 * 1024) * 64;
//How many entries that have been polled have from this file have been discarded.
//Once this == the number of entries the segment can close and delete itself
private int m_discardsUntilDeletion = 0;
private int m_lastReadNumEntries = -1;
public DequeSegment(Long index, File file) {
m_index = index;
m_file = file;
}
private final ByteBuffer m_bufferForNumEntries = ByteBuffer.allocateDirect(4);
private int getNumEntries() throws IOException {
if (m_fc == null) {
open();
}
if (m_fc.size() > 0) {
m_bufferForNumEntries.clear();
while (m_bufferForNumEntries.hasRemaining()) {
int read = m_fc.read(m_bufferForNumEntries, 0);
if (read == -1) {
throw new EOFException();
}
}
m_bufferForNumEntries.flip();
int numEntries = m_bufferForNumEntries.getInt();
m_lastReadNumEntries = numEntries;
return numEntries;
} else {
return 0;
}
}
private void initNumEntries() throws IOException {
m_bufferForNumEntries.clear();
m_bufferForNumEntries.putInt(0).flip();
while (m_bufferForNumEntries.hasRemaining()) {
m_fc.write(m_bufferForNumEntries, 0);
}
m_syncedSinceLastEdit = false;
}
private void incrementNumEntries() throws IOException {
//First read the existing amount
m_bufferForNumEntries.clear();
while (m_bufferForNumEntries.hasRemaining()) {
int read = m_fc.read(m_bufferForNumEntries, 0);
if (read == -1) {
throw new EOFException();
}
}
m_bufferForNumEntries.flip();
//Then write the incremented value
int numEntries = m_bufferForNumEntries.getInt();
m_bufferForNumEntries.flip();
m_bufferForNumEntries.putInt(++numEntries).flip();
while (m_bufferForNumEntries.hasRemaining()) {
m_fc.write(m_bufferForNumEntries, 0);
}
m_syncedSinceLastEdit = false;
//For when this buffer is eventually finished and starts being polled
//Stored on disk and in memory
m_discardsUntilDeletion++;
}
/**
* Bytes of space available for inserting more entries
* @return
*/
private int remaining() throws IOException {
//Subtract 4 for the length prefix
return (int)(m_chunkSize - m_fc.position()) - 4;
}
private void open() throws IOException {
if (!m_file.exists()) {
m_syncedSinceLastEdit = false;
}
if (m_ras != null) {
throw new IOException(m_file + " was already opened");
}
m_ras = new RandomAccessFile( m_file, "rw");
m_fc = m_ras.getChannel();
m_fc.position(4);
if (m_fc.size() >= 4) {
m_discardsUntilDeletion = getNumEntries();
}
}
private void closeAndDelete() throws IOException {
close();
m_sizeInBytes.addAndGet(-sizeInBytes());
m_file.delete();
}
private void close() throws IOException {
if (m_fc != null) {
m_fc.close();
m_ras = null;
m_fc = null;
}
}
private void sync() throws IOException {
if (!m_syncedSinceLastEdit) {
m_fc.force(true);
}
m_syncedSinceLastEdit = true;
}
private boolean hasMoreEntries() throws IOException {
return m_objectReadIndex < getNumEntries();
}
private BBContainer poll() throws IOException {
if (m_fc == null) {
open();
}
//No more entries to read
int numEntries = getNumEntries();
if (m_objectReadIndex >= numEntries) {
return null;
}
m_objectReadIndex++;
//If this is the last object to read from this segment
//increment the poll segment index so that the next poll
//selects the correct segment
if (m_objectReadIndex >= numEntries) {
m_currentPollSegmentIndex++;
/*
* Check that the poll segment index we are pointing to
* actually contains more entries to be polled.
* If someone pushes entries into the deque after they have polled
* entries from the head segment you can end up in a scenario where
* the next segment is actually empty and not the place to poll from
* next. It's a pretty messed up scenario and it is up to the caller to
* make sense of it.
*
*/
while (m_finishedSegments.containsKey(m_currentPollSegmentIndex)) {
DequeSegment ds = m_finishedSegments.get(m_currentPollSegmentIndex);
if (ds.hasMoreEntries()) break;
//The deque segment that follows has no more entries, check the next one
//or point to the current write segment
m_currentPollSegmentIndex++;
//If this is going to point to the write segment, sanity check the indexes match
if (!m_finishedSegments.containsKey(m_currentPollSegmentIndex) && m_writeSegment != null) {
assert(m_writeSegment.m_index.intValue() == m_currentPollSegmentIndex);
}
}
}
//Get the length prefix and then read the object
m_bufferForNumEntries.clear();
while (m_bufferForNumEntries.hasRemaining()) {
int read = m_fc.read(m_bufferForNumEntries);
if (read == -1) {
throw new EOFException();
}
}
m_bufferForNumEntries.flip();
int length = m_bufferForNumEntries.getInt();
if (length < 1) {
throw new IOException("Read an invalid length");
}
ByteBuffer resultBuffer = ByteBuffer.allocate(length);
while (resultBuffer.hasRemaining()) {
int read = m_fc.read(resultBuffer);
if (read == -1) {
throw new EOFException();
}
}
resultBuffer.flip();
return new BBContainer( resultBuffer, 0L) {
private boolean discarded = false;
private final Throwable t = new Throwable();
@Override
public void discard() {
if (!discarded) {
discarded = true;
m_discardsUntilDeletion
if (m_discardsUntilDeletion == 0) {
m_finishedSegments.remove(m_index);
try {
closeAndDelete();
} catch (IOException e) {
exportLog.error("Error closing and deleting binary deque segment", e);
}
}
} else {
exportLog.error("An export buffer was discarded multiple times");
}
}
@Override
public void finalize() {
if (!discarded && !m_closed) {
exportLog.error(m_file + " had a buffer that was finalized without being discarded");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
exportLog.error(sw.toString());
discard();
}
}
};
}
private void offer(BBContainer objects[]) throws IOException {
int length = 0;
for (BBContainer obj : objects ) {
length += obj.b.remaining();
}
if (remaining() < length) {
throw new IOException(m_file + " has insufficient space");
}
m_bufferForNumEntries.clear();
m_bufferForNumEntries.putInt(length).flip();
while (m_bufferForNumEntries.hasRemaining()) {
m_fc.write(m_bufferForNumEntries);
}
int objectIndex = 0;
for (BBContainer obj : objects ) {
boolean success = false;
try {
while (obj.b.hasRemaining()) {
m_fc.write(obj.b);
}
obj.discard();
success = true;
objectIndex++;
} finally {
if (!success) {
for (int ii = objectIndex; ii < objects.length; ii++) {
objects[ii].discard();
}
}
}
}
m_sizeInBytes.addAndGet(4 + length);
incrementNumEntries();
}
//A white lie, don't include the object count prefix
//so that the size is 0 when there is no user data
private long sizeInBytes() {
return m_file.length() - 4;
}
}
//Segments that are no longer being written to and can be polled
//These segments are "immutable". They will not be modified until deletion
private final TreeMap<Long, DequeSegment> m_finishedSegments = new TreeMap<Long, DequeSegment>();
//The current segment being written to
private DequeSegment m_writeSegment = null;
//Index of the segment being polled
private Long m_currentPollSegmentIndex = 0L;
private volatile boolean m_closed = false;
/**
* Create a persistent binary deque with the specified nonce and storage back at the specified path.
* Existing files will
* @param nonce
* @param path
* @throws IOException
*/
public PersistentBinaryDeque(final String nonce, final File path) throws IOException {
m_path = path;
m_nonce = nonce;
if (!path.exists() || !path.canRead() || !path.canWrite() || !path.canExecute() || !path.isDirectory()) {
throw new IOException(path + " is not usable ( !exists || !readable " +
"|| !writable || !executable || !directory)");
}
//Parse the files in the directory by name to find files
//that are part of this deque
path.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
// PBD file names have three parts: nonce.seq.pbd
// nonce may contain '.', seq is a sequence number.
String[] parts = pathname.getName().split("\\.");
String parsedNonce = null;
String seqNum = null;
String extension = null;
// If more than 3 parts, it means nonce contains '.', assemble them.
if (parts.length > 3) {
Joiner joiner = Joiner.on('.').skipNulls();
parsedNonce = joiner.join(Arrays.asList(parts).subList(0, parts.length - 2));
seqNum = parts[parts.length - 2];
extension = parts[parts.length - 1];
} else if (parts.length == 3) {
parsedNonce = parts[0];
seqNum = parts[1];
extension = parts[2];
}
if (nonce.equals(parsedNonce) && "pbd".equals(extension)) {
if (pathname.length() == 4) {
//Doesn't have any objects, just the object count
pathname.delete();
return false;
}
Long index = Long.valueOf(seqNum);
DequeSegment ds = new DequeSegment( index, pathname);
m_finishedSegments.put( index, ds);
m_sizeInBytes.addAndGet(ds.sizeInBytes());
}
return false;
}
});
Long lastKey = null;
for (Long key : m_finishedSegments.keySet()) {
if (lastKey == null) {
lastKey = key;
} else {
if (lastKey + 1 != key) {
throw new IOException("Missing " + nonce +
" pbd segments between " + lastKey + " and " + key + " in directory " + path +
". The data files found in the export overflow directory were inconsistent.");
}
lastKey = key;
}
}
//Find the first and last segment for polling and writing (after)
Long writeSegmentIndex = 0L;
try {
m_currentPollSegmentIndex = m_finishedSegments.firstKey();
writeSegmentIndex = m_finishedSegments.lastKey() + 1;
} catch (NoSuchElementException e) {}
m_writeSegment =
new DequeSegment(
writeSegmentIndex,
new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd"));
m_writeSegment.open();
m_writeSegment.initNumEntries();
assert(postconditions());
}
@Override
public synchronized void offer(BBContainer[] objects) throws IOException {
assert(preconditions());
if (m_writeSegment == null) {
throw new IOException("Closed");
}
int needed = 0;
for (BBContainer b : objects) {
needed += b.b.remaining();
}
if (needed > DequeSegment.m_chunkSize - 4) {
throw new IOException("Maxiumum object size is " + (DequeSegment.m_chunkSize - 4));
}
if (m_writeSegment.remaining() < needed) {
openNewWriteSegment();
}
m_writeSegment.offer(objects);
assert(postconditions());
}
@Override
public synchronized void push(BBContainer[][] objects) throws IOException {
assert(preconditions());
if (m_writeSegment == null) {
throw new IOException("Closed");
}
ArrayDeque<ArrayDeque<BBContainer[]>> segments = new ArrayDeque<ArrayDeque<BBContainer[]>>();
ArrayDeque<BBContainer[]> currentSegment = new ArrayDeque<BBContainer[]>();
//Take the objects that were provided and separate them into deques of objects
//that will fit in a single write segment
int available = DequeSegment.m_chunkSize - 4;
for (BBContainer object[] : objects) {
int needed = 4;
for (BBContainer obj : object) {
needed += obj.b.remaining();
}
if (available - needed < 0) {
if (needed > DequeSegment.m_chunkSize - 4) {
throw new IOException("Maximum object size is " + (DequeSegment.m_chunkSize - 4));
}
segments.offer( currentSegment );
currentSegment = new ArrayDeque<BBContainer[]>();
available = DequeSegment.m_chunkSize - 4;
}
available -= needed;
currentSegment.add(object);
}
segments.add(currentSegment);
assert(segments.size() > 0);
//Calculate the index for the first segment to push at the front
//This will be the index before the first segment available for read or
//before the write segment if there are no finished segments
Long nextIndex = 0L;
if (m_finishedSegments.size() > 0) {
nextIndex = m_finishedSegments.firstKey() - 1;
} else {
nextIndex = m_writeSegment.m_index - 1;
}
while (segments.peek() != null) {
ArrayDeque<BBContainer[]> currentSegmentContents = segments.poll();
DequeSegment writeSegment =
new DequeSegment(
nextIndex,
new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd"));
m_currentPollSegmentIndex = nextIndex;
writeSegment.open();
writeSegment.initNumEntries();
nextIndex
while (currentSegmentContents.peek() != null) {
writeSegment.offer(currentSegmentContents.pollFirst());
}
writeSegment.m_fc.position(4);
m_finishedSegments.put(writeSegment.m_index, writeSegment);
}
assert(postconditions());
}
private void openNewWriteSegment() throws IOException {
if (m_writeSegment == null) {
throw new IOException("Closed");
}
m_writeSegment.m_fc.position(4);
m_finishedSegments.put(m_writeSegment.m_index, m_writeSegment);
Long nextIndex = m_writeSegment.m_index + 1;
m_writeSegment =
new DequeSegment(
nextIndex,
new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd"));
m_writeSegment.open();
m_writeSegment.initNumEntries();
}
@Override
public synchronized BBContainer poll() throws IOException {
assert(preconditions());
if (m_writeSegment == null) {
throw new IOException("Closed");
}
DequeSegment segment = m_finishedSegments.get(m_currentPollSegmentIndex);
if (segment == null) {
assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex));
//See if we can steal the write segment, otherwise return null
if (m_writeSegment.getNumEntries() > 0) {
openNewWriteSegment();
return poll();
} else {
return null;
}
}
BBContainer retval = segment.poll();
assert(postconditions());
return retval;
}
@Override
public synchronized void sync() throws IOException {
if (m_writeSegment == null) {
throw new IOException("Closed");
}
m_writeSegment.sync();
for (DequeSegment segment : m_finishedSegments.values()) {
segment.sync();
}
}
@Override
public synchronized void close() throws IOException {
if (m_writeSegment == null) {
throw new IOException("Closed");
}
if (m_writeSegment.getNumEntries() > 0) {
m_finishedSegments.put(m_writeSegment.m_index, m_writeSegment);
} else {
m_writeSegment.closeAndDelete();
}
m_writeSegment = null;
for (DequeSegment segment : m_finishedSegments.values()) {
segment.close();
}
m_closed = true;
}
@Override
public synchronized boolean isEmpty() throws IOException {
assert(preconditions());
if (m_writeSegment == null) {
throw new IOException("Closed");
}
DequeSegment segment = m_finishedSegments.get(m_currentPollSegmentIndex);
if (segment == null) {
assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex));
//See if we can steal the write segment, otherwise return null
if (m_writeSegment.getNumEntries() > 0) {
return false;
} else {
return true;
}
}
return segment.m_objectReadIndex >= segment.getNumEntries();
}
@Override
public long sizeInBytes() {
assert(preconditions());
return m_sizeInBytes.get();
}
@Override
public synchronized void closeAndDelete() throws IOException {
m_writeSegment.closeAndDelete();
for (DequeSegment ds : m_finishedSegments.values()) {
ds.closeAndDelete();
}
}
@Override
public synchronized void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException {
assert(preconditions());
if (m_finishedSegments.isEmpty()) {
exportLog.debug("PBD " + m_nonce + " has no finished segments");
return;
}
//+16 because I am not sure if the max chunk size is enforced right
ByteBuffer readBuffer = ByteBuffer.allocateDirect(DequeSegment.m_chunkSize + 16);
/*
* Iterator all the objects in all the segments and pass them to the truncator
* When it finds the truncation point
*/
Long lastSegmentIndex = null;
for (Map.Entry<Long, DequeSegment> entry : m_finishedSegments.entrySet()) {
readBuffer.clear();
DequeSegment segment = entry.getValue();
long segmentIndex = entry.getKey();
File segmentFile = segment.m_file;
RandomAccessFile ras = new RandomAccessFile(segmentFile, "rw");
FileChannel fc = ras.getChannel();
try {
/*
* Read the entire segment into memory
*/
while (readBuffer.hasRemaining()) {
int read = fc.read(readBuffer);
if (read == -1) {
break;
}
}
readBuffer.flip();
//Get the number of objects and then iterator over them
int numObjects = readBuffer.getInt();
exportLog.debug("PBD " + m_nonce + " has " + numObjects + " objects to parse and truncate");
for (int ii = 0; ii < numObjects; ii++) {
final int nextObjectLength = readBuffer.getInt();
//Copy the next object into a separate heap byte buffer
//do the old limit stashing trick to avoid buffer overflow
ByteBuffer nextObject = ByteBuffer.allocate(nextObjectLength);
final int oldLimit = readBuffer.limit();
readBuffer.limit(readBuffer.position() + nextObjectLength);
nextObject.put(readBuffer).flip();
//Put back the original limit
readBuffer.limit(oldLimit);
//Handoff the object to the truncator and await a decision
ByteBuffer retval = truncator.parse(nextObject);
if (retval == null) {
//Nothing to do, leave the object alone and move to the next
continue;
} else {
long startSize = fc.size();
//If the returned bytebuffer is empty, remove the object and truncate the file
if (retval.remaining() == 0) {
if (ii == 0) {
/*
* If truncation is occuring at the first object
* Whammo! Delete the file. Do it by setting the lastSegmentIndex
* to 1 previous. We may end up with an empty finished segment
* set.
*/
lastSegmentIndex = segmentIndex - 1;
} else {
//Don't forget to update the number of entries in the file
ByteBuffer numObjectsBuffer = ByteBuffer.allocate(4);
numObjectsBuffer.putInt(0, ii);
fc.position(0);
while (numObjectsBuffer.hasRemaining()) {
fc.write(numObjectsBuffer);
}
fc.truncate(readBuffer.position() - (nextObjectLength + 4));
}
} else {
readBuffer.position(readBuffer.position() - (nextObjectLength + 4));
readBuffer.putInt(retval.remaining());
readBuffer.put(retval);
readBuffer.flip();
readBuffer.putInt(0, ii + 1);
/*
* SHOULD REALLY make a copy of the original and then swap them with renaming
*/
fc.position(0);
fc.truncate(0);
while (readBuffer.hasRemaining()) {
fc.write(readBuffer);
}
}
long endSize = fc.size();
m_sizeInBytes.addAndGet(endSize - startSize);
//Set last segment and break the loop over this segment
if (lastSegmentIndex == null) {
lastSegmentIndex = segmentIndex;
}
break;
}
}
//If this is set the just processed segment was the last one
if (lastSegmentIndex != null) {
break;
}
} finally {
fc.close();
}
}
/*
* If it was found that no truncation is necessary, lastSegmentIndex will be null.
* Return and the parseAndTruncate is a noop.
*/
if (lastSegmentIndex == null) {
return;
}
/*
* Now truncate all the segments after the truncation point
*/
Iterator<Map.Entry<Long, DequeSegment>> iterator = m_finishedSegments.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, DequeSegment> entry = iterator.next();
if (entry.getKey() <= lastSegmentIndex) {
continue;
}
DequeSegment ds = entry.getValue();
iterator.remove();
ds.closeAndDelete();
}
//The write segment may have the wrong index, delete it
m_writeSegment.closeAndDelete();
/*
* Reset the poll and write segments
*/
//Find the first and last segment for polling and writing (after)
m_currentPollSegmentIndex = 0L;
Long writeSegmentIndex = 0L;
try {
m_currentPollSegmentIndex = m_finishedSegments.firstKey();
writeSegmentIndex = m_finishedSegments.lastKey() + 1;
} catch (NoSuchElementException e) {}
m_writeSegment =
new DequeSegment(
writeSegmentIndex,
new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd"));
m_writeSegment.open();
m_writeSegment.initNumEntries();
if (m_finishedSegments.isEmpty()) {
assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex));
}
assert(postconditions());
}
private boolean preconditions() {
return postconditions();
}
private boolean postconditions() {
//Closed
if (m_writeSegment == null) return true;
try {
if (!m_finishedSegments.isEmpty()) {
for (Map.Entry<Long, DequeSegment> e : m_finishedSegments.entrySet()) {
if (e.getValue().hasMoreEntries() && !e.getKey().equals(m_currentPollSegmentIndex)) {
return false;
} else if (e.getValue().hasMoreEntries()) {
//Break because the current poll segment index obviously only matches
//up to the first buffer with remaining entries
break;
}
}
} else if (m_currentPollSegmentIndex != m_writeSegment.m_index.intValue()) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
|
package ed.lang.ruby;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import ed.js.JSArray;
import ed.js.engine.Scope;
import static ed.lang.ruby.RubyObjectWrapper.toJS;
import static ed.lang.ruby.RubyObjectWrapper.toRuby;
/**
* RubyJSArrayWrapper acts as a bridge between Ruby arrays and JSArrays. An
* instance of RubyJSArrayWrapper is a Ruby object that turns reads and writes
* of Ruby array contents into reads and writes of the underlying JSArray's
* instance variables.
*/
public class RubyJSArrayWrapper extends RubyArray {
private Scope _scope;
private org.jruby.Ruby _runtime;
private JSArray _jsarray;
RubyJSArrayWrapper(Scope s, org.jruby.Ruby runtime, JSArray obj) {
super(runtime, 0, null);
_scope = s;
_runtime = runtime;
_jsarray = obj;
js2ruby();
if (RubyObjectWrapper.DEBUG)
System.err.println(" creating RubyJSArrayWrapper");
}
public JSArray getJSArray() { return _jsarray; }
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject o = super.initialize(context, args, block);
ruby2js();
return o;
}
public IRubyObject replace(IRubyObject orig) {
IRubyObject o = super.replace(orig);
ruby2js();
return o;
}
public IRubyObject insert(IRubyObject arg1, IRubyObject arg2) {
IRubyObject o = super.insert(arg1, arg2);
ruby2js();
return o;
}
public IRubyObject insert(IRubyObject[] args) {
IRubyObject o = super.insert(args);
ruby2js();
return o;
}
public RubyArray append(IRubyObject item) {
RubyArray o = super.append(item);
_jsarray.add(toJS(_scope, _runtime, item));
return o;
}
public RubyArray push_m(IRubyObject[] items) {
RubyArray o = super.push_m(items);
ruby2js();
return o;
}
public IRubyObject pop() {
IRubyObject o = super.pop();
_jsarray.remove(_jsarray.size() - 1);
return o;
}
public IRubyObject shift() {
IRubyObject o = super.shift();
_jsarray.remove(0);
return o;
}
public RubyArray unshift_m(IRubyObject[] items) {
RubyArray o = super.unshift_m(items);
ruby2js();
return o;
}
public IRubyObject aset(IRubyObject arg0, IRubyObject arg1) {
IRubyObject o = super.aset(arg0, arg1);
ruby2js();
return o;
}
public IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
IRubyObject o = super.aset(arg0, arg1, arg2);
ruby2js();
return o;
}
public RubyArray concat(IRubyObject obj) {
RubyArray o = super.concat(obj);
ruby2js();
return o;
}
public IRubyObject compact_bang() {
IRubyObject o = super.compact_bang();
ruby2js();
return o;
}
public IRubyObject rb_clear() {
IRubyObject o = super.rb_clear();
_jsarray.clear();
return o;
}
public IRubyObject fill(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject o = super.fill(context, args, block);
ruby2js();
return o;
}
public IRubyObject reverse_bang() {
IRubyObject o = super.reverse_bang();
ruby2js();
return o;
}
public RubyArray collect_bang(ThreadContext context, Block block) {
RubyArray o = super.collect_bang(context, block);
ruby2js();
return o;
}
public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) {
IRubyObject o = super.delete(context, item, block);
ruby2js();
return o;
}
public IRubyObject delete_at(IRubyObject obj) {
IRubyObject o = super.delete_at(obj);
ruby2js();
return o;
}
public IRubyObject reject_bang(ThreadContext context, Block block) {
IRubyObject o = super.reject_bang(context, block);
ruby2js();
return o;
}
public IRubyObject slice_bang(IRubyObject arg0) {
IRubyObject o = super.slice_bang(arg0);
ruby2js();
return o;
}
public IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) {
IRubyObject o = super.slice_bang(arg0, arg1);
ruby2js();
return o;
}
public IRubyObject flatten_bang(ThreadContext context) {
IRubyObject o = super.flatten_bang(context);
ruby2js();
return o;
}
public IRubyObject uniq_bang() {
IRubyObject o = super.uniq_bang();
ruby2js();
return o;
}
public RubyArray sort_bang(Block block) {
RubyArray o = super.sort_bang(block);
ruby2js();
return o;
}
/** Writes contents of JSArray into RubyArray. */
private void js2ruby() {
int len = _jsarray.size();
IRubyObject[] a = new IRubyObject[len];
for (int i = 0; i < len; ++i)
a[i] = toRuby(_scope, _runtime, _jsarray.get(i));
replace(new RubyArray(_runtime, len, a));
}
/** Writes contents of RubyArrray into JSArray. */
private void ruby2js() {
_jsarray.clear();
int len = size();
for (int i = 0; i < len; ++i)
_jsarray.add(toJS(_scope, _runtime, entry(i)));
}
}
|
package Application;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.heroku.sdk.jdbc.DatabaseUrl;
import dataTransfer.LoginData;
import dataTransfer.LoginValidation;
import dataTransfer.RegisterData;
//import Models.RegisterUserCredentials;
import dataTransfer.ValidationCodes;
@Controller
public class HomeController {
@RequestMapping("/")
public String home() {
return "index";
}
@RequestMapping("/loginPage")
public String loginPage() {
return "users/login";
}
@RequestMapping("/registerPage")
public String registerPage() {
return "users/register";
}
@RequestMapping("/worldPage")
public String worldPage() {
return "worldPage";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public LoginValidation loginGet(@RequestBody LoginData data) {
LoginValidation code = new LoginValidation();
try {
Connection connection = DatabaseUrl.extract().getConnection();
Statement stmtCount = connection.createStatement();
Statement stmt = connection.createStatement();
ResultSet user = stmtCount.executeQuery("SELECT count(*) FROM Users WHERE username = '" + data.userName + "' AND password = '" + data.password + "'");
while (user.next()) {
if(user.getInt(0) == 0) {
code.IncorrectUsernameOrPassword = true;
}
}
if(!code.IncorrectUsernameOrPassword) {
ResultSet userInfo = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + data.userName + "' AND password = '" + data.password + "'");
while (userInfo.next()) {
if(userInfo.getInt(0) == 0) {
code.userId = userInfo.getInt(0);
code.userName = userInfo.getString(1);
}
}
}
} catch (Exception e) {
code.databaseError = true;
}
return code;
// return new ResponseEntity<String>(HttpStatus.ACCEPTED);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ValidationCodes registerTransfer(@RequestBody RegisterData data) {
ValidationCodes code = new ValidationCodes();
try {
// URI dbUri = new URI("postgres://fghhopulwiaynq:OfvO_N_KLpwGqwbOZY7wEwKfL_@ec2-54-221-201-165.compute-1.amazonaws.com:5432/df02650vnkne80");
// String dbusername = dbUri.getUserInfo().split(":")[0];
// String dbpassword = dbUri.getUserInfo().split(":")[1];
// String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
Connection connection = DatabaseUrl.extract().getConnection();
Statement stmtUser = connection.createStatement();
Statement stmtEmail = connection.createStatement();
Statement stmtInsert = connection.createStatement();
ResultSet userName = stmtUser.executeQuery("SELECT COUNT(*) FROM Users where username = '" + data.userName + "'");
ResultSet email = stmtEmail.executeQuery("SELECT count(*) FROM Users where email = '" + data.email + "'");
// while (userNames.next()) {
// System.out.println("Number of Users: " + userNames.getString(0));
while (userName.next()) {
if(userName.getInt(0) != 0) {
code.UsernameTaken = true;
}
}
while (email.next()) {
if(email.getInt(0) != 0) {
code.EmailTaken = true;
}
}
String newPassword = data.password;
String newConfirmPassword = data.confirmPassword;
if(!newPassword.equals(newConfirmPassword)) {
code.PasswordMismatch = true;
}
if(!code.UsernameTaken && !code.EmailTaken && !code.PasswordMismatch) {
stmtInsert.execute("Insert into Users (username, email, password) values (" + data.userName + "," + data.email + "," + data.password + ")");
}
//return new ResponseEntity<String>(HttpStatus.ACCEPTED);
} catch (Exception e) {
//return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
code.databaseError = true;
}
return code;
}
// @RequestMapping(value = "/validate", method = RequestMethod.POST)
// public String registerPost(@ModelAttribute("registerUserCredentials") RegisterUserCredentials userCredentials, BindingResult result) {
// try {
// URI dbUri = new URI("postgres://fghhopulwiaynq:OfvO_N_KLpwGqwbOZY7wEwKfL_@ec2-54-221-201-165.compute-1.amazonaws.com:5432/df02650vnkne80");
// String dbusername = dbUri.getUserInfo().split(":")[0];
// String dbpassword = dbUri.getUserInfo().split(":")[1];
// String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
// System.out.println(userCredentials.getUserName());
// System.out.println(userCredentials.getEmail());
// System.out.println(userCredentials.getPassword());
// System.out.println(userCredentials.getConfirmPassword());
// //"Select * from Users
// return "redirect:login";
// } catch (Exception e) {
// return registerTransfer();
// @ModelAttribute("registerUserCredentials")
// public RegisterUserCredentials getRegisterUserCredentials() {
// return new RegisterUserCredentials();
}
|
package Controllers;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import Views.GameScene;
import Models.Marker;
import Utilities.Constants;
import Utilities.XML;
public class GameController extends Application {
private static Logger logger = LoggerFactory.getLogger(GameController.class);
static GameScene gs;
public ArrayList<Marker> markers;
public ArrayList<Marker> freeMarkers;
public Marker lastMarker;
public static int currentPlayer = Constants.kPlayerNone;
/**
*
* @param args
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Game");
logger.debug("Controller felépítése.");
gs = new GameScene();
gs.setGC(this);
primaryStage.setScene(new Scene(gs, 700, 400));
primaryStage.show();
freeMarkers = new ArrayList<Marker>();
lastMarker = null;
if (markers != null) markers.clear();
markers = mergeMarkers(initEmptyMarkers(), initBluePlayer());
markers = mergeMarkers(markers, initRedPlayer());
makeVisibleOnScreen(markers);
currentPlayer = changePlayer(Constants.kPlayerNone);
}
public void reset() {
freeMarkers = new ArrayList<Marker>();
lastMarker = null;
if (markers != null) markers.clear();
markers = mergeMarkers(initEmptyMarkers(), initBluePlayer());
markers = mergeMarkers(markers, initRedPlayer());
makeVisibleOnScreen(markers);
currentPlayer = changePlayer(Constants.kPlayerNone);
}
/**
*
* @param listToOverWrite
* @param newValues
* @return
*/
public static ArrayList<Marker> mergeMarkers(ArrayList<Marker> listToOverWrite, ArrayList<Marker> newValues) {
for (int i = 0; i < newValues.size(); i++) {
int indexToOverWrite = newValues.get(i).getIndex();
listToOverWrite.set(indexToOverWrite, newValues.get(i));
}
return listToOverWrite;
}
public static ArrayList<Marker> initEmptyMarkers() {
ArrayList<Marker> emptyMarkers = new ArrayList<Marker>();
for (int i = 0; i < Constants.kNumberOfRows; i++) {
for (int j = 0; j < Constants.kNumberOfColumns; j++) {
Marker marker = new Marker(i,j,Constants.kFieldStateEmpty);
emptyMarkers.add(marker);
/*modifyFieldImageAndState(marker,
Constants.kEmptyFieldImageName,
Constants.kFieldStateEmpty);*/
}
}
return emptyMarkers;
}
public static ArrayList<Marker> initBluePlayer() {
logger.debug("Kék játékos betöltése:");
ArrayList<Marker> blueMarkers = new ArrayList<Marker>();
blueMarkers.add(new Marker(3,9, Constants.kFieldStateBlue));
blueMarkers.add(new Marker(2,9, Constants.kFieldStateBlue));
blueMarkers.add(new Marker(1,9, Constants.kFieldStateBlue));
blueMarkers.add(new Marker(2,4, Constants.kFieldStateBlue));
blueMarkers.add(new Marker(1,4, Constants.kFieldStateBlue));
blueMarkers.add(new Marker(0,4, Constants.kFieldStateBlue));
/*for (int i = 0; i < blueMarkers.size(); i++) {
Marker blueMarker = blueMarkers.get(i);
Marker marker = markers.get(blueMarker.getIndex());
((Marker)markers.get(marker.getIndex())).markerState = Constants.kFieldStateBlue;
logger.debug("(" + marker.row + ", " + marker.column + ")");
modifyFieldImageAndState(marker,
Constants.kBlueFieldImageName,
Constants.kFieldStateBlue);
}
logger.debug("hely(ek)re.");*/
return blueMarkers;
}
public static ArrayList<Marker> initRedPlayer() {
logger.debug("Piros játékos betöltése:");
ArrayList<Marker> redMarkers = new ArrayList<Marker>();
redMarkers.add(new Marker(0,0, Constants.kFieldStateRed));
redMarkers.add(new Marker(1,0, Constants.kFieldStateRed));
redMarkers.add(new Marker(2,0, Constants.kFieldStateRed));
redMarkers.add(new Marker(1,5, Constants.kFieldStateRed));
redMarkers.add(new Marker(2,5, Constants.kFieldStateRed));
redMarkers.add(new Marker(3,5, Constants.kFieldStateRed));
/*for (int i = 0; i < redMarkers.size(); i++) {
Marker redMarker = redMarkers.get(i);
Marker marker = markers.get(redMarker.getIndex());
((Marker)markers.get(marker.getIndex())).markerState = Constants.kFieldStateRed;
logger.debug("(" + marker.row + ", " + marker.column + ")");
modifyFieldImageAndState(marker,
Constants.kRedFieldImageName,
Constants.kFieldStateRed);
}
logger.debug("hely(ek)re.");*/
return redMarkers;
}
public void buttonPressed(Marker pressedMarker) {
//Marker pressedMarker = (Marker)((Field)event.getSource()).marker;
String filename = Constants.kSelectableFieldImageName;
String playerLogString = null;
if (currentPlayer == Constants.kPlayerBlue) {
filename = Constants.kBlueFieldImageName;
playerLogString = "Kék";
} else if (currentPlayer == Constants.kPlayerRed) {
filename = Constants.kRedFieldImageName;
playerLogString = "Piros";
}
Boolean willMove = false;
int winner = Constants.kPlayerNone;
if (!freeMarkers.isEmpty()) {
for (int i = 0; i <freeMarkers.size(); i++) {
Marker marker = freeMarkers.get(i);
modifyFieldImage(marker, Constants.kEmptyFieldImageName);
if (pressedMarker.getIndex() == marker.getIndex()) {
willMove = true;
if (lastMarker != null) {
Marker markerToEmpty = markers.get(lastMarker.getIndex());
pressedMarker.markerState = currentPlayer;
modifyFieldImageAndState(pressedMarker, filename, pressedMarker.markerState);
markerToEmpty.markerState = Constants.kFieldStateEmpty;
modifyFieldImageAndState(markerToEmpty, Constants.kEmptyFieldImageName, markerToEmpty.markerState);
logger.debug(playerLogString + " játékos kiválasztja, hogy hova lép. ("+pressedMarker.row+", "+pressedMarker.column+")");
winner = checkWinner(markers);
if (winner == Constants.kPlayerRed || winner == Constants.kPlayerBlue) {
currentPlayer = Constants.kPlayerNone;
}
}
}
}
if (!willMove) {
freeMarkers = getFreeNeighborsForMarker(pressedMarker.getIndex(), markers, currentPlayer);
for (int i = 0; i <freeMarkers.size(); i++) {
Marker freeMarker = freeMarkers.get(i);
modifyFieldImage(freeMarker, Constants.kSelectableFieldImageName);
}
if (pressedMarker.markerState == currentPlayer)
logger.debug(playerLogString + " játékos kiválasztja, hogy honnan lép. ("+pressedMarker.row+", "+pressedMarker.column+")");
} else {
lastMarker = null;
freeMarkers.clear();
if (winner != Constants.kPlayerNone) {
if (winner == Constants.kPlayerRed ) {
modifyViewTitle(Constants.kWinnerRedText);
} else if (winner == Constants.kPlayerBlue ) {
modifyViewTitle(Constants.kWinnerBlueText);
}
logger.debug(playerLogString + " játékos nyert. (Játék vége.)");
} else {
currentPlayer = changePlayer(currentPlayer);
}
return;
}
} else {
freeMarkers = getFreeNeighborsForMarker(pressedMarker.getIndex(), markers, currentPlayer);
for (int i = 0; i <freeMarkers.size(); i++) {
Marker freeMarker = freeMarkers.get(i);
modifyFieldImage(freeMarker, Constants.kSelectableFieldImageName);
}
if (pressedMarker.markerState == currentPlayer)
logger.debug(playerLogString + " játékos kiválasztja, hogy honnan lép. ("+pressedMarker.row+", "+pressedMarker.column+")");
}
if (!willMove) {
lastMarker = pressedMarker;
}
}
public static int changePlayer(int current) {
if (current == Constants.kPlayerBlue) {
modifyViewTitle(Constants.redTurnText);
return Constants.kPlayerRed;
} else if (current == Constants.kPlayerRed) {
modifyViewTitle(Constants.blueTurnText);
return Constants.kPlayerBlue;
}
modifyViewTitle(Constants.blueTurnText);
return Constants.kPlayerBlue;
}
public static ArrayList<Marker> getFreeNeighborsForMarker(int index, ArrayList<Marker> currentGameState, int player) {
ArrayList<Marker> free = new ArrayList<Marker>();
Marker marker = currentGameState.get(index);
if (marker.markerState != player) {
return free;
}
Marker neighbor;
if (marker.hasAbove()) {
neighbor = currentGameState.get(getMarkerIndex(marker.row-1,marker.column));
if (neighbor.markerState == Constants.kFieldStateEmpty) {
free.add(neighbor);
}
}
if (marker.hasBelow()) {
neighbor = currentGameState.get(getMarkerIndex(marker.row+1,marker.column));
if (neighbor.markerState == Constants.kFieldStateEmpty) {
free.add(neighbor);
}
}
if (marker.hasRight()) {
neighbor = currentGameState.get(getMarkerIndex(marker.row,marker.column+1));
if (neighbor.markerState == Constants.kFieldStateEmpty) {
free.add(neighbor);
}
}
if (marker.hasLeft()) {
neighbor = currentGameState.get(getMarkerIndex(marker.row,marker.column-1));
if (neighbor.markerState == Constants.kFieldStateEmpty) {
free.add(neighbor);
}
}
return free;
}
public static int getMarkerIndex(int row, int column) {
return row*Constants.kNumberOfColumns+column;
}
public static int checkWinner(ArrayList<Marker> currentGameState) {
int index = 0;
int redCounter = 0;
int blueCounter = 0;
for (int i = 0; i < Constants.kNumberOfRows; i++) {
redCounter = 0;
blueCounter = 0;
for (int j = 0; j < Constants.kNumberOfColumns; j++) {
index = i*Constants.kNumberOfColumns+j;
Marker marker = currentGameState.get(index);
if (marker.markerState == Constants.kFieldStateRed) {
redCounter++;
if (redCounter == 4) {
return Constants.kPlayerRed;
}
} else redCounter = 0;
if (marker.markerState == Constants.kFieldStateBlue) {
blueCounter++;
if (blueCounter == 4) {
return Constants.kPlayerBlue;
}
} else blueCounter = 0;
}
}
for (int i = 0; i < Constants.kNumberOfColumns; i++) {
redCounter = 0;
blueCounter = 0;
for (int j = 0; j < Constants.kNumberOfRows; j++) {
index = j*Constants.kNumberOfColumns+i;
Marker marker = currentGameState.get(index);
if (marker.markerState == Constants.kFieldStateRed) {
redCounter++;
if (redCounter == 4) {
return Constants.kPlayerRed;
}
} else redCounter = 0;
if (marker.markerState == Constants.kFieldStateBlue) {
blueCounter++;
if (blueCounter == 4) {
return Constants.kPlayerBlue;
}
} else blueCounter = 0;
}
}
return Constants.kPlayerNone;
}
/**
*
* @param currentGameState
* @return
*/
public static ArrayList<Marker> getGameStateToSave(ArrayList<Marker> currentGameState, int player) {
ArrayList<Marker> markersToSave = new ArrayList<Marker>();
for (int i = 0; i < currentGameState.size(); i++) {
Marker marker = currentGameState.get(i);
if (marker.markerState == player) {
markersToSave.add(marker);
}
}
player = changePlayer(player);
for (int i = 0; i < currentGameState.size(); i++) {
Marker marker = currentGameState.get(i);
if (marker.markerState == player) {
markersToSave.add(marker);
}
}
player = changePlayer(player);
return markersToSave;
}
public static void saveGame(ArrayList<Marker> currentGameState, int player) {
XML.saveGame(getGameStateToSave(currentGameState, player));
}
/**
*
* @return
*/
public static ArrayList<Marker> getGameStateToLoad() {
logger.debug("Játék betöltése az adatbázisból.");
ArrayList<Marker> loadedMarkers = XML.loadGame();
if (loadedMarkers.size() != 12) {
logger.warn("Nem sikerült betölteni a játékállást.");
return new ArrayList<Marker>();
}
logger.debug("Sikeres betöltés.");
for (int i = 0; i < loadedMarkers.size(); i++) {
Marker marker = loadedMarkers.get(i);
if (i == loadedMarkers.size()-1) currentPlayer = marker.markerState;
}
currentPlayer = changePlayer(currentPlayer);
return mergeMarkers(initEmptyMarkers(), loadedMarkers);
}
public void loadGame() {
freeMarkers = new ArrayList<Marker>();
lastMarker = null;
makeVisibleOnScreen(getGameStateToLoad());
}
/**
*
* @param state
* @return
*/
public static String getImageNameForState(int state) {
switch (state) {
case Constants.kFieldStateEmpty:
return Constants.kEmptyFieldImageName;
case Constants.kFieldStateBlue:
return Constants.kBlueFieldImageName;
case Constants.kFieldStateRed:
return Constants.kRedFieldImageName;
case Constants.kFieldStateSelectable:
return Constants.kSelectableFieldImageName;
default: return Constants.kEmptyFieldImageName;
}
}
/**
*
* @param currentGameState
*/
public void makeVisibleOnScreen(ArrayList<Marker> currentGameState) {
for (int i = 0; i < currentGameState.size(); i++) {
Marker m = currentGameState.get(i);
modifyFieldImage(m, getImageNameForState(m.markerState));
}
}
public static void modifyViewTitle(String title) {
if (gs != null) {
gs.setTitle(title);
logger.debug(title);
}
}
public void modifyFieldImage(Marker marker, String imageName) {
if (gs != null) {
if (imageName != null) {
gs.changeIcon(marker.getIndex(), imageName);
} else {
gs.changeIcon(marker.getIndex(), (marker.markerState == Constants.kPlayerBlue ? Constants.kBlueFieldImageName : Constants.kRedFieldImageName));
}
}
}
public void modifyFieldImageAndState(Marker marker, String imageName, int state) {
((Marker)markers.get(marker.getIndex())).markerState = state;
if (gs != null) {
if (imageName != null) {
gs.changeField(marker.getIndex(), imageName, state);
} else {
gs.changeField(marker.getIndex(), (marker.markerState == Constants.kPlayerBlue ? Constants.kBlueFieldImageName : Constants.kRedFieldImageName), state);
}
}
}
}
|
package blang.mcmc;
import java.util.List;
import bayonet.distributions.Random;
import blang.core.LogScaleFactor;
import blang.core.WritableIntVar;
import blang.distributions.Generators;
public class IntSliceSampler implements Sampler
{
@SampledVariable
protected WritableIntVar variable;
@ConnectedFactor
protected List<LogScaleFactor> numericFactors;
private final Integer fixedWindowLeft, fixedWindowRight;
public boolean useFixedWindow()
{
return fixedWindowLeft != null;
}
private static final int initialWindowSize = 10;
private static final int maxNDoublingRounds = 20;
private IntSliceSampler(Integer fixedWindowLeft, Integer fixedWindowRight)
{
this.fixedWindowLeft = fixedWindowLeft;
this.fixedWindowRight = fixedWindowRight;
}
private IntSliceSampler()
{
this(null, null);
}
public static IntSliceSampler build(WritableIntVar variable, List<LogScaleFactor> numericFactors)
{
return build(variable, numericFactors, null, null);
}
public static IntSliceSampler build(WritableIntVar variable, List<LogScaleFactor> numericFactors, Integer fixedWinLeft, Integer fixedWinRight)
{
IntSliceSampler result = new IntSliceSampler(fixedWinLeft, fixedWinRight);
result.variable = variable;
result.numericFactors = numericFactors;
return result;
}
public void execute(Random random)
{
// sample slice
final double logSliceHeight = RealSliceSampler.nextLogSliceHeight(random, logDensity()); // log(Y) in Neal's paper
final int oldState = variable.intValue(); // x0 in Neal's paper
int leftProposalEndPoint, rightProposalEndPoint;
if (useFixedWindow())
{
leftProposalEndPoint = fixedWindowLeft;
rightProposalEndPoint = fixedWindowRight;
}
else
{
// doubling procedure
leftProposalEndPoint = oldState - random.nextInt(initialWindowSize); // L in Neal's paper
rightProposalEndPoint = leftProposalEndPoint + initialWindowSize; // R in Neal's paper
// convention: left is inclusive, right is exclusive
int iter = 0;
while (iter++ < maxNDoublingRounds &&
(logSliceHeight < logDensityAt(leftProposalEndPoint) || logSliceHeight < logDensityAt(rightProposalEndPoint - 1)))
if (random.nextBernoulli(0.5))
{
leftProposalEndPoint += - (rightProposalEndPoint - leftProposalEndPoint);
// note 1: check we don't diverge to INF
// this as that can arise e.g. when encountering an improper posterior
// avoid infinite loop then and warn user.
if (leftProposalEndPoint == Double.NEGATIVE_INFINITY)
throw new RuntimeException(RealSliceSampler.INFINITE_SLICE_MESSAGE);
}
else
{
rightProposalEndPoint += rightProposalEndPoint - leftProposalEndPoint;
// same as note 1 above
if (rightProposalEndPoint == Double.POSITIVE_INFINITY)
throw new RuntimeException(RealSliceSampler.INFINITE_SLICE_MESSAGE);
}
}
// shrinkage procedure
int
leftShrankEndPoint = leftProposalEndPoint, // bar L in Neal's paper
rightShrankEndPoint = rightProposalEndPoint; // bar R in Neal's paper
while (true)
{
final int newState = Generators.discreteUniform(random, leftShrankEndPoint, rightShrankEndPoint); // x1 in Neal's paper
if (logSliceHeight <= logDensityAt(newState) && accept(oldState, newState, logSliceHeight, leftProposalEndPoint, rightProposalEndPoint))
{
variable.set(newState);
return;
}
if (newState < oldState)
leftShrankEndPoint = newState + 1;
else
rightShrankEndPoint = newState;
}
}
private boolean accept(int oldState, int newState, double logSliceHeight, int leftProposalEndPoint, int rightProposalEndPoint)
{
boolean differ = false; // D in Neal's paper; whether the intervals generated by new and old differ; used for optimization
while (rightProposalEndPoint - leftProposalEndPoint > initialWindowSize)
{
final int middle = (leftProposalEndPoint + rightProposalEndPoint) / 2; // M in Neal's paper
if ((oldState < middle && newState >= middle) ||
(oldState >= middle && newState < middle))
differ = true;
if (newState < middle)
rightProposalEndPoint = middle;
else
leftProposalEndPoint = middle;
if (differ && logSliceHeight >= logDensityAt(leftProposalEndPoint) && logSliceHeight >= logDensityAt(rightProposalEndPoint - 1))
return false;
}
return true;
}
private double logDensityAt(int x)
{
variable.set(x);
return logDensity();
}
private double logDensity() {
double sum = 0.0;
for (LogScaleFactor f : numericFactors)
sum += f.logDensity();
return sum;
}
}
|
package com.akiban.ais.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Definitive declaration of supported data types. The fields in each Type
* instance are:
*
* <dl>
* <dt>name</dt>
* <dd>Canonical name for the type</dd>
*
* <dt>nparams</dt>
* <dd>How many parameters are specified by DDL (0, 1 or 2)</dd>
*
* <dt>fixed</dt>
* <dd>Whether the storage size is fixed, e.g., true for int, false for
* varchar</dt>
*
* <dt>maxBytesize</dt>
* <dd>Storage size of elements. For fixed types, the chunk server relies on
* this to determine how to encode/decode values. For variable-length fields,
* this is the maximum number of bytes of data MySQL may encode, it DOES NOT
* include an allowance for the prefix bytes written by MySQL.
*
* <dt>encoding</dt>
* <dd>Name of a member of the chunk server's Encoding enum. This guides
* translation of a column value into a chunk server's internal format.</dd>
* </dl>
*
* @author peter
*
*/
public class Types {
// TODO -
// This is the largest BLOB size that will fit in a message. Increase or
// remove this when we are no longer limited by the message size.
// Note that the Type objects for the BLOB types carry their MySQL-defined
// values so that the prefix size will be computed correctly. The
// cap is imposed by the constructor of a Column object.
public final static int MAX_STORAGE_SIZE_CAP = 1024 * 1024 - 1024;
// The basic numeric types, fixed length, implemented
// (except bigint unsigned fails for numbers larger than Long.MAX_VALUE).
public static Type BIGINT = new Type("bigint", 0, true, 8L, "INT");
public static Type U_BIGINT = new Type("bigint unsigned", 0, true, 8L, "U_INT");
public static Type DOUBLE = new Type("double", 0, true, 8L, "FLOAT");
public static Type U_DOUBLE = new Type("double unsigned", 0, true, 8L, "U_FLOAT");
public static Type FLOAT = new Type("float", 0, true, 4L, "FLOAT");
public static Type U_FLOAT = new Type("float unsigned", 0, true, 4L, "U_FLOAT");
public static Type INT = new Type("int", 0, true, 4L, "INT");
public static Type U_INT = new Type("int unsigned", 0, true, 4L, "U_INT");
public static Type MEDIUMINT = new Type("mediumint", 0, true, 3L, "INT");
public static Type U_MEDIUMINT = new Type("mediumint unsigned", 0, true, 3L, "U_INT");
public static Type SMALLINT = new Type("smallint", 0, true, 2L, "INT");
public static Type U_SMALLINT = new Type("smallint unsigned", 0, true, 2L, "U_INT");
public static Type TINYINT = new Type("tinyint", 0, true, 1L, "INT");
public static Type U_TINYINT = new Type("tinyint unsigned", 0, true, 1L, "U_INT");
// Date & Time types, fixed length, implemented.
public static Type DATE = new Type("date", 0, true, 3L, "DATE");
public static Type DATETIME = new Type("datetime", 0, true, 8L, "DATETIME");
public static Type YEAR = new Type("year", 0, true, 1L, "YEAR");
public static Type TIME = new Type("time", 0, true, 3L, "TIME");
public static Type TIMESTAMP = new Type("timestamp", 0, true, 4L, "TIMESTAMP");
// VARCHAR and TEXT types. Maximum storage size is computed in Column, numbers
// here are not used. MaxByteSize numbers here are not used.
public static Type VARBINARY = new Type("varbinary", 1, false, 65535L, "VARBINARY");
public static Type BINARY = new Type("binary", 1, false, 255L, "VARBINARY");
public static Type VARCHAR = new Type("varchar", 1, false, 65535L, "VARCHAR");
public static Type CHAR = new Type("char", 1, false, 767L, "VARCHAR");
// BLOB and TEXT types. Currently handled identically. The maxByteSize values
// here are used in computing the correct prefix size. The maximum allow size
// is constrained in Column.
public static Type TINYBLOB = new Type("tinyblob", 0, false, 0xFFl, "BLOB");
public static Type TINYTEXT = new Type("tinytext", 0, false, 0xFFl, "TEXT");
public static Type BLOB = new Type("blob", 0, false, 0xFFFFl, "BLOB");
public static Type TEXT = new Type("text", 0, false, 0xFFFFl, "TEXT");
public static Type MEDIUMBLOB = new Type("mediumblob", 0, false, 0xFFFFFFL, "BLOB");
public static Type MEDIUMTEXT = new Type("mediumtext", 0, false, 0xFFFFFFL, "TEXT");
public static Type LONGBLOB = new Type("longblob", 0, false, 0xFFFFFFFFL, "BLOB");
public static Type LONGTEXT = new Type("longtext", 0, false, 0xFFFFFFFFL, "TEXT");
// DECIMAL types. The maxByteSize values are computed in Column as they are fixed for
// a given instance. Numbers are a maximum possible (ie, decimal(65,30));
public static Type DECIMAL = new Type("decimal", 2, true, 30L, "DECIMAL");
public static Type U_DECIMAL = new Type("decimal unsigned", 2, true, 30L, "U_DECIMAL");
// Halo unsupported
public static Type ENUM = new Type("enum", 1, true, 2L, "U_INT");
public static Type SET = new Type("set", 1, true, 8L, "U_INT");
public static Type BIT = new Type("bit", 1, true, 9L, "BIT");
public static Type GEOMETRY = new Type("geometry", 0, false, 0L, "GEOMETRY");
public static Type GEOMETRYCOLLECTION = new Type("geometrycollection", 0, false, 0L, "GEOMETRYCOLLECTION");
public static Type POINT = new Type("point", 0, false, 0L, "POINT");
public static Type MULTIPOINT = new Type("multipoint", 0, false, 0L, "MULTIPOINT");
public static Type LINESTRING = new Type("linestring", 0, false, 0L, "LINESTRING");
public static Type MULTILINESTRING = new Type("multilinestring", 0, false, 0L, "MULTILINESTRING");
public static Type POLYGON = new Type("polygon", 0, false, 0L, "POLYGON");
public static Type MULTIPOLYGON = new Type("multipolygon", 0, false, 0L, "MULTIPOLYGON");
private final static List<Type> types = listOfTypes();
private final static Set<Type> unsupported = setOfUnsupportedTypes();
private final static Map<Type,Long[]> defaultParams = mapOfDefaults();
private static List<Type> listOfTypes() {
List<Type> types = new ArrayList<Type>();
types.add(BIGINT);
types.add(U_BIGINT);
types.add(BINARY);
types.add(BIT);
types.add(BLOB);
types.add(CHAR);
types.add(DATE);
types.add(DATETIME);
types.add(DECIMAL);
types.add(U_DECIMAL);
types.add(DOUBLE);
types.add(U_DOUBLE);
types.add(ENUM);
types.add(FLOAT);
types.add(U_FLOAT);
types.add(GEOMETRY);
types.add(GEOMETRYCOLLECTION);
types.add(INT);
types.add(U_INT);
types.add(LINESTRING);
types.add(LONGBLOB);
types.add(LONGTEXT);
types.add(MEDIUMBLOB);
types.add(MEDIUMINT);
types.add(U_MEDIUMINT);
types.add(MEDIUMTEXT);
types.add(MULTILINESTRING);
types.add(MULTIPOINT);
types.add(MULTIPOLYGON);
types.add(POINT);
types.add(POLYGON);
types.add(SET);
types.add(SMALLINT);
types.add(U_SMALLINT);
types.add(TEXT);
types.add(TIME);
types.add(TIMESTAMP);
types.add(TINYBLOB);
types.add(TINYINT);
types.add(U_TINYINT);
types.add(TINYTEXT);
types.add(VARBINARY);
types.add(VARCHAR);
types.add(YEAR);
return Collections.unmodifiableList(types);
}
private static Set<Type> setOfUnsupportedTypes() {
Set<Type> unsupported = new HashSet<Type>();
unsupported.add(null);
unsupported.add(BIT);
unsupported.add(ENUM);
unsupported.add(SET);
unsupported.add(GEOMETRY);
unsupported.add(GEOMETRYCOLLECTION);
unsupported.add(POINT);
unsupported.add(MULTIPOINT);
unsupported.add(LINESTRING);
unsupported.add(MULTILINESTRING);
unsupported.add(POLYGON);
unsupported.add(MULTIPOLYGON);
return Collections.unmodifiableSet(unsupported);
}
private static Map<Type,Long[]> mapOfDefaults() {
Map<Type,Long[]> map = new HashMap<Type,Long[]>();
map.put(BIT, new Long[]{1L,null});
map.put(BINARY, new Long[]{1L,null});
map.put(CHAR, new Long[]{1L,null});
map.put(DECIMAL, new Long[]{10L,0L});
map.put(U_DECIMAL, new Long[]{10L,0L});
return Collections.unmodifiableMap(map);
}
public static List<Type> types() {
return types;
}
public static Set<Type> unsupportedTypes() {
return unsupported;
}
public static Map<Type,Long[]> defaultParams() {
return defaultParams;
}
}
|
package com.rocketnia.mvtron.analyzer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LumaAverager implements IIntArrayReferenceListener
{
private List< IFloatListener > floatListeners =
Collections.synchronizedList( new ArrayList< IFloatListener >() );
private static final float maxAverageLuma = 0xFF * 3;
public LumaAverager() {}
public static RgbArrayListenerTool makeTool()
{ return new RgbArrayListenerTool( new LumaAverager() ); }
public RgbArrayListenerTool newTool()
{ return new RgbArrayListenerTool( this ); }
@Override
public void onIntArrayReference( int[] rgb )
{ propagateFloat( calculate( rgb ) ); }
public static float calculate( int[] rgb )
{
int thisAverageLuma = 0;
for ( int pixel: rgb )
{
// The pixels are in ARGB format.
// assert 0xFF == (0xFF & pixel >>> 24); // alpha
thisAverageLuma +=
(0xFF & pixel >>> 16) +
(0xFF & pixel >>> 8) +
(0xFF & pixel );
}
return thisAverageLuma / maxAverageLuma / rgb.length;
}
public void addListener( IFloatListener listener )
{ floatListeners.add( listener ); }
protected void propagateFloat( float f )
{
for ( IFloatListener listener: floatListeners )
listener.onFloat( f );
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.akiban.cserver;
import java.io.DataInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.akiban.ais.ddl.DDLSource;
import com.akiban.ais.io.Reader;
import com.akiban.ais.message.AISExecutionContext;
import com.akiban.ais.message.AISRequest;
import com.akiban.ais.message.AISResponse;
import com.akiban.ais.model.AkibaInformationSchema;
import com.akiban.ais.model.AkibaInformationSchemaImpl;
import com.akiban.ais.model.Source;
import com.akiban.cserver.message.ShutdownRequest;
import com.akiban.cserver.message.ShutdownResponse;
import com.akiban.cserver.store.PersistitStore;
import com.akiban.cserver.store.Store;
import com.akiban.message.AkibaConnection;
import com.akiban.message.ErrorResponse;
import com.akiban.message.ExecutionContext;
import com.akiban.message.Message;
import com.akiban.message.MessageRegistry;
import com.akiban.network.AkibaNetworkHandler;
import com.akiban.network.CommEventNotifier;
import com.akiban.network.NetworkHandlerFactory;
/**
*
* @author peter
*/
public class CServer {
private static final Log LOG = LogFactory.getLog(CServer.class.getName());
private static final String AIS_DDL_NAME = "akiba_information_schema.ddl";
/**
* Config property name and default for the port on which the CServer will
* listen for requests.
*/
private static final String P_CSERVER_HOST = "cserver.host|localhost";
/**
* Config property name and default for the port on which the CServer will
* listen for requests.
*/
private static final String P_CSERVER_PORT = "cserver.port|8080";
/**
* Config property name and default for setting of the verbose flag. When
* true, many CServer methods log verbosely at INFO level.
*/
private static final String VERBOSE_PROPERTY_NAME = "cserver.verbose";
private final RowDefCache rowDefCache = new RowDefCache();
private final CServerConfig config = new CServerConfig();
private final Store store = new PersistitStore(config, rowDefCache);
private AkibaInformationSchema ais0;
private AkibaInformationSchema ais;
private volatile boolean stopped = false;
private boolean verbose;
private Map<Integer, Thread> threadMap = new TreeMap<Integer, Thread>();
public void start() throws Exception {
MessageRegistry.initialize();
MessageRegistry.only().registerModule("com.akiban.cserver");
MessageRegistry.only().registerModule("com.akiban.ais");
MessageRegistry.only().registerModule("com.akiban.message");
ChannelNotifier callback = new ChannelNotifier();
NetworkHandlerFactory.initializeNetwork(property(P_CSERVER_HOST),
property(P_CSERVER_PORT), (CommEventNotifier) callback);
final String verboseString = config.property(VERBOSE_PROPERTY_NAME
+ "|false");
if ("true".equalsIgnoreCase(verboseString)) {
verbose = true;
}
store.startUp();
store.setVerbose(verbose);
ais0 = primordialAIS();
rowDefCache.setAIS(ais0);
acquireAIS();
}
public void stop() throws Exception {
stopped = true;
final List<Thread> copy;
synchronized (threadMap) {
copy = new ArrayList<Thread>(threadMap.values());
}
// for now I think this is the only way to make these threads
// bail from their reads.
for (final Thread thread : copy) {
thread.interrupt();
}
store.shutDown();
NetworkHandlerFactory.closeNetwork();
}
public class ChannelNotifier implements CommEventNotifier {
@Override
public void onConnect(AkibaNetworkHandler handler) {
if (LOG.isInfoEnabled()) {
LOG.info("Connection #" + handler.getId() + " created");
}
final String threadName = "CServer_" + handler.getId();
final Thread thread = new Thread(new CServerRunnable(
AkibaConnection.createConnection(handler)), threadName);
thread.setDaemon(true);
thread.start();
synchronized (threadMap) {
threadMap.put(handler.getId(), thread);
}
}
@Override
public void onDisconnect(AkibaNetworkHandler handler) {
final Thread thread;
synchronized (threadMap) {
thread = threadMap.remove(handler.getId());
}
if (thread != null && thread.isAlive()) {
thread.interrupt();
if (LOG.isInfoEnabled()) {
LOG.info("Connection #" + handler.getId() + " ended");
}
} else {
LOG.error("CServer thread for connection #" + handler.getId()
+ " was missing or dead");
}
}
}
public Store getStore() {
return store;
}
public class CServerContext implements ExecutionContext,
AISExecutionContext, CServerShutdownExecutionContext {
public Store getStore() {
return store;
}
@Override
public void executeRequest(AkibaConnection connection,
AISRequest request) throws Exception {
acquireAIS();
AISResponse aisResponse = new AISResponse(ais);
connection.send(aisResponse);
}
@Override
public void executeResponse(AkibaConnection connection,
AISResponse response) throws Exception {
ais = response.ais();
installAIS();
}
@Override
public void executeRequest(AkibaConnection connection,
ShutdownRequest request) throws Exception {
if (LOG.isInfoEnabled()) {
LOG.info("CServer stopping due to ShutdownRequest");
}
stop();
ShutdownResponse response = new ShutdownResponse();
connection.send(response);
}
}
/**
* A Runnable that reads Network messages, acts on them and returns results.
*
* @author peter
*
*/
private class CServerRunnable implements Runnable {
private final AkibaConnection connection;
private final ExecutionContext context = new CServerContext();
private int requestCounter;
public CServerRunnable(final AkibaConnection connection) {
this.connection = connection;
}
public void run() {
Message message = null;
while (!stopped) {
try {
message = connection.receive();
if (LOG.isTraceEnabled()) {
LOG.trace("Serving message " + message);
}
message.execute(connection, context);
requestCounter++;
} catch (InterruptedException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Thread " + Thread.currentThread().getName()
+ (stopped ? " stopped" : " interrupted"));
}
break;
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Unexpected error on " + message, e);
}
if (message != null) {
try {
connection.send(new ErrorResponse(e));
} catch (Exception f) {
LOG.error("Caught " + f.getClass()
+ " while sending error response to "
+ message + ": " + f.getMessage(), f);
}
}
}
}
}
}
public RowDefCache getRowDefCache() {
return rowDefCache;
}
/**
* Acquire an AkibaInformationSchema from MySQL and install it into the
* local RowDefCache.
*
* This method always refreshes the locally cached AkibaInformationSchema to
* support schema modifications at the MySQL head.
*
* @return an AkibaInformationSchema
* @throws Exception
*/
public synchronized void acquireAIS() throws Exception {
final Source source = new CServerAisSource(store);
this.ais = new Reader(source)
.load(new AkibaInformationSchemaImpl(ais0));
installAIS();
}
private synchronized void installAIS() throws Exception {
if (LOG.isInfoEnabled()) {
LOG.info("Installing " + ais.getDescription() + " in ChunkServer");
}
rowDefCache.clear();
rowDefCache.setAIS(ais);
store.setOrdinals();
}
/**
* Loads the built-in primordial table definitions for the
* akiba_information_schema tables.
*
* @throws Exception
*/
AkibaInformationSchema primordialAIS() throws Exception {
if (ais0 != null) {
return ais0;
}
final DataInputStream stream = new DataInputStream(getClass()
.getClassLoader().getResourceAsStream(AIS_DDL_NAME));
// TODO: ugly, but gets the job done
final StringBuilder sb = new StringBuilder();
for (;;) {
final String line = stream.readLine();
if (line == null) {
break;
}
sb.append(line);
sb.append("\n");
}
ais0 = (new DDLSource()).buildAISFromString(sb.toString());
return ais0;
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) throws Exception {
final CServer server = new CServer();
server.config.load();
if (server.config.getException() != null) {
LOG.fatal("CServer configuration failed");
return;
}
server.start();
// HAZEL: MySQL Conference Demo 4/2010: MySQL/Drizzle/Memcache to Chunk Server
/*
com.thimbleware.jmemcached.protocol.MemcachedCommandHandler.registerCallback(
new com.thimbleware.jmemcached.protocol.MemcachedCommandHandler.Callback()
{
public byte[] get(byte[] key)
{
byte[] result = null;
String request = new String(key);
String[] tokens = request.split(":");
if (tokens.length == 4)
{
String schema = tokens[0];
String table = tokens[1];
String colkey = tokens[2];
String colval = tokens[3];
try
{
List<RowData> list = null;
// list = store.fetchRows(schema, table, colkey, colval, colval);
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(bos);
out.writeObject(list);
out.close();
result = bos.toByteArray();
}
catch (Exception e)
{
result = new String("read error: " + e.getMessage()).getBytes();
}
}
else
{
result = new String("invalid key: " + request).getBytes();
}
return result;
}
});
com.thimbleware.jmemcached.Main.main(new String[0]);
*/
}
public String property(final String key) {
return config.property(key);
}
public String property(final String key, final String dflt) {
return config.property(key, dflt);
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.servlet.user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import com.samskivert.io.PersistenceException;
import com.samskivert.jdbc.ConnectionProvider;
import com.samskivert.jdbc.DatabaseLiaison;
import com.samskivert.jdbc.JDBCUtil;
import com.samskivert.jdbc.JORARepository;
import com.samskivert.jdbc.jora.FieldMask;
import com.samskivert.jdbc.jora.Table;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.StringUtil;
import com.samskivert.util.Tuple;
import com.samskivert.servlet.SiteIdentifier;
/**
* Interfaces with the RDBMS in which the user information is stored. The user repository
* encapsulates the creating, loading and management of users and sessions.
*/
public class UserRepository extends JORARepository
{
/**
* The database identifier used to obtain a connection from our connection provider. The value
* is <code>userdb</code> which you'll probably need to know to provide the proper
* configuration to your connection provider.
*/
public static final String USER_REPOSITORY_IDENT = "userdb";
/**
* Creates the repository and opens the user database. The database identifier used to fetch
* our database connection is documented by {@link #USER_REPOSITORY_IDENT}.
*
* @param provider the database connection provider.
*/
public UserRepository (ConnectionProvider provider)
{
super(provider, USER_REPOSITORY_IDENT);
}
/**
* Requests that a new user be created in the repository.
*
* @param username the username of the new user to create.
* @param password the password for the new user.
* @param realname the user's real name.
* @param email the user's email address.
* @param siteId the unique identifier of the site through which this account is being
* created. The resulting user will be tracked as originating from this site for accounting
* purposes ({@link SiteIdentifier#DEFAULT_SITE_ID} can be used by systems that don't desire to
* perform site tracking.
*
* @return The userid of the newly created user.
*/
public int createUser (
Username username, Password password, String realname, String email, int siteId)
throws UserExistsException, PersistenceException
{
// create a new user object...
User user = new User();
user.setDirtyMask(_utable.getFieldMask());
// ...configure it...
populateUser(user, username, password, realname, email, siteId);
// ...and stick it into the database
return insertUser(user);
}
/**
* Looks up a user by username.
*
* @return the user with the specified user id or null if no user with that id exists.
*/
public User loadUser (String username)
throws PersistenceException
{
return loadUserWhere("where username = " + JDBCUtil.escape(username));
}
/**
* Looks up a user by userid.
*
* @return the user with the specified user id or null if no user with that id exists.
*/
public User loadUser (int userId)
throws PersistenceException
{
return loadUserWhere("where userId = " + userId);
}
/**
* Looks up a user by a session identifier.
*
* @return the user associated with the specified session or null of no session exists with the
* supplied identifier.
*/
public User loadUserBySession (String sessionKey)
throws PersistenceException
{
User user = load(_utable, "sessions", "where authcode = '" + sessionKey + "' " +
"AND sessions.userId = users.userId");
if (user != null) {
user.setDirtyMask(_utable.getFieldMask());
}
return user;
}
/**
* Looks up users by userid
*
* @return the users whom have a user id in the userIds array.
*/
public HashIntMap<User> loadUsersFromId (int[] userIds)
throws PersistenceException
{
HashIntMap<User> data = new HashIntMap<User>();
if (userIds.length > 0) {
String query = "where userId in (" + genIdString(userIds) + ")";
for (User user : loadAll(_utable, query)) {
user.setDirtyMask(_utable.getFieldMask());
data.put(user.userId, user);
}
}
return data;
}
/**
* Lookup a user by email address, something that is not efficient and should really only be
* done by site admins attempting to look up a user record.
*
* @return the user with the specified user id or null if no user with that id exists.
*/
public ArrayList<User> lookupUsersByEmail (String email)
throws PersistenceException
{
return loadAll(_utable, "where email = " + JDBCUtil.escape(email));
}
/**
* Looks up a list of users that match an arbitrary query. Care should be taken in constructing
* these queries as the user table is likely to be large and a query that does not make use of
* indices could be very slow.
*
* @return the users matching the specified query or an empty list if there are no matches.
*/
public ArrayList<User> lookupUsersWhere (final String where)
throws PersistenceException
{
ArrayList<User> users = loadAll(_utable, where);
for (User user : users) {
// configure the user record with its field mask
user.setDirtyMask(_utable.getFieldMask());
}
return users;
}
/**
* Updates a user that was previously fetched from the repository. Only fields that have been
* modified since it was loaded will be written to the database and those fields will
* subsequently be marked clean once again.
*
* @return true if the record was updated, false if the update was skipped because no fields in
* the user record were modified.
*/
public boolean updateUser (final User user)
throws PersistenceException
{
if (!user.getDirtyMask().isModified()) {
// nothing doing!
return false;
}
update(_utable, user, user.getDirtyMask());
return true;
}
/**
* 'Delete' the users account such that they can no longer access it, however we do not delete
* the record from the db. The name is changed such that the original name has XX=FOO if the
* name were FOO originally. If we have to lop off any of the name to get our prefix to fit we
* use a minus sign instead of a equals side. The password field is set to be the empty string
* so that no one can log in (since nothing hashes to the empty string. We also make sure
* their email address no longer works, so in case we don't ignore 'deleted' users when we do
* the sql to get emailaddresses for the mass mailings we still won't spam delete folk. We
* leave the emailaddress intact exect for the @ sign which gets turned to a #, so that we can
* see what their email was incase it was an accidently deletion and we have to verify through
* email.
*/
public void deleteUser (final User user)
throws PersistenceException
{
if (user.isDeleted()) {
return;
}
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
// create our modified fields mask
FieldMask mask = _utable.getFieldMask();
mask.setModified("username");
mask.setModified("password");
mask.setModified("email");
// set the password to unusable
user.password = "";
// 'disable' their email address
String newEmail = user.email.replace('@','
user.email = newEmail;
String oldName = user.username;
for (int ii = 0; ii < 100; ii++) {
try {
user.username = StringUtil.truncate(ii + "=" + oldName, 24);
_utable.update(conn, user, mask);
return null; // nothing to return
} catch (SQLException se) {
if (!liaison.isDuplicateRowException(se)) {
throw se;
}
}
}
// ok we failed to rename the user, lets bust an error
throw new PersistenceException("Failed to 'delete' the user");
}
});
}
/**
* Creates a new session for the specified user and returns the randomly generated session
* identifier for that session. If a session entry already exists for the specified user it
* will be reused.
*
* @param expireDays the number of days in which the session token should expire.
*/
public String registerSession (User user, int expireDays)
throws PersistenceException
{
// look for an existing session for this user
final String query = "select authcode from sessions where userId = " + user.userId;
String authcode = execute(new Operation<String>() {
public String invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
return rs.getString(1);
}
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
// figure out when to expire the session
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// if we found one, update its expires time and reuse it
if (authcode != null) {
update("update sessions set expires = '" + expires + "' where authcode = " + authcode);
} else {
// otherwise create a new one and insert it into the table
authcode = UserUtil.genAuthCode(user);
update("insert into sessions (authcode, userId, expires) values('" + authcode + "', " +
user.userId + ", '" + expires + "')");
}
return authcode;
}
/**
* Validates that the supplied session key is still valid and if so, refreshes it for the
* specified number of days.
*
* @return true if the session was located and refreshed, false if it no longer exists.
*/
public boolean refreshSession (String sessionKey, int expireDays)
throws PersistenceException
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// attempt to update an existing session row, returning true if we found and updated it
return (update("update sessions set expires = '" + expires + "' " +
"where authcode = " + JDBCUtil.escape(sessionKey)) == 1);
}
/**
* Prunes any expired sessions from the sessions table.
*/
public void pruneSessions ()
throws PersistenceException
{
update("delete from sessions where expires <= CURRENT_DATE()");
}
/**
* Loads the usernames of the users identified by the supplied user ids and returns them in an
* array. If any users do not exist, their slot in the array will contain a null.
*/
public String[] loadUserNames (int[] userIds)
throws PersistenceException
{
return loadNames(userIds, "username");
}
/**
* Loads the real names of the users identified by the supplied user ids and returns them in an
* array. If any users do not exist, their slot in the array will contain a null.
*/
public String[] loadRealNames (int[] userIds)
throws PersistenceException
{
return loadNames(userIds, "realname");
}
/**
* Returns an array with the real names of every user in the system.
*/
public String[] loadAllRealNames ()
throws PersistenceException
{
final ArrayList<String> names = new ArrayList<String>();
// do the query
execute(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
Statement stmt = conn.createStatement();
try {
String query = "select realname from users";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
names.add(rs.getString(1));
}
// nothing to return
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
// finally construct our result
return names.toArray(new String[names.size()]);
}
/**
* Configures the supplied user record with the provided information in preparation for
* inserting the record into the database for the first time.
*/
protected void populateUser (
User user, Username name, Password pass, String realname, String email, int siteId)
{
user.username = name.getUsername();
user.setPassword(pass);
user.setRealName(realname);
user.setEmail(email);
user.created = new Date(System.currentTimeMillis());
user.setSiteId(siteId);
}
/**
* Inserts the supplied user record into the user database, assigning it a userid in the
* process, which is returned.
*/
protected int insertUser (final User user)
throws UserExistsException, PersistenceException
{
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
try {
_utable.insert(conn, user);
// update the userid now that it's known
user.userId = liaison.lastInsertedId(conn, _utable.getName(), "userId");
// nothing to return
return null;
} catch (SQLException sqe) {
if (liaison.isDuplicateRowException(sqe)) {
throw new UserExistsException("error.user_exists");
} else {
throw sqe;
}
}
}
});
return user.userId;
}
/**
* Loads up a user record that matches the specified where clause. Returns null if no record
* matches.
*/
protected User loadUserWhere (String where)
throws PersistenceException
{
User user = load(_utable, where);
if (user != null) {
user.setDirtyMask(_utable.getFieldMask());
}
return user;
}
protected String[] loadNames (int[] userIds, final String column)
throws PersistenceException
{
// if userids is zero length, we've got no work to do
if (userIds.length == 0) {
return new String[0];
}
// do the query
final String ids = genIdString(userIds);
final HashIntMap<String> map = new HashIntMap<String>();
execute(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
Statement stmt = conn.createStatement();
try {
String query = "select userId, " + column + " from users " +
"where userId in (" + ids + ")";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int userId = rs.getInt(1);
String name = rs.getString(2);
map.put(userId, name);
}
// nothing to return
return null;
} finally {
JDBCUtil.close(stmt);
}
}
});
// finally construct our result
String[] result = new String[userIds.length];
for (int i = 0; i < userIds.length; i++) {
result[i] = map.get(userIds[i]);
}
return result;
}
/**
* Take the passed in int array and create the a string suitable for using in a SQL set query
* (I.e., "select foo, from bar where userId in (genIdString(userIds))"; )
*/
protected String genIdString (int[] userIds)
{
// build up the string we need for the query
StringBuilder ids = new StringBuilder();
for (int i = 0; i < userIds.length; i++) {
if (ids.length() > 0) {
ids.append(",");
}
ids.append(userIds[i]);
}
return ids.toString();
}
@Override
protected void createTables ()
{
// create our table object
_utable = new Table<User>(User.class, "users", "userId");
}
/** A wrapper that provides access to the userstable. */
protected Table<User> _utable;
}
|
// $Id: SceneManager.java,v 1.17 2004/05/19 22:09:04 ray Exp $
package com.threerings.whirled.server;
import com.samskivert.io.PersistenceException;
import com.threerings.crowd.server.PlaceManager;
import com.threerings.presents.server.PresentsServer;
import com.threerings.presents.util.Invoker;
import com.threerings.whirled.Log;
import com.threerings.whirled.data.Scene;
import com.threerings.whirled.data.SceneCodes;
import com.threerings.whirled.data.SceneUpdate;
import com.threerings.whirled.server.WhirledServer;
import com.threerings.whirled.util.UpdateList;
/**
* The scene manager extends the place manager and takes care of basic
* scene services. Presently that is little more than registering the
* scene manager with the scene registry so that the manager can be looked
* up by scene id in addition to place object id.
*/
public class SceneManager extends PlaceManager
{
/**
* Returns the scene object (not the scene distributed object) being
* managed by this scene manager.
*/
public Scene getScene ()
{
return _scene;
}
/**
* Returns {@link UpdateList#getUpdates} for this scene's updates.
*/
public SceneUpdate[] getUpdates (int fromVersion)
{
return _updates.getUpdates(fromVersion);
}
/**
* Called by the scene registry once the scene manager has been
* created (and initialized), but before it is started up.
*/
protected void setSceneData (Scene scene, UpdateList updates,
SceneRegistry screg)
{
// make sure the list and our version of the scene are in
// accordance
if (!updates.validate(scene.getVersion())) {
Log.warning("Provided with invalid updates; flushing " +
"[where=" + where() +
", sceneId=" + scene.getId() + "].");
// clear out the update list as it will not allow us to bring
// clients up to date with our current scene version; instead
// they'll have to download the whole thing
updates = new UpdateList();
}
_scene = scene;
_screg = screg;
_updates = updates;
// let derived classes react to the receipt of scene data
gotSceneData();
}
/**
* A method that can be overridden by derived classes to perform
* initialization processing after we receive our scene information
* but before we're started up (and hence registered as an active
* place).
*/
protected void gotSceneData ()
{
}
/**
* We're fully ready to go, so now we register ourselves with the
* scene registry which will make us available to the clients and
* system at large.
*/
protected void didStartup ()
{
super.didStartup();
// Wait until us and all of our subclasses have completely finished
// running didStartup prior to registering the scene as being ready.
PresentsServer.omgr.postUnit(new Runnable() {
public void run () {
_screg.sceneManagerDidStart(SceneManager.this);
}
});
}
/**
* Called when we have shutdown.
*/
protected void didShutdown ()
{
super.didShutdown();
// unregister ourselves with the scene registry
_screg.unmapSceneManager(this);
}
/**
* When a modification is made to a scene, the scene manager should
* update its internal structures, update the {@link Scene} object,
* update the repository (either by storing the updated scene
* wholesale or more efficiently updating only what has changed), and
* then it should create a {@link SceneUpdate} record that can be
* delivered to clients to effect the update to the clients's cached
* copy of the scene model. This update will be stored persistently
* and provided (along with any other accumulated updates) to clients
* that later request to enter the scene with an old version of the
* scene data. Updates are not stored forever, but a sizable number of
* recent updates are stored so that moderately current clients can
* apply incremental patches to their scenes rather than redownloading
* the entire scenes when they change.
*/
protected void recordUpdate (final SceneUpdate update)
{
// add it to our in memory update list
_updates.addUpdate(update);
// and store it in the repository
WhirledServer.invoker.postUnit(new Invoker.Unit() {
public boolean invoke () {
try {
_screg.getSceneRepository().addUpdate(update);
} catch (PersistenceException pe) {
Log.warning("Failed to store scene update " +
"[update=" + update + ", error=" + pe + "].");
}
return false;
}
});
// broadcast the update to all occupants of the scene
_plobj.postMessage(SceneCodes.SCENE_UPDATE, new Object[] { update });
}
// documentation inherited
public String where ()
{
return _scene.getName() + " (" + super.where() + ":" +
_scene.getId() + ")";
}
// documentation inherited
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", scene=").append(_scene);
}
/** A reference to our scene implementation which provides a
* meaningful interpretation of the data in the scene model. */
protected Scene _scene;
/** A list of the updates tracked for this scene. These will be used
* to attempt to bring clients up to date efficiently if they request
* to enter our scene with old scene model data. */
protected UpdateList _updates;
/** A reference to the scene registry so that we can call back to it
* when we're fully initialized. */
protected SceneRegistry _screg;
}
|
package com.vaklinov.zcashui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.vaklinov.zcashui.OSUtil.OS_TYPE;
import com.vaklinov.zcashui.ZCashClientCaller.WalletCallException;
public class StartupProgressDialog extends JFrame {
private static final int POLL_PERIOD = 1500;
private static final int STARTUP_ERROR_CODE = -28;
private BorderLayout borderLayout1 = new BorderLayout();
private JLabel imageLabel = new JLabel();
private JLabel progressLabel = new JLabel();
private JPanel southPanel = new JPanel();
private BorderLayout southPanelLayout = new BorderLayout();
private JProgressBar progressBar = new JProgressBar();
private ImageIcon imageIcon;
private final ZCashClientCaller clientCaller;
public StartupProgressDialog(ZCashClientCaller clientCaller)
{
this.clientCaller = clientCaller;
URL iconUrl = this.getClass().getClassLoader().getResource("images/Z-yellow.orange-logo.png");
imageIcon = new ImageIcon(iconUrl);
imageLabel.setIcon(imageIcon);
imageLabel.setBorder(BorderFactory.createEmptyBorder(16, 16, 0, 16));
Container contentPane = getContentPane();
contentPane.setLayout(borderLayout1);
southPanel.setLayout(southPanelLayout);
southPanel.setBorder(BorderFactory.createEmptyBorder(0, 16, 16, 16));
contentPane.add(imageLabel, BorderLayout.NORTH);
JLabel zcashWalletLabel = new JLabel(
"<html><span style=\"font-style:italic;font-weight:bold;font-size:25px\">" +
"Zen Cash Wallet</span></html>");
zcashWalletLabel.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));
contentPane.add(zcashWalletLabel, BorderLayout.CENTER);
contentPane.add(southPanel, BorderLayout.SOUTH);
progressBar.setIndeterminate(true);
southPanel.add(progressBar, BorderLayout.NORTH);
progressLabel.setText("Starting...");
southPanel.add(progressLabel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
public void waitForStartup() throws IOException,
InterruptedException,WalletCallException,InvocationTargetException {
// special handling of OSX app bundle
// if (OSUtil.getOSType() == OS_TYPE.MAC_OS) {
// ProvingKeyFetcher keyFetcher = new ProvingKeyFetcher();
// keyFetcher.fetchIfMissing(this);
// if ("true".equalsIgnoreCase(System.getProperty("launching.from.appbundle")))
// performOSXBundleLaunch();
if (OSUtil.getOSType() == OS_TYPE.WINDOWS)
{
ProvingKeyFetcher keyFetcher = new ProvingKeyFetcher();
keyFetcher.fetchIfMissing(this);
performZenConf();
}
System.out.println("Splash: checking if zend is already running...");
boolean shouldStartZCashd = false;
try {
clientCaller.getDaemonRawRuntimeInfo();
} catch (IOException e) {
// Relying on a general exception may be unreliable
// may be thrown for an unexpected reason!!! - so message is checked
if (e.getMessage() != null &&
e.getMessage().toLowerCase(Locale.ROOT).contains("error: couldn't connect to server"))
{
shouldStartZCashd = true;
}
}
if (!shouldStartZCashd) {
System.out.println("Splash: zend already running...");
// What if started by hand but taking long to initialize???
// doDispose();
// return;
} else
{
System.out.println("Splash: zend will be started...");
}
final Process daemonProcess =
shouldStartZCashd ? clientCaller.startDaemon() : null;
Thread.sleep(POLL_PERIOD); // just a little extra
int iteration = 0;
while(true) {
iteration++;
Thread.sleep(POLL_PERIOD);
JsonObject info = null;
try
{
info = clientCaller.getDaemonRawRuntimeInfo();
} catch (IOException e)
{
if (iteration > 4)
{
throw e;
} else
{
continue;
}
}
JsonValue code = info.get("code");
if (code == null || (code.asInt() != STARTUP_ERROR_CODE))
break;
final String message = info.getString("message", "???");
setProgressText(message);
}
// doDispose(); - will be called later by the main GUI
if (daemonProcess != null) // Shutdown only if we started it
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Stopping zend because we started it - now it is alive: " +
StartupProgressDialog.this.isAlive(daemonProcess));
try
{
clientCaller.stopDaemon();
long start = System.currentTimeMillis();
while (!StartupProgressDialog.this.waitFor(daemonProcess, 3000))
{
long end = System.currentTimeMillis();
System.out.println("Waiting for " + ((end - start) / 1000) + " seconds for zend to exit...");
if (end - start > 10 * 1000)
{
clientCaller.stopDaemon();
daemonProcess.destroy();
}
if (end - start > 1 * 60 * 1000)
{
break;
}
}
if (StartupProgressDialog.this.isAlive(daemonProcess)) {
System.out.println("zend is still alive although we tried to stop it. " +
"Hopefully it will stop later!");
//System.out.println("zend is still alive, killing forcefully");
//daemonProcess.destroyForcibly();
} else
System.out.println("zend shut down successfully");
} catch (Exception bad) {
System.out.println("Couldn't stop zend!");
bad.printStackTrace();
}
}
});
}
public void doDispose() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setVisible(false);
dispose();
}
});
}
public void setProgressText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressLabel.setText(text);
}
});
}
// TODO: Unused for now
private void performOSXBundleLaunch() throws IOException, InterruptedException {
System.out.println("performing OSX Bundle-specific launch");
File bundlePath = new File(System.getProperty("zcash.location.dir"));
bundlePath = bundlePath.getCanonicalFile();
// run "first-run.sh"
File firstRun = new File(bundlePath,"first-run.sh");
Process firstRunProcess = Runtime.getRuntime().exec(firstRun.getCanonicalPath());
firstRunProcess.waitFor();
}
private void performZenConf() throws IOException, InterruptedException
{
System.out.println("Copying a default zen.conf");
File zConf = new File(System.getenv("APPDATA") + "/Zen");
zConf = zConf.getCanonicalFile();
if (!zConf.exists()) {
zConf.mkdirs();
File zenConfFile = new File(zConf,"zen.conf");
FileOutputStream fos = new FileOutputStream(zenConfFile);
InputStream is = ProvingKeyFetcher.class.getClassLoader().getResourceAsStream("conf/zen.conf");
copy(is,fos);
fos.close();
is = null;
}
}
private static void copy(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[0x1 << 13];
int read;
while ((read = is.read(buf)) >- 0) {
os.write(buf,0,read);
}
os.flush();
}
// Custom code - to allow JDK7 compilation.
public boolean isAlive(Process p)
{
if (p == null)
{
return false;
}
try
{
int val = p.exitValue();
return false;
} catch (IllegalThreadStateException itse)
{
return true;
}
}
// Custom code - to allow JDK7 compilation.
public boolean waitFor(Process p, long interval)
{
synchronized (this)
{
long startWait = System.currentTimeMillis();
long endWait = startWait;
do
{
boolean ended = !isAlive(p);
if (ended)
{
return true; // End here
}
try
{
this.wait(100);
} catch (InterruptedException ie)
{
// One of the rare cases where we do nothing
ie.printStackTrace();
}
endWait = System.currentTimeMillis();
} while ((endWait - startWait) <= interval);
}
return false;
}
}
|
package com.akiban.server;
import com.akiban.server.service.servicemanager.GuicedServiceManager;
import com.akiban.util.OsUtils;
import com.akiban.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.akiban.server.error.TapBeanFailureException;
import com.akiban.server.manage.ManageMXBean;
import com.akiban.server.manage.ManageMXBeanImpl;
import com.akiban.server.service.Service;
import com.akiban.server.service.ServiceManager;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.service.jmx.JmxManageable;
import com.akiban.util.Tap;
import javax.management.ObjectName;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;
/**
* @author peter
*/
public class AkServer implements Service<AkServerInterface>, JmxManageable, AkServerInterface
{
private static final String VERSION_STRING_FILE = "version/akserver_version";
public static final String VERSION_STRING = getVersionString();
private static final Logger LOG = LoggerFactory.getLogger(AkServer.class.getName());
private static final String AKSERVER_NAME = System.getProperty("akserver.name");
private static final String pidFileName = System.getProperty("akserver.pidfile");
private final JmxObjectInfo jmxObjectInfo;
private volatile int queryTimeoutSec = Integer.MAX_VALUE / 1000; // /1000 because we'll be measuring times in msec
public AkServer() {
this.jmxObjectInfo = new JmxObjectInfo("AKSERVER", new ManageMXBeanImpl(this), ManageMXBean.class);
}
@Override
public void start() {
LOG.info("Starting AkServer {}", AKSERVER_NAME);
try {
Tap.registerMXBean();
} catch (Exception e) {
throw new TapBeanFailureException (e.getMessage());
}
}
@Override
public void stop()
{
LOG.info("Stopping AkServer {}", AKSERVER_NAME);
try {
Tap.unregisterMXBean();
} catch (Exception e) {
throw new TapBeanFailureException(e.getMessage());
}
}
@Override
public void crash() {
stop();
}
public ServiceManager getServiceManager()
{
return ServiceManagerImpl.get();
}
@Override
public JmxObjectInfo getJmxObjectInfo() {
return jmxObjectInfo;
}
@Override
public AkServer cast() {
return this;
}
@Override
public Class<AkServerInterface> castClass() {
return AkServerInterface.class;
}
public int queryTimeoutSec()
{
return queryTimeoutSec;
}
public void queryTimeoutSec(int queryTimeoutSet)
{
this.queryTimeoutSec = queryTimeoutSet;
}
private static String getVersionString()
{
try {
return Strings.join(Strings.dumpResource(null,
VERSION_STRING_FILE));
} catch (IOException e) {
LOG.warn("Couldn't read resource file");
return "Error: " + e;
}
}
public interface ShutdownMXBean {
public void shutdown();
}
private static class ShutdownMXBeanImpl implements ShutdownMXBean {
private static final String BEAN_NAME = "com.akiban:type=SHUTDOWN";
private final ServiceManager sm;
public ShutdownMXBeanImpl(ServiceManager sm) {
this.sm = sm;
}
@Override
public void shutdown() {
try {
if(sm != null) {
sm.stopServices();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
GuicedServiceManager.BindingsConfigurationProvider bindingsConfigurationProvider = GuicedServiceManager.standardUrls();
ServiceManager serviceManager = new GuicedServiceManager(bindingsConfigurationProvider);
final ShutdownMXBeanImpl shutdownBean = new ShutdownMXBeanImpl(serviceManager);
// JVM shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
shutdownBean.shutdown();
}
}, "ShutdownHook"));
// Bring system up
serviceManager.startServices();
// JMX shutdown method
try {
ObjectName name = new ObjectName(ShutdownMXBeanImpl.BEAN_NAME);
ManagementFactory.getPlatformMBeanServer().registerMBean(shutdownBean, name);
} catch(Exception e) {
LOG.error("Exception registering shutdown bean", e);
}
// services started successfully, now create pidfile and write pid to it
if (pidFileName != null) {
File pidFile = new File(pidFileName);
pidFile.deleteOnExit();
FileWriter out = new FileWriter(pidFile);
out.write(OsUtils.getProcessID());
out.flush();
}
}
}
|
package com.brettonw.bag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
enum BagHelper { ;
private static final Logger log = LogManager.getLogger (BagHelper.class);
public static String enclose (String input, String bracket) {
char bracket0 = bracket.charAt (0);
char bracket1 = bracket.length () > 1 ? bracket.charAt (1) : bracket0;
return bracket0 + input + bracket1;
}
public static String quote (String input) {
return enclose (input, "\"");
}
public static String stringify (Object value) {
if (value != null) {
switch (value.getClass ().getName ()) {
case "java.lang.String":
return quote ((String) value);
case "com.brettonw.bag.BagObject":
case "com.brettonw.bag.BagArray":
return value.toString ();
// we omit the default case, because there should not be any other types stored in
// the Bag class - as in, they would not make it into the container, as the
// "objectify" method will gate that
}
}
// if we stored a null, we need to emit it as a value. This will only happen in the
// array types, and is handled on the parsing side with a special case for reading
// the bare value 'null' (not quoted)
return "null";
}
public static Object objectify (Object value) {
if (value != null) {
String className = value.getClass ().getName ();
switch (className) {
case "java.lang.String":
// is this the right place to do a transformation that converts quotes to some
// escape character?
return value;
case "java.lang.Long": case "java.lang.Integer": case "java.lang.Short": case "java.lang.Byte":
case "java.lang.Character":
case "java.lang.Boolean":
case "java.lang.Double": case "java.lang.Float":
return value.toString ();
case "com.brettonw.bag.BagObject":
case "com.brettonw.bag.BagArray":
return value;
default:
// no other type should be stored in the bag classes
log.error ("Unhandled type: " + className);
break;
}
}
return null;
}
}
|
package org.apache.bcel.generic;
import org.apache.bcel.Constants;
/**
* Instances of this class may be used, e.g., to generate typed
* versions of instructions. Its main purpose is to be used as the
* byte code generating backend of a compiler. You can subclass it to
* add your own create methods.
*
* @version $Id$
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see Constants
*/
public class InstructionFactory implements InstructionConstants {
protected ClassGen cg;
protected ConstantPoolGen cp;
public InstructionFactory(ClassGen cg, ConstantPoolGen cp) {
this.cg = cg;
this.cp = cp;
}
/** Initialize with ClassGen object
*/
public InstructionFactory(ClassGen cg) {
this(cg, cg.getConstantPool());
}
/** Initialize just with ConstantPoolGen object
*/
public InstructionFactory(ConstantPoolGen cp) {
this(null, cp);
}
/** Create an invoke instruction.
*
* @param class_name name of the called class
* @param name name of the called method
* @param ret_type return type of method
* @param arg_types argument types of method
* @param kind how to invoke, i.e., INVOKEINTERFACE, INVOKESTATIC, INVOKEVIRTUAL,
* or INVOKESPECIAL
* @see Constants
*/
public InvokeInstruction createInvoke(String class_name, String name, Type ret_type,
Type[] arg_types, short kind) {
int index;
int nargs = 0;
String signature = Type.getMethodSignature(ret_type, arg_types);
for(int i=0; i < arg_types.length; i++) // Count size of arguments
nargs += arg_types[i].getSize();
if(kind == Constants.INVOKEINTERFACE)
index = cp.addInterfaceMethodref(class_name, name, signature);
else
index = cp.addMethodref(class_name, name, signature);
switch(kind) {
case Constants.INVOKESPECIAL: return new INVOKESPECIAL(index);
case Constants.INVOKEVIRTUAL: return new INVOKEVIRTUAL(index);
case Constants.INVOKESTATIC: return new INVOKESTATIC(index);
case Constants.INVOKEINTERFACE: return new INVOKEINTERFACE(index, nargs + 1);
default:
throw new RuntimeException("Oops: Unknown invoke kind:" + kind);
}
}
/** Create a call to the most popular System.out.println() method.
*
* @param s the string to print
*/
public InstructionList createPrintln(String s) {
InstructionList il = new InstructionList();
int out = cp.addFieldref("java.lang.System", "out",
"Ljava/io/PrintStream;");
int println = cp.addMethodref("java.io.PrintStream", "println",
"(Ljava/lang/String;)V");
il.append(new GETSTATIC(out));
il.append(new PUSH(cp, s));
il.append(new INVOKEVIRTUAL(println));
return il;
}
/** Uses PUSH to push a constant value onto the stack.
* @param value must be of type Number, Boolean, Character or String
*/
public Instruction createConstant(Object value) {
PUSH push;
if(value instanceof Number)
push = new PUSH(cp, (Number)value);
else if(value instanceof String)
push = new PUSH(cp, (String)value);
else if(value instanceof Boolean)
push = new PUSH(cp, (Boolean)value);
else if(value instanceof Character)
push = new PUSH(cp, (Character)value);
else
throw new ClassGenException("Illegal type: " + value.getClass());
return push.getInstruction();
}
private static class MethodObject {
Type[] arg_types;
Type result_type;
String[] arg_names;
String class_name;
String name;
int access;
MethodObject(String c, String n, Type r, Type[] a, int acc) {
class_name = c;
name = n;
result_type = r;
arg_types = a;
access = acc;
}
}
private InvokeInstruction createInvoke(MethodObject m, short kind) {
return createInvoke(m.class_name, m.name, m.result_type, m.arg_types, kind);
}
private static MethodObject[] append_mos = {
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.STRING }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.OBJECT }, Constants.ACC_PUBLIC),
null, null, // indices 2, 3
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.BOOLEAN }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.CHAR }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.FLOAT }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.DOUBLE }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.INT }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER, // No append(byte)
new Type[] { Type.INT }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER, // No append(short)
new Type[] { Type.INT }, Constants.ACC_PUBLIC),
new MethodObject("java.lang.StringBuffer", "append", Type.STRINGBUFFER,
new Type[] { Type.LONG }, Constants.ACC_PUBLIC)
};
private static final boolean isString(Type type) {
return ((type instanceof ObjectType) &&
((ObjectType)type).getClassName().equals("java.lang.String"));
}
public Instruction createAppend(Type type) {
byte t = type.getType();
if(isString(type))
return createInvoke(append_mos[0], Constants.INVOKEVIRTUAL);
switch(t) {
case Constants.T_BOOLEAN:
case Constants.T_CHAR:
case Constants.T_FLOAT:
case Constants.T_DOUBLE:
case Constants.T_BYTE:
case Constants.T_SHORT:
case Constants.T_INT:
case Constants.T_LONG
: return createInvoke(append_mos[t], Constants.INVOKEVIRTUAL);
case Constants.T_ARRAY:
case Constants.T_OBJECT:
return createInvoke(append_mos[1], Constants.INVOKEVIRTUAL);
default:
throw new RuntimeException("Oops: No append for this type? " + type);
}
}
/** Create a field instruction.
*
* @param class_name name of the accessed class
* @param name name of the referenced field
* @param type type of field
* @param kind how to access, i.e., GETFIELD, PUTFIELD, GETSTATIC, PUTSTATIC
* @see Constants
*/
public FieldInstruction createFieldAccess(String class_name, String name, Type type, short kind) {
int index;
String signature = type.getSignature();
index = cp.addFieldref(class_name, name, signature);
switch(kind) {
case Constants.GETFIELD: return new GETFIELD(index);
case Constants.PUTFIELD: return new PUTFIELD(index);
case Constants.GETSTATIC: return new GETSTATIC(index);
case Constants.PUTSTATIC: return new PUTSTATIC(index);
default:
throw new RuntimeException("Oops: Unknown getfield kind:" + kind);
}
}
/** Create reference to `this'
*/
public static Instruction createThis() {
return new ALOAD(0);
}
/** Create typed return
*/
public static ReturnInstruction createReturn(Type type) {
switch(type.getType()) {
case Constants.T_ARRAY:
case Constants.T_OBJECT: return ARETURN;
case Constants.T_INT:
case Constants.T_SHORT:
case Constants.T_BOOLEAN:
case Constants.T_CHAR:
case Constants.T_BYTE: return IRETURN;
case Constants.T_FLOAT: return FRETURN;
case Constants.T_DOUBLE: return DRETURN;
case Constants.T_LONG: return LRETURN;
case Constants.T_VOID: return RETURN;
default:
throw new RuntimeException("Invalid type: " + type);
}
}
private static final ArithmeticInstruction createBinaryIntOp(char first, String op) {
switch(first) {
case '-' : return ISUB;
case '+' : return IADD;
case '%' : return IREM;
case '*' : return IMUL;
case '/' : return IDIV;
case '&' : return IAND;
case '|' : return IOR;
case '^' : return IXOR;
case '<' : return ISHL;
case '>' : return op.equals(">>>")? (ArithmeticInstruction)IUSHR :
(ArithmeticInstruction)ISHR;
default: throw new RuntimeException("Invalid operand " + op);
}
}
private static final ArithmeticInstruction createBinaryLongOp(char first, String op) {
switch(first) {
case '-' : return LSUB;
case '+' : return LADD;
case '%' : return LREM;
case '*' : return LMUL;
case '/' : return LDIV;
case '&' : return LAND;
case '|' : return LOR;
case '^' : return LXOR;
case '<' : return LSHL;
case '>' : return op.equals(">>>")? (ArithmeticInstruction)LUSHR :
(ArithmeticInstruction)LSHR;
default: throw new RuntimeException("Invalid operand " + op);
}
}
private static final ArithmeticInstruction createBinaryFloatOp(char op) {
switch(op) {
case '-' : return FSUB;
case '+' : return FADD;
case '*' : return FMUL;
case '/' : return FDIV;
default: throw new RuntimeException("Invalid operand " + op);
}
}
private static final ArithmeticInstruction createBinaryDoubleOp(char op) {
switch(op) {
case '-' : return DSUB;
case '+' : return DADD;
case '*' : return DMUL;
case '/' : return DDIV;
default: throw new RuntimeException("Invalid operand " + op);
}
}
/**
* Create binary operation for simple basic types, such as int and float.
*
* @param op operation, such as "+", "*", "<<", etc.
*/
public static ArithmeticInstruction createBinaryOperation(String op, Type type) {
char first = op.toCharArray()[0];
switch(type.getType()) {
case Constants.T_BYTE:
case Constants.T_SHORT:
case Constants.T_INT:
case Constants.T_CHAR: return createBinaryIntOp(first, op);
case Constants.T_LONG: return createBinaryLongOp(first, op);
case Constants.T_FLOAT: return createBinaryFloatOp(first);
case Constants.T_DOUBLE: return createBinaryDoubleOp(first);
default: throw new RuntimeException("Invalid type " + type);
}
}
/**
* @param size size of operand, either 1 (int, e.g.) or 2 (double)
*/
public static StackInstruction createPop(int size) {
return (size == 2)? (StackInstruction)POP2 :
(StackInstruction)POP;
}
/**
* @param size size of operand, either 1 (int, e.g.) or 2 (double)
*/
public static StackInstruction createDup(int size) {
return (size == 2)? (StackInstruction)DUP2 :
(StackInstruction)DUP;
}
/**
* @param size size of operand, either 1 (int, e.g.) or 2 (double)
*/
public static StackInstruction createDup_2(int size) {
return (size == 2)? (StackInstruction)DUP2_X2 :
(StackInstruction)DUP_X2;
}
/**
* @param size size of operand, either 1 (int, e.g.) or 2 (double)
*/
public static StackInstruction createDup_1(int size) {
return (size == 2)? (StackInstruction)DUP2_X1 :
(StackInstruction)DUP_X1;
}
/**
* @param index index of local variable
*/
public static LocalVariableInstruction createStore(Type type, int index) {
switch(type.getType()) {
case Constants.T_BOOLEAN:
case Constants.T_CHAR:
case Constants.T_BYTE:
case Constants.T_SHORT:
case Constants.T_INT: return new ISTORE(index);
case Constants.T_FLOAT: return new FSTORE(index);
case Constants.T_DOUBLE: return new DSTORE(index);
case Constants.T_LONG: return new LSTORE(index);
case Constants.T_ARRAY:
case Constants.T_OBJECT: return new ASTORE(index);
default: throw new RuntimeException("Invalid type " + type);
}
}
/**
* @param index index of local variable
*/
public static LocalVariableInstruction createLoad(Type type, int index) {
switch(type.getType()) {
case Constants.T_BOOLEAN:
case Constants.T_CHAR:
case Constants.T_BYTE:
case Constants.T_SHORT:
case Constants.T_INT: return new ILOAD(index);
case Constants.T_FLOAT: return new FLOAD(index);
case Constants.T_DOUBLE: return new DLOAD(index);
case Constants.T_LONG: return new LLOAD(index);
case Constants.T_ARRAY:
case Constants.T_OBJECT: return new ALOAD(index);
default: throw new RuntimeException("Invalid type " + type);
}
}
/**
* @param type type of elements of array, i.e., array.getElementType()
*/
public static ArrayInstruction createArrayLoad(Type type) {
switch(type.getType()) {
case Constants.T_BOOLEAN:
case Constants.T_BYTE: return BALOAD;
case Constants.T_CHAR: return CALOAD;
case Constants.T_SHORT: return SALOAD;
case Constants.T_INT: return IALOAD;
case Constants.T_FLOAT: return FALOAD;
case Constants.T_DOUBLE: return DALOAD;
case Constants.T_LONG: return LALOAD;
case Constants.T_ARRAY:
case Constants.T_OBJECT: return AALOAD;
default: throw new RuntimeException("Invalid type " + type);
}
}
/**
* @param type type of elements of array, i.e., array.getElementType()
*/
public static ArrayInstruction createArrayStore(Type type) {
switch(type.getType()) {
case Constants.T_BOOLEAN:
case Constants.T_BYTE: return BASTORE;
case Constants.T_CHAR: return CASTORE;
case Constants.T_SHORT: return SASTORE;
case Constants.T_INT: return IASTORE;
case Constants.T_FLOAT: return FASTORE;
case Constants.T_DOUBLE: return DASTORE;
case Constants.T_LONG: return LASTORE;
case Constants.T_ARRAY:
case Constants.T_OBJECT: return AASTORE;
default: throw new RuntimeException("Invalid type " + type);
}
}
/** Create conversion operation for two stack operands, this may be an I2C, instruction, e.g.,
* if the operands are basic types and CHECKCAST if they are reference types.
*/
public Instruction createCast(Type src_type, Type dest_type) {
if((src_type instanceof BasicType) && (dest_type instanceof BasicType)) {
byte dest = dest_type.getType();
byte src = src_type.getType();
if(dest == Constants.T_LONG && (src == Constants.T_CHAR || src == Constants.T_BYTE ||
src == Constants.T_SHORT))
src = Constants.T_INT;
String[] short_names = { "C", "F", "D", "B", "S", "I", "L" };
String name = "org.apache.bcel.generic." + short_names[src - Constants.T_CHAR] +
"2" + short_names[dest - Constants.T_CHAR];
Instruction i = null;
try {
i = (Instruction)java.lang.Class.forName(name).newInstance();
} catch(Exception e) {
throw new RuntimeException("Could not find instruction: " + name);
}
return i;
} else if((src_type instanceof ReferenceType) && (dest_type instanceof ReferenceType)) {
if(dest_type instanceof ArrayType)
return new CHECKCAST(cp.addArrayClass((ArrayType)dest_type));
else
return new CHECKCAST(cp.addClass(((ObjectType)dest_type).getClassName()));
}
else
throw new RuntimeException("Can not cast " + src_type + " to " + dest_type);
}
public GETFIELD createGetField(String class_name, String name, Type t) {
return new GETFIELD(cp.addFieldref(class_name, name, t.getSignature()));
}
public GETSTATIC createGetStatic(String class_name, String name, Type t) {
return new GETSTATIC(cp.addFieldref(class_name, name, t.getSignature()));
}
public PUTFIELD createPutField(String class_name, String name, Type t) {
return new PUTFIELD(cp.addFieldref(class_name, name, t.getSignature()));
}
public PUTSTATIC createPutStatic(String class_name, String name, Type t) {
return new PUTSTATIC(cp.addFieldref(class_name, name, t.getSignature()));
}
public CHECKCAST createCheckCast(ReferenceType t) {
if(t instanceof ArrayType)
return new CHECKCAST(cp.addArrayClass((ArrayType)t));
else
return new CHECKCAST(cp.addClass((ObjectType)t));
}
public INSTANCEOF createInstanceOf(ReferenceType t) {
if(t instanceof ArrayType)
return new INSTANCEOF(cp.addArrayClass((ArrayType)t));
else
return new INSTANCEOF(cp.addClass((ObjectType)t));
}
public NEW createNew(ObjectType t) {
return new NEW(cp.addClass(t));
}
public NEW createNew(String s) {
return createNew(new ObjectType(s));
}
/** Create new array of given size and type.
* @return an instruction that creates the corresponding array at runtime, i.e. is an AllocationInstruction
*/
public Instruction createNewArray(Type t, short dim) {
if(dim == 1) {
if(t instanceof ObjectType)
return new ANEWARRAY(cp.addClass((ObjectType)t));
else if(t instanceof ArrayType)
return new ANEWARRAY(cp.addArrayClass((ArrayType)t));
else
return new NEWARRAY(((BasicType)t).getType());
} else {
ArrayType at;
if(t instanceof ArrayType)
at = (ArrayType)t;
else
at = new ArrayType(t, dim);
return new MULTIANEWARRAY(cp.addArrayClass(at), dim);
}
}
/** Create "null" value for reference types, 0 for basic types like int
*/
public static Instruction createNull(Type type) {
switch(type.getType()) {
case Constants.T_ARRAY:
case Constants.T_OBJECT: return ACONST_NULL;
case Constants.T_INT:
case Constants.T_SHORT:
case Constants.T_BOOLEAN:
case Constants.T_CHAR:
case Constants.T_BYTE: return ICONST_0;
case Constants.T_FLOAT: return FCONST_0;
case Constants.T_DOUBLE: return DCONST_0;
case Constants.T_LONG: return LCONST_0;
case Constants.T_VOID: return NOP;
default:
throw new RuntimeException("Invalid type: " + type);
}
}
/** Create branch instruction by given opcode, except LOOKUPSWITCH and TABLESWITCH.
* For those you should use the SWITCH compound instruction.
*/
public static BranchInstruction createBranchInstruction(short opcode, InstructionHandle target) {
switch(opcode) {
case Constants.IFEQ: return new IFEQ(target);
case Constants.IFNE: return new IFNE(target);
case Constants.IFLT: return new IFLT(target);
case Constants.IFGE: return new IFGE(target);
case Constants.IFGT: return new IFGT(target);
case Constants.IFLE: return new IFLE(target);
case Constants.IF_ICMPEQ: return new IF_ICMPEQ(target);
case Constants.IF_ICMPNE: return new IF_ICMPNE(target);
case Constants.IF_ICMPLT: return new IF_ICMPLT(target);
case Constants.IF_ICMPGE: return new IF_ICMPGE(target);
case Constants.IF_ICMPGT: return new IF_ICMPGT(target);
case Constants.IF_ICMPLE: return new IF_ICMPLE(target);
case Constants.IF_ACMPEQ: return new IF_ACMPEQ(target);
case Constants.IF_ACMPNE: return new IF_ACMPNE(target);
case Constants.GOTO: return new GOTO(target);
case Constants.JSR: return new JSR(target);
case Constants.IFNULL: return new IFNULL(target);
case Constants.IFNONNULL: return new IFNONNULL(target);
case Constants.GOTO_W: return new GOTO_W(target);
case Constants.JSR_W: return new JSR_W(target);
default:
throw new RuntimeException("Invalid opcode: " + opcode);
}
}
public void setClassGen(ClassGen c) { cg = c; }
public ClassGen getClassGen() { return cg; }
public void setConstantPool(ConstantPoolGen c) { cp = c; }
public ConstantPoolGen getConstantPool() { return cp; }
}
|
package com.turn.ttorrent.client;
import com.turn.ttorrent.TempFiles;
import com.turn.ttorrent.WaitFor;
import com.turn.ttorrent.client.peer.SharingPeer;
import com.turn.ttorrent.common.Torrent;
import com.turn.ttorrent.tracker.TrackedPeer;
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import static org.testng.Assert.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Test(timeOut = 600000)
public class ClientTest {
private List<Client> clientList;
private static final String TEST_RESOURCES = "src/test/resources";
private Tracker tracker;
private TempFiles tempFiles;
public ClientTest(){
if (Logger.getRootLogger().getAllAppenders().hasMoreElements())
return;
BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%d{MMdd HH:mm:ss,SSS} %t] %6p - %20.20c - %m %n")));
Torrent.setHashingThreadsCount(1);
}
@BeforeMethod
public void setUp() throws IOException {
tempFiles = new TempFiles();
clientList = new ArrayList<Client>();
Logger.getRootLogger().setLevel(Level.INFO);
startTracker();
}
// @Test(invocationCount = 50)
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = Torrent.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
torrent.save(torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
SharedTorrent st1 = SharedTorrent.fromFile(torrentFile, f.getParentFile(), true);
seeder.addTorrent(st1);
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null);
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir, true);
leech.addTorrent(st2);
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")){
count++;
partItems.add(s);
}
}
if (count < 5){
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
}
private Set<String> listFileNames(File downloadDir) {
if (downloadDir == null) return Collections.emptySet();
Set<String> names = new HashSet<String>();
File[] files = downloadDir.listFiles();
if (files == null) return Collections.emptySet();
for (File f : files) {
names.add(f.getName());
}
return names;
}
// @Test(invocationCount = 50)
public void large_file_download() throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
File tempFile = tempFiles.createTempFile(201 * 1025 * 1024);
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
Torrent torrent = Torrent.create(tempFile, announceURI, "Test");
File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent");
torrent.save(torrentFile);
Client seeder = createClient();
seeder.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), true));
final File downloadDir = tempFiles.createTempDir();
Client leech = createClient();
leech.addTorrent(SharedTorrent.fromFile(torrentFile, downloadDir, true));
try {
seeder.start(InetAddress.getLocalHost());
leech.start(InetAddress.getLocalHost());
waitForFileInDir(downloadDir, tempFile.getName());
assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName()));
} finally {
seeder.stop();
leech.stop();
}
}
public void more_than_one_seeder_for_same_torrent() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
this.tracker.setAcceptForeignTorrents(true);
assertEquals(0, this.tracker.getTrackedTorrents().size());
int numSeeders = 5;
List<Client> seeders = new ArrayList<Client>();
for (int i = 0; i < numSeeders; i++) {
seeders.add(createClient());
}
try {
File tempFile = tempFiles.createTempFile(100 * 1024);
Torrent torrent = Torrent.create(tempFile, this.tracker.getAnnounceURI(), "Test");
File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i = 0; i < numSeeders; i++) {
Client client = seeders.get(i);
client.addTorrent(SharedTorrent.fromFile(torrentFile, tempFile.getParentFile(), false));
client.start(InetAddress.getLocalHost());
}
waitForPeers(numSeeders);
Collection<TrackedTorrent> torrents = this.tracker.getTrackedTorrents();
assertEquals(torrents.size(), 1);
assertEquals(numSeeders, torrents.iterator().next().seeders());
} finally {
for (Client client : seeders) {
client.stop();
}
}
}
public void no_full_seeder_test() throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders * 3 + 15;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File tempFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(tempFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(tempFile, md5);
validateMultipleClientsResults(clientsList, md5, tempFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
public void testDelete() throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
final File downloadDir2 = tempFiles.createTempDir();
Client seeder = createClient();
seeder.start(InetAddress.getLocalHost());
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
File tempFile = tempFiles.createTempFile(513 * 1024);
final File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = Torrent.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
torrent.save(torrentFile);
names.add(srcFile.getName());
seeder.addTorrent(new SharedTorrent(torrent, srcFile.getParentFile(), false));
Client leech1 = createClient();
leech1.start(InetAddress.getLocalHost());
SharedTorrent sharedTorrent = SharedTorrent.fromFile(torrentFile, downloadDir, true);
leech1.addTorrent(sharedTorrent);
new WaitFor(15 * 1000) {
@Override
protected boolean condition() {
return listFileNames(downloadDir).contains(srcFile.getName());
}
};
assertTrue(listFileNames(downloadDir).contains(srcFile.getName()));
leech1.stop();
leech1=null;
assertTrue(srcFile.delete());
Client leech2 = createClient();
leech2.start(InetAddress.getLocalHost());
SharedTorrent st2 = SharedTorrent.fromFile(torrentFile, downloadDir2, true);
leech2.addTorrent(st2);
Thread.sleep(10 * 1000); // the file no longer exists. Stop seeding and announce that to tracker
final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(torrent.getHexInfoHash());
assertEquals(0, seeder.getTorrents().size());
for (SharingPeer peer : seeder.getPeers()) {
assertFalse(trackedTorrent.getPeers().keySet().contains(peer.getTorrentHexInfoHash()));
}
}
// @Test(invocationCount = 50)
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders +7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
Client firstClient = clientsList.get(0);
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount()-1){
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()){
fail("All seeders didn't get their files");
}
Thread.sleep(10*1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
public void corrupted_seeder() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int piecesCount = 35;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
final File badFile = tempFiles.createTempFile(piecesCount * pieceSize);
final Client client2 = createAndStartClient();
final File client2Dir = tempFiles.createTempDir();
final File client2File = new File(client2Dir, baseFile.getName());
FileUtils.copyFile(badFile, client2File);
final Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
client2.addTorrent(new SharedTorrent(torrent, client2Dir, false, true));
final String baseMD5 = getFileMD5(baseFile, md5);
final Client leech = createAndStartClient();
final File leechDestDir = tempFiles.createTempDir();
final AtomicReference<Exception> thrownException = new AtomicReference<Exception>();
final Thread th = new Thread(new Runnable() {
@Override
public void run() {
try {
leech.downloadUninterruptibly(new SharedTorrent(torrent, leechDestDir, false), 7);
} catch (Exception e) {
thrownException.set(e);
throw new RuntimeException(e);
}
}
});
th.start();
final WaitFor waitFor = new WaitFor(30 * 1000) {
@Override
protected boolean condition() {
return th.getState() == Thread.State.TERMINATED;
}
};
final Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
System.out.printf("%s:%n", entry.getKey().getName());
for (StackTraceElement elem : entry.getValue()) {
System.out.println(elem.toString());
}
}
assertTrue(waitFor.isMyResult());
assertNotNull(thrownException.get());
assertTrue(thrownException.get().getMessage().contains("Unable to download torrent completely"));
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
public void unlock_file_when_no_leechers() throws InterruptedException, NoSuchAlgorithmException, IOException {
Client seeder = createClient();
tracker.setAcceptForeignTorrents(true);
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
seeder.start(InetAddress.getLocalHost());
downloadAndStop(torrent, 15*1000, createClient());
Thread.sleep(2 * 1000);
assertTrue(dwnlFile.exists() && dwnlFile.isFile());
final boolean delete = dwnlFile.delete();
assertTrue(delete && !dwnlFile.exists());
}
public void download_many_times() throws InterruptedException, NoSuchAlgorithmException, IOException {
Client seeder = createClient();
tracker.setAcceptForeignTorrents(true);
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
seeder.start(InetAddress.getLocalHost());
for(int i=0; i<5; i++) {
downloadAndStop(torrent, 250*1000, createClient());
Thread.sleep(3*1000);
}
}
public void download_io_error() throws InterruptedException, NoSuchAlgorithmException, IOException{
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
seeder.start(InetAddress.getLocalHost());
final AtomicInteger interrupts = new AtomicInteger(0);
final Client leech = new Client(){
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
super.handlePieceCompleted(peer, piece);
if (piece.getIndex()%4==0 && interrupts.incrementAndGet() <= 2){
peer.getSocketChannel().close();
}
}
};
//manually add leech here for graceful shutdown.
clientList.add(leech);
downloadAndStop(torrent, 45 * 1000, leech);
Thread.sleep(2*1000);
}
public void download_uninterruptibly_positive() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
leecher.downloadUninterruptibly(st, 10);
assertTrue(st.getClientState()==ClientState.SEEDING);
}
public void download_uninterruptibly_negative() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
final AtomicInteger downloadedPiecesCount = new AtomicInteger(0);
final Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
final Client leecher = new Client(){
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
super.handlePieceCompleted(peer, piece);
if (downloadedPiecesCount.incrementAndGet() > 10){
seeder.stop();
}
}
};
clientList.add(leecher);
leecher.start(InetAddress.getLocalHost());
final File destDir = tempFiles.createTempDir();
final SharedTorrent st = new SharedTorrent(torrent, destDir, true);
try {
leecher.downloadUninterruptibly(st, 5);
fail("Must fail, because file wasn't downloaded completely");
} catch (IOException ex){
assertEquals(st.getClientState(),ClientState.DONE);
// ensure .part was deleted:
assertEquals(0, destDir.list().length);
}
}
public void download_uninterruptibly_timeout() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
final AtomicInteger piecesDownloaded = new AtomicInteger(0);
Client leecher = new Client(){
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
piecesDownloaded.incrementAndGet();
try {
Thread.sleep(piecesDownloaded.get()*500);
} catch (InterruptedException e) {
}
}
};
clientList.add(leecher);
leecher.start(InetAddress.getLocalHost());
final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
try {
leecher.downloadUninterruptibly(st, 5);
fail("Must fail, because file wasn't downloaded completely");
} catch (IOException ex){
assertEquals(st.getClientState(),ClientState.DONE);
}
}
public void canStartAndStopClientTwice() throws Exception {
final Client client = createClient();
client.start(InetAddress.getLocalHost());
client.stop();
client.start(InetAddress.getLocalHost());
client.stop();
}
public void peer_dies_during_download() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAnnounceInterval(5);
final Client seed1 = createClient();
final Client seed2 = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 240);
final Torrent torrent = Torrent.create(dwnlFile, tracker.getAnnounceURI(), "Test");
seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true));
seed1.start(InetAddress.getLocalHost());
seed1.setAnnounceInterval(5);
seed2.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true));
seed2.start(InetAddress.getLocalHost());
seed2.setAnnounceInterval(5);
Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
leecher.setAnnounceInterval(5);
final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
final ExecutorService service = Executors.newFixedThreadPool(1);
service.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
seed1.removeTorrent(torrent);
Thread.sleep(3*1000);
seed1.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true, true));
seed2.removeTorrent(torrent);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
leecher.downloadUninterruptibly(st, 60);
/*
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
leecher.downloadUninterruptibly(st, 10);
assertTrue(st.getClientState()==ClientState.SEEDING);
*/
}
public void interrupt_download() throws IOException, InterruptedException, NoSuchAlgorithmException {
tracker.setAcceptForeignTorrents(true);
final Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 60);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(new SharedTorrent(torrent, dwnlFile.getParentFile(), true));
final Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
final SharedTorrent st = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
final AtomicBoolean interrupted = new AtomicBoolean();
final Thread th = new Thread(){
@Override
public void run() {
try {
leecher.downloadUninterruptibly(st, 30);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
interrupted.set(true);
return;
}
}
};
th.start();
Thread.sleep(1000);
th.interrupt();
new WaitFor(10*1000){
@Override
protected boolean condition() {
return !th.isAlive();
}
};
assertTrue(st.getClientState() != ClientState.SEEDING);
assertTrue(interrupted.get());
}
public void test_connect_to_unknown_host() throws InterruptedException, NoSuchAlgorithmException, IOException {
final File torrent = new File("src/test/resources/torrents/file1.jar.torrent");
final TrackedTorrent tt = TrackedTorrent.load(torrent);
final Client seeder = createAndStartClient();
final Client leecher = createAndStartClient();
final TrackedTorrent announce = tracker.announce(tt);
final Random random = new Random();
final File leechFolder = tempFiles.createTempDir();
for (int i=0; i<40; i++) {
byte[] data = new byte[20];
random.nextBytes(data);
announce.addPeer(new TrackedPeer(tt, "my_unknown_and_unreachablehost" + i, 6881, ByteBuffer.wrap(data)));
}
seeder.addTorrent(completeTorrent("file1.jar.torrent"));
final SharedTorrent incompleteTorrent = incompleteTorrent("file1.jar.torrent", leechFolder);
leecher.addTorrent(incompleteTorrent);
new WaitFor(10*1000){
@Override
protected boolean condition() {
return incompleteTorrent.isComplete();
}
};
}
public void test_seeding_does_not_change_file_modification_date() throws IOException, InterruptedException, NoSuchAlgorithmException {
File srcFile = tempFiles.createTempFile(1024);
long time = srcFile.lastModified();
Thread.sleep(1000);
Client seeder = createAndStartClient();
final Torrent torrent = Torrent.create(srcFile, null, tracker.getAnnounceURI(), "Test");
final SharedTorrent sharedTorrent = new SharedTorrent(torrent, srcFile.getParentFile(), true, true);
seeder.addTorrent(sharedTorrent);
assertEquals(time, srcFile.lastModified());
}
private void downloadAndStop(Torrent torrent, long timeout, final Client leech) throws IOException, NoSuchAlgorithmException, InterruptedException {
final File tempDir = tempFiles.createTempDir();
leech.addTorrent(new SharedTorrent(torrent, tempDir, false));
leech.start(InetAddress.getLocalHost());
final WaitFor waitFor = new WaitFor(timeout) {
@Override
protected boolean condition() {
final SharedTorrent leechTorrent = leech.getTorrents().iterator().next();
if (leech.isRunning()) {
return leechTorrent.getClientState() == ClientState.SEEDING;
} else {
return true;
}
}
};
assertTrue(waitFor.isMyResult(), "File wasn't downloaded in time");
}
private void validateMultipleClientsResults(final List<Client> clientsList, MessageDigest md5, File baseFile, String baseMD5) throws IOException {
final WaitFor waitFor = new WaitFor(75 * 1000) {
@Override
protected boolean condition() {
boolean retval = true;
for (Client client : clientsList) {
if (!retval) return false;
final boolean torrentState = client.getTorrents().iterator().next().getClientState() == ClientState.SEEDING;
retval = retval && torrentState;
}
return retval;
}
};
assertTrue(waitFor.isMyResult(), "All seeders didn't get their files");
// check file contents here:
for (Client client : clientsList) {
final SharedTorrent st = client.getTorrents().iterator().next();
final File file = new File(st.getParentFile(), st.getFilenames().get(0));
assertEquals(baseMD5, getFileMD5(file, md5), String.format("MD5 hash is invalid. C:%s, O:%s ",
file.getAbsolutePath(), baseFile.getAbsolutePath()));
}
}
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount);
FileInputStream fin = new FileInputStream(baseFile);
for (int i=0; i<piecesCount; i++){
byte[] piece = new byte[pieceSize];
fin.read(piece);
piecesList.add(piece);
}
fin.close();
final long torrentFileLength = baseFile.length();
Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i=0; i<numSeeders; i++){
final File baseDir = tempFiles.createTempDir();
final File seederPiecesFile = new File(baseDir, baseFile.getName());
RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw");
raf.setLength(torrentFileLength);
for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){
raf.seek(pieceIdx*pieceSize);
raf.write(piecesList.get(pieceIdx));
}
Client client = createClient(" client idx " + i);
clientList.add(client);
client.addTorrent(new SharedTorrent(torrent, baseDir, false));
client.start(InetAddress.getLocalHost());
}
}
private String getFileMD5(File file, MessageDigest digest) throws IOException {
DigestInputStream dIn = new DigestInputStream(new FileInputStream(file), digest);
while (dIn.read() >= 0);
return dIn.getMessageDigest().toString();
}
private void waitForSeeder(final byte[] torrentHash) {
new WaitFor() {
@Override
protected boolean condition() {
for (TrackedTorrent tt : tracker.getTrackedTorrents()) {
if (tt.seeders() == 1 && tt.getHexInfoHash().equals(Torrent.byteArrayToHexString(torrentHash))) return true;
}
return false;
}
};
}
private void waitForPeers(final int numPeers) {
new WaitFor() {
@Override
protected boolean condition() {
for (TrackedTorrent tt : tracker.getTrackedTorrents()) {
if (tt.getPeers().size() == numPeers) return true;
}
return false;
}
};
}
private void waitForFileInDir(final File downloadDir, final String fileName) {
new WaitFor() {
@Override
protected boolean condition() {
return new File(downloadDir, fileName).isFile();
}
};
assertTrue(new File(downloadDir, fileName).isFile());
}
@AfterMethod
protected void tearDown() throws Exception {
for (Client client : clientList) {
client.stop();
}
stopTracker();
tempFiles.cleanup();
}
private void startTracker() throws IOException {
this.tracker = new Tracker(6969);
tracker.setAnnounceInterval(5);
this.tracker.start(true);
}
private Client createAndStartClient() throws IOException, NoSuchAlgorithmException, InterruptedException {
Client client = createClient();
client.start(InetAddress.getLocalHost());
return client;
}
private Client createClient(String name) throws IOException, NoSuchAlgorithmException, InterruptedException {
final Client client = new Client(name);
clientList.add(client);
return client;
}
private Client createClient() throws IOException, NoSuchAlgorithmException, InterruptedException {
return createClient("");
}
private SharedTorrent completeTorrent(String name) throws IOException, NoSuchAlgorithmException {
File torrentFile = new File(TEST_RESOURCES + "/torrents", name);
File parentFiles = new File(TEST_RESOURCES + "/parentFiles");
return SharedTorrent.fromFile(torrentFile, parentFiles, false);
}
private SharedTorrent incompleteTorrent(String name, File destDir) throws IOException, NoSuchAlgorithmException {
File torrentFile = new File(TEST_RESOURCES + "/torrents", name);
return SharedTorrent.fromFile(torrentFile, destDir, false);
}
private void stopTracker() {
this.tracker.stop();
}
private void assertFilesEqual(File f1, File f2) throws IOException {
assertEquals(f1.length(), f2.length(), "Files sizes differ");
Checksum c1 = FileUtils.checksum(f1, new CRC32());
Checksum c2 = FileUtils.checksum(f2, new CRC32());
assertEquals(c1.getValue(), c2.getValue());
}
}
|
package org.apache.commons.betwixt;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.betwixt.expression.EmptyExpression;
import org.apache.commons.betwixt.expression.IteratorExpression;
import org.apache.commons.betwixt.expression.MethodExpression;
import org.apache.commons.betwixt.expression.MethodUpdater;
import org.apache.commons.betwixt.expression.StringExpression;
import org.apache.commons.betwixt.digester.XMLBeanInfoDigester;
import org.apache.commons.betwixt.digester.XMLIntrospectorHelper;
import org.apache.commons.betwixt.strategy.DefaultNameMapper;
import org.apache.commons.betwixt.strategy.DefaultPluralStemmer;
import org.apache.commons.betwixt.strategy.NameMapper;
import org.apache.commons.betwixt.strategy.PluralStemmer;
/**
* <p><code>XMLIntrospector</code> an introspector of beans to create a
* XMLBeanInfo instance.</p>
*
* <p>By default, <code>XMLBeanInfo</code> caching is switched on.
* This means that the first time that a request is made for a <code>XMLBeanInfo</code>
* for a particular class, the <code>XMLBeanInfo</code> is cached.
* Later requests for the same class will return the cached value.</p>
*
* <p>Note :</p>
* <p>This class makes use of the <code>java.bean.Introspector</code>
* class, which contains a BeanInfoSearchPath. To make sure betwixt can
* do his work correctly, this searchpath is completely ignored during
* processing. The original values will be restored after processing finished
* </p>
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @author <a href="mailto:martin@mvdb.net">Martin van den Bemt</a>
* @version $Id: XMLIntrospector.java,v 1.10 2002/10/26 14:30:54 mvdb Exp $
*/
public class XMLIntrospector {
/** Log used for logging (Doh!) */
protected Log log = LogFactory.getLog( XMLIntrospector.class );
/** should attributes or elements be used for primitive types */
private boolean attributesForPrimitives = false;
/** should we wrap collections in an extra element? */
private boolean wrapCollectionsInElement = true;
/** Is <code>XMLBeanInfo</code> caching enabled? */
boolean cachingEnabled = true;
/** Maps classes to <code>XMLBeanInfo</code>'s */
protected Map cacheXMLBeanInfos = new HashMap();
/** Digester used to parse the XML descriptor files */
private XMLBeanInfoDigester digester;
// pluggable strategies
/** The strategy used to detect matching singular and plural properties */
private PluralStemmer pluralStemmer;
/** The strategy used to convert bean type names into element names */
private NameMapper elementNameMapper;
/**
* The strategy used to convert bean type names into attribute names
* It will default to the normal nameMapper.
*/
private NameMapper attributeNameMapper;
private boolean useBeanInfoSearchPath = false;
/** Base constructor */
public XMLIntrospector() {
}
/**
* <p> Get the current logging implementation. </p>
*/
public Log getLog() {
return log;
}
/**
* <p> Set the current logging implementation. </p>
*/
public void setLog(Log log) {
this.log = log;
}
/**
* Is <code>XMLBeanInfo</code> caching enabled?
*/
public boolean isCachingEnabled() {
return cachingEnabled;
}
/**
* Set whether <code>XMLBeanInfo</code> caching should be enabled.
*/
public void setCachingEnabled(boolean cachingEnabled) {
this.cachingEnabled = cachingEnabled;
}
/**
* Flush existing cached <code>XMLBeanInfo</code>'s.
*/
public void flushCache() {
cacheXMLBeanInfos.clear();
}
/** Create a standard <code>XMLBeanInfo</code> by introspection
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(Object bean) throws IntrospectionException {
if (log.isDebugEnabled()) {
log.debug( "Introspecting..." );
log.debug(bean);
}
return introspect( bean.getClass() );
}
/** Create a standard <code>XMLBeanInfo</code> by introspection.
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(Class aClass) throws IntrospectionException {
// we first reset the beaninfo searchpath.
String[] searchPath = null;
if (!useBeanInfoSearchPath)
{
searchPath = Introspector.getBeanInfoSearchPath();
Introspector.setBeanInfoSearchPath(new String[] { });
}
XMLBeanInfo xmlInfo = null;
if ( cachingEnabled ) {
// if caching is enabled, try in caching first
xmlInfo = (XMLBeanInfo) cacheXMLBeanInfos.get( aClass );
}
if (xmlInfo == null) {
// lets see if we can find an XML descriptor first
if ( log.isDebugEnabled() ) {
log.debug( "Attempting to lookup an XML descriptor for class: " + aClass );
}
xmlInfo = findByXMLDescriptor( aClass );
if ( xmlInfo == null ) {
BeanInfo info = Introspector.getBeanInfo( aClass );
xmlInfo = introspect( info );
}
if (xmlInfo != null) {
cacheXMLBeanInfos.put( aClass, xmlInfo );
}
} else {
log.trace("Used cached XMLBeanInfo.");
}
if (log.isTraceEnabled()) {
log.trace(xmlInfo);
}
if (!useBeanInfoSearchPath)
{
// we restore the beaninfo searchpath.
Introspector.setBeanInfoSearchPath(searchPath);
}
return xmlInfo;
}
/** Create a standard <code>XMLBeanInfo</code> by introspection.
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(BeanInfo beanInfo) throws IntrospectionException {
XMLBeanInfo answer = createXMLBeanInfo( beanInfo );
BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
Class beanClass = beanDescriptor.getBeanClass();
ElementDescriptor elementDescriptor = new ElementDescriptor();
elementDescriptor.setLocalName( getElementNameMapper().mapTypeToElementName( beanDescriptor.getName() ) );
elementDescriptor.setPropertyType( beanInfo.getBeanDescriptor().getBeanClass() );
if (log.isTraceEnabled()) {
log.trace(elementDescriptor);
}
// add default string value for primitive types
if ( isPrimitiveType( beanClass ) ) {
elementDescriptor.setTextExpression( StringExpression.getInstance() );
elementDescriptor.setPrimitiveType(true);
}
else if ( isLoopType( beanClass ) ) {
ElementDescriptor loopDescriptor = new ElementDescriptor();
loopDescriptor.setContextExpression(
new IteratorExpression( EmptyExpression.getInstance() )
);
if ( Map.class.isAssignableFrom( beanClass ) ) {
loopDescriptor.setQualifiedName( "entry" );
}
elementDescriptor.setElementDescriptors( new ElementDescriptor[] { loopDescriptor } );
/*
elementDescriptor.setContextExpression(
new IteratorExpression( EmptyExpression.getInstance() )
);
*/
}
else {
List elements = new ArrayList();
List attributes = new ArrayList();
addProperties( beanInfo, elements, attributes );
BeanInfo[] additionals = beanInfo.getAdditionalBeanInfo();
if ( additionals != null ) {
for ( int i = 0, size = additionals.length; i < size; i++ ) {
BeanInfo otherInfo = additionals[i];
addProperties( otherInfo, elements, attributes );
}
}
int size = elements.size();
if ( size > 0 ) {
ElementDescriptor[] descriptors = new ElementDescriptor[size];
elements.toArray( descriptors );
elementDescriptor.setElementDescriptors( descriptors );
}
size = attributes.size();
if ( size > 0 ) {
AttributeDescriptor[] descriptors = new AttributeDescriptor[size];
attributes.toArray( descriptors );
elementDescriptor.setAttributeDescriptors( descriptors );
}
}
answer.setElementDescriptor( elementDescriptor );
// default any addProperty() methods
XMLIntrospectorHelper.defaultAddMethods( this, elementDescriptor, beanClass );
return answer;
}
// Properties
/** Should attributes (or elements) be used for primitive types.
*/
public boolean isAttributesForPrimitives() {
return attributesForPrimitives;
}
/** Set whether attributes (or elements) should be used for primitive types. */
public void setAttributesForPrimitives(boolean attributesForPrimitives) {
this.attributesForPrimitives = attributesForPrimitives;
}
/** @return whether we should we wrap collections in an extra element? */
public boolean isWrapCollectionsInElement() {
return wrapCollectionsInElement;
}
/** Sets whether we should we wrap collections in an extra element? */
public void setWrapCollectionsInElement(boolean wrapCollectionsInElement) {
this.wrapCollectionsInElement = wrapCollectionsInElement;
}
/**
* @return the strategy used to detect matching singular and plural properties
*/
public PluralStemmer getPluralStemmer() {
if ( pluralStemmer == null ) {
pluralStemmer = createPluralStemmer();
}
return pluralStemmer;
}
/**
* Sets the strategy used to detect matching singular and plural properties
*/
public void setPluralStemmer(PluralStemmer pluralStemmer) {
this.pluralStemmer = pluralStemmer;
}
/**
* @return the strategy used to convert bean type names into element names
* @deprecated getNameMapper is split up in {@link #getElementNameMapper()} and {@link #getAttributeNameMapper()}
*/
public NameMapper getNameMapper() {
return getElementNameMapper();
}
/**
* Sets the strategy used to convert bean type names into element names
* @param nameMapper
* @deprecated setNameMapper is split up in {@link #setElementNameMapper(NameMapper)} and {@link #setAttributeNameMapper(NameMapper)}
*/
public void setNameMapper(NameMapper nameMapper) {
setElementNameMapper(nameMapper);
}
/**
* @return the strategy used to convert bean type names into element
* names. If no element mapper is currently defined then a default one is created.
*/
public NameMapper getElementNameMapper() {
if ( elementNameMapper == null ) {
elementNameMapper = createNameMapper();
}
return elementNameMapper;
}
/**
* Sets the strategy used to convert bean type names into element names
* @param nameMapper
*/
public void setElementNameMapper(NameMapper nameMapper) {
this.elementNameMapper = nameMapper;
}
/**
* @return the strategy used to convert bean type names into attribute
* names. If no attributeNamemapper is known, it will default to the ElementNameMapper
*/
public NameMapper getAttributeNameMapper() {
if (attributeNameMapper == null) {
attributeNameMapper = createNameMapper();
}
return attributeNameMapper;
}
/**
* Sets the strategy used to convert bean type names into attribute names
* @param nameMapper
*/
public void setAttributeNameMapper(NameMapper nameMapper) {
this.attributeNameMapper = nameMapper;
}
// Implementation methods
/**
* A Factory method to lazily create a new strategy to detect matching singular and plural properties
*/
protected PluralStemmer createPluralStemmer() {
return new DefaultPluralStemmer();
}
/**
* A Factory method to lazily create a strategy used to convert bean type names into element names
*/
protected NameMapper createNameMapper() {
return new DefaultNameMapper();
}
/**
* Attempt to lookup the XML descriptor for the given class using the
* classname + ".betwixt" using the same ClassLoader used to load the class
* or return null if it could not be loaded
*/
protected synchronized XMLBeanInfo findByXMLDescriptor( Class aClass ) {
// trim the package name
String name = aClass.getName();
int idx = name.lastIndexOf( '.' );
if ( idx >= 0 ) {
name = name.substring( idx + 1 );
}
name += ".betwixt";
URL url = aClass.getResource( name );
if ( url != null ) {
try {
String urlText = url.toString();
if ( log.isDebugEnabled( )) {
log.debug( "Parsing Betwixt XML descriptor: " + urlText );
}
// synchronized method so this digester is only used by
// one thread at once
if ( digester == null ) {
digester = new XMLBeanInfoDigester();
digester.setXMLIntrospector( this );
}
digester.setBeanClass( aClass );
return (XMLBeanInfo) digester.parse( urlText );
}
catch (Exception e) {
log.warn( "Caught exception trying to parse: " + name, e );
}
}
return null;
}
/** Loop through properties and process each one */
protected void addProperties(
BeanInfo beanInfo,
List elements,
List attributes)
throws
IntrospectionException {
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
if ( descriptors != null ) {
for ( int i = 0, size = descriptors.length; i < size; i++ ) {
addProperty(beanInfo, descriptors[i], elements, attributes);
}
}
if (log.isTraceEnabled()) {
log.trace(elements);
log.trace(attributes);
}
}
/**
* Process a property.
* Go through and work out whether it's a loop property, a primitive or a standard.
* The class property is ignored.
*/
protected void addProperty(
BeanInfo beanInfo,
PropertyDescriptor propertyDescriptor,
List elements,
List attributes)
throws
IntrospectionException {
NodeDescriptor nodeDescriptor = XMLIntrospectorHelper
.createDescriptor(propertyDescriptor,
isAttributesForPrimitives(),
this);
if (nodeDescriptor == null) {
return;
}
if (nodeDescriptor instanceof ElementDescriptor) {
elements.add(nodeDescriptor);
} else {
attributes.add(nodeDescriptor);
}
}
/** Factory method to create XMLBeanInfo instances */
protected XMLBeanInfo createXMLBeanInfo( BeanInfo beanInfo ) {
XMLBeanInfo answer = new XMLBeanInfo( beanInfo.getBeanDescriptor().getBeanClass() );
return answer;
}
/** Returns true if the type is a loop type */
public boolean isLoopType(Class type) {
return XMLIntrospectorHelper.isLoopType(type);
}
/** Returns true for primitive types */
public boolean isPrimitiveType(Class type) {
return XMLIntrospectorHelper.isPrimitiveType(type);
}
/**
* By default it will be false.
*
* @return boolean if the beanInfoSearchPath should be used.
*/
public boolean useBeanInfoSearchPath() {
return useBeanInfoSearchPath;
}
/**
* Specifies if you want to use the beanInfoSearchPath
* @see java.beans.Introspector for more details
* @param useBeanInfoSearchPath
*/
public void setUseBeanInfoSearchPath(boolean useBeanInfoSearchPath) {
this.useBeanInfoSearchPath = useBeanInfoSearchPath;
}
}
|
package com.codeborne.selenide;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import static com.codeborne.selenide.Condition.hidden;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Navigation.sleep;
import static com.codeborne.selenide.WebDriverRunner.fail;
import static com.codeborne.selenide.WebDriverRunner.getWebDriver;
import static com.codeborne.selenide.impl.ShouldableWebElementProxy.wrap;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
public class DOM {
public static long defaultWaitingTimeout = Long.getLong("timeout", 4000);
/**
* Find the first element matching given CSS selector
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(String cssSelector) {
return getElement(By.cssSelector(cssSelector));
}
/**
* Find the first element matching given CSS selector
* @param seleniumSelector any Selenium selector like By.id(), By.name() etc.
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(By seleniumSelector) {
return getElement(seleniumSelector);
}
/**
* @see #getElement(By, int)
*/
public static ShouldableWebElement $(By seleniumSelector, int index) {
return getElement(seleniumSelector, index);
}
/**
* Find the first element matching given CSS selector
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(WebElement parent, String cssSelector) {
return wrap(parent.findElement(By.cssSelector(cssSelector)));
}
/**
* Find the Nth element matching given criteria
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @param index 1..N
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(String cssSelector, int index) {
return wrap($$(cssSelector).get(index));
}
/**
* Find the Nth element matching given criteria
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @param index 1..N
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(WebElement parent, String cssSelector, int index) {
return wrap($$(parent, cssSelector).get(index));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return empty list if element was no found
*/
public static ElementsCollection $$(String cssSelector) {
return new ElementsCollection(getElements(By.cssSelector(cssSelector)));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param seleniumSelector any Selenium selector like By.id(), By.name() etc.
* @return empty list if element was no found
*/
public static ElementsCollection $$(By seleniumSelector) {
return new ElementsCollection(getElements(seleniumSelector));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return empty list if element was no found
*/
public static ElementsCollection $$(WebElement parent, String cssSelector) {
return new ElementsCollection(parent.findElements(By.cssSelector(cssSelector)));
}
/**
* Find the first element matching given criteria
* @param criteria instance of By: By.id(), By.className() etc.
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement getElement(By criteria) {
try {
return wrap(getWebDriver().findElement(criteria));
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
/**
* Find the Nth element matching given criteria
* @param criteria instance of By: By.id(), By.className() etc.
* @param index 1..N
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement getElement(By criteria, int index) {
try {
return wrap(getWebDriver().findElements(criteria).get(index));
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
/**
* Find all elements matching given CSS selector
* @param criteria instance of By: By.id(), By.className() etc.
* @return empty list if element was no found
*/
public static ElementsCollection getElements(By criteria) {
try {
return new ElementsCollection(getWebDriver().findElements(criteria));
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
public static void setValue(By by, String value) {
try {
WebElement element = getElement(by);
setValue(element, value);
triggerChangeEvent(by);
} catch (WebDriverException e) {
fail("Cannot get element " + by + ", caused by: " + e);
}
}
public static void setValue(By by, int index, String value) {
try {
WebElement element = getElement(by, index);
setValue(element, value);
triggerChangeEvent(by, index);
} catch (WebDriverException e) {
fail("Cannot get element " + by + " and index " + index + ", caused by: " + e);
}
}
public static void setValue(WebElement element, String value) {
element.clear();
element.sendKeys(value);
}
public static boolean isJQueryAvailable() {
Object result = executeJavaScript("return (typeof jQuery);");
return !"undefined".equalsIgnoreCase(String.valueOf(result));
}
public static void click(By by) {
getElement(by).click();
}
/** Calls onclick javascript code, useful for invisible (hovered) elements that cannot be clicked directly */
public static void callOnClick(By by) {
executeJavaScript("eval(\"" + getElement(by).getAttribute("onclick") + "\")");
}
public static void click(By by, int index) {
List<WebElement> matchedElements = getWebDriver().findElements(by);
if (index >= matchedElements.size()) {
throw new IllegalArgumentException("Cannot click " + index + "th element: there is only " + matchedElements.size() + " elements on the page");
}
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".eq(" + index + ").click();");
} else {
matchedElements.get(index).click();
}
}
public static void triggerChangeEvent(By by) {
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".change();");
}
}
public static void triggerChangeEvent(By by, int index) {
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".eq(" + index + ").change();");
}
}
public static String getJQuerySelector(By seleniumSelector) {
return "$(\"" + getJQuerySelectorString(seleniumSelector) + "\")";
}
public static String getJQuerySelectorString(By seleniumSelector) {
if (seleniumSelector instanceof By.ByName) {
String name = seleniumSelector.toString().replaceFirst("By\\.name:\\s*(.*)", "$1");
return "*[name='" + name + "']";
} else if (seleniumSelector instanceof By.ById) {
String id = seleniumSelector.toString().replaceFirst("By\\.id:\\s*(.*)", "$1");
return "
} else if (seleniumSelector instanceof By.ByClassName) {
String className = seleniumSelector.toString().replaceFirst("By\\.className:\\s*(.*)", "$1");
return "." + className;
} else if (seleniumSelector instanceof By.ByCssSelector) {
return seleniumSelector.toString().replaceFirst("By\\.selector:\\s*(.*)", "$1");
} else if (seleniumSelector instanceof By.ByXPath) {
String seleniumXPath = seleniumSelector.toString().replaceFirst("By\\.xpath:\\s*(.*)", "$1");
return seleniumXPath.replaceFirst("//(.*)", "$1").replaceAll("\\[@", "[");
}
return seleniumSelector.toString();
}
public static Object executeJavaScript(String jsCode) {
return ((JavascriptExecutor) getWebDriver()).executeScript(jsCode);
}
/**
* It works only if jQuery "scroll" plugin is included in page being tested
*
* @param element HTML element to scroll to.
*/
public static void scrollTo(By element) {
if (!isJQueryAvailable()) {
throw new IllegalStateException("JQuery is not available on current page");
}
executeJavaScript("$.scrollTo('" + getJQuerySelectorString(element) + "')");
}
public static ShouldableWebElement selectRadio(By radioField, String value) {
assertEnabled(radioField);
for (WebElement radio : getElements(radioField)) {
if (value.equals(radio.getAttribute("value"))) {
radio.click();
return wrap(radio);
}
}
throw new NoSuchElementException("With " + radioField);
}
public static String getSelectedValue(By selectField) {
WebElement option = findSelectedOption(selectField);
return option == null ? null : option.getAttribute("value");
}
public static String getSelectedText(By selectField) {
WebElement option = findSelectedOption(selectField);
return option == null ? null : option.getText();
}
private static ShouldableWebElement findSelectedOption(By selectField) {
WebElement selectElement = getElement(selectField);
List<WebElement> options = selectElement.findElements(By.tagName("option"));
for (WebElement option : options) {
if (option.getAttribute("selected") != null) {
return wrap(option);
}
}
return null;
}
public static Select select(By selectField) {
return new Select(getElement(selectField));
}
public static void selectOption(By selectField, String value) {
select(selectField).selectByValue(value);
}
public static void selectOptionByText(By selectField, String text) {
select(selectField).selectByVisibleText(text);
}
public static boolean existsAndVisible(By selector) {
try {
return getWebDriver().findElement(selector).isDisplayed();
} catch (NoSuchElementException doesNotExist) {
return false;
}
}
public static void followLink(By by) {
WebElement link = getElement(by);
String href = link.getAttribute("href");
link.click();
// JavaScript $.click() doesn't take effect for <a href>
if (href != null) {
Navigation.navigateToAbsoluteUrl(href);
}
}
private static String getActualValue(WebElement element, Condition condition) {
try {
return condition.actualValue(element);
}
catch (WebDriverException e) {
return e.toString();
}
}
public static void assertChecked(By element) {
assertThat(getElement(element).getAttribute("checked"), equalTo("true"));
}
public static void assertNotChecked(By element) {
assertNull(getElement(element).getAttribute("checked"));
}
public static void assertDisabled(By element) {
assertThat(getElement(element).getAttribute("disabled"), equalTo("true"));
}
public static void assertEnabled(By element) {
String disabled = getElement(element).getAttribute("disabled");
if (disabled != null) {
assertThat(disabled, equalTo("false"));
}
}
public static void assertSelected(By element) {
assertTrue(getElement(element).isSelected());
}
public static void assertNotSelected(By element) {
assertFalse(getElement(element).isSelected());
}
public static boolean isVisible(By selector) {
return getElement(selector).isDisplayed();
}
public static ShouldableWebElement assertVisible(By selector) {
return assertElement(selector, visible);
}
/**
* Method fails if element does not exists.
*/
public static ShouldableWebElement assertHidden(By selector) {
return assertElement(selector, hidden);
}
public static ShouldableWebElement assertElement(By selector, Condition condition) {
try {
return assertElement(getWebDriver().findElement(selector), condition);
}
catch (WebDriverException elementNotFound) {
if (!condition.applyNull()) {
throw elementNotFound;
}
return null;
}
}
public static ShouldableWebElement assertElement(WebElement element, Condition condition) {
if (!condition.apply(element)) {
fail("Element " + element.getTagName() + " hasn't " + condition + "; actual value is '" + getActualValue(element, condition) + "'");
}
return wrap(element);
}
public static ShouldableWebElement waitFor(By elementSelector) {
return waitUntil(elementSelector, 0, visible, defaultWaitingTimeout);
}
public static ShouldableWebElement waitFor(String cssSelector) {
return waitFor(By.cssSelector(cssSelector));
}
@Deprecated
public static ShouldableWebElement waitFor(By elementSelector, Condition condition) {
return waitUntil(elementSelector, condition);
}
public static ShouldableWebElement waitUntil(By elementSelector, Condition condition) {
return waitUntil(elementSelector, 0, condition, defaultWaitingTimeout);
}
public static ShouldableWebElement waitUntil(String cssSelector, Condition condition) {
return waitUntil(By.cssSelector(cssSelector), condition);
}
public static ShouldableWebElement waitUntil(By elementSelector, int index, Condition condition) {
return waitUntil(elementSelector, index, condition, defaultWaitingTimeout);
}
public static ShouldableWebElement waitUntil(String cssSelector, int index, Condition condition) {
return waitUntil(By.cssSelector(cssSelector), index, condition);
}
@Deprecated
public static ShouldableWebElement waitFor(By elementSelector, Condition condition, long milliseconds) {
return waitUntil(elementSelector, condition, milliseconds);
}
public static ShouldableWebElement waitUntil(By elementSelector, Condition condition, long milliseconds) {
return waitUntil(elementSelector, 0, condition, milliseconds);
}
public static ShouldableWebElement waitUntil(String cssSelector, Condition condition, long milliseconds) {
return waitUntil(By.cssSelector(cssSelector), condition, milliseconds);
}
@Deprecated
public static ShouldableWebElement waitFor(By elementSelector, int index, Condition condition, long milliseconds) {
return waitUntil(elementSelector, index, condition, milliseconds);
}
public static ShouldableWebElement waitUntil(String cssSelector, int index, Condition condition, long milliseconds) {
return waitUntil(By.cssSelector(cssSelector), index, condition, milliseconds);
}
public static ShouldableWebElement waitUntil(By elementSelector, int index, Condition condition, long milliseconds) {
final long startTime = System.currentTimeMillis();
WebElement element = null;
do {
try {
if (index == 0) {
element = getWebDriver().findElement(elementSelector);
}
else {
element = getWebDriver().findElements(elementSelector).get(index);
}
if (condition.apply(element)) {
return wrap(element);
}
} catch (WebDriverException elementNotFound) {
if (condition.applyNull()) {
return null;
}
}
sleep(50);
}
while (System.currentTimeMillis() - startTime < milliseconds);
fail("Element " + elementSelector + " hasn't " + condition + " in " + milliseconds + " ms.; actual value is '" + getActualValue(element, condition) + "'");
return null;
}
public static void confirm(String expectedConfirmationText) {
try {
Alert alert = getWebDriver().switchTo().alert();
assertEquals(expectedConfirmationText, alert.getText());
alert.accept();
} catch (UnsupportedOperationException alertIsNotSupportedInHtmlUnit) {
return;
}
try {
long start = System.currentTimeMillis();
while (getWebDriver().switchTo().alert() != null) {
getWebDriver().switchTo().alert();
if (System.currentTimeMillis() - start > defaultWaitingTimeout) {
fail("Confirmation dialog has not disappeared in " + defaultWaitingTimeout + " milliseconds");
}
sleep(50);
}
}
catch (NoAlertPresentException ignore) {
}
}
/**
* @deprecated Use $("selector").toString()
*/
@Deprecated
public static String describeElement(WebElement element) {
return wrap(element).toString();
}
}
|
package com.walkertribe.ian.enums;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import com.walkertribe.ian.Context;
import com.walkertribe.ian.model.Model;
import com.walkertribe.ian.util.BoolState;
import com.walkertribe.ian.util.TestUtil;
import com.walkertribe.ian.util.Util;
import com.walkertribe.ian.vesseldata.Faction;
import com.walkertribe.ian.vesseldata.Vessel;
import com.walkertribe.ian.world.ArtemisBase;
import com.walkertribe.ian.world.ArtemisCreature;
import com.walkertribe.ian.world.ArtemisNpc;
import com.walkertribe.ian.world.ArtemisObject;
import com.walkertribe.ian.world.ArtemisPlayer;
/**
* Exercises all enums in the enums package.
* @author rjwut
*/
public class EnumsTest {
private static final List<Class<? extends Enum<?>>> ENUMS = new LinkedList<Class<? extends Enum<?>>>();
private static final Set<CommsMessage> MESSAGE_HAS_ARGUMENT = new HashSet<CommsMessage>();
private static final Set<ObjectType> NAMED_OBJECT_TYPES = new HashSet<ObjectType>();
private static final Set<ObjectType> OBJECT_TYPES_WITH_ONE_MODEL = new HashSet<ObjectType>();
private static final Map<Upgrade, Console> UPGRADE_ACTIVATION_CONSOLES = new HashMap<Upgrade, Console>();
static {
ENUMS.add(AlertStatus.class);
ENUMS.add(AudioCommand.class);
ENUMS.add(AudioMode.class);
ENUMS.add(BaseMessage.class);
ENUMS.add(BeamFrequency.class);
ENUMS.add(CommsRecipientType.class);
ENUMS.add(Origin.class);
ENUMS.add(Console.class);
ENUMS.add(ConsoleStatus.class);
ENUMS.add(CreatureType.class);
ENUMS.add(DriveType.class);
ENUMS.add(EnemyMessage.class);
ENUMS.add(FactionAttribute.class);
ENUMS.add(GameType.class);
ENUMS.add(MainScreenView.class);
ENUMS.add(ObjectType.class);
ENUMS.add(OrdnanceType.class);
ENUMS.add(OtherMessage.class);
ENUMS.add(Perspective.class);
ENUMS.add(PlayerMessage.class);
ENUMS.add(ShipSystem.class);
ENUMS.add(SpecialAbility.class);
ENUMS.add(TargetingMode.class);
ENUMS.add(TubeState.class);
ENUMS.add(Upgrade.class);
ENUMS.add(VesselAttribute.class);
MESSAGE_HAS_ARGUMENT.add(OtherMessage.GO_DEFEND);
NAMED_OBJECT_TYPES.add(ObjectType.ANOMALY);
NAMED_OBJECT_TYPES.add(ObjectType.BASE);
NAMED_OBJECT_TYPES.add(ObjectType.CREATURE);
NAMED_OBJECT_TYPES.add(ObjectType.GENERIC_MESH);
NAMED_OBJECT_TYPES.add(ObjectType.NPC_SHIP);
NAMED_OBJECT_TYPES.add(ObjectType.PLAYER_SHIP);
OBJECT_TYPES_WITH_ONE_MODEL.add(ObjectType.ANOMALY);
OBJECT_TYPES_WITH_ONE_MODEL.add(ObjectType.ASTEROID);
OBJECT_TYPES_WITH_ONE_MODEL.add(ObjectType.DRONE);
OBJECT_TYPES_WITH_ONE_MODEL.add(ObjectType.MINE);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.HIDENS_POWER_CELL, null);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.VIGORANIUM_NODULE, null);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.CETROCITE_HEATSINKS, Console.ENGINEERING);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.LATERAL_ARRAY, Console.SCIENCE);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.TAURON_FOCUSERS, Console.WEAPONS);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.INFUSION_P_COILS, Console.HELM);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.CARPACTION_COILS, Console.WEAPONS);
UPGRADE_ACTIVATION_CONSOLES.put(Upgrade.SECRET_CODE_CASE, Console.COMMUNICATIONS);
}
@Test
public void testBaseMessage() {
for (BaseMessage value : BaseMessage.values()) {
Assert.assertEquals(CommsRecipientType.BASE, value.getRecipientType());
Assert.assertEquals(MESSAGE_HAS_ARGUMENT.contains(value), value.hasArgument());
}
for (OrdnanceType ordnance : OrdnanceType.values()) {
Assert.assertEquals(ordnance, BaseMessage.build(ordnance).getOrdnanceType());
}
Assert.assertNull(BaseMessage.STAND_BY_FOR_DOCKING_OR_CEASE_OPERATION.getOrdnanceType());
Assert.assertNull(BaseMessage.PLEASE_REPORT_STATUS.getOrdnanceType());
}
@Test
public void testCommsRecipientType() {
Assert.assertEquals(
CommsRecipientType.BASE,
CommsRecipientType.fromObject(new ArtemisBase(0), null)
);
ArtemisNpc npc = new ArtemisNpc(0);
npc.setEnemy(BoolState.TRUE);
Assert.assertEquals(
CommsRecipientType.ENEMY,
CommsRecipientType.fromObject(npc, null)
);
npc = new ArtemisNpc(0);
npc.setEnemy(BoolState.FALSE);
Assert.assertEquals(
CommsRecipientType.OTHER,
CommsRecipientType.fromObject(npc, null)
);
Assert.assertEquals(
CommsRecipientType.PLAYER,
CommsRecipientType.fromObject(new ArtemisPlayer(0), null)
);
Assert.assertNull(
CommsRecipientType.fromObject(new ArtemisCreature(0), null)
);
}
@Test
public void testCommsRecipientTypeRequiringContext() {
Context ctx = TestUtil.assumeContext();
ArtemisNpc npc = new ArtemisNpc(0);
npc.setVessel(findNpcVessel(ctx, false));
Assert.assertEquals(
CommsRecipientType.ENEMY,
CommsRecipientType.fromObject(npc, ctx)
);
npc = new ArtemisNpc(0);
npc.setVessel(findNpcVessel(ctx, true));
Assert.assertEquals(
CommsRecipientType.OTHER,
CommsRecipientType.fromObject(npc, ctx)
);
}
@Test
public void testConnectionType() {
Assert.assertEquals(Origin.SERVER, Origin.fromInt(1));
Assert.assertEquals(Origin.CLIENT, Origin.fromInt(2));
Assert.assertNull(Origin.fromInt(0));
Assert.assertEquals(Origin.CLIENT, Origin.SERVER.opposite());
Assert.assertEquals(Origin.SERVER, Origin.CLIENT.opposite());
}
@Test
public void testConsoleToString() {
Assert.assertEquals("Captain's map", Console.CAPTAINS_MAP.toString());
}
@Test
public void testCreatureTypeGetModel() {
Context ctx = TestUtil.assumeContext();
for (CreatureType type : CreatureType.values()) {
Model model = type.getModel(ctx);
Assert.assertEquals(type != CreatureType.CLASSIC, model != null);
}
}
@Test
public void testEnemyMessage() {
for (EnemyMessage value : EnemyMessage.values()) {
Assert.assertEquals(CommsRecipientType.ENEMY, value.getRecipientType());
Assert.assertEquals(MESSAGE_HAS_ARGUMENT.contains(value), value.hasArgument());
}
}
@Test
public void testFactionAttribute() {
Set<FactionAttribute> attrs = FactionAttribute.build("player");
Assert.assertEquals("PLAYER", Util.enumSetToString(attrs));
attrs = FactionAttribute.build("enemy loner biomech");
Assert.assertEquals("ENEMY LONER BIOMECH", Util.enumSetToString(attrs));
// conditionals coverage for some valid combinations
FactionAttribute.build("enemy standard whalelover");
FactionAttribute.build("enemy standard whalehater");
FactionAttribute.build("player jumpmaster");
}
@Test(expected = IllegalArgumentException.class)
public void testFactionAttributeMustHaveStance() {
FactionAttribute.build("standard");
}
@Test(expected = IllegalArgumentException.class)
public void testFactionAttributeEnemyMustHaveOrg() {
FactionAttribute.build("enemy");
}
@Test(expected = IllegalArgumentException.class)
public void testFactionAttributeWhaleAttitudeExclusivity() {
FactionAttribute.build("enemy standard whalelover whalehater");
}
@Test(expected = IllegalArgumentException.class)
public void testFactionAttributeNonPlayerJumpMaster() {
FactionAttribute.build("enemy standard jumpmaster");
}
@Test
public void testObjectType() throws ReflectiveOperationException {
for (ObjectType type : ObjectType.values()) {
Assert.assertEquals(type, ObjectType.fromId(type.getId()));
Assert.assertEquals(NAMED_OBJECT_TYPES.contains(type), type.isNamed());
Class<? extends ArtemisObject> clazz = type.getObjectClass();
Constructor<? extends ArtemisObject> constructor = clazz.getConstructor(int.class);
Assert.assertTrue(type.isCompatible(constructor.newInstance(0)));
float scale = OBJECT_TYPES_WITH_ONE_MODEL.contains(type) ? ObjectType.MODEL_SCALE : 0;
Assert.assertEquals(scale, type.getScale(), TestUtil.EPSILON);
}
Assert.assertNull(ObjectType.fromId(0));
}
@Test
public void testObjectTypeRequiringContext() {
Context ctx = TestUtil.assumeContext();
for (ObjectType type : ObjectType.values()) {
Model model = type.getModel(ctx);
Assert.assertEquals(OBJECT_TYPES_WITH_ONE_MODEL.contains(type), model != null);
}
}
@Test(expected = IllegalArgumentException.class)
public void testObjectTypeInvalidId() {
ObjectType.fromId(9);
}
@Test
public void testOrdnanceTypeToString() {
Assert.assertEquals("Homing", OrdnanceType.HOMING.toString());
Assert.assertEquals("Nuke", OrdnanceType.NUKE.toString());
Assert.assertEquals("Mine", OrdnanceType.MINE.toString());
Assert.assertEquals("EMP", OrdnanceType.EMP.toString());
Assert.assertEquals("PlasmaShock", OrdnanceType.PSHOCK.toString());
}
@Test
public void testOtherMessage() {
for (OtherMessage value : OtherMessage.values()) {
Assert.assertEquals(value, OtherMessage.fromId(value.getId()));
Assert.assertEquals(CommsRecipientType.OTHER, value.getRecipientType());
Assert.assertEquals(MESSAGE_HAS_ARGUMENT.contains(value), value.hasArgument());
}
Assert.assertNull(OtherMessage.fromId(-1));
}
@Test
public void testPlayerMessage() {
for (PlayerMessage value : PlayerMessage.values()) {
Assert.assertEquals(CommsRecipientType.PLAYER, value.getRecipientType());
Assert.assertEquals(MESSAGE_HAS_ARGUMENT.contains(value), value.hasArgument());
}
}
@Test
public void testSpecialAbility() {
Set<SpecialAbility> set = SpecialAbility.fromValue(0);
Assert.assertTrue(set.isEmpty());
set = SpecialAbility.fromValue(0x555);
for (SpecialAbility ability : SpecialAbility.values()) {
boolean on = ability.ordinal() % 2 == 0;
Assert.assertEquals(on, set.contains(ability));
Assert.assertEquals(on, ability.on(0x555));
}
}
@Test
public void testUpgradeActivations() {
for (Map.Entry<Upgrade, Console> entry : UPGRADE_ACTIVATION_CONSOLES.entrySet()) {
Assert.assertEquals(entry.getKey().getActivatedBy(), entry.getValue());
}
}
@Test
public void coverValueOf() {
for (Class<? extends Enum<?>> clazz : ENUMS) {
TestUtil.coverEnumValueOf(clazz);
}
}
private static Vessel findNpcVessel(Context ctx, boolean friendly) {
for (Iterator<Vessel> iter = ctx.getVesselData().vesselIterator(); iter.hasNext(); ) {
Vessel vessel = iter.next();
if (vessel.is(VesselAttribute.BASE) || vessel.is(VesselAttribute.PLAYER)) {
continue;
}
Faction faction = vessel.getFaction();
if (faction.is(FactionAttribute.PLAYER)) {
continue;
}
if (friendly ^ faction.is(FactionAttribute.ENEMY)) {
return vessel;
}
}
return null; // shouldn't happen
}
}
|
package com.codeborne.selenide;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Navigation.sleep;
import static com.codeborne.selenide.WebDriverRunner.fail;
import static com.codeborne.selenide.WebDriverRunner.getWebDriver;
import static com.codeborne.selenide.impl.ShouldableWebElementProxy.wrap;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
public class DOM {
public static long defaultWaitingTimeout = Long.getLong("timeout", 4000);
/**
* Find the first element matching given CSS selector
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(String cssSelector) {
return wrap(getElement(By.cssSelector(cssSelector)));
}
/**
* Find the first element matching given CSS selector
* @param seleniumSelector any Selenium selector like By.id(), By.name() etc.
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(By seleniumSelector) {
return wrap(getElement(seleniumSelector));
}
/**
* Find the first element matching given CSS selector
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(WebElement parent, String cssSelector) {
return wrap(parent.findElement(By.cssSelector(cssSelector)));
}
/**
* Find the Nth element matching given criteria
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @param index 1..N
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(String cssSelector, int index) {
return wrap($$(cssSelector).get(index));
}
/**
* Find the Nth element matching given criteria
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @param index 1..N
* @return ShouldableWebElement
* @throws NoSuchElementException if element was no found
*/
public static ShouldableWebElement $(WebElement parent, String cssSelector, int index) {
return wrap($$(parent, cssSelector).get(index));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return empty list if element was no found
*/
public static ElementsCollection $$(String cssSelector) {
return new ElementsCollection(getElements(By.cssSelector(cssSelector)));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param seleniumSelector any Selenium selector like By.id(), By.name() etc.
* @return empty list if element was no found
*/
public static ElementsCollection $$(By seleniumSelector) {
return new ElementsCollection(getElements(seleniumSelector));
}
/**
* Find all elements matching given CSS selector.
* Methods returns an ElementsCollection which is a list of WebElement objects that can be iterated,
* and at the same time is implementation of WebElement interface, meaning that you can call methods .sendKeys(), click() etc. on it.
* @param parent the WebElement to search elements in
* @param cssSelector any CSS selector like "input[name='first_name']" or "#messages .new_message"
* @return empty list if element was no found
*/
public static ElementsCollection $$(WebElement parent, String cssSelector) {
return new ElementsCollection(parent.findElements((By.cssSelector(cssSelector))));
}
/**
* Find the first element matching given criteria
* @param criteria instance of By: By.id(), By.className() etc.
* @return WebElement
* @throws NoSuchElementException if element was no found
*/
public static WebElement getElement(By criteria) {
try {
return getWebDriver().findElement(criteria);
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
/**
* Find the Nth element matching given criteria
* @param criteria instance of By: By.id(), By.className() etc.
* @param index 1..N
* @return WebElement
* @throws NoSuchElementException if element was no found
*/
public static WebElement getElement(By criteria, int index) {
try {
return getWebDriver().findElements(criteria).get(index);
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
/**
* Find all elements matching given CSS selector
* @param criteria instance of By: By.id(), By.className() etc.
* @return empty list if element was no found
*/
public static ElementsCollection getElements(By criteria) {
try {
return new ElementsCollection(getWebDriver().findElements(criteria));
} catch (WebDriverException e) {
return fail("Cannot get element " + criteria + ", caused criteria: " + e);
}
}
public static void setValue(By by, String value) {
try {
WebElement element = getElement(by);
setValue(element, value);
triggerChangeEvent(by);
} catch (WebDriverException e) {
fail("Cannot get element " + by + ", caused by: " + e);
}
}
public static void setValue(By by, int index, String value) {
try {
WebElement element = getElement(by, index);
setValue(element, value);
triggerChangeEvent(by, index);
} catch (WebDriverException e) {
fail("Cannot get element " + by + " and index " + index + ", caused by: " + e);
}
}
public static void setValue(WebElement element, String value) {
element.clear();
element.sendKeys(value);
}
public static boolean isJQueryAvailable() {
Object result = executeJavaScript("return (typeof jQuery);");
return !"undefined".equalsIgnoreCase(String.valueOf(result));
}
public static void click(By by) {
getElement(by).click();
}
/** Calls onclick javascript code, useful for invisible (hovered) elements that cannot be clicked directly */
public static void callOnClick(By by) {
executeJavaScript("eval(\"" + getElement(by).getAttribute("onclick") + "\")");
}
public static void click(By by, int index) {
List<WebElement> matchedElements = com.codeborne.selenide.WebDriverRunner.getWebDriver().findElements(by);
if (index >= matchedElements.size()) {
throw new IllegalArgumentException("Cannot click " + index + "th element: there is only " + matchedElements.size() + " elements on the page");
}
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".eq(" + index + ").click();");
} else {
matchedElements.get(index).click();
}
}
public static void triggerChangeEvent(By by) {
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".change();");
}
}
public static void triggerChangeEvent(By by, int index) {
if (isJQueryAvailable()) {
executeJavaScript(getJQuerySelector(by) + ".eq(" + index + ").change();");
}
}
public static String getJQuerySelector(By seleniumSelector) {
return "$(\"" + getJQuerySelectorString(seleniumSelector) + "\")";
}
public static String getJQuerySelectorString(By seleniumSelector) {
if (seleniumSelector instanceof By.ByName) {
String name = seleniumSelector.toString().replaceFirst("By\\.name:\\s*(.*)", "$1");
return "*[name='" + name + "']";
} else if (seleniumSelector instanceof By.ById) {
String id = seleniumSelector.toString().replaceFirst("By\\.id:\\s*(.*)", "$1");
return "
} else if (seleniumSelector instanceof By.ByClassName) {
String className = seleniumSelector.toString().replaceFirst("By\\.className:\\s*(.*)", "$1");
return "." + className;
} else if (seleniumSelector instanceof By.ByXPath) {
String seleniumXPath = seleniumSelector.toString().replaceFirst("By\\.xpath:\\s*(.*)", "$1");
return seleniumXPath.replaceFirst("//(.*)", "$1").replaceAll("\\[@", "[");
}
return seleniumSelector.toString();
}
public static String describeElement(WebElement element) {
return "<" + element.getTagName() +
" value=" + element.getAttribute("value") +
" class=" + element.getAttribute("class") +
" id=" + element.getAttribute("id") +
" name=" + element.getAttribute("name") +
" onclick=" + element.getAttribute("onclick") +
" onClick=" + element.getAttribute("onClick") +
" onchange=" + element.getAttribute("onchange") +
" onChange=" + element.getAttribute("onChange") +
">" + element.getText() +
"</" + element.getTagName() + ">";
}
public static Object executeJavaScript(String jsCode) {
return ((JavascriptExecutor) getWebDriver()).executeScript(jsCode);
}
/**
* It works only if jQuery "scroll" plugin is included in page being tested
*
* @param element HTML element to scroll to.
*/
public static void scrollTo(By element) {
if (!isJQueryAvailable()) {
throw new IllegalStateException("JQuery is not available on current page");
}
executeJavaScript("$.scrollTo('" + getJQuerySelectorString(element) + "')");
}
public static WebElement selectRadio(By radioField, String value) {
assertEnabled(radioField);
for (WebElement radio : getElements(radioField)) {
if (value.equals(radio.getAttribute("value"))) {
radio.click();
return radio;
}
}
throw new NoSuchElementException("With " + radioField);
}
public static String getSelectedValue(By selectField) {
WebElement option = findSelectedOption(selectField);
return option == null ? null : option.getAttribute("value");
}
public static String getSelectedText(By selectField) {
WebElement option = findSelectedOption(selectField);
return option == null ? null : option.getText();
}
private static WebElement findSelectedOption(By selectField) {
WebElement selectElement = getElement(selectField);
List<WebElement> options = selectElement.findElements(By.tagName("option"));
for (WebElement option : options) {
if (option.getAttribute("selected") != null) {
return option;
}
}
return null;
}
public static Select select(By selectField) {
return new Select(getElement(selectField));
}
public static void selectOption(By selectField, String value) {
select(selectField).selectByValue(value);
}
public static void selectOptionByText(By selectField, String text) {
select(selectField).selectByVisibleText(text);
}
public static boolean existsAndVisible(By selector) {
try {
return getWebDriver().findElement(selector).isDisplayed();
} catch (NoSuchElementException doesNotExist) {
return false;
}
}
public static void followLink(By by) {
WebElement link = getElement(by);
String href = link.getAttribute("href");
link.click();
// JavaScript $.click() doesn't take effect for <a href>
if (href != null) {
Navigation.navigateToAbsoluteUrl(href);
}
}
private static String getActualValue(WebElement element, Condition condition) {
try {
return condition.actualValue(element);
}
catch (WebDriverException e) {
return e.toString();
}
}
public static void assertChecked(By element) {
assertThat(getElement(element).getAttribute("checked"), equalTo("true"));
}
public static void assertNotChecked(By element) {
assertNull(getElement(element).getAttribute("checked"));
}
public static void assertDisabled(By element) {
assertThat(getElement(element).getAttribute("disabled"), equalTo("true"));
}
public static void assertEnabled(By element) {
String disabled = getElement(element).getAttribute("disabled");
if (disabled != null) {
assertThat(disabled, equalTo("false"));
}
}
public static void assertSelected(By element) {
assertTrue(getElement(element).isSelected());
}
public static void assertNotSelected(By element) {
assertFalse(getElement(element).isSelected());
}
public static boolean isVisible(By selector) {
return getElement(selector).isDisplayed();
}
public static WebElement assertVisible(By selector) {
return assertElement(selector, visible);
}
/**
* Method fails if element does not exists.
*/
public static WebElement assertHidden(By selector) {
return assertElement(selector, Condition.hidden);
}
public static WebElement assertElement(By selector, Condition condition) {
try {
WebElement element = getWebDriver().findElement(selector);
if (!condition.apply(element)) {
fail("Element " + selector + " hasn't " + condition + "; actual value is '" + getActualValue(element, condition) + "'");
}
return element;
}
catch (WebDriverException elementNotFound) {
if (!condition.applyNull()) {
throw elementNotFound;
}
return null;
}
}
public static WebElement assertElement(WebElement element, Condition condition) {
if (!condition.apply(element)) {
fail("Element " + element.getTagName() + " hasn't " + condition + "; actual value is '" + getActualValue(element, condition) + "'");
}
return element;
}
public static WebElement waitFor(By elementSelector) {
return waitUntil(elementSelector, 0, visible, defaultWaitingTimeout);
}
public static WebElement waitFor(String cssSelector) {
return waitFor(By.cssSelector(cssSelector));
}
@Deprecated
public static WebElement waitFor(By elementSelector, Condition condition) {
return waitUntil(elementSelector, condition);
}
public static WebElement waitUntil(By elementSelector, Condition condition) {
return waitUntil(elementSelector, 0, condition, defaultWaitingTimeout);
}
public static WebElement waitUntil(String cssSelector, Condition condition) {
return waitUntil(By.cssSelector(cssSelector), condition);
}
public static WebElement waitUntil(By elementSelector, int index, Condition condition) {
return waitUntil(elementSelector, index, condition, defaultWaitingTimeout);
}
public static WebElement waitUntil(String cssSelector, int index, Condition condition) {
return waitUntil(By.cssSelector(cssSelector), index, condition);
}
@Deprecated
public static WebElement waitFor(By elementSelector, Condition condition, long milliseconds) {
return waitUntil(elementSelector, condition, milliseconds);
}
public static WebElement waitUntil(By elementSelector, Condition condition, long milliseconds) {
return waitUntil(elementSelector, 0, condition, milliseconds);
}
public static WebElement waitUntil(String cssSelector, Condition condition, long milliseconds) {
return waitUntil(By.cssSelector(cssSelector), condition, milliseconds);
}
@Deprecated
public static WebElement waitFor(By elementSelector, int index, Condition condition, long milliseconds) {
return waitUntil(elementSelector, index, condition, milliseconds);
}
public static WebElement waitUntil(String cssSelector, int index, Condition condition, long milliseconds) {
return waitUntil(By.cssSelector(cssSelector), index, condition, milliseconds);
}
public static WebElement waitUntil(By elementSelector, int index, Condition condition, long milliseconds) {
final long startTime = System.currentTimeMillis();
WebElement element = null;
do {
try {
if (index == 0) {
element = getWebDriver().findElement(elementSelector);
}
else {
element = getWebDriver().findElements(elementSelector).get(index);
}
if (condition.apply(element)) {
return element;
}
} catch (WebDriverException elementNotFound) {
if (condition.applyNull()) {
return null;
}
}
sleep(50);
}
while (System.currentTimeMillis() - startTime < milliseconds);
fail("Element " + elementSelector + " hasn't " + condition + " in " + milliseconds + " ms.; actual value is '" + getActualValue(element, condition) + "'");
return null;
}
}
|
package de.ailis.usb4java.libusb;
import static de.ailis.usb4java.test.UsbAssume.assumeUsbTestsEnabled;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileDescriptor;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import org.junit.Test;
import de.ailis.usb4java.libusb.mocks.PollfdListenerMock;
/**
* Tests the {@link LibUsb} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class LibUSBTest
{
/**
* Tests the constant values.
*/
@Test
public void testConstants()
{
// Log levels
assertEquals(0, LibUsb.LOG_LEVEL_NONE);
assertEquals(1, LibUsb.LOG_LEVEL_ERROR);
assertEquals(2, LibUsb.LOG_LEVEL_WARNING);
assertEquals(3, LibUsb.LOG_LEVEL_INFO);
assertEquals(4, LibUsb.LOG_LEVEL_DEBUG);
// Speed codes
assertEquals(0, LibUsb.SPEED_UNKNOWN);
assertEquals(1, LibUsb.SPEED_LOW);
assertEquals(2, LibUsb.SPEED_FULL);
assertEquals(3, LibUsb.SPEED_HIGH);
assertEquals(4, LibUsb.SPEED_SUPER);
// Standard requests
assertEquals(0x00, LibUsb.REQUEST_GET_STATUS);
assertEquals(0x01, LibUsb.REQUEST_CLEAR_FEATURE);
assertEquals(0x03, LibUsb.REQUEST_SET_FEATURE);
assertEquals(0x05, LibUsb.REQUEST_SET_ADDRESS);
assertEquals(0x06, LibUsb.REQUEST_GET_DESCRIPTOR);
assertEquals(0x07, LibUsb.REQUEST_SET_DESCRIPTOR);
assertEquals(0x08, LibUsb.REQUEST_GET_CONFIGURATION);
assertEquals(0x09, LibUsb.REQUEST_SET_CONFIGURATION);
assertEquals(0x0a, LibUsb.REQUEST_GET_INTERFACE);
assertEquals(0x0b, LibUsb.REQUEST_SET_INTERFACE);
assertEquals(0x0c, LibUsb.REQUEST_SYNCH_FRAME);
assertEquals(0x30, LibUsb.REQUEST_SET_SEL);
assertEquals(0x31, LibUsb.SET_ISOCH_DELAY);
// Request type
assertEquals(0x00 << 5, LibUsb.REQUEST_TYPE_STANDARD);
assertEquals(0x01 << 5, LibUsb.REQUEST_TYPE_CLASS);
assertEquals(0x02 << 5, LibUsb.REQUEST_TYPE_VENDOR);
assertEquals(0x03 << 5, LibUsb.REQUEST_TYPE_RESERVED);
// Recipient bits
assertEquals(0x00, LibUsb.RECIPIENT_DEVICE);
assertEquals(0x01, LibUsb.RECIPIENT_INTERFACE);
assertEquals(0x02, LibUsb.RECIPIENT_ENDPOINT);
assertEquals(0x03, LibUsb.RECIPIENT_OTHER);
// Error codes
assertEquals(0, LibUsb.SUCCESS);
assertEquals(-1, LibUsb.ERROR_IO);
assertEquals(-2, LibUsb.ERROR_INVALID_PARAM);
assertEquals(-3, LibUsb.ERROR_ACCESS);
assertEquals(-4, LibUsb.ERROR_NO_DEVICE);
assertEquals(-5, LibUsb.ERROR_NOT_FOUND);
assertEquals(-6, LibUsb.ERROR_BUSY);
assertEquals(-7, LibUsb.ERROR_TIMEOUT);
assertEquals(-8, LibUsb.ERROR_OVERFLOW);
assertEquals(-9, LibUsb.ERROR_PIPE);
assertEquals(-10, LibUsb.ERROR_INTERRUPTED);
assertEquals(-11, LibUsb.ERROR_NO_MEM);
assertEquals(-12, LibUsb.ERROR_NOT_SUPPORTED);
assertEquals(-99, LibUsb.ERROR_OTHER);
// Capabilities
assertEquals(0, LibUsb.CAP_HAS_CAPABILITY);
// Device and/or Interface class codes
assertEquals(0, LibUsb.CLASS_PER_INTERFACE);
assertEquals(1, LibUsb.CLASS_AUDIO);
assertEquals(2, LibUsb.CLASS_COMM);
assertEquals(3, LibUsb.CLASS_HID);
assertEquals(5, LibUsb.CLASS_PHYSICAL);
assertEquals(7, LibUsb.CLASS_PRINTER);
assertEquals(6, LibUsb.CLASS_PTP);
assertEquals(6, LibUsb.CLASS_IMAGE);
assertEquals(8, LibUsb.CLASS_MASS_STORAGE);
assertEquals(9, LibUsb.CLASS_HUB);
assertEquals(10, LibUsb.CLASS_DATA);
assertEquals(0x0b, LibUsb.CLASS_SMART_CARD);
assertEquals(0x0d, LibUsb.CLASS_CONTENT_SECURITY);
assertEquals(0x0e, LibUsb.CLASS_VIDEO);
assertEquals(0x0f, LibUsb.CLASS_PERSONAL_HEALTHCARE);
assertEquals(0xdc, LibUsb.CLASS_DIAGNOSTIC_DEVICE);
assertEquals(0xe0, LibUsb.CLASS_WIRELESS);
assertEquals(0xfe, LibUsb.CLASS_APPLICATION);
assertEquals(0xff, LibUsb.CLASS_VENDOR_SPEC);
// Descriptor types
assertEquals(0x01, LibUsb.DT_DEVICE);
assertEquals(0x02, LibUsb.DT_CONFIG);
assertEquals(0x03, LibUsb.DT_STRING);
assertEquals(0x04, LibUsb.DT_INTERFACE);
assertEquals(0x05, LibUsb.DT_ENDPOINT);
assertEquals(0x21, LibUsb.DT_HID);
assertEquals(0x22, LibUsb.DT_REPORT);
assertEquals(0x23, LibUsb.DT_PHYSICAL);
assertEquals(0x29, LibUsb.DT_HUB);
assertEquals(0x2a, LibUsb.DT_SUPERSPEED_HUB);
// Endpoint direction
assertEquals(0x80, LibUsb.ENDPOINT_IN);
assertEquals(0x00, LibUsb.ENDPOINT_OUT);
// Transfer types
assertEquals(0, LibUsb.TRANSFER_TYPE_CONTROL);
assertEquals(1, LibUsb.TRANSFER_TYPE_ISOCHRONOUS);
assertEquals(2, LibUsb.TRANSFER_TYPE_BULK);
assertEquals(3, LibUsb.TRANSFER_TYPE_INTERRUPT);
// ISO Sync types
assertEquals(0, LibUsb.ISO_SYNC_TYPE_NONE);
assertEquals(1, LibUsb.ISO_SYNC_TYPE_ASYNC);
assertEquals(2, LibUsb.ISO_SYNC_TYPE_ADAPTIVE);
assertEquals(3, LibUsb.ISO_SYNC_TYPE_SYNC);
// ISO usage types
assertEquals(0, LibUsb.ISO_USAGE_TYPE_DATA);
assertEquals(1, LibUsb.ISO_USAGE_TYPE_FEEDBACK);
assertEquals(2, LibUsb.ISO_USAGE_TYPE_IMPLICIT);
}
/**
* Tests the {@link LibUsb#getVersion()} method.
*/
@Test
public void testGetVersion()
{
assumeUsbTestsEnabled();
final Version version = LibUsb.getVersion();
assertNotNull(version);
assertEquals(1, version.major());
assertEquals(0, version.minor());
assertTrue((version.micro() > 0) && (version.micro() < 100));
assertNotNull(version.rc());
assertTrue(version.toString().startsWith("1.0."));
}
/**
* Tests the initialization and deinitialization of libusb with default
* context.
*/
@Test
public void testInitDeinitWithDefaultContext()
{
assumeUsbTestsEnabled();
assertEquals(LibUsb.SUCCESS, LibUsb.init(null));
LibUsb.exit(null);
try
{
// Double-exit should throw exception
LibUsb.exit(null);
fail("Double-exit should throw IllegalStateException");
}
catch (IllegalStateException e)
{
// Expected behavior
}
}
/**
* Tests the initialization and deinitialization of libusb with a custom USB
* context.
*/
@Test
public void testInitDeinitWithContext()
{
assumeUsbTestsEnabled();
Context context = new Context();
assertEquals(LibUsb.SUCCESS, LibUsb.init(context));
LibUsb.exit(context);
try
{
LibUsb.exit(context);
fail("Double-exit should throw IllegalStateException");
}
catch (IllegalStateException e)
{
// Expected behavior
}
}
/**
* Tests {@link LibUsb#exit(Context)} method with uninitialized Context
*/
@Test(expected = IllegalStateException.class)
public void testExitWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.exit(context);
}
/**
* Tests {@link LibUsb#setDebug(Context, int)} method with uninitialized USB
* context
*/
@Test(expected = IllegalStateException.class)
public void testSetDebugWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.setDebug(context, 0);
}
/**
* Tests {@link LibUsb#getDeviceList(Context, DeviceList)} method with
* uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testGetDeviceListWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.getDeviceList(context, new DeviceList());
}
/**
* Tests {@link LibUsb#freeDeviceList(DeviceList, boolean)} method with
* uninitialized list.
*/
@Test(expected = IllegalStateException.class)
public void testFreeDeviceListWithUninitializedList()
{
assumeUsbTestsEnabled();
LibUsb.freeDeviceList(new DeviceList(), true);
}
/**
* Tests {@link LibUsb#freeDeviceList(DeviceList, boolean)} method without
* list.
*/
@Test(expected = IllegalArgumentException.class)
public void testFreeDeviceListWithoutList()
{
assumeUsbTestsEnabled();
LibUsb.freeDeviceList(null, true);
}
/**
* Tests the {@link LibUsb#getBusNumber(Device)} method without a device.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetBusNumberWithoutDevice()
{
assumeUsbTestsEnabled();
LibUsb.getBusNumber(null);
}
/**
* Tests the {@link LibUsb#getBusNumber(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testGetBusNumberWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getBusNumber(new Device());
}
/**
* Tests the {@link LibUsb#getPortNumber(Device)} method without a device.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetPortNumberWithoutDevice()
{
assumeUsbTestsEnabled();
LibUsb.getPortNumber(null);
}
/**
* Tests the {@link LibUsb#getPortNumber(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testGetPortNumberWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getPortNumber(new Device());
}
/**
* Tests the {@link LibUsb#getParent(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testGetParentWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getParent(new Device());
}
/**
* Tests the {@link LibUsb#getDeviceAddress(Device)} method with
* uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testGetDeviceAddressWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getDeviceAddress(new Device());
}
/**
* Tests the {@link LibUsb#getDeviceSpeed(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testGetDeviceDeviceSpeedWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getDeviceSpeed(new Device());
}
/**
* Tests the {@link LibUsb#getMaxPacketSize(Device, int)} method with
* uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testMaxPacketSizeWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getMaxPacketSize(new Device(), 0);
}
/**
* Tests the {@link LibUsb#getMaxIsoPacketSize(Device, int)} method with
* uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testMaxIsoPacketSizeWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getMaxIsoPacketSize(new Device(), 0);
}
/**
* Tests the {@link LibUsb#refDevice(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testRefDeviceWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.refDevice(new Device());
}
/**
* Tests the {@link LibUsb#unrefDevice(Device)} method with uninitialized
* device.
*/
@Test(expected = IllegalStateException.class)
public void testUnrefDeviceWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.unrefDevice(new Device());
}
/**
* Tests the {@link LibUsb#open(Device, DeviceHandle)} method with
* uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testOpenWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.open(new Device(), new DeviceHandle());
}
/**
* Tests the {@link LibUsb#close(DeviceHandle)} method with uninitialized
* device handle.
*/
@Test(expected = IllegalStateException.class)
public void testCloseWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.close(new DeviceHandle());
}
/**
* Tests the {@link LibUsb#getDevice(DeviceHandle)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testGetDeviceWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.getDevice(new DeviceHandle());
}
/**
* Tests the {@link LibUsb#getConfiguration(DeviceHandle, IntBuffer)} method
* with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testGetConfigurationWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.getConfiguration(new DeviceHandle(), IntBuffer.allocate(1));
}
/**
* Tests the {@link LibUsb#setConfiguration(DeviceHandle, int)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testSetConfigurationWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.setConfiguration(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#claimInterface(DeviceHandle, int)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testClaimInterfaceWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.claimInterface(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#releaseInterface(DeviceHandle, int)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testReleaseInterfaceWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.releaseInterface(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#setInterfaceAltSetting(DeviceHandle, int, int)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testSetInterfaceAltSettingWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.setInterfaceAltSetting(new DeviceHandle(), 0, 0);
}
/**
* Tests the {@link LibUsb#clearHalt(DeviceHandle, int)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testClearHaltWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.clearHalt(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#resetDevice(DeviceHandle)} method with
* uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testResetDeviceWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.resetDevice(new DeviceHandle());
}
/**
* Tests the {@link LibUsb#kernelDriverActive(DeviceHandle, int)} method
* with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testKernelDriverActiveWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.kernelDriverActive(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#detachKernelDriver(DeviceHandle, int)} method
* with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testDetachKernelDriverWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.detachKernelDriver(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#attachKernelDriver(DeviceHandle, int)} method
* with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testAttachKernelDriverWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.attachKernelDriver(new DeviceHandle(), 0);
}
/**
* Tests the {@link LibUsb#getDeviceDescriptor(Device, DeviceDescriptor)}
* method with uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testGetDeviceDescriptorWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getDeviceDescriptor(new Device(), new DeviceDescriptor());
}
/**
* Tests the
* {@link LibUsb#getStringDescriptorAscii(DeviceHandle, int, StringBuffer, int)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testGetStringDescriptorAsciiWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.getStringDescriptorAscii(new DeviceHandle(), 0,
new StringBuffer());
}
/**
* Tests the
* {@link LibUsb#getActiveConfigDescriptor(Device, ConfigDescriptor)} method
* with uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testGetActiveConfigDescriptorWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getActiveConfigDescriptor(new Device(), new ConfigDescriptor());
}
/**
* Tests the
* {@link LibUsb#getConfigDescriptor(Device, int, ConfigDescriptor)} method
* with uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testGetConfigDescriptorWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getConfigDescriptor(new Device(), 0, new ConfigDescriptor());
}
/**
* Tests the
* {@link LibUsb#getConfigDescriptorByValue(Device, int, ConfigDescriptor)}
* method with uninitialized device.
*/
@Test(expected = IllegalStateException.class)
public void testGetConfigDescriptorByValueWithUninitializedDevice()
{
assumeUsbTestsEnabled();
LibUsb.getConfigDescriptorByValue(new Device(), 0,
new ConfigDescriptor());
}
/**
* Tests the {@link LibUsb#freeConfigDescriptor(ConfigDescriptor)} method
* with uninitialized descriptor.
*/
@Test(expected = IllegalStateException.class)
public void testFreeConfigDescriptorWithUninitializedDescriptor()
{
assumeUsbTestsEnabled();
LibUsb.freeConfigDescriptor(new ConfigDescriptor());
}
/**
* Tests the
* {@link LibUsb#getDescriptor(DeviceHandle, int, int, ByteBuffer)} method
* with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testGetDescriptorWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.getDescriptor(new DeviceHandle(), 0, 0,
ByteBuffer.allocateDirect(1));
}
/**
* Tests the
* {@link LibUsb#getStringDescriptor(DeviceHandle, int, int, ByteBuffer)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testGetStringDescriptorWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.getStringDescriptor(new DeviceHandle(), 0, 0,
ByteBuffer.allocateDirect(1));
}
/**
* Tests the
* {@link LibUsb#controlTransfer(DeviceHandle, int, int, int, int, ByteBuffer, int)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testControlTransferWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.controlTransfer(new DeviceHandle(), 0, 0, 0, 0,
ByteBuffer.allocateDirect(1), 0);
}
/**
* Tests the
* {@link LibUsb#bulkTransfer(DeviceHandle, int, ByteBuffer, IntBuffer, int)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testBulkTransferWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.bulkTransfer(new DeviceHandle(), 0,
ByteBuffer.allocateDirect(1), IntBuffer.allocate(1), 0);
}
/**
* Tests the
* {@link LibUsb#interruptTransfer(DeviceHandle, int, ByteBuffer, IntBuffer, int)}
* method with uninitialized device handle.
*/
@Test(expected = IllegalStateException.class)
public void testInterruptTransferWithUninitializedHandle()
{
assumeUsbTestsEnabled();
LibUsb.interruptTransfer(new DeviceHandle(), 0,
ByteBuffer.allocateDirect(1), IntBuffer.allocate(1), 0);
}
/**
* Tests the {@link LibUsb#freeTransfer(Transfer)} method with uninitialized
* device handle.
*/
@Test(expected = IllegalStateException.class)
public void testFreeTransferWithUninitializedTransfer()
{
assumeUsbTestsEnabled();
LibUsb.freeTransfer(new Transfer());
}
/**
* Tests {@link LibUsb#openDeviceWithVidPid(Context, int, int)} with
* uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testOpenDeviceWithVidPid()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.openDeviceWithVidPid(context, 0, 0);
}
/**
* Tests {@link LibUsb#tryLockEvents(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testTryLockEventsWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.tryLockEvents(context);
}
/**
* Tests {@link LibUsb#lockEvents(Context)} with uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testLockEventsWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.lockEvents(context);
}
/**
* Tests {@link LibUsb#unlockEvents(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testUnlockEventsWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.unlockEvents(context);
}
/**
* Tests {@link LibUsb#eventHandlingOk(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testEventHandlingOkWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.eventHandlingOk(context);
}
/**
* Tests {@link LibUsb#eventHandlerActive(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testEventHandlerActiveWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.eventHandlerActive(context);
}
/**
* Tests {@link LibUsb#lockEventWaiters(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testLockEventWaitersWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.lockEventWaiters(context);
}
/**
* Tests {@link LibUsb#unlockEventWaiters(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testUnlockEventWaitersWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.unlockEventWaiters(context);
}
/**
* Tests {@link LibUsb#waitForEvent(Context, long)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testWaitForEventWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.waitForEvent(context, 53);
}
/**
* Tests
* {@link LibUsb#handleEventsTimeoutCompleted(Context, long, IntBuffer)}
* with uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testHandleEventsTimeoutCompletedWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.handleEventsTimeoutCompleted(context, 53, IntBuffer.allocate(1));
}
/**
* Tests {@link LibUsb#handleEventsTimeout(Context, long)} with
* uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testHandleEventsTimeoutWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.handleEventsTimeout(context, 53);
}
/**
* Tests {@link LibUsb#handleEvents(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testHandleEventsWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.handleEvents(context);
}
/**
* Tests {@link LibUsb#handleEventsCompleted(Context, IntBuffer)} with
* uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testHandleEventsCompletedWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.handleEventsCompleted(context, IntBuffer.allocate(1));
}
/**
* Tests {@link LibUsb#handleEventsLocked(Context, long)} with uninitialized
* USB context.
*/
@Test(expected = IllegalStateException.class)
public void testHandleEventsLockedWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.handleEventsLocked(context, 53);
}
/**
* Tests {@link LibUsb#pollfdsHandleTimeouts(Context)} with uninitialized
* USB context.
*/
@Test(expected = IllegalStateException.class)
public void testPollfdsHandleTimeoutsWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.pollfdsHandleTimeouts(context);
}
/**
* Tests {@link LibUsb#getNextTimeout(Context, IntBuffer)} with
* uninitialized USB context.
*/
@Test(expected = IllegalStateException.class)
public void testGetNextTimeoutWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.getNextTimeout(context, LongBuffer.allocate(1));
}
/**
* Tests {@link LibUsb#setPollfdNotifiers(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testSetPollfdNotifiersWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.setPollfdNotifiers(context, context.getPointer());
}
/**
* Tests {@link LibUsb#unsetPollfdNotifiers(Context)} with uninitialized USB
* context.
*/
@Test(expected = IllegalStateException.class)
public void testUnsetPollfdNotifiersWithUninitializedContext()
{
assumeUsbTestsEnabled();
final Context context = new Context();
LibUsb.unsetPollfdNotifiers(context);
}
/**
* Tests the
* {@link LibUsb#setPollfdNotifiers(Context, PollfdListener, Object)}
* method.
*/
@Test
public void testPollFdNotifiers()
{
assumeUsbTestsEnabled();
PollfdListenerMock listener = new PollfdListenerMock();
Context context = new Context();
LibUsb.init(context);
LibUsb.setPollfdNotifiers(context, listener, "test");
FileDescriptor fd = new FileDescriptor();
LibUsb.triggerPollfdAdded(fd, 53, context.getPointer());
assertEquals(53, listener.addedEvents);
assertSame(fd, listener.addedFd);
assertSame("test", listener.addedUserData);
assertNull(listener.removedFd);
assertNull(listener.removedUserData);
listener.reset();
fd = new FileDescriptor();
LibUsb.triggerPollfdRemoved(fd, context.getPointer());
assertEquals(0, listener.addedEvents);
assertNull(listener.addedFd);
assertNull(listener.addedUserData);
assertSame(fd, listener.removedFd);
assertSame("test", listener.removedUserData);
LibUsb.setPollfdNotifiers(context, null, null);
listener.reset();
fd = new FileDescriptor();
LibUsb.triggerPollfdAdded(fd, 53, context.getPointer());
assertEquals(0, listener.addedEvents);
assertNull(listener.addedFd);
assertNull(listener.addedUserData);
assertNull(listener.removedFd);
assertNull(listener.removedUserData);
listener.reset();
fd = new FileDescriptor();
LibUsb.triggerPollfdRemoved(fd, context.getPointer());
assertEquals(0, listener.addedEvents);
assertNull(listener.addedFd);
assertNull(listener.addedUserData);
assertNull(listener.removedFd);
assertNull(listener.removedUserData);
}
}
|
package org.concord.otrunk.view;
import java.awt.BorderLayout;
import java.util.Hashtable;
import javax.swing.JFrame;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.view.OTFrame;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewEntry;
import org.concord.framework.otrunk.view.OTViewFactory;
public class OTFrameManagerImpl implements OTFrameManager
{
Hashtable frameContainers = new Hashtable();
OTViewFactory viewFactory;
private JFrame jFrame;
private int oldX = 0;
private int oldY = 0;
public class FrameContainer
{
OTViewContainerPanel container;
JFrame frame;
}
public void setViewFactory(OTViewFactory viewFactory)
{
this.viewFactory = viewFactory;
}
public void putObjectInFrame(OTObject otObject,
OTFrame otFrame)
{
putObjectInFrame(otObject, null, otFrame, null);
}
public void putObjectInFrame(OTObject otObject,
OTFrame otFrame, int positionX, int positionY)
{
putObjectInFrame(otObject, null, otFrame, null, positionX, positionY);
}
public void putObjectInFrame(OTObject otObject,
org.concord.framework.otrunk.view.OTViewEntry viewEntry,
OTFrame otFrame)
{
putObjectInFrame(otObject, viewEntry, otFrame, null);
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.view.OTFrameManager#putObjectInFrame(org.concord.framework.otrunk.OTObject, org.concord.framework.otrunk.view.OTViewEntry, org.concord.framework.otrunk.view.OTFrame, java.lang.String)
*/
public void putObjectInFrame(OTObject otObject, OTViewEntry viewEntry, OTFrame otFrame, String viewMode)
{
putObjectInFrame(otObject, viewEntry, otFrame, viewMode, 30, 30);
}
public void putObjectInFrame(OTObject otObject, OTViewEntry viewEntry, OTFrame otFrame, String viewMode,
int positionX, int positionY)
{
// look up view container with the frame.
FrameContainer frameContainer =
(FrameContainer)frameContainers.get(otFrame.getGlobalId());
if(frameContainer == null || oldX != positionX || oldY != positionY) {
jFrame = new JFrame(otFrame.getTitle());
frameContainer = new FrameContainer();
frameContainer.frame = jFrame;
OTViewContainerPanel otContainer = new OTViewContainerPanel(this);
otContainer.setTopLevelContainer(true);
otContainer.setUseScrollPane(otFrame.getUseScrollPane());
frameContainer.container = otContainer;
OTViewContext factoryContext = viewFactory.getViewContext();
frameContainer.container.setOTViewFactory(factoryContext.createChildViewFactory());
jFrame.getContentPane().setLayout(new BorderLayout());
jFrame.getContentPane().add(otContainer, BorderLayout.CENTER);
jFrame.setBounds(positionX, positionY, otFrame.getWidth(), otFrame.getHeight());
oldX = positionX;
oldY = positionY;
if (otFrame.getBorderlessPopup()){
jFrame.setUndecorated(true);
}
if (otFrame.isResourceSet("alwaysOnTop")){
jFrame.setAlwaysOnTop(otFrame.getAlwaysOnTop());
}
frameContainers.put(otFrame.getGlobalId(), frameContainer);
}
// call setCurrentObject on that view container with a null
// frame
frameContainer.container.setViewMode(viewMode);
frameContainer.container.setCurrentObject(otObject, viewEntry);
frameContainer.frame.setVisible(true);
}
public void destroyFrame(){
jFrame.dispose();
}
}
|
package eu.over9000.skadi.ui;
import java.util.Objects;
import java.util.Random;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.Border;
import javafx.stage.Stage;
import javafx.util.Duration;
public class DebugSortedBug extends Application {
private static final int NUM_CHANNELS = 10;
private final ObservableList<TestEntry> entryList = FXCollections.observableArrayList(c -> new Observable[]{c.nameProperty(), c.onlineProperty()});
public static void main(final String[] args) {
Application.launch(args);
}
@Override
public void start(final Stage stage) throws Exception {
for (int i = 0; i < NUM_CHANNELS; i++) {
final TestEntry entry = new TestEntry("Entry" + i);
entryList.add(entry);
final EntryUpdateService updateService = new EntryUpdateService(entry);
updateService.start();
}
final TableView<TestEntry> table = new TableView<>();
table.setBorder(Border.EMPTY);
table.setPadding(Insets.EMPTY);
final TableColumn<TestEntry, TestEntry.EntryState> onlineColumn = new TableColumn<>("State");
onlineColumn.setCellValueFactory(p -> p.getValue().onlineProperty());
final TableColumn<TestEntry, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(p -> p.getValue().nameProperty());
table.getColumns().add(onlineColumn);
table.getColumns().add(nameColumn);
table.getSortOrder().add(onlineColumn); // if commented out the bug disappears
table.getSortOrder().add(nameColumn);
final FilteredList<TestEntry> filteredList = entryList.filtered(c -> TestEntry.EntryState.ONLINE == c.getOnline());
final SortedList<TestEntry> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(table.comparatorProperty());
table.setItems(sortedList);
final Scene scene = new Scene(table, 800, 600);
stage.setScene(scene);
stage.show();
}
private static class TestEntry {
private final StringProperty name;
private final ObjectProperty<EntryState> online;
public TestEntry(final String channelName) {
name = new ReadOnlyStringWrapper(channelName);
online = new SimpleObjectProperty<>(EntryState.UNKNOWN);
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public EntryState getOnline() {
return online.get();
}
public void setOnline(final EntryState online) {
this.online.set(online);
}
public ObjectProperty<EntryState> onlineProperty() {
return online;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TestEntry that = (TestEntry) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
public enum EntryState {UNKNOWN, OFFLINE, ONLINE}
}
private class EntryUpdateService extends ScheduledService<Void> {
private final Random RND = new Random();
public EntryUpdateService(final TestEntry toUpdate) {
setPeriod(Duration.seconds(1));
setOnSucceeded(event -> {
final TestEntry.EntryState newState = TestEntry.EntryState.values()[RND.nextInt(TestEntry.EntryState.values().length)];
toUpdate.setOnline(newState);
});
}
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
Thread.sleep(RND.nextInt(100)); // simulate REST request
return null;
}
};
}
}
}
|
package com.example;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.xml.bind.JAXBException;
import uk.org.taverna.scufl2.api.common.Scufl2Tools;
import uk.org.taverna.scufl2.api.common.URITools;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.Processor;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.io.ReaderException;
import uk.org.taverna.scufl2.api.io.WorkflowBundleIO;
import uk.org.taverna.scufl2.api.profiles.Profile;
import uk.org.taverna.scufl2.api.property.PropertyException;
import uk.org.taverna.scufl2.api.property.PropertyResource;
public class ProcessorNames {
public static void main(String[] args) throws JAXBException, IOException,
ReaderException {
WorkflowBundleIO io = new WorkflowBundleIO();
ProcessorNames processorNames = new ProcessorNames();
for (String filename : args) {
WorkflowBundle ro = io.readBundle(new File(filename),
"application/vnd.taverna.t2flow+xml");
// System.out.print(filename + ": ");
// System.out.println(processorNames.showProcessorNames(ro));
System.out.println(processorNames.showProcessorTree(ro));
}
}
private Scufl2Tools scufl2Tools = new Scufl2Tools();
private URITools uriTools = new URITools();
private Workflow findNestedWorkflow(Processor processor) {
URI NESTED_WORKFLOW = URI
.create("http://ns.taverna.org.uk/2010/activity/nested-workflow");
WorkflowBundle bundle = processor.getParent().getParent();
// Look for nested workflows
Profile mainProfile = bundle.getMainProfile();
Configuration activityConfig = scufl2Tools
.configurationForActivityBoundToProcessor(processor,
mainProfile);
if (activityConfig != null
&& activityConfig.getConfigurableType().equals(
NESTED_WORKFLOW.resolve("#Config"))) {
PropertyResource props = activityConfig.getPropertyResource();
try {
URI nestedWfRel = props
.getPropertyAsResourceURI(NESTED_WORKFLOW
.resolve("#workflow"));
URI nestedWf = uriTools.uriForBean(mainProfile).resolve(
nestedWfRel);
Workflow wf = (Workflow) uriTools.resolveUri(nestedWf, bundle);
return wf;
} catch (PropertyException ex) {
}
}
return null;
}
private void findProcessors(WorkflowBundle ro, Workflow workflow,
DefaultMutableTreeNode parent) {
for (Processor processor : workflow.getProcessors()) {
DefaultMutableTreeNode processorNode = new DefaultMutableTreeNode(
processor.getName());
parent.add(processorNode);
Workflow wf = findNestedWorkflow(processor);
if (wf != null) {
findProcessors(ro, wf, processorNode);
}
}
}
public TreeModel makeProcessorTree(WorkflowBundle workflowBundle)
throws JAXBException, IOException {
Workflow workflow = workflowBundle.getMainWorkflow();
TreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(
workflow.getName()));
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) treeModel
.getRoot();
findProcessors(workflowBundle, workflow, parent);
return treeModel;
}
public List<String> showProcessorNames(WorkflowBundle ro)
throws JAXBException, IOException {
ArrayList<String> names = new ArrayList<String>();
for (Processor processor : ro.getMainWorkflow().getProcessors()) {
names.add(processor.getName());
}
Collections.sort(names);
return names;
}
public String showProcessorTree(WorkflowBundle ro) throws JAXBException,
IOException {
TreeModel treeModel = makeProcessorTree(ro);
return treeModelAsString(treeModel);
}
public String treeModelAsString(TreeModel treeModel) {
StringBuffer sb = new StringBuffer();
Object root = treeModel.getRoot();
treeModelAsString(treeModel, root, sb, "");
return sb.toString();
}
protected void treeModelAsString(TreeModel treeModel, Object parent,
StringBuffer sb, String indentation) {
sb.append(indentation);
int childCount = treeModel.getChildCount(parent);
if (childCount == 0) {
sb.append("- ");
} else {
sb.append("+ ");
indentation = indentation + " ";
}
sb.append(parent);
sb.append("\n");
for (int i = 0; i < childCount; i++) {
Object child = treeModel.getChild(parent, i);
treeModelAsString(treeModel, child, sb, indentation);
}
}
}
|
package com.gossiperl.client;
import com.gossiperl.client.thrift.Digest;
import com.gossiperl.client.thrift.DigestAck;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class State {
public enum Status {
CONNECTED,
DISCONNECTED
}
private OverlayWorker worker;
private ArrayList<String> subscriptions;
private Status currentStatus;
private long lastTs;
private static Logger LOG = Logger.getLogger(State.class);
public State(OverlayWorker worker) {
this.subscriptions = new ArrayList<String>();
this.currentStatus = Status.DISCONNECTED;
this.worker = worker;
LOG.info("[" + this.worker.getConfiguration().getClientName() + "] State initialized.");
}
public void receive(DigestAck digestAck) {
if ( this.currentStatus == Status.DISCONNECTED ) {
this.worker.getListener().connected( this.worker );
if ( this.subscriptions.size() > 0 ) {
this.worker.getMessaging().digestSubscribe(this.subscriptions);
}
}
this.currentStatus = Status.CONNECTED;
this.lastTs = digestAck.getHeartbeat();
}
public void start() {
(new Thread(new StateTask())).start();
LOG.info("[" + this.worker.getConfiguration().getClientName() + "] State task started.");
}
public List<String> subscribe(List<String> events) {
this.worker.getMessaging().digestSubscribe(events);
this.subscriptions.addAll( events );
return this.subscriptions;
}
public List<String> unsubscribe(List<String> events) {
this.worker.getMessaging().digestUnsubscribe(events);
this.subscriptions.removeAll( events );
return this.subscriptions;
}
public Status getCurrentState() {
return this.currentStatus;
}
public List<String> getSubscriptions() {
return this.subscriptions;
}
private void sendDigest() {
Digest digest = new Digest();
digest.setSecret( this.worker.getConfiguration().getClientSecret() );
digest.setId(UUID.randomUUID().toString());
digest.setHeartbeat(Util.getTimestamp());
digest.setPort(this.worker.getConfiguration().getClientPort());
digest.setName(this.worker.getConfiguration().getClientName());
LOG.debug("[" + this.worker.getConfiguration().getClientName() + "] Offering digest " + digest.getId() + ".");
this.worker.getMessaging().send( digest );
}
class StateTask implements Runnable {
public void run() {
try {
Thread.sleep(1000);
while (worker.isWorking()) {
sendDigest();
if ( Util.getTimestamp() - lastTs > 5f ) {
LOG.debug("[" + worker.getConfiguration().getClientName() + "] Announcing disconnected.");
if (currentStatus == Status.CONNECTED) {
worker.getListener().disconnected(worker);
}
currentStatus = Status.DISCONNECTED;
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
LOG.error("[" + worker.getConfiguration().getClientName() + "] Error in state worker. State worker will stop. Reason: ", ex);
break;
}
}
LOG.debug("[" + worker.getConfiguration().getClientName() + "] Announcing disconnected. Worker stopped.");
worker.getListener().disconnected( worker );
currentStatus = Status.DISCONNECTED;
LOG.info("[" + worker.getConfiguration().getClientName() + "] Stopping state service.");
} catch (InterruptedException ex) {
LOG.error("[" + worker.getConfiguration().getClientName() + "] Error while starting state worker. Reason: ", ex);
}
}
}
}
|
package io.teknek.nibiru.engine;
import io.teknek.nibiru.Configuration;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import junit.framework.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class SSTableTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void aTest() throws IOException{
File tempFolder = testFolder.newFolder("sstable");
System.out.println("Test folder: " + testFolder.getRoot());
Configuration configuration = new Configuration();
configuration.setSstableDirectory(tempFolder);
Memtable m = new Memtable();
Keyspace ks1 = MemtableTest.keyspaceWithNaturalPartitioner();
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition("row1"), "column2", "c", 1, 0L);
Assert.assertEquals("c", m.get(ks1.getKeyspaceMetadata().getPartitioner().partition("row1"), "column2").getValue());
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition("row1"), "column2", "d", 2, 0L);
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition("row1"), "column3", "e", 2, 0L);
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition("row2"), "column1", "e", 2, 0L);
SSTable s = new SSTable();
s.flushToDisk("1", configuration, m);
s.open("1", configuration);
long x = System.currentTimeMillis();
for (int i = 0 ; i < 50000 ; i++) {
Assert.assertEquals("d", s.get("row1", "column2").getValue());
Assert.assertEquals("e", s.get("row1", "column3").getValue());
Assert.assertEquals("e", s.get("row2", "column1").getValue());
}
System.out.println((System.currentTimeMillis() - x));
}
@Test
public void aBiggerTest() throws IOException, InterruptedException{
File tempFolder = testFolder.newFolder("sstable");
System.out.println("Test folder: " + testFolder.getRoot());
Configuration configuration = new Configuration();
configuration.setSstableDirectory(tempFolder);
Memtable m = new Memtable();
Keyspace ks1 = MemtableTest.keyspaceWithNaturalPartitioner();
NumberFormat nf = new DecimalFormat("00000");
for (int i = 0; i < 10000; i++) {
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition(nf.format(i)), "column2", "c", 1, 0L);
m.put(ks1.getKeyspaceMetadata().getPartitioner().partition(nf.format(i)), "column3", "c", 1, 0L);
}
SSTable s = new SSTable();
s.flushToDisk("1", configuration, m);
s.open("1", configuration);
{
long x = System.currentTimeMillis();
for (int i = 0 ; i < 50000 ; i++) {
Assert.assertEquals("c", s.get("00001", "column2").getValue());
}
System.out.println("index match " + (System.currentTimeMillis() - x));
}
{
long x = System.currentTimeMillis();
for (int i = 0 ; i < 50000 ; i++) {
Assert.assertEquals("c", s.get("08999", "column2").getValue());
}
System.out.println("far from index " +(System.currentTimeMillis() - x));
}
{
long x = System.currentTimeMillis();
for (int i = 0 ; i < 50000 ; i++) {
Assert.assertEquals("c", s.get("00001", "column2").getValue());
}
System.out.println("index match " + (System.currentTimeMillis() - x));
}
{
long x = System.currentTimeMillis();
for (int i = 0 ; i < 50000 ; i++) {
Assert.assertEquals("c", s.get("08999", "column2").getValue());
}
System.out.println("far from index " +(System.currentTimeMillis() - x));
}
}
}
|
package com.nucleus.vecmath;
/**
* This class is NOT thread safe since it uses static temp float arrays
* 4 x 4 matrix laid out contiguously in memory, translation component is at the 3rd, 7th, and 11th element
* Left handed coordinate system
* Use this for classes that can represent the data as a matrix, for instance a scale or translation
*
* Matrices are 4 x 4 column-vector matrices stored in column-major
* order:
*
* @author Richard Sahlin
*
*/
public abstract class Matrix extends VecMath {
/**
* Number of elements (values) in a matrix
*/
public final static int MATRIX_ELEMENTS = 16;
/**
* Identity matrix to be used to read from
* DO NOT WRITE TO THIS MATRIX
*/
public final static float[] IDENTITY_MATRIX = Matrix.setIdentity(Matrix.createMatrix(), 0);
/**
* Used to store the transform
*/
transient protected float[] matrix = Matrix.createMatrix();
private static float[] temp = new float[16];
private static float[] result = new float[16];
/**
* Returns a matrix with the values contained in the implementing class, ie the rotate, translate and scale values.
*
* @return Matrix with the data contained in the implementing class
*/
public abstract float[] getMatrix();
/**
* Creates a new, empty, matrix
*
* @return
*/
public final static float[] createMatrix() {
return new float[MATRIX_ELEMENTS];
}
/**
* Sets the matrix to identity.
*
* @param matrix The matrix
* @offset Offset into array where matrix values are stored.
* @return The matrix, this is the same as passed into this method
*/
public final static float[] setIdentity(float[] matrix, int offset) {
matrix[offset++] = 1f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 1f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 1f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 0f;
matrix[offset++] = 1f;
return matrix;
}
/**
* Scales the matrix
*
* @param m
* @param mOffset
* @param x
* @param y
* @param z
*/
public static void scaleM(float[] matrix, int offset, float[] scale) {
for (int i = 0; i < 4; i++) {
int index = offset + i;
matrix[index] *= scale[X];
matrix[index + 4] *= scale[Y];
matrix[index + 8] *= scale[Z];
}
}
/**
* Multiply a number of 2 element vector with a matrix, the resultvectors will be transformed using the matrix
* and stored sequentially
*
* @param matrix
* @param offset Offset in matrix array where matrix starts
* @param vec
* @param resultVec The output vector, this may not be the same as vec
* @param count Number of vectors to transform
*/
public final static void transformVec2(float[] matrix, int offset, float[] vec, float[] resultVec, int count) {
int output = 0;
int input = 0;
for (int i = 0; i < count; i++) {
resultVec[output++] = matrix[offset] * vec[input] + matrix[offset + 1] * vec[input + 1]
+ matrix[offset + 3];
resultVec[output++] = matrix[offset + 4] * vec[input] + matrix[offset + 5] * vec[input + 1]
+ matrix[offset + 7];
input += 2;
}
}
/**
* Transposes a 4 x 4 matrix.
*
* @param mTrans the array that holds the output inverted matrix
* @param mTransOffset an offset into mInv where the inverted matrix is
* stored.
* @param m the input array
* @param mOffset an offset into m where the matrix is stored.
*/
public static void transposeM(float[] mTrans, int mTransOffset, float[] m,
int mOffset) {
for (int i = 0; i < 4; i++) {
int mBase = i * 4 + mOffset;
mTrans[i + mTransOffset] = m[mBase];
mTrans[i + 4 + mTransOffset] = m[mBase + 1];
mTrans[i + 8 + mTransOffset] = m[mBase + 2];
mTrans[i + 12 + mTransOffset] = m[mBase + 3];
}
}
/**
* Concatenate Matrix m1 with Matrix m2 and store the result in destination matrix.
*
* @param m1
* @param m2
* @param destination
*/
public final static void mul4(float[] m1, float[] m2, float[] destination) {
// Concatenate matrix 1 with matrix 2, 4*4
destination[0] = (m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]);
destination[4] = (m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]);
destination[8] = (m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]);
destination[12] = (m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]);
destination[1] = (m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]);
destination[5] = (m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]);
destination[9] = (m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]);
destination[13] = (m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]);
destination[2] = (m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]);
destination[6] = (m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]);
destination[10] = (m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]);
destination[14] = (m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]);
destination[3] = (m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]);
destination[7] = (m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]);
destination[11] = (m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]);
destination[15] = (m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]);
}
/**
* Concatenate matrix with matrix2 and store the result in matrix
*
* @param matrix Source 1 matrix - matrix1 * matrix2 stored here
* @param matrix2 Source 2 matrix
*/
public static void mul4(float[] matrix, float[] matrix2) {
float temp_float1, temp_float2, temp_float3, temp_float4;
// Concatenate this with matrix 2, 4*4
temp_float1 = (matrix[0] * matrix2[0] + matrix[1] * matrix2[4] + matrix[2] * matrix2[8] +
matrix[3] * matrix2[12]);
temp_float2 = (matrix[0] * matrix2[1] + matrix[1] * matrix2[5] + matrix[2] * matrix2[9] +
matrix[3] * matrix2[13]);
temp_float3 = (matrix[0] * matrix2[2] + matrix[1] * matrix2[6] + matrix[2] * matrix2[10] +
matrix[3] * matrix2[14]);
temp_float4 = (matrix[0] * matrix2[3] + matrix[1] * matrix2[7] + matrix[2] * matrix2[11] +
matrix[3] * matrix2[15]);
matrix[0] = temp_float1;
matrix[4] = temp_float2;
matrix[8] = temp_float3;
matrix[12] = temp_float4;
temp_float1 = (matrix[4] * matrix2[0] + matrix[5] * matrix2[4] + matrix[6] * matrix2[8] +
matrix[7] * matrix2[12]);
temp_float2 = (matrix[4] * matrix2[1] + matrix[5] * matrix2[5] + matrix[6] * matrix2[9] +
matrix[7] * matrix2[13]);
temp_float3 = (matrix[4] * matrix2[2] + matrix[5] * matrix2[6] + matrix[6] * matrix2[10] +
matrix[7] * matrix2[14]);
temp_float4 = (matrix[4] * matrix2[3] + matrix[5] * matrix2[7] + matrix[6] * matrix2[11] +
matrix[7] * matrix2[15]);
matrix[1] = temp_float1;
matrix[5] = temp_float2;
matrix[9] = temp_float3;
matrix[13] = temp_float4;
temp_float1 = (matrix[8] * matrix2[0] + matrix[9] * matrix2[4] + matrix[10] * matrix2[8] +
matrix[11] * matrix2[12]);
temp_float2 = (matrix[8] * matrix2[1] + matrix[9] * matrix2[5] + matrix[10] * matrix2[9] +
matrix[11] * matrix2[13]);
temp_float3 = (matrix[8] * matrix2[2] + matrix[9] * matrix2[6] + matrix[10] * matrix2[10] +
matrix[11] * matrix2[14]);
temp_float4 = (matrix[8] * matrix2[3] + matrix[9] * matrix2[7] + matrix[10] * matrix2[11] +
matrix[11] * matrix2[15]);
matrix[2] = temp_float1;
matrix[6] = temp_float2;
matrix[10] = temp_float3;
matrix[14] = temp_float4;
temp_float1 = (matrix[12] * matrix2[0] + matrix[13] * matrix2[4] + matrix[14] * matrix2[8] +
matrix[15] * matrix2[12]);
temp_float2 = (matrix[12] * matrix2[1] + matrix[13] * matrix2[5] + matrix[14] * matrix2[9] +
matrix[15] * matrix2[13]);
temp_float3 = (matrix[12] * matrix2[2] + matrix[13] * matrix2[6] + matrix[14] * matrix2[10]
+ matrix[15] * matrix2[14]);
temp_float4 = (matrix[12] * matrix2[3] + matrix[13] * matrix2[7] + matrix[14] * matrix2[11]
+ matrix[15] * matrix2[15]);
matrix[3] = temp_float1;
matrix[7] = temp_float2;
matrix[11] = temp_float3;
matrix[15] = temp_float4;
}
/**
* Inverts a 4 x 4 matrix.
*
* @param mInv the array that holds the output inverted matrix
* @param mInvOffset an offset into mInv where the inverted matrix is
* stored.
* @param m the input array
* @param mOffset an offset into m where the matrix is stored.
* @return true if the matrix could be inverted, false if it could not.
*/
public static boolean invertM(float[] mInv, int mInvOffset, float[] m,
int mOffset) {
// Invert a 4 x 4 matrix using Cramer's Rule
// array of transpose source matrix
float[] src = new float[16];
// transpose matrix
transposeM(src, 0, m, mOffset);
// temp array for pairs
float[] tmp = new float[12];
// calculate pairs for first 8 elements (cofactors)
tmp[0] = src[10] * src[15];
tmp[1] = src[11] * src[14];
tmp[2] = src[9] * src[15];
tmp[3] = src[11] * src[13];
tmp[4] = src[9] * src[14];
tmp[5] = src[10] * src[13];
tmp[6] = src[8] * src[15];
tmp[7] = src[11] * src[12];
tmp[8] = src[8] * src[14];
tmp[9] = src[10] * src[12];
tmp[10] = src[8] * src[13];
tmp[11] = src[9] * src[12];
// Holds the destination matrix while we're building it up.
float[] dst = new float[16];
// calculate first 8 elements (cofactors)
dst[0] = tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7];
dst[0] -= tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7];
dst[1] = tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7];
dst[1] -= tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7];
dst[2] = tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7];
dst[2] -= tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7];
dst[3] = tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6];
dst[3] -= tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6];
dst[4] = tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3];
dst[4] -= tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3];
dst[5] = tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3];
dst[5] -= tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3];
dst[6] = tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3];
dst[6] -= tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3];
dst[7] = tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2];
dst[7] -= tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2];
// calculate pairs for second 8 elements (cofactors)
tmp[0] = src[2] * src[7];
tmp[1] = src[3] * src[6];
tmp[2] = src[1] * src[7];
tmp[3] = src[3] * src[5];
tmp[4] = src[1] * src[6];
tmp[5] = src[2] * src[5];
tmp[6] = src[0] * src[7];
tmp[7] = src[3] * src[4];
tmp[8] = src[0] * src[6];
tmp[9] = src[2] * src[4];
tmp[10] = src[0] * src[5];
tmp[11] = src[1] * src[4];
// calculate second 8 elements (cofactors)
dst[8] = tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15];
dst[8] -= tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15];
dst[9] = tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15];
dst[9] -= tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15];
dst[10] = tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15];
dst[10] -= tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15];
dst[11] = tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14];
dst[11] -= tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14];
dst[12] = tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9];
dst[12] -= tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10];
dst[13] = tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10];
dst[13] -= tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8];
dst[14] = tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8];
dst[14] -= tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9];
dst[15] = tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9];
dst[15] -= tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8];
// calculate determinant
float det = src[0] * dst[0] + src[1] * dst[1] + src[2] * dst[2] + src[3]
* dst[3];
if (det == 0.0f) {
}
// calculate matrix inverse
det = 1 / det;
for (int j = 0; j < 16; j++)
mInv[j + mInvOffset] = dst[j] * det;
return true;
}
/**
* Computes an orthographic projection matrix for a left handed coordinate system.
*
* @param m returns the result
* @param mOffset
* @param left
* @param right
* @param bottom
* @param top
* @param near
* @param far
*/
public static void orthoM(float[] m, int mOffset,
float left, float right, float bottom, float top,
float near, float far) {
if (left == right) {
throw new IllegalArgumentException("left == right");
}
if (bottom == top) {
throw new IllegalArgumentException("bottom == top");
}
if (near == far) {
throw new IllegalArgumentException("near == far");
}
final float r_width = 1.0f / (right - left);
final float r_height = 1.0f / (top - bottom);
final float r_depth = 1.0f / (far - near);
final float x = 2.0f * (r_width);
final float y = 2.0f * (r_height);
final float z = 2.0f * (r_depth);
final float tx = -(right + left) * r_width;
final float ty = -(top + bottom) * r_height;
final float tz = -(far + near) * r_depth;
m[mOffset + 0] = x;
m[mOffset + 5] = y;
m[mOffset + 10] = z;
m[mOffset + 12] = tx;
m[mOffset + 13] = ty;
m[mOffset + 14] = tz;
m[mOffset + 15] = 1.0f;
m[mOffset + 1] = 0.0f;
m[mOffset + 2] = 0.0f;
m[mOffset + 3] = 0.0f;
m[mOffset + 4] = 0.0f;
m[mOffset + 6] = 0.0f;
m[mOffset + 7] = 0.0f;
m[mOffset + 8] = 0.0f;
m[mOffset + 9] = 0.0f;
m[mOffset + 11] = 0.0f;
// float[] transpose = Matrix.createMatrix();
// transposeM(transpose, 0, m, 0);
// System.arraycopy(transpose, 0, m, 0, 16);
}
/**
* Define a projection matrix in terms of six clip planes
*
* @param m the float array that holds the perspective matrix
* @param offset the offset into float array m where the perspective
* matrix data is written
* @param left
* @param right
* @param bottom
* @param top
* @param near
* @param far
*/
public static void frustumM(float[] m, int offset,
float left, float right, float bottom, float top,
float near, float far) {
if (left == right) {
throw new IllegalArgumentException("left == right");
}
if (top == bottom) {
throw new IllegalArgumentException("top == bottom");
}
if (near == far) {
throw new IllegalArgumentException("near == far");
}
if (near <= 0.0f) {
throw new IllegalArgumentException("near <= 0.0f");
}
if (far <= 0.0f) {
throw new IllegalArgumentException("far <= 0.0f");
}
final float r_width = 1.0f / (right - left);
final float r_height = 1.0f / (top - bottom);
final float r_depth = 1.0f / (near - far);
final float x = 2.0f * (near * r_width);
final float y = 2.0f * (near * r_height);
final float A = 2.0f * ((right + left) * r_width);
final float B = (top + bottom) * r_height;
final float C = -(far + near) * r_depth;
final float D = 2.0f * (far * near * r_depth);
m[offset + 0] = x;
m[offset + 5] = y;
m[offset + 8] = A;
m[offset + 9] = B;
m[offset + 10] = C;
m[offset + 14] = D;
m[offset + 11] = 1.0f;
m[offset + 1] = 0.0f;
m[offset + 2] = 0.0f;
m[offset + 3] = 0.0f;
m[offset + 4] = 0.0f;
m[offset + 6] = 0.0f;
m[offset + 7] = 0.0f;
m[offset + 12] = 0.0f;
m[offset + 13] = 0.0f;
m[offset + 15] = 0.0f;
}
/**
* Computes the length of a vector
*
* @param x x coordinate of a vector
* @param y y coordinate of a vector
* @param z z coordinate of a vector
* @return the length of a vector
*/
public static float length(float x, float y, float z) {
return (float) Math.sqrt(x * x + y * y + z * z);
}
/**
* Sets matrix m to the identity matrix.
*
* @param sm returns the result
* @param smOffset index into sm where the result matrix starts
*/
public static void setIdentityM(float[] sm, int smOffset) {
for (int i = 0; i < 16; i++) {
sm[smOffset + i] = 0;
}
for (int i = 0; i < 16; i += 5) {
sm[smOffset + i] = 1.0f;
}
}
/**
* Scales matrix m in place by sx, sy, and sz
*
* @param m matrix to scale
* @param mOffset index into m where the matrix starts
* @param x scale factor x
* @param y scale factor y
* @param z scale factor z
*/
public static void scaleM(float[] m, int mOffset,
float x, float y, float z) {
for (int i = 0; i < 4; i++) {
int mi = mOffset + i;
m[mi] *= x;
m[4 + mi] *= y;
m[8 + mi] *= z;
}
}
/**
* Translate the matrix, OpenGL row wise, along x,y and z axis
*
* @param matrix
* @param x
* @param y
* @param z
*/
public final static void translate(float[] matrix, float x, float y, float z) {
matrix[3] = x;
matrix[7] = y;
matrix[11] = z;
}
/**
* Translate the matrix, OpenGL row wise, along x,y and z axis
*
* @param matrix
* @param translate
*/
public final static void translate(float[] matrix, float[] translate) {
translate(matrix, translate[0], translate[1], translate[2]);
}
public static void rotateM(float[] m, AxisAngle axisAngle) {
if (axisAngle != null) {
// TODO - should a check be made for 0 values in X,Y,Z axis which results in NaN?
float[] values = axisAngle.axisAngle;
setRotateM(temp, 0, values[AxisAngle.ANGLE], values[AxisAngle.X], values[AxisAngle.Y], values[AxisAngle.Z]);
mul4(m, temp, result);
System.arraycopy(result, 0, m, 0, 16);
}
}
/**
* Rotates matrix m by angle a (in degrees) around the axis (x, y, z) using left handed coordinate system.
*
* @param rm returns the result
* @param rmOffset index into rm where the result matrix starts
* @param a angle to rotate in radians
* @param x scale factor x
* @param y scale factor y
* @param z scale factor z
*/
public static void setRotateM(float[] rm, int rmOffset,
float a, float x, float y, float z) {
rm[rmOffset + 3] = 0;
rm[rmOffset + 7] = 0;
rm[rmOffset + 11] = 0;
rm[rmOffset + 12] = 0;
rm[rmOffset + 13] = 0;
rm[rmOffset + 14] = 0;
rm[rmOffset + 15] = 1;
float s = (float) Math.sin(a);
float c = (float) Math.cos(a);
if (1.0f == x && 0.0f == y && 0.0f == z) {
rm[rmOffset + 5] = c;
rm[rmOffset + 10] = c;
rm[rmOffset + 6] = s;
rm[rmOffset + 9] = -s;
rm[rmOffset + 1] = 0;
rm[rmOffset + 2] = 0;
rm[rmOffset + 4] = 0;
rm[rmOffset + 8] = 0;
rm[rmOffset + 0] = 1;
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
rm[rmOffset + 0] = c;
rm[rmOffset + 10] = c;
rm[rmOffset + 8] = s;
rm[rmOffset + 2] = -s;
rm[rmOffset + 1] = 0;
rm[rmOffset + 4] = 0;
rm[rmOffset + 6] = 0;
rm[rmOffset + 9] = 0;
rm[rmOffset + 5] = 1;
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
rm[rmOffset + 0] = c;
rm[rmOffset + 5] = c;
rm[rmOffset + 1] = s;
rm[rmOffset + 4] = -s;
rm[rmOffset + 2] = 0;
rm[rmOffset + 6] = 0;
rm[rmOffset + 8] = 0;
rm[rmOffset + 9] = 0;
rm[rmOffset + 10] = 1;
} else {
float len = length(x, y, z);
if (1.0f != len) {
float recipLen = 1.0f / len;
x *= recipLen;
y *= recipLen;
z *= recipLen;
}
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
rm[rmOffset + 0] = x * x * nc + c;
rm[rmOffset + 4] = xy * nc - zs;
rm[rmOffset + 8] = zx * nc + ys;
rm[rmOffset + 1] = xy * nc + zs;
rm[rmOffset + 5] = y * y * nc + c;
rm[rmOffset + 9] = yz * nc - xs;
rm[rmOffset + 2] = zx * nc - ys;
rm[rmOffset + 6] = yz * nc + xs;
rm[rmOffset + 10] = z * z * nc + c;
}
}
/**
* Exctract the scale from the given matrix
*
* @param matrix
* @param result
*/
public static final void getScale(float[] matrix, float[] result) {
result[0] = (float) Math.sqrt(matrix[0] * matrix[0] + matrix[4] * matrix[4] + matrix[8] * matrix[8]);
result[1] = (float) Math.sqrt(matrix[1] * matrix[1] + matrix[5] * matrix[5] + matrix[9] * matrix[9]);
result[2] = (float) Math.sqrt(matrix[2] * matrix[2] + matrix[6] * matrix[6] + matrix[10] * matrix[10]);
}
}
|
package net.joelinn.quartz;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.joelinn.quartz.jobstore.RedisJobStoreSchema;
import net.joelinn.quartz.jobstore.AbstractRedisStorage;
import net.joelinn.quartz.jobstore.RedisStorage;
import net.joelinn.quartz.jobstore.RedisTriggerState;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.quartz.*;
import org.quartz.impl.calendar.WeeklyCalendar;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.spi.OperableTrigger;
import org.quartz.spi.SchedulerSignaler;
import org.quartz.spi.TriggerFiredResult;
import java.util.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
/**
* Joe Linn
* 7/15/2014
*/
public class StoreTriggerTest extends BaseTest{
@Test
public void storeTrigger() throws Exception {
CronTriggerImpl trigger = getCronTrigger();
trigger.getJobDataMap().put("foo", "bar");
jobStore.storeTrigger(trigger, false);
final String triggerHashKey = schema.triggerHashKey(trigger.getKey());
Map<String, String> triggerMap = jedis.hgetAll(triggerHashKey);
assertThat(triggerMap, hasKey("description"));
assertEquals(trigger.getDescription(), triggerMap.get("description"));
assertThat(triggerMap, hasKey("trigger_class"));
assertEquals(trigger.getClass().getName(), triggerMap.get("trigger_class"));
assertTrue("The trigger hash key is not a member of the triggers set.", jedis.sismember(schema.triggersSet(), triggerHashKey));
assertTrue("The trigger group set key is not a member of the trigger group set.", jedis.sismember(schema.triggerGroupsSet(), schema.triggerGroupSetKey(trigger.getKey())));
assertTrue(jedis.sismember(schema.triggerGroupSetKey(trigger.getKey()), triggerHashKey));
assertTrue(jedis.sismember(schema.jobTriggersSetKey(trigger.getJobKey()), triggerHashKey));
String triggerDataMapHashKey = schema.triggerDataMapHashKey(trigger.getKey());
MatcherAssert.assertThat(jedis.exists(triggerDataMapHashKey), equalTo(true));
MatcherAssert.assertThat(jedis.hget(triggerDataMapHashKey, "foo"), equalTo("bar"));
}
@Test(expected = JobPersistenceException.class)
public void storeTriggerNoReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), false);
jobStore.storeTrigger(getCronTrigger(), false);
}
@Test
public void storeTriggerWithReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), true);
jobStore.storeTrigger(getCronTrigger(), true);
}
@Test
public void retrieveTrigger() throws Exception {
CronTriggerImpl cronTrigger = getCronTrigger();
jobStore.storeJob(getJobDetail(), false);
jobStore.storeTrigger(cronTrigger, false);
OperableTrigger operableTrigger = jobStore.retrieveTrigger(cronTrigger.getKey());
assertThat(operableTrigger, instanceOf(CronTriggerImpl.class));
CronTriggerImpl retrievedTrigger = (CronTriggerImpl) operableTrigger;
assertEquals(cronTrigger.getCronExpression(), retrievedTrigger.getCronExpression());
assertEquals(cronTrigger.getTimeZone(), retrievedTrigger.getTimeZone());
assertEquals(cronTrigger.getStartTime(), retrievedTrigger.getStartTime());
}
@Test
public void removeTrigger() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
trigger1.getJobDataMap().put("foo", "bar");
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
jobStore.removeTrigger(trigger1.getKey());
// ensure that the trigger was removed, but the job was not
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
// remove the second trigger
jobStore.removeTrigger(trigger2.getKey());
// ensure that both the trigger and job were removed
assertThat(jobStore.retrieveTrigger(trigger2.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), nullValue());
MatcherAssert.assertThat(jedis.exists(schema.triggerDataMapHashKey(trigger1.getKey())), equalTo(false));
}
@Test
public void getTriggersForJob() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
List<OperableTrigger> triggers = jobStore.getTriggersForJob(job.getKey());
assertThat(triggers, hasSize(2));
}
@Test
public void getNumberOfTriggers() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
int numberOfTriggers = jobStore.getNumberOfTriggers();
assertEquals(4, numberOfTriggers);
}
@Test
public void getTriggerKeys() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
Set<TriggerKey> triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEquals("group1"));
assertThat(triggerKeys, hasSize(2));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"), new TriggerKey("trigger1", "group1")));
jobStore.storeTrigger(getCronTrigger("trigger4", "triggergroup1", job.getKey()), false);
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupContains("group"));
assertThat(triggerKeys, hasSize(5));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(triggerKeys, hasSize(3));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"),
new TriggerKey("trigger1", "group1"), new TriggerKey("trigger4", "triggergroup1")));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupStartsWith("trig"));
assertThat(triggerKeys, hasSize(1));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger4", "triggergroup1")));
}
@Test
public void getTriggerGroupNames() throws Exception {
List<String> triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, not(nullValue()));
assertThat(triggerGroupNames, hasSize(0));
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, hasSize(3));
assertThat(triggerGroupNames, containsInAnyOrder("group3", "group2", "group1"));
}
@Test
public void getTriggerState() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// attempt to retrieve the state of a non-existent trigger
Trigger.TriggerState state = jobStore.getTriggerState(new TriggerKey("foobar"));
assertEquals(Trigger.TriggerState.NONE, state);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(cronTrigger, false);
// the newly-stored trigger's state should be NONE
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
// set the trigger's state
storageDriver.setTriggerState(RedisTriggerState.WAITING, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
// the trigger's state should now be NORMAL
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
}
@Test
public void pauseTrigger() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
cronTrigger.setNextFireTime(new Date(System.currentTimeMillis()));
jobStore.storeTrigger(cronTrigger, false);
// set the trigger's state to COMPLETED
storageDriver.setTriggerState(RedisTriggerState.COMPLETED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should not have changed
assertEquals(Trigger.TriggerState.COMPLETE, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to BLOCKED
storageDriver.setTriggerState(RedisTriggerState.BLOCKED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to ACQUIRED
storageDriver.setTriggerState(RedisTriggerState.ACQUIRED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
}
@Test
public void pauseTriggersEquals() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void pauseTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedTriggerGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("group"));
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group2"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void pauseTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("oup1"));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group1", "foogroup1"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void resumeTrigger() throws Exception {
// create and store a job and trigger
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger = getCronTrigger("trigger1", "group1", job.getKey());
trigger.computeFirstFireTime(new WeeklyCalendar());
jobStore.storeTrigger(trigger, false);
// pause the trigger
jobStore.pauseTrigger(trigger.getKey());
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
// resume the trigger
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should now be NORMAL
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
// attempt to resume the trigger, again
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should not have changed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
@Test
public void resumeTriggersEquals() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void resumeTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
}
@Test
public void resumeTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "mygroup1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
}
@Test
public void getPausedTriggerGroups() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
pausedGroups.addAll(jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group3")));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group3", "group1"));
// retrieve paused trigger groups
Set<String> pausedTriggerGroups = jobStore.getPausedTriggerGroups();
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group3"));
}
@Test
public void pauseAndResumeAll() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
// ensure that all triggers are in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
jobStore.pauseAll();
// ensure that all triggers were paused
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
}
}
// resume all triggers
jobStore.resumeAll();
// ensure that all triggers are again in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
}
@Test
@SuppressWarnings("unchecked")
public void triggersFired() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2, "* * * * * ?");
// disallow concurrent execution for one of the jobs
Map.Entry<JobDetail, Set<? extends Trigger>> firstEntry = jobsAndTriggers.entrySet().iterator().next();
JobDetail nonConcurrentKey = firstEntry.getKey().getJobBuilder().ofType(TestJobNonConcurrent.class).build();
Set<? extends Trigger> nonConcurrentTriggers = firstEntry.getValue();
jobsAndTriggers.remove(firstEntry.getKey());
jobsAndTriggers.put(nonConcurrentKey, nonConcurrentTriggers);
jobStore.storeCalendar("testCalendar", new WeeklyCalendar(), false, true);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
List<OperableTrigger> acquiredTriggers = jobStore.acquireNextTriggers(System.currentTimeMillis() - 1000, 500, 4000);
assertThat(acquiredTriggers, hasSize(13));
int lockedTriggers = 0;
// ensure that all triggers are in the NORMAL state and have been ACQUIRED
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
String triggerHashKey = schema.triggerHashKey(trigger.getKey());
if (jobDetailSetEntry.getKey().isConcurrentExectionDisallowed()) {
if (jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey) != null) {
assertThat("acquired trigger should be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
lockedTriggers++;
} else {
assertThat("non-acquired trigger should not be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), nullValue());
}
} else {
assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
}
}
}
assertThat(lockedTriggers, equalTo(1));
Set<? extends OperableTrigger> triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(0).getValue();
List<TriggerFiredResult> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
assertThat("exactly one trigger fired for job with concurrent execution disallowed", triggerFiredResults, hasSize(1));
triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(1).getValue();
triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
assertThat("all triggers fired for job with concurrent execution allowed", triggerFiredResults, hasSize(4));
}
@Test
public void replaceTrigger() throws Exception {
assertFalse(jobStore.replaceTrigger(TriggerKey.triggerKey("foo", "bar"), getCronTrigger()));
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(2));
List<TriggerKey> jobTriggerKeys = new ArrayList<>(jobTriggers.size());
for (OperableTrigger jobTrigger : jobTriggers) {
jobTriggerKeys.add(jobTrigger.getKey());
}
assertThat(jobTriggerKeys, containsInAnyOrder(trigger2.getKey(), newTrigger.getKey()));
}
@Test
public void replaceTriggerSingleTriggerNonDurableJob() throws Exception {
// store trigger and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
storeJobAndTriggers(job, trigger1);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(1));
// ensure that the job still exists
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
}
@Test(expected = JobPersistenceException.class)
public void replaceTriggerWithDifferentJob() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(trigger1, false);
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
jobStore.storeTrigger(trigger2, false);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", JobKey.jobKey("foo", "bar"));
jobStore.replaceTrigger(trigger1.getKey(), newTrigger);
}
}
|
package com.pollistics.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.bson.types.ObjectId;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.HashMap;
import java.util.Objects;
@Document(collection="polls")
public class Poll {
@Id
private ObjectId id;
@Length(min=3, max=500, message="Poll title must be be between 3 and 500 characters")
private String title;
private HashMap<String,Integer> options;
private User user;
@Indexed(unique = true, sparse = true)
private String slug;
// todo: orden these constructors with `this(...arg)`
public Poll(String title, HashMap<String,Integer> options) {
this.title = title;
this.options = options;
this.slug = createSlug();
}
private String createSlug() {
// random three-word combo
return "meme-meme-meme";
}
public Poll(ObjectId id, String title, HashMap<String, Integer> options) {
this.id = id;
this.title = title;
this.options = options;
this.slug = createSlug();
}
public Poll(String title, HashMap<String,Integer> options, String slug) {
this.title = title;
this.options = options;
this.slug = slug;
}
public Poll(String title, HashMap<String,Integer> options, User user, String slug) {
this.title = title;
this.options = options;
this.user = user;
this.slug = slug;
}
public Poll(String title, HashMap<String,Integer> options, User user) {
this.title = title;
this.options = options;
this.user = user;
this.slug = createSlug();
}
public Poll() {
}
public String getId() {
return id.toHexString();
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public HashMap<String, Integer> getOptions() {
return options;
}
public void setOptions(HashMap<String, Integer> options) {
this.options = options;
}
@JsonIgnore
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getSlug() {
return slug;
}
public boolean vote(String option) {
if(!options.containsKey(option)) {
return false;
} else {
int val = options.get(option);
val++;
options.put(option,val);
return true;
}
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
Poll poll = (Poll) obj;
return this.getId().equals(poll.getId());
}
}
|
package org.adridadou;
import org.adridadou.ethereum.*;
import org.adridadou.ethereum.ethj.TestConfig;
import org.adridadou.ethereum.ethj.provider.EthereumFacadeProvider;
import org.adridadou.ethereum.ethj.provider.PrivateEthereumFacadeProvider;
import org.adridadou.ethereum.keystore.AccountProvider;
import org.adridadou.ethereum.values.*;
import static org.adridadou.ethereum.ethj.provider.EthereumJConfigs.ropsten;
import static org.adridadou.ethereum.ethj.provider.PrivateNetworkConfig.config;
import static org.adridadou.ethereum.values.EthValue.ether;
import static org.junit.Assert.*;
import org.adridadou.ethereum.values.config.ChainId;
import org.adridadou.exception.EthereumApiException;
import org.junit.Test;
import java.io.File;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class TestnetConnectionTest {
private final PrivateEthereumFacadeProvider privateNetwork = new PrivateEthereumFacadeProvider();
private EthAccount mainAccount = AccountProvider.fromSeed("cow");
private SoliditySource contractSource = SoliditySource.from(new File(this.getClass().getResource("/contract.sol").toURI()));
public TestnetConnectionTest() throws URISyntaxException {
}
private EthereumFacade fromRopsten() {
EthereumFacadeProvider.Builder ethereumProvider = EthereumFacadeProvider.forNetwork(ropsten());
ethereumProvider.extendConfig().fastSync(true);
return ethereumProvider.create();
}
private EthereumFacade fromPrivateNetwork() {
return privateNetwork.create(config()
.reset(true)
.initialBalance(mainAccount, ether(10)));
}
private EthereumFacade fromTest() {
return EthereumFacadeProvider.forTest(TestConfig.builder()
.balance(mainAccount, ether(10000000))
.build());
}
private EthereumFacade fromRpc() {
return EthereumFacadeProvider.forRemoteNode("http://localhost:8545", ChainId.id(16123));
}
private EthAddress publishAndMapContract(EthereumFacade ethereum) throws Exception {
CompiledContract compiledContract = ethereum.compile(contractSource).get().get("myContract2");
CompletableFuture<EthAddress> futureAddress = ethereum.publishContract(compiledContract, mainAccount);
return futureAddress.get();
}
private void testMethodCalls(MyContract2 myContract, EthAddress address, EthereumFacade ethereum) throws Exception {
assertEquals("", myContract.getI1());
System.out.println("*** calling contractSource myMethod");
Future<Integer> future = myContract.myMethod("this is a test");
assertEquals(12, future.get().intValue());
assertEquals("this is a test", myContract.getI1());
assertTrue(myContract.getT());
Integer[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertArrayEquals(expected, myContract.getArray().toArray(new Integer[10]));
assertArrayEquals(expected, myContract.getSet().toArray(new Integer[10]));
assertEquals(new MyReturnType(true, "hello", 34), myContract.getM());
assertEquals("", myContract.getI2());
System.out.println("*** calling contractSource myMethod2 async");
myContract.myMethod2("async call").get();
myContract.myMethod3("async call").with(ether(150)).get();
assertEquals(ether(150), ethereum.getBalance(address));
assertEquals("async call", myContract.getI2());
assertEquals(EnumTest.VAL2, myContract.getEnumValue());
assertEquals(new Date(150_000), myContract.getInitTime(new Date(150_000)));
assertEquals(mainAccount.getAddress(), myContract.getAccountAddress(mainAccount));
try {
myContract.throwMe().get();
fail("the call should fail!");
} catch (final ExecutionException ex) {
assertEquals(EthereumApiException.class, ex.getCause().getClass());
}
}
@Test
public void main_example_how_the_lib_works() throws Exception {
final EthereumFacade ethereum = fromTest();
EthAddress address = publishAndMapContract(ethereum);
CompiledContract compiledContract = ethereum.compile(contractSource).get().get("myContract2");
MyContract2 myContract = ethereum.createContractProxy(compiledContract, address, mainAccount, MyContract2.class);
testMethodCalls(myContract, address, ethereum);
assertEquals(mainAccount.getAddress(), myContract.getOwner());
}
public static class MyReturnType {
private final Boolean val1;
private final String val2;
private final Integer val3;
public MyReturnType(Boolean val1, String val2, Integer val3) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
@Override
public String toString() {
return "MyReturnType{" +
"val1=" + val1 +
", val2='" + val2 + '\'' +
", val3=" + val3 +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyReturnType that = (MyReturnType) o;
if (val1 != null ? !val1.equals(that.val1) : that.val1 != null) return false;
if (val2 != null ? !val2.equals(that.val2) : that.val2 != null) return false;
return val3 != null ? val3.equals(that.val3) : that.val3 == null;
}
@Override
public int hashCode() {
int result = val1 != null ? val1.hashCode() : 0;
result = 31 * result + (val2 != null ? val2.hashCode() : 0);
result = 31 * result + (val3 != null ? val3.hashCode() : 0);
return result;
}
}
private enum EnumTest {
VAL1, VAL2, VAL3
}
private interface MyContract2 {
CompletableFuture<Integer> myMethod(String value);
CompletableFuture<Void> myMethod2(String value);
Payable<Void> myMethod3(String value);
EnumTest getEnumValue();
String getI1();
String getI2();
boolean getT();
MyReturnType getM();
List<Integer> getArray();
Set<Integer> getSet();
CompletableFuture<Void> throwMe();
EthAddress getOwner();
Date getInitTime(final Date date);
EthAddress getAccountAddress(final EthAccount account);
}
}
|
package cz.muni.fi.webmias;
import cz.muni.fi.mias.Settings;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
/**
* Class responsible for loading indexes from indexes.properties file
*
* @author Martin Liska
*/
public class Indexes {
private static final List<IndexDef> indexes = new ArrayList<>();
private static final char dirSep = System.getProperty("file.separator").charAt(0);
static {
try {
Properties prop = new Properties();
prop.load(Indexes.class.getResourceAsStream("indexes.properties"));
String[] indexesNames = prop.getProperty("INDEX_NAMES").split(",");
String[] indexesPaths = prop.getProperty("PATHS").split(",");
String[] storageArray = prop.getProperty("STORAGES").split(",");
for (int i = 0; i < indexesNames.length; i++) {
String name = indexesNames[i];
IndexSearcher is = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File(indexesPaths[i]))));
String storage = storageArray[i];
int sl = storage.length();
if (storage.charAt(sl - 1) != dirSep) {
storage = storage + dirSep;
}
IndexDef indexDef = new IndexDef(name, storage, is);
indexes.add(indexDef);
}
Settings.init();
Settings.setMaxResults(prop.getProperty("MAXRESULTS"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public Indexes() {
}
public static IndexDef getIndexDef(int i) {
return indexes.get(i);
}
public static String[] getIndexNames() {
String[] result = new String[indexes.size()];
for (int i = 0; i < result.length; i++) {
result[i] = indexes.get(i).getName();
}
return result;
}
}
|
package kabbage.customentitylibrary;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.server.v1_4_6.EntityLiving;
import net.minecraft.server.v1_4_6.ItemStack;
import net.minecraft.server.v1_4_6.PathfinderGoal;
import net.minecraft.server.v1_4_6.PathfinderGoalSelector;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_4_6.CraftWorld;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_4_6.util.UnsafeList;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class CustomEntityWrapper
{
private static Map<EntityLiving, CustomEntityWrapper> customEntities = new HashMap<EntityLiving, CustomEntityWrapper>();
private EntityLiving entity;
private String name;
private int health;
private int maxHealth;
private EntityType type;
Map<String, Integer> damagers = new LinkedHashMap<String, Integer>();
public boolean immune;
@SuppressWarnings("rawtypes")
public CustomEntityWrapper(final EntityLiving entity, World world, final double x, final double y, final double z, EntityType type)
{
this.entity = entity;
this.type = type;
entity.world = ((CraftWorld) world).getHandle();
this.name = type.toString();
immune = true;
entity.setPosition(x, y-5, z);
//The arduous process of changing the entities speed without disrupting the pathfinders in any other way
try
{
float initialSpeed = 0;
Field speed = EntityLiving.class.getDeclaredField("bG");
speed.setAccessible(true);
initialSpeed = speed.getFloat(entity);
speed.setFloat(entity, type.getSpeed());
UnsafeList goalSelectorList = null;
UnsafeList targetSelectorList = null;
PathfinderGoalSelector goalSelector;
PathfinderGoalSelector targetSelector;
Field gsa = PathfinderGoalSelector.class.getDeclaredField("a");
Field goalSelectorField = EntityLiving.class.getDeclaredField("goalSelector");
Field targetSelectorField = EntityLiving.class.getDeclaredField("targetSelector");
gsa.setAccessible(true);
goalSelectorField.setAccessible(true);
targetSelectorField.setAccessible(true);
goalSelector = (PathfinderGoalSelector) goalSelectorField.get(entity);
targetSelector = (PathfinderGoalSelector) targetSelectorField.get(entity);
goalSelectorList = (UnsafeList) gsa.get(goalSelector);
targetSelectorList = (UnsafeList) gsa.get(targetSelector);
for(Object goalObject : goalSelectorList)
{
Field goalField = goalObject.getClass().getDeclaredField("a");
goalField.setAccessible(true);
PathfinderGoal goal = (PathfinderGoal) goalField.get(goalObject);
for(Field f : goal.getClass().getDeclaredFields())
{
if(f.getType().equals(Float.TYPE))
{
f.setAccessible(true);
float fl = f.getFloat(goal);
if(fl == initialSpeed)
f.setFloat(goal, type.getSpeed());
}
}
}
for(Object goalObject : targetSelectorList)
{
Field goalField = goalObject.getClass().getDeclaredField("a");
goalField.setAccessible(true);
PathfinderGoal goal = (PathfinderGoal) goalField.get(goalObject);
for(Field f : goal.getClass().getDeclaredFields())
{
if(f.getType().equals(Float.TYPE))
{
f.setAccessible(true);
float fl = f.getFloat(goal);
if(fl == initialSpeed)
f.setFloat(goal, type.getSpeed());
}
}
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
org.bukkit.inventory.ItemStack[] items = type.getItems();
if(items != null)
{
for(int i = 0; i <= 4; i++)
{
if(items[i] != null)
{
ItemStack item = CraftItemStack.asNMSCopy(items[i]);
if(item != null)
entity.setEquipment(i, item);
}
}
}
maxHealth = type.getHealth();
health = type.getHealth();
customEntities.put(entity, this);
//Reload visibility
Bukkit.getScheduler().scheduleSyncDelayedTask(CustomEntityLibrary.plugin, new Runnable()
{
@Override
public void run()
{
entity.setPosition(x, y, z);
immune = false;
}
},1L);
}
public void setHealth(int health)
{
this.health = health;
}
public EntityLiving getEntity()
{
return entity;
}
public int getHealth()
{
return health;
}
public void setMaxHealth(int maxHealth)
{
this.maxHealth = maxHealth;
if(health > maxHealth)
health = maxHealth;
}
public int getMaxHealth()
{
return maxHealth;
}
public void restoreHealth()
{
health = maxHealth;
}
public void modifySpeed(double modifier)
{
Field f;
try
{
f = EntityLiving.class.getDeclaredField("bG");
f.setAccessible(true);
float newSpeed = (float) (f.getFloat(entity) * modifier);
f.setFloat(entity, newSpeed);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
public EntityType getType()
{
return type;
}
public void addAttack(Player p, int damage)
{
int damagex = 0;
if(damagers.get(p.getName()) != null)
damagex = damagers.get(p.getName());
damagers.put(p.getName(), damage + damagex);
}
public Player getBestAttacker()
{
String p = null;
int damage = 0;
for(Entry<String, Integer> e: damagers.entrySet())
{
if(e.getValue() > damage)
{
p = e.getKey();
damage = e.getValue();
}
}
if(p == null)
return null;
return Bukkit.getPlayer(p);
}
public Player getAssistAttacker()
{
String p = null;
String p2 = null;
int damage = 0;
for(Entry<String, Integer> e: damagers.entrySet())
{
if(e.getValue() > damage)
{
p2 = p;
p = e.getKey();
damage = e.getValue();
}
}
if(p2 == null)
return null;
return Bukkit.getPlayer(p2);
}
public String getName()
{
return name;
}
/**
* Allows for a simpler way of checking if an Entity is an instance of a CustomEntityWrapper
* @param entity the entity being checked
* @return whether or not an Entity is an instanceof a CustomEntityWrapper
*/
public static boolean instanceOf(Entity entity)
{
if(customEntities.containsKey(((CraftEntity) entity).getHandle()))
return true;
return false;
}
/**
* Allows for a simpler way of converting an Entity to a CustomEntity
* @param entity being converted to a CustomEntityWrapper
* @return a CustomEntityWrapper instance of the entity, or null if none exists
*/
public static CustomEntityWrapper getCustomEntity(Entity entity)
{
if(customEntities.containsKey(((CraftEntity) entity).getHandle()))
return customEntities.get(((CraftEntity) entity).getHandle());
return null;
}
public static CustomEntityWrapper spawnCustomEntity(EntityLiving entity, World world, double x, double y, double z, EntityType type)
{
return new CustomEntityWrapper(entity, world, x, y, z, type);
}
public static CustomEntityWrapper spawnCustomEntity(EntityLiving entity, Location location, EntityType type)
{
return spawnCustomEntity(entity, location.getWorld(), location.getX(), location.getY(), location.getZ(), type);
}
}
|
package org.pitest.cucumber;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.examples.java.calculator.Cornichon;
import cucumber.examples.java.calculator.DateCalculator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.pitest.testapi.Description;
import org.pitest.testapi.ResultCollector;
import org.pitest.testapi.TestUnit;
import java.util.List;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class IntegrationTest {
@Mock
private ResultCollector resultCollector;
@Before
public void setUp() throws Exception {
DateCalculator.failMode.set(null);
}
@Test
public void should_run_scenarios_successfully() throws Exception {
// given
TestUnit firstTest = getScenarioTestUnit();
// when
firstTest.execute(resultCollector);
// then
Description description = firstTest.getDescription();
verify(resultCollector, times(1)).notifyStart(description);
verify(resultCollector, atLeastOnce()).notifyEnd(description);
}
@Test
public void should_detect_scenario_failure() throws Exception {
// given
TestUnit firstTest = getScenarioTestUnit();
DateCalculator.failMode.set(true);
// when
firstTest.execute(resultCollector);
// then
Description description = firstTest.getDescription();
verify(resultCollector, times(1)).notifyStart(description);
verify(resultCollector, times(1)).notifyEnd(any(Description.class), any(Throwable.class));
}
@Test
public void should_detect_skipped_scenario() throws Exception {
// given
CucumberTestUnitFinder finder = new CucumberTestUnitFinder();
List<TestUnit> testUnits = finder.findTestUnits(HideFromJUnit.Cornichon.class);
TestUnit firstTest = testUnits.get(0);
// when
firstTest.execute(resultCollector);
// then
Description description = firstTest.getDescription();
verify(resultCollector, times(1)).notifyStart(description);
verify(resultCollector, times(1)).notifySkipped(description);
}
private TestUnit getScenarioTestUnit() {
CucumberTestUnitFinder finder = new CucumberTestUnitFinder();
List<TestUnit> testUnits = finder.findTestUnits(Cornichon.class);
return testUnits.get(0);
}
private static class HideFromJUnit {
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:cucumber/examples/java/calculator/date_calculator.feature")
private static class Cornichon {
}
}
}
|
package de.bmoth.app;
import de.bmoth.modelchecker.ModelChecker;
import de.bmoth.modelchecker.ModelCheckingResult;
import javafx.application.Platform;
import javafx.collections.SetChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Region;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.fxmisc.richtext.LineNumberFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.ResourceBundle;
public class AppController implements Initializable {
@FXML MenuItem open;
@FXML MenuItem save;
@FXML MenuItem saveAs;
@FXML MenuItem options;
@FXML MenuItem exit;
@FXML MenuItem modelCheck;
@FXML CodeArea codeArea;
@FXML TextArea infoArea;
private Stage primaryStage = new Stage();
private PersonalPreference personalPreference;
private String currentFile;
private Boolean hasChanged = false;
private final String APPNAME = "Bmoth";
@Override
public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
save.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_ANY));
codeArea.selectRange(0,0);
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
codeArea.richChanges().filter(ch -> !ch.getInserted().equals(ch.getRemoved())) // XXX
.subscribe(change -> {
codeArea.setStyleSpans(0, Highlighter.computeHighlighting(codeArea.getText()));
});
codeArea.setStyleSpans(0, Highlighter.computeHighlighting(codeArea.getText()));
}
void setupStage(Stage stage) {
primaryStage = stage;
primaryStage.setTitle(APPNAME);
primaryStage.setOnCloseRequest(event -> {
event.consume();
handleExit();
});
}
void setupPersonalPreference(PersonalPreference preference) {
personalPreference = preference;
if (personalPreference.getLastFile() != null) {
currentFile = personalPreference.getLastFile();
String fileContent = openFile(new File(personalPreference.getLastFile()));
codeArea.replaceText(fileContent);
codeArea.deletehistory();
}
codeArea.textProperty().addListener((observableValue, s, t1) -> {
hasChanged = true;
infoArea.setText("Unsaved changes");
});
}
@FXML
public void handleOpen() {
int nextStep = -1;
if (hasChanged) {
nextStep = saveChangedDialog();
switch (nextStep) {
case 0:
break;
case 1:
handleSave();
break;
case 2:
handleSaveAs();
break;
case -1:
break;
}
}
if (nextStep != 0) {
String fileContent = openFileChooser();
if(fileContent!=null) {
codeArea.replaceText(fileContent);
codeArea.deletehistory();
codeArea.selectRange(0, 0);
hasChanged = false;
infoArea.clear();
}
}
}
@FXML
public void handleSave() {
if (currentFile != null) {
try {
saveFile(currentFile);
hasChanged = false;
infoArea.clear();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
saveFileAs();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@FXML
public Boolean handleSaveAs() {
try {
Boolean saved = saveFileAs();
if (saved) {
hasChanged = false;
infoArea.clear();
}
return saved;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@FXML
public void handleExit() {
PersonalPreference.savePrefToFile(personalPreference);
if (hasChanged) {
int nextStep = saveChangedDialog();
switch (nextStep) {
case 0:
break;
case 1:
handleSave();
Platform.exit();
break;
case 2:
Boolean saved = handleSaveAs();
if (saved) {
Platform.exit();
}
break;
case -1:
Platform.exit();
break;
}
} else {
Platform.exit();
}
}
public void handleOptions() throws IOException {
}
@FXML
public void handleCheck() {
if (codeArea.getText().replaceAll("\\s+","").length()>0) {
ModelCheckingResult result = ModelChecker.doModelCheck(codeArea.getText(), personalPreference);
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Model Checking Result");
alert.setHeaderText("The model is...");
if (result.isCorrect()) {
alert.setContentText("...correct!\nNo counter-example found.");
} else {
alert.setContentText("...not correct!\nCounter-example found in state " + result.getLastState().toString()
+ ".\nReversed path: " + ModelCheckingResult.getPath(result.getLastState()));
}
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.showAndWait();
}
}
/**
* Save codeArea to a file.
*
* @param path Save-location
* @throws IOException
*/
private void saveFile(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(codeArea.getText());
fileWriter.close();
}
/**
* Ask for location and name and save codeArea.
*
* @throws IOException
* @see #saveFile(String)
*/
private Boolean saveFileAs() throws IOException {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("MCH File", "*.mch"));
File file = fileChooser.showSaveDialog(primaryStage);
if (file != null) { //add .mch ending if not added by OS
if (!file.getAbsolutePath().endsWith(".mch")) {
saveFile(file.getAbsolutePath() + ".mch");
} else {
saveFile(file.getAbsolutePath());
}
return true;
}
else return false;
}
/**
* Open a confirmation-alert to decide how to proceed with unsaved changes.
*
* @return UserChoice as Integer: -1 = Ignore, 0 = Cancel, 1 = Save , 2 = SaveAs
*/
private int saveChangedDialog() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("UNSAVED CHANGES!");
alert.setHeaderText("Unsaved Changes! What do you want to do?");
alert.setContentText(null);
ButtonType buttonTypeSave = new ButtonType("Save");
ButtonType buttonTypeSaveAs = new ButtonType("Save As");
ButtonType buttonTypeIgnoreChanges = new ButtonType("Ignore");
ButtonType buttonTypeCancel = new ButtonType("Back", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeSave, buttonTypeSaveAs, buttonTypeIgnoreChanges, buttonTypeCancel);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent()) {
if (result.get() == buttonTypeSave) return 1;
if (result.get() == buttonTypeSaveAs) return 2;
if (result.get() == buttonTypeCancel) return 0;
if (result.get() == buttonTypeIgnoreChanges) return -1;
}
return 0;
}
/**
* Ask the user which file to open into the textarea. If the file is found, openFile is called.
*
* @return Returns the filepath as string or null if cancelled
* @see #openFile(File)
*/
private String openFileChooser() {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Open MCH File", "*.mch"));
fileChooser.setTitle("Choose File");
fileChooser.setInitialDirectory(new File(personalPreference.getPrefdir()));
File file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
personalPreference.setLastFile(file.getAbsolutePath());
personalPreference.setPrefdir(file.getParent());
String content = openFile(file);
primaryStage.setTitle(APPNAME + " - " + file.getName());
return content;
}
return null;
}
/**
* Load a given file into the CodeArea and change the title of the stage.
*
* @param file File to read from
*/
private String openFile(File file) {
String content = null;
try {
content = new String(Files.readAllBytes(Paths.get(file.getPath())));
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
|
package com.izforge.izpack.panels;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.File;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.VariableSubstitutor;
/**
* The simple finish panel class.
*
* @author Julien Ponge
*/
public class SimpleFinishPanel extends IzPanel
{
/** The layout. */
private BoxLayout layout;
/** The center panel. */
protected JPanel centerPanel;
/** The variables substitutor. */
private VariableSubstitutor vs;
/**
* The constructor.
*
* @param parent The parent.
* @param idata The installation data.
*/
public SimpleFinishPanel(InstallerFrame parent, InstallData idata)
{
super(parent, idata);
vs = new VariableSubstitutor(idata.getVariables());
// The 'super' layout
GridBagLayout superLayout = new GridBagLayout();
setLayout(superLayout);
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.insets = new Insets(0, 0, 0, 0);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.anchor = GridBagConstraints.CENTER;
// We initialize our 'real' layout
centerPanel = new JPanel();
layout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS);
centerPanel.setLayout(layout);
superLayout.addLayoutComponent(centerPanel, gbConstraints);
add(centerPanel);
}
/**
* Indicates wether the panel has been validated or not.
*
* @return true if the panel has been validated.
*/
public boolean isValidated()
{
return true;
}
/** Called when the panel becomes active. */
public void panelActivate()
{
parent.lockNextButton();
parent.lockPrevButton();
parent.setQuitButtonText(parent.langpack.getString("FinishPanel.done"));
if (idata.installSuccess)
{
// We set the information
centerPanel.add(new JLabel(parent.icons.getImageIcon("check")));
centerPanel.add(Box.createVerticalStrut(20));
centerPanel.add(new JLabel(parent.langpack
.getString("FinishPanel.success"), parent.icons
.getImageIcon("information"), JLabel.TRAILING));
centerPanel.add(Box.createVerticalStrut(20));
if (idata.uninstallOutJar != null)
{
// We prepare a message for the uninstaller feature
String path = translatePath("$INSTALL_PATH") + File.separator
+ "Uninstaller";
centerPanel.add(new JLabel(parent.langpack
.getString("FinishPanel.uninst.info"), parent.icons
.getImageIcon("information"), JLabel.TRAILING));
centerPanel.add(new JLabel(path, parent.icons.getImageIcon("empty"),
JLabel.TRAILING));
}
}
}
/**
* Translates a relative path to a local system path.
*
* @param destination The path to translate.
* @return The translated path.
*/
private String translatePath(String destination)
{
// Parse for variables
destination = vs.substitute(destination, null);
// Convert the file separator characters
return destination.replace('/', File.separatorChar);
}
}
|
package org.scijava.script;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.script.ScriptEngine;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.MenuPath;
import org.scijava.plugin.Plugin;
import org.scijava.test.TestUtils;
import org.scijava.util.FileUtils;
/**
* Tests the {@link ScriptFinder}.
*
* @author Curtis Rueden
*/
public class ScriptFinderTest {
private static File scriptsDir;
// -- Test setup --
@BeforeClass
public static void setUp() throws IOException {
scriptsDir = TestUtils.createTemporaryDirectory("script-finder-");
TestUtils.createPath(scriptsDir, "ignored.foo");
TestUtils.createPath(scriptsDir, "Scripts/quick.foo");
TestUtils.createPath(scriptsDir, "Scripts/brown.foo");
TestUtils.createPath(scriptsDir, "Scripts/fox.foo");
TestUtils.createPath(scriptsDir, "Scripts/The_Lazy_Dog.foo");
TestUtils.createPath(scriptsDir, "Math/add.foo");
TestUtils.createPath(scriptsDir, "Math/subtract.foo");
TestUtils.createPath(scriptsDir, "Math/multiply.foo");
TestUtils.createPath(scriptsDir, "Math/divide.foo");
TestUtils.createPath(scriptsDir, "Math/Trig/cos.foo");
TestUtils.createPath(scriptsDir, "Math/Trig/sin.foo");
TestUtils.createPath(scriptsDir, "Math/Trig/tan.foo");
}
@AfterClass
public static void tearDown() {
FileUtils.deleteRecursively(scriptsDir);
}
// -- Unit tests --
@Test
public void testFindScripts() {
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.service(ScriptService.class);
scriptService.addScriptDirectory(scriptsDir);
final ArrayList<ScriptInfo> scripts = findScripts(scriptService);
assertEquals(11, scripts.size());
assertMenuPath("Scripts > The Lazy Dog", scripts, 0);
assertMenuPath("Math > add", scripts, 1);
assertMenuPath("Scripts > brown", scripts, 2);
assertMenuPath("Math > Trig > cos", scripts, 3);
assertMenuPath("Math > divide", scripts, 4);
assertMenuPath("Scripts > fox", scripts, 5);
assertMenuPath("Math > multiply", scripts, 6);
assertMenuPath("Scripts > quick", scripts, 7);
assertMenuPath("Math > Trig > sin", scripts, 8);
assertMenuPath("Math > subtract", scripts, 9);
assertMenuPath("Math > Trig > tan", scripts, 10);
}
/**
* Tests that menu prefixes work as expected when
* {@link ScriptService#addScriptDirectory(File, org.scijava.MenuPath)} is
* called.
*/
@Test
public void testMenuPrefixes() {
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.service(ScriptService.class);
final MenuPath menuPrefix = new MenuPath("Foo > Bar");
assertEquals(2, menuPrefix.size());
assertEquals("Bar", menuPrefix.getLeaf().getName());
scriptService.addScriptDirectory(scriptsDir, menuPrefix);
final ArrayList<ScriptInfo> scripts = findScripts(scriptService);
assertEquals(12, scripts.size());
assertMenuPath("Foo > Bar > Scripts > The Lazy Dog", scripts, 0);
assertMenuPath("Foo > Bar > Math > add", scripts, 1);
assertMenuPath("Foo > Bar > Scripts > brown", scripts, 2);
assertMenuPath("Foo > Bar > Math > Trig > cos", scripts, 3);
assertMenuPath("Foo > Bar > Math > divide", scripts, 4);
assertMenuPath("Foo > Bar > Scripts > fox", scripts, 5);
assertMenuPath("Foo > Bar > ignored", scripts, 6);
assertMenuPath("Foo > Bar > Math > multiply", scripts, 7);
assertMenuPath("Foo > Bar > Scripts > quick", scripts, 8);
assertMenuPath("Foo > Bar > Math > Trig > sin", scripts, 9);
assertMenuPath("Foo > Bar > Math > subtract", scripts, 10);
assertMenuPath("Foo > Bar > Math > Trig > tan", scripts, 11);
}
/**
* Tests that scripts are discovered only once when present in multiple base
* directories.
*/
@Test
public void testOverlappingDirectories() {
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.service(ScriptService.class);
// Scripts -> Plugins
scriptService.addScriptDirectory(new File(scriptsDir, "Scripts"),
new MenuPath("Plugins"));
// everything else "in place"
scriptService.addScriptDirectory(scriptsDir);
final ArrayList<ScriptInfo> scripts = findScripts(scriptService);
assertEquals(11, scripts.size());
assertMenuPath("Plugins > The Lazy Dog", scripts, 0);
assertMenuPath("Math > add", scripts, 1);
assertMenuPath("Plugins > brown", scripts, 2);
assertMenuPath("Math > Trig > cos", scripts, 3);
assertMenuPath("Math > divide", scripts, 4);
assertMenuPath("Plugins > fox", scripts, 5);
assertMenuPath("Math > multiply", scripts, 6);
assertMenuPath("Plugins > quick", scripts, 7);
assertMenuPath("Math > Trig > sin", scripts, 8);
assertMenuPath("Math > subtract", scripts, 9);
assertMenuPath("Math > Trig > tan", scripts, 10);
}
// -- Helper methods --
private ArrayList<ScriptInfo> findScripts(final ScriptService scriptService) {
final ScriptFinder scriptFinder = new ScriptFinder(scriptService);
final ArrayList<ScriptInfo> scripts = new ArrayList<ScriptInfo>();
scriptFinder.findScripts(scripts);
Collections.sort(scripts);
return scripts;
}
private void assertMenuPath(final String menuString,
final ArrayList<ScriptInfo> scripts, final int i)
{
assertEquals(menuString, scripts.get(i).getMenuPath().getMenuString());
}
// -- Helper classes --
/** "Handles" scripts with .foo extension. */
@Plugin(type = ScriptLanguage.class)
public static class FooScriptLanguage extends AbstractScriptLanguage {
@Override
public List<String> getExtensions() {
return Arrays.asList("foo");
}
@Override
public ScriptEngine getScriptEngine() {
// NB: Should never be called by the unit tests.
throw new IllegalStateException();
}
}
}
|
package org.sqldroid;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 16)
public class SQLDroidConnectionTest {
@Test
public void shouldConnectToEmptyFile() throws SQLException, IOException {
Properties properties = new Properties();
properties.put(SQLDroidDriver.ADDITONAL_DATABASE_FLAGS,
android.database.sqlite.SQLiteDatabase.CREATE_IF_NECESSARY | android.database.sqlite.SQLiteDatabase.OPEN_READWRITE);
File dbFile = cleanDbFile("exisising-file.db");
try (FileOutputStream output = new FileOutputStream(dbFile)) {
}
assertThat(dbFile).exists();
String jdbcUrl = "jdbc:sqlite:" + dbFile.getAbsolutePath();
Connection conn = new SQLDroidDriver().connect(jdbcUrl, properties);
assertThat(conn.isClosed()).isFalse();
conn.close();
}
@Test
public void shouldSupportQueryPartOfURL() throws SQLException {
File dbFile = cleanDbFile("query-test.db");
String jdbcUrl = "jdbc:sqlite:" + dbFile.getAbsolutePath() + "?timeout=30";
Connection conn = new SQLDroidDriver().connect(jdbcUrl, new Properties());
assertThat(conn.isClosed()).isFalse();
conn.close();
}
@Test
public void shouldDealWithDatabaseAsDirectory() throws SQLException {
File dbFile = cleanDbFile("db-as-dir.db");
final String jdbcUrl = "jdbc:sqlite:" + dbFile.getParentFile().getAbsolutePath();
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
new SQLDroidDriver().connect(jdbcUrl, new Properties());
}
}).isInstanceOf(SQLException.class)
.hasMessageContaining("SQLiteCantOpenDatabaseException");
}
@Test
// TODO: Many issues seem to stem from users expecting subdirectories to be created. Should this be supported?
public void shouldFailOnMissingSubdirectory() throws SQLException {
DB_DIR.mkdirs();
assertThat(DB_DIR).isDirectory();
File dbSubdir = new File(DB_DIR, "non-existing-dir");
assertThat(dbSubdir).doesNotExist();
File dbFile = new File(dbSubdir, "database.db");
final String jdbcUrl = "jdbc:sqlite:" + dbFile.getAbsolutePath();
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
new SQLDroidDriver().connect(jdbcUrl, new Properties());
}
}).isInstanceOf(SQLException.class)
.hasMessageContaining("SQLiteCantOpenDatabaseException");
assertThat(dbSubdir).doesNotExist();
}
private static final File DB_DIR = new File("./target/data/org.sqldroid/databases/");
private File cleanDbFile(String filename) {
DB_DIR.mkdirs();
assertThat(DB_DIR).isDirectory();
File dbFile = new File(DB_DIR, filename);
dbFile.delete();
assertThat(dbFile).doesNotExist();
return dbFile;
}
}
|
package seedu.taskmanager.testutil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import com.google.common.io.Files;
import guitests.guihandles.TaskCardHandle;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import junit.framework.AssertionFailedError;
import seedu.taskmanager.TestApp;
import seedu.taskmanager.commons.exceptions.IllegalValueException;
import seedu.taskmanager.commons.util.FileUtil;
import seedu.taskmanager.commons.util.XmlUtil;
import seedu.taskmanager.model.TaskManager;
import seedu.taskmanager.model.tag.Tag;
import seedu.taskmanager.model.tag.UniqueTagList;
import seedu.taskmanager.model.task.Description;
import seedu.taskmanager.model.task.EndDate;
import seedu.taskmanager.model.task.Title;
import seedu.taskmanager.model.task.Task;
import seedu.taskmanager.model.task.StartDate;
import seedu.taskmanager.model.task.ReadOnlyTask;
import seedu.taskmanager.storage.XmlSerializableTaskManager;
/**
* A utility class for test cases.
*/
public class TestUtil {
public static final String LS = System.lineSeparator();
/**
* Folder used for temp files created during testing. Ignored by Git.
*/
public static final String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/");
public static final Task[] SAMPLE_TASK_DATA = getSampleTaskData();
public static final Tag[] SAMPLE_TAG_DATA = getSampleTagData();
public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) {
try {
executable.run();
} catch (Throwable actualException) {
if (actualException.getClass().isAssignableFrom(expected)) {
return;
}
String message = String.format("Expected thrown: %s, actual: %s", expected.getName(),
actualException.getClass().getName());
throw new AssertionFailedError(message);
}
throw new AssertionFailedError(
String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName()));
}
private static Task[] getSampleTaskData() {
try {
//CHECKSTYLE.OFF: LineLength
return new Task[]{
new Task(new Title("Visit Alex Yeoh"), new StartDate("01/11/2017"), new EndDate("02/11/2017"), new Description("His address is Blk 30 Geylang Street 29, #06-40"), new UniqueTagList()),
new Task(new Title("Borrow Pencils"), new StartDate("04/03/2017"), new EndDate("04/03/2017"), new Description("Must be non-mechanical"), new UniqueTagList()),
new Task(new Title("Finish CS2103 testing"), new StartDate("10/03/2017"), new EndDate("15/03/2017"), new Description("The best module eva"), new UniqueTagList()),
new Task(new Title("Buy Toothpick"), new StartDate("20/05/2016"), new EndDate("21/05/2017"), new Description("Buy 1000pcs"), new UniqueTagList()),
new Task(new Title("Make baos for gathering"), new StartDate("10/03/2017"), new EndDate("20/03/2017"), new Description("3 flavours: chocolate, red bean, and green bean"), new UniqueTagList())
};
//CHECKSTYLE.ON: LineLength
} catch (IllegalValueException e) {
assert false;
// not possible
return null;
}
}
private static Tag[] getSampleTagData() {
try {
return new Tag[]{
new Tag("relatives"),
new Tag("friends")
};
} catch (IllegalValueException e) {
assert false;
return null;
//not possible
}
}
public static List<Task> generateSampleTaskData() {
return Arrays.asList(SAMPLE_TASK_DATA);
}
/**
* Appends the file name to the sandbox folder path.
* Creates the sandbox folder if it doesn't exist.
* @param fileName
* @return
*/
public static String getFilePathInSandboxFolder(String fileName) {
try {
FileUtil.createDirs(new File(SANDBOX_FOLDER));
} catch (IOException e) {
throw new RuntimeException(e);
}
return SANDBOX_FOLDER + fileName;
}
public static void createDataFileWithSampleData(String filePath) {
createDataFileWithData(generateSampleStorageTaskManager(), filePath);
}
public static <T> void createDataFileWithData(T data, String filePath) {
try {
File saveFileForTesting = new File(filePath);
FileUtil.createIfMissing(saveFileForTesting);
XmlUtil.saveDataToFile(saveFileForTesting, data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String... s) {
createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING);
}
public static XmlSerializableTaskManager generateSampleStorageTaskManager() {
return new XmlSerializableTaskManager(new TaskManager());
}
/**
* Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their
* respective platform-specific keycodes
*/
public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) {
List<KeyCode> keys = new ArrayList<>();
if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.ALT);
}
if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.SHIFT);
}
if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.META);
}
if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) {
keys.add(KeyCode.CONTROL);
}
keys.add(keyCodeCombination.getCode());
return keys.toArray(new KeyCode[]{});
}
public static boolean isHeadlessEnvironment() {
String headlessProperty = System.getProperty("testfx.headless");
return headlessProperty != null && headlessProperty.equals("true");
}
public static void captureScreenShot(String fileName) {
File file = GuiTest.captureScreenshot();
try {
Files.copy(file, new File(fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String descOnFail(Object... comparedObjects) {
return "Comparison failed \n"
+ Arrays.asList(comparedObjects).stream()
.map(Object::toString)
.collect(Collectors.joining("\n"));
}
public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException,
IllegalAccessException {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
// ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer
// final and can be changed
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void initRuntime() throws TimeoutException {
FxToolkit.registerPrimaryStage();
FxToolkit.hideStage();
}
public static void tearDownRuntime() throws Exception {
FxToolkit.cleanupStages();
}
/**
* Gets private method of a class
* Invoke the method using method.invoke(objectInstance, params...)
*
* Caveat: only find method declared in the current Class, not inherited from supertypes
*/
public static Method getPrivateMethod(Class<?> objectClass, String methodName) throws NoSuchMethodException {
Method method = objectClass.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
}
public static void renameFile(File file, String newFileName) {
try {
Files.copy(file, new File(newFileName));
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Gets mid point of a node relative to the screen.
* @param node
* @return
*/
public static Point2D getScreenMidPoint(Node node) {
double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x, y);
}
/**
* Gets mid point of a node relative to its scene.
* @param node
* @return
*/
public static Point2D getSceneMidPoint(Node node) {
double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2;
double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2;
return new Point2D(x, y);
}
/**
* Gets the bound of the node relative to the parent scene.
* @param node
* @return
*/
public static Bounds getScenePos(Node node) {
return node.localToScene(node.getBoundsInLocal());
}
public static Bounds getScreenPos(Node node) {
return node.localToScreen(node.getBoundsInLocal());
}
public static double getSceneMaxX(Scene scene) {
return scene.getX() + scene.getWidth();
}
public static double getSceneMaxY(Scene scene) {
return scene.getX() + scene.getHeight();
}
public static Object getLastElement(List<?> list) {
return list.get(list.size() - 1);
}
/**
* Removes a subset from the list of tasks.
* @param tasks The list of tasks
* @param tasksToRemove The subset of tasks.
* @return The modified tasks after removal of the subset from tasks.
*/
public static TestTask[] removeTasksFromList(final TestTask[] tasks, TestTask... tasksToRemove) {
List<TestTask> listOfTasks = asList(tasks);
listOfTasks.removeAll(asList(tasksToRemove));
return listOfTasks.toArray(new TestTask[listOfTasks.size()]);
}
/**
* Returns a copy of the list with the task at specified index removed.
* @param list original list to copy from
* @param targetIndexInOneIndexedFormat e.g. index 1 if the first element is to be removed
*/
public static TestTask[] removeTaskFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) {
return removeTasksFromList(list, list[targetIndexInOneIndexedFormat - 1]);
}
/**
* Replaces tasks[i] with a task.
* @param tasks The array of tasks.
* @param task The replacement task
* @param index The index of the task to be replaced.
* @return
*/
public static TestTask[] replaceTaskFromList(TestTask[] tasks, TestTask task, int index) {
tasks[index] = task;
return tasks;
}
/**
* Appends tasks to the array of tasks.
* @param tasks A array of tasks.
* @param tasksToAdd The tasks that are to be appended behind the original array.
* @return The modified array of tasks.
*/
public static TestTask[] addTasksToList(final TestTask[] tasks, TestTask... tasksToAdd) {
List<TestTask> listOfTasks = asList(tasks);
listOfTasks.addAll(asList(tasksToAdd));
return listOfTasks.toArray(new TestTask[listOfTasks.size()]);
}
private static <T> List<T> asList(T[] objs) {
List<T> list = new ArrayList<>();
for (T obj : objs) {
list.add(obj);
}
return list;
}
public static boolean compareCardAndTask(TaskCardHandle card, ReadOnlyTask task) {
return card.isSameTask(task);
}
public static Tag[] getTagList(String tags) {
if ("".equals(tags)) {
return new Tag[]{};
}
final String[] split = tags.split(", ");
final List<Tag> collect = Arrays.asList(split).stream().map(e -> {
try {
return new Tag(e.replaceFirst("Tag: ", ""));
} catch (IllegalValueException e1) {
//not possible
assert false;
return null;
}
}).collect(Collectors.toList());
return collect.toArray(new Tag[split.length]);
}
}
|
package seedu.unburden.testutil;
import seedu.unburden.commons.exceptions.IllegalValueException;
import seedu.unburden.model.tag.Tag;
import seedu.unburden.model.task.*;
/**
*A class that builds sample Task testcases
*Author A0147986H
*/
public class TaskBuilder {
private TestTask task;
public TaskBuilder() {
this.task = new TestTask();
}
public TaskBuilder withName(String name) throws IllegalValueException {
this.task.setName(new Name(name));
return this;
}
public TaskBuilder withDate(String date) throws IllegalValueException {
this.task.setDate(new Date(date));
return this;
}
public TaskBuilder withStartTime(String startTime) throws IllegalValueException {
this.task.setStartTime(new Time(startTime));
return this;
}
public TaskBuilder withEndTime(String endTime) throws IllegalValueException {
this.task.setEndTime(new Time(endTime));
return this;
}
public TaskBuilder withTaskDescription(String taskD) throws IllegalValueException {
this.task.setTaskDescription(new TaskDescription(taskD));
return this;
}
public TaskBuilder withTags(String ... tags) throws IllegalValueException {
for (String tag: tags) {
task.getTags().add(new Tag(tag));
}
return this;
}
public TestTask build() {
return this.task;
}
}
|
package hello;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.restfb.DefaultJsonMapper;
import com.restfb.JsonMapper;
import com.restfb.types.webhook.WebhookObject;
import ai.api.model.AIContext;
import ai.api.model.AIRequest;
import ai.api.model.Entity;
@Controller
@RequestMapping("/webhook")
public class HelloWorldController {
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody WebhookResponse webhook(@RequestBody String obj) {
String response = "";
System.out.println("Entramos al metodo webhook");
System.out.println(obj);
System.out.println("
System.out.println("Parseamos el request");
AIRequest request = new AIRequest(obj);
System.out.println(request);
System.out.println("
if (obj.contains("facebook")) {
System.out.println("Peticion de facebook");
response = "hola usuario de facebook";
System.out.println("entidades: ");
System.out.println("***");
if (null != request.getEntities()) {
for (Entity entidad : request.getEntities()) {
System.out.println(entidad);
System.out.println("***");
}
} else {
System.out.println("No hay entidades");
}
System.out.println("***");
System.out.println("Recuperamos los datos de la query");
String[] query = new String[]{obj};
System.out.println(query[3]);
//List<AIContext> contexts = query[3];
JsonMapper mapper = new DefaultJsonMapper();
WebhookObject webhookObject = mapper.toJavaObject(obj.toString(),
WebhookObject.class);
System.out.println(webhookObject.toString());
} else {
response = "webhook Hello!";
}
return new WebhookResponse(response, "webhook Text");
}
}
|
package bdv.img.cache;
import java.util.ArrayList;
import bdv.cache.SoftRefVolatileCacheImp;
import bdv.cache.VolatileCache;
import bdv.cache.VolatileCacheEntry;
import bdv.cache.VolatileCacheValue;
import bdv.cache.VolatileCacheValueLoader;
import bdv.img.cache.CacheIoTiming.IoStatistics;
import bdv.img.cache.CacheIoTiming.IoTimeBudget;
import bdv.img.cache.VolatileImgCells.CellCache;
import net.imglib2.img.basictypeaccess.volatiles.VolatileAccess;
public class VolatileGlobalCellCache implements Cache
{
private final int maxNumLevels;
public static class Key
{
private final int timepoint;
private final int setup;
private final int level;
private final long index;
private final int[] cellDims;
private final long[] cellMin;
public Key( final int timepoint, final int setup, final int level, final long index, final int[] cellDims, final long[] cellMin )
{
this.timepoint = timepoint;
this.setup = setup;
this.level = level;
this.index = index;
this.cellDims = cellDims;
this.cellMin = cellMin;
int value = Long.hashCode( index );
value = 31 * value + level;
value = 31 * value + setup;
value = 31 * value + timepoint;
hashcode = value;
}
@Override
public boolean equals( final Object other )
{
if ( this == other )
return true;
if ( !( other instanceof VolatileGlobalCellCache.Key ) )
return false;
final Key that = ( Key ) other;
return ( this.timepoint == that.timepoint ) && ( this.setup == that.setup ) && ( this.level == that.level ) && ( this.index == that.index );
}
final int hashcode;
@Override
public int hashCode()
{
return hashcode;
}
protected int[] getCellDims()
{
return cellDims;
}
protected long[] getCellMin()
{
return cellMin;
}
}
protected VolatileCache volatileCache = SoftRefVolatileCacheImp.getInstance();
protected final BlockingFetchQueues< Object > queue;
protected volatile long currentQueueFrame = 0;
class Fetcher extends Thread
{
@Override
public final void run()
{
Object key = null;
while ( true )
{
while ( key == null )
try
{
key = queue.take();
}
catch ( final InterruptedException e )
{}
long waitMillis = pauseUntilTimeMillis - System.currentTimeMillis();
while ( waitMillis > 0 )
{
try
{
synchronized ( lock )
{
lock.wait( waitMillis );
}
}
catch ( final InterruptedException e )
{}
waitMillis = pauseUntilTimeMillis - System.currentTimeMillis();
}
try
{
volatileCache.loadIfNotValid( key );
key = null;
}
catch ( final InterruptedException e )
{}
}
}
private final Object lock = new Object();
private volatile long pauseUntilTimeMillis = 0;
public void pauseUntil( final long timeMillis )
{
pauseUntilTimeMillis = timeMillis;
interrupt();
}
public void wakeUp()
{
pauseUntilTimeMillis = 0;
synchronized ( lock )
{
lock.notify();
}
}
}
/**
* pause all {@link Fetcher} threads for the specified number of milliseconds.
*/
public void pauseFetcherThreadsFor( final long ms )
{
pauseFetcherThreadsUntil( System.currentTimeMillis() + ms );
}
/**
* pause all {@link Fetcher} threads until the given time (see
* {@link System#currentTimeMillis()}).
*/
public void pauseFetcherThreadsUntil( final long timeMillis )
{
for ( final Fetcher f : fetchers )
f.pauseUntil( timeMillis );
}
/**
* Wake up all Fetcher threads immediately. This ends any
* {@link #pauseFetcherThreadsFor(long)} and
* {@link #pauseFetcherThreadsUntil(long)} set earlier.
*/
public void wakeFetcherThreads()
{
for ( final Fetcher f : fetchers )
f.wakeUp();
}
private final ArrayList< Fetcher > fetchers;
private final CacheIoTiming cacheIoTiming;
@Deprecated
public VolatileGlobalCellCache( final int maxNumTimepoints, final int maxNumSetups, final int maxNumLevels, final int numFetcherThreads )
{
this( maxNumLevels, numFetcherThreads );
}
/**
* @param maxNumLevels
* the highest occurring mipmap level plus 1.
* @param numFetcherThreads
*/
public VolatileGlobalCellCache( final int maxNumLevels, final int numFetcherThreads )
{
this.maxNumLevels = maxNumLevels;
cacheIoTiming = new CacheIoTiming();
queue = new BlockingFetchQueues< Object >( maxNumLevels );
fetchers = new ArrayList< Fetcher >();
for ( int i = 0; i < numFetcherThreads; ++i )
{
final Fetcher f = new Fetcher();
f.setDaemon( true );
f.setName( "Fetcher-" + i );
fetchers.add( f );
f.start();
}
}
/**
* Enqueue the {@link Entry} if it hasn't been enqueued for this frame
* already.
*/
protected void enqueueEntry( final VolatileCacheEntry< ?, ? > entry, final int priority, final boolean enqueuToFront )
{
if ( entry.getEnqueueFrame() < currentQueueFrame )
{
entry.setEnqueueFrame( currentQueueFrame );
queue.put( entry.getKey(), priority, enqueuToFront );
}
}
/**
* Load the data for the {@link Entry} if it is not yet loaded (valid) and
* there is enough {@link IoTimeBudget} left. Otherwise, enqueue the
* {@link Entry} if it hasn't been enqueued for this frame already.
*/
protected void loadOrEnqueue( final VolatileCacheEntry< ?, ? > entry, final int priority, final boolean enqueuToFront )
{
final IoStatistics stats = cacheIoTiming.getThreadGroupIoStatistics();
final IoTimeBudget budget = stats.getIoTimeBudget();
final long timeLeft = budget.timeLeft( priority );
if ( timeLeft > 0 )
{
synchronized ( entry )
{
if ( entry.getValue().isValid() )
return;
enqueueEntry( entry, priority, enqueuToFront );
final long t0 = stats.getIoNanoTime();
stats.start();
try
{
entry.wait( timeLeft / 1000000l, 1 );
}
catch ( final InterruptedException e )
{}
stats.stop();
final long t = stats.getIoNanoTime() - t0;
budget.use( t, priority );
}
}
else
enqueueEntry( entry, priority, enqueuToFront );
}
private void loadEntryWithCacheHints( final VolatileCacheEntry< ?, ? > entry, final CacheHints cacheHints )
{
switch ( cacheHints.getLoadingStrategy() )
{
case VOLATILE:
default:
enqueueEntry( entry, cacheHints.getQueuePriority(), cacheHints.isEnqueuToFront() );
break;
case BLOCKING:
while ( true )
try
{
entry.loadIfNotValid();
break;
}
catch ( final InterruptedException e )
{}
break;
case BUDGETED:
if ( !entry.getValue().isValid() )
loadOrEnqueue( entry, cacheHints.getQueuePriority(), cacheHints.isEnqueuToFront() );
break;
case DONTLOAD:
break;
}
}
/**
* Get a cell if it is in the cache or null. Note, that a cell being in the
* cache only means that there is a data array, but not necessarily that the
* data has already been loaded.
*
* If the cell data has not been loaded, do the following, depending on the
* {@link LoadingStrategy}:
* <ul>
* <li> {@link LoadingStrategy#VOLATILE}:
* Enqueue the cell for asynchronous loading by a fetcher thread, if
* it has not been enqueued in the current frame already.
* <li> {@link LoadingStrategy#BLOCKING}:
* Load the cell data immediately.
* <li> {@link LoadingStrategy#BUDGETED}:
* Load the cell data immediately if there is enough
* {@link IoTimeBudget} left for the current thread group.
* Otherwise enqueue for asynchronous loading, if it has not been
* enqueued in the current frame already.
* <li> {@link LoadingStrategy#DONTLOAD}:
* Do nothing.
* </ul>
*
* @param timepoint
* timepoint coordinate of the cell
* @param setup
* setup coordinate of the cell
* @param level
* level coordinate of the cell
* @param index
* index of the cell (flattened spatial coordinate of the cell)
* @param cacheHints
* {@link LoadingStrategy}, queue priority, and queue order.
* @return a cell with the specified coordinates or null.
*/
public < V extends VolatileCacheValue > V getGlobalIfCached( final Key key, final CacheHints cacheHints )
{
final VolatileCacheEntry< Key, V > entry = volatileCache.get( key );
if ( entry != null )
{
loadEntryWithCacheHints( entry, cacheHints );
return entry.getValue();
}
return null;
}
private final Object cacheLock = new Object();
/**
* Create a new cell with the specified coordinates, if it isn't in the
* cache already. Depending on the {@link LoadingStrategy}, do the
* following:
* <ul>
* <li> {@link LoadingStrategy#VOLATILE}:
* Enqueue the cell for asynchronous loading by a fetcher thread.
* <li> {@link LoadingStrategy#BLOCKING}:
* Load the cell data immediately.
* <li> {@link LoadingStrategy#BUDGETED}:
* Load the cell data immediately if there is enough
* {@link IoTimeBudget} left for the current thread group.
* Otherwise enqueue for asynchronous loading.
* <li> {@link LoadingStrategy#DONTLOAD}:
* Do nothing.
* </ul>
*
* @param cellDims
* dimensions of the cell in pixels
* @param cellMin
* minimum spatial coordinates of the cell in pixels
* @param timepoint
* timepoint coordinate of the cell
* @param setup
* setup coordinate of the cell
* @param level
* level coordinate of the cell
* @param index
* index of the cell (flattened spatial coordinate of the cell)
* @param cacheHints
* {@link LoadingStrategy}, queue priority, and queue order.
* @return a cell with the specified coordinates.
*/
public < K, V extends VolatileCacheValue > V createGlobal( final K key, final CacheHints cacheHints, final VolatileCacheValueLoader< K, V > cacheLoader )
{
VolatileCacheEntry< K, V > entry = null;
synchronized ( cacheLock )
{
entry = volatileCache.get( key );
if ( entry == null )
{
final V value = cacheLoader.createEmptyValue( key );
entry = volatileCache.put( key, value, cacheLoader );
}
}
loadEntryWithCacheHints( entry, cacheHints );
return entry.getValue();
}
/**
* Prepare the cache for providing data for the "next frame":
* <ul>
* <li>the contents of fetch queues is moved to the prefetch.
* <li>some cleaning up of garbage collected entries ({@link #finalizeRemovedCacheEntries()}).
* <li>the internal frame counter is incremented, which will enable
* previously enqueued requests to be enqueued again for the new frame.
* </ul>
*/
@Override
public void prepareNextFrame()
{
queue.clear();
volatileCache.finalizeRemovedCacheEntries();
++currentQueueFrame;
}
/**
* (Re-)initialize the IO time budget, that is, the time that can be spent
* in blocking IO per frame/
*
* @param partialBudget
* Initial budget (in nanoseconds) for priority levels 0 through
* <em>n</em>. The budget for level <em>i>j</em> must always be
* smaller-equal the budget for level <em>j</em>. If <em>n</em>
* is smaller than the maximum number of mipmap levels, the
* remaining priority levels are filled up with budget[n].
*/
@Override
public void initIoTimeBudget( final long[] partialBudget )
{
final IoStatistics stats = cacheIoTiming.getThreadGroupIoStatistics();
if ( stats.getIoTimeBudget() == null )
stats.setIoTimeBudget( new IoTimeBudget( maxNumLevels ) );
stats.getIoTimeBudget().reset( partialBudget );
}
/**
* Get the {@link CacheIoTiming} that provides per thread-group IO
* statistics and budget.
*/
@Override
public CacheIoTiming getCacheIoTiming()
{
return cacheIoTiming;
}
/**
* Remove all references to loaded data as well as all enqueued requests
* from the cache.
*/
public void clearCache()
{
// TODO: we should only clear out our own cache entries not the entire global cache!
volatileCache.clearCache();
prepareNextFrame();
// TODO: add a full clear to BlockingFetchQueues.
// (BlockingFetchQueues.clear() moves stuff to the prefetchQueue.)
}
/**
* Wraps a {@link CacheArrayLoader} as a {@link VolatileCacheValueLoader}.
*/
public static class CacheArrayLoaderWrapper< A extends VolatileAccess > implements VolatileCacheValueLoader< Key, VolatileCell< A > >
{
private final CacheArrayLoader< A > loader;
public CacheArrayLoaderWrapper( final CacheArrayLoader< A > loader )
{
this.loader = loader;
}
@Override
public VolatileCell< A > createEmptyValue( final Key key )
{
final VolatileCell< A > cell = new VolatileCell< A >( key.cellDims, key.cellMin, loader.emptyArray( key.getCellDims() ) );
return cell;
}
@Override
public VolatileCell< A > load( final Key key ) throws InterruptedException
{
final VolatileCell< A > cell = new VolatileCell< A >( key.cellDims, key.cellMin, loader.loadArray( key.timepoint, key.setup, key.level, key.cellDims, key.cellMin ) );
return cell;
}
}
/**
* A {@link CellCache} that forwards to the {@link VolatileGlobalCellCache}.
*
* @param <A>
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public class VolatileCellCache< A extends VolatileAccess > implements CellCache< A >
{
private final int timepoint;
private final int setup;
private final int level;
private CacheHints cacheHints;
private final VolatileCacheValueLoader< Key, VolatileCell< A > > loader;
public VolatileCellCache( final int timepoint, final int setup, final int level, final CacheHints cacheHints, final CacheArrayLoader< A > cacheArrayLoader )
{
this.timepoint = timepoint;
this.setup = setup;
this.level = level;
this.cacheHints = cacheHints;
this.loader = new CacheArrayLoaderWrapper< A >( cacheArrayLoader );
}
@Override
public VolatileCell< A > get( final long index )
{
final Key key = new Key( timepoint, setup, level, index, null, null );
return getGlobalIfCached( key, cacheHints );
}
@Override
public VolatileCell< A > load( final long index, final int[] cellDims, final long[] cellMin )
{
final Key key = new Key( timepoint, setup, level, index, cellDims, cellMin );
return createGlobal( key, cacheHints, loader );
}
@Override
public void setCacheHints( final CacheHints cacheHints )
{
this.cacheHints = cacheHints;
}
}
}
|
package org.jdesktop.swingx.decorator;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Unit test for divers sort-related classes/issues.
*
* <ul>
* <li> SortKey
* <li> SortOrder
* <li> Sorter
* </ul>
* @author Jeanette Winzenburg
*/
public class SorterTest extends TestCase {
/**
* test that sorter returns SortKey
* synched to internal state.
*
*/
public void testSorterSynchedToSortKey() {
int column = 1;
Sorter sorter = new ShuttleSorter(column, false, Collator.getInstance());
SortKey sortKey = sorter.getSortKey();
assertSorterSortKeySynched(sortKey, sorter);
}
/**
* test that sorter updates internal state from SortKey.
*
*/
public void testSorterSynchedFromSortKey() {
// create a sorter for column 0, ascending,
// without explicit comparator
Sorter sorter = new ShuttleSorter();
SortKey sortKey = new SortKey(SortOrder.DESCENDING, 1, Collator.getInstance());
sorter.setSortKey(sortKey);
assertSorterSortKeySynched(sortKey, sorter);
}
public static void assertSorterSortKeySynched(SortKey sortKey, Sorter sorter) {
assertNotNull(sorter);
assertEquals(sortKey.getColumn(), sorter.getColumnIndex());
assertTrue(sortKey.getSortOrder().isSorted(sorter.isAscending()));
assertEquals(sortKey.getSortOrder().isAscending(), sorter.isAscending());
assertSame(sortKey.getComparator(), sorter.getComparator());
}
/**
* test that sorter.setSortKey(..) throws the documented exceptions.
*
*/
public void testSorterSortKeyExceptions() {
Sorter sorter = new ShuttleSorter();
try {
sorter.setSortKey(null);
fail("sorter must throw IllegalArgument for null SortKey");
} catch (IllegalArgumentException e) {
// this is documented behaviour
} catch (Exception e) {
fail("unexpected exception for null Sortkey" + e);
}
try {
SortKey sortKey = new SortKey(SortOrder.UNSORTED, 0, Collator.getInstance());
sorter.setSortKey(sortKey);
fail("sorter must throw IllegalArgument for unsorted SortKey");
} catch (IllegalArgumentException e) {
// this is documented behaviour
} catch (Exception e) {
fail("unexpected exception for unsorted Sortkey" + e);
}
}
/**
* initial addition.
* Testing exceptions thrown in constructors
*/
public void testSortKeyConstructorExceptions() {
try {
new SortKey(null, 2);
fail("SortKey must throw IllegalArgument for null SortOrder");
} catch (IllegalArgumentException e) {
// this is documented behaviour
} catch (Exception e) {
fail("unexpected exception in SortKey with null SortOrder" + e);
}
try {
new SortKey(SortOrder.ASCENDING, -1);
fail("SortKey must throw IllegalArgument for negative column");
} catch (IllegalArgumentException e) {
// this is documented behaviour
} catch (Exception e) {
fail("unexpected exception in SortKey with negative column" + e);
}
}
/**
* initial addition, test constructors parameters.
*/
public void testSortKeyConstructor() {
int column = 3;
SortOrder sortOrder = SortOrder.ASCENDING;
// two parameter constructor
SortKey sortKey = new SortKey(sortOrder, column);
assertEquals(column, sortKey.getColumn());
assertEquals(sortOrder, sortKey.getSortOrder());
assertNull(sortKey.getComparator());
Comparator comparator = Collator.getInstance();
// three parameter constructor
sortKey = new SortKey(sortOrder, column, comparator);
assertEquals(column, sortKey.getColumn());
assertEquals(sortOrder, sortKey.getSortOrder());
assertSame(comparator, sortKey.getComparator());
}
/**
* sanity - SortOrders convenience method state.
*
*/
public void testSortOrderConvenience() {
assertTrue(SortOrder.ASCENDING.isSorted());
assertTrue(SortOrder.ASCENDING.isAscending());
assertTrue(SortOrder.DESCENDING.isSorted());
assertFalse(SortOrder.DESCENDING.isAscending());
assertFalse(SortOrder.UNSORTED.isSorted());
assertFalse(SortOrder.UNSORTED.isAscending());
// wanted: ascending sort
assertEquals(false, SortOrder.UNSORTED.isSorted(true));
assertEquals(false, SortOrder.DESCENDING.isSorted(true));
assertEquals(true, SortOrder.ASCENDING.isSorted(true));
// wanted: descending sort
assertEquals(false, SortOrder.UNSORTED.isSorted(false));
assertEquals(true, SortOrder.DESCENDING.isSorted(false));
assertEquals(false, SortOrder.ASCENDING.isSorted(false));
}
/**
* test new method sorter.getSortOrder(), must be in synch with
* sorter.isAscending()
*
*/
public void testSortOrder() {
Sorter sorter = new ShuttleSorter();
assertSame(SortOrder.ASCENDING, sorter.getSortOrder());
Sorter other = new ShuttleSorter(0, false);
assertSame(SortOrder.DESCENDING, other.getSortOrder());
other.setAscending(true);
assertSame(SortOrder.ASCENDING, other.getSortOrder());
}
/**
* Issue #179: make sure to use the correct default collator.
*
*/
public void testCollator() {
Locale defaultLocale = Locale.getDefault();
Locale western = Locale.GERMAN;
Locale eastern = Locale.CHINESE;
Collator westernCol = Collator.getInstance(western);
Collator easternCol = Collator.getInstance(eastern);
// sanity assert: collators are different
assertFalse(westernCol.equals(easternCol));
Locale.setDefault(western);
// sanity assert: default collator is western
assertEquals(westernCol, Collator.getInstance());
Sorter sorter = new ShuttleSorter();
assertEquals("sorter must use collator default locale",
Collator.getInstance(), sorter.getCollator());
Locale.setDefault(eastern);
// sanity assert: default collator is eastern
assertEquals(easternCol, Collator.getInstance());
sorter.toggle();
assertEquals("collator must use default locale",
Collator.getInstance(), sorter.getCollator());
Locale.setDefault(defaultLocale);
}
}
|
package interfaz;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import dominio.Personaje;
import mensajeria.PaquetePersonaje;
import recursos.Recursos;
/**
* Esta clase es la responsable de graficar a los personajes
* @author Marvix
*/
public final class EstadoDePersonaje {
private static final int ANCHOBARRA = 122;
private static final int ALTOSALUD = 14;
private static final int ALTOENERGIA = 14;
private static final int ALTOEXPERIENCIA = 6;
private static final int ALTOMINIATURA = 64;
private static final int ANCHOMINIATURA = 64;
private static final int OFFSET_X_MINIATURA_PERSONAJE = 10;
private static final int OFFSET_Y_MINIATURA_PERSONAJE = 9;
private static final int FONT_SIZE_10 = 10;
private static final int FONT_SIZE_8 = 8;
private static final int OFFSET_X_BARRA_SALUD_ENERGIA = 80;
private static final int OFFSET_Y_BARRA_SALUD = 26;
private static final int OFFSET_Y_BARRA_ENERGIA = 42;
private static final int OFFSET_X_BARRA_SALUD_ENERGIA_TOPE = 132;
private static final int OFFSET_Y_BARRA_SALUD_TOPE = 37;
private static final int OFFSET_Y_BARRA_ENERGIA_TOPE = 52;
private static final int OFFSET_X_BARRA_EXP = 77;
private static final int OFFSET_Y_BARRA_EXP = 65;
private static final int OFFSET_X_TABLA_NIVELES = 132;
private static final int OFFSET_Y_NIVELES = 70;
private static final int OFFSET_X_NIVELES = 59;
/**
* Constructor de EstadoDePersonaje
*/
private EstadoDePersonaje() { }
/**
* @param g graficador
* @param x posicion x del personaje
* @param y posicion y del personaje
* @param personaje la informacion del personaje
* @param miniaturaPersonaje imagen del personaje
*/
public static void dibujarEstadoDePersonaje(final Graphics g, final int x,
final int y, final Personaje personaje, final BufferedImage miniaturaPersonaje) {
int drawBarra = 0;
g.drawImage(Recursos.getEstadoPersonaje(), x, y, null);
g.drawImage(miniaturaPersonaje, x + OFFSET_X_MINIATURA_PERSONAJE, y
+ OFFSET_Y_MINIATURA_PERSONAJE, ANCHOMINIATURA, ALTOMINIATURA, null);
if (personaje.getSalud() == personaje.getSaludTope()) {
drawBarra = ANCHOBARRA;
} else {
drawBarra = (personaje.getSalud() * ANCHOBARRA) / personaje.getSaludTope();
}
g.setColor(Color.WHITE);
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_10));
g.drawImage(Recursos.getBarraSalud(), x + OFFSET_X_BARRA_SALUD_ENERGIA,
y + OFFSET_Y_BARRA_SALUD, drawBarra, ALTOSALUD, null);
g.drawString(String.valueOf(personaje.getSalud()) + " / "
+ String.valueOf(personaje.getSaludTope()), x + OFFSET_X_BARRA_SALUD_ENERGIA_TOPE,
y + OFFSET_Y_BARRA_SALUD_TOPE);
if (personaje.getEnergia() == personaje.getEnergiaTope()) {
drawBarra = ANCHOBARRA;
} else {
drawBarra = (personaje.getEnergia() * ANCHOBARRA) / personaje.getEnergiaTope();
}
g.drawImage(Recursos.getBarraEnergia(), x + OFFSET_X_BARRA_SALUD_ENERGIA,
y + OFFSET_Y_BARRA_ENERGIA, drawBarra, ALTOENERGIA, null);
g.drawString(String.valueOf(personaje.getEnergia()) + " / "
+ String.valueOf(personaje.getEnergiaTope()), x + OFFSET_X_BARRA_SALUD_ENERGIA_TOPE,
y + OFFSET_Y_BARRA_ENERGIA_TOPE);
if (personaje.getExperiencia() == Personaje.getTablaDeNiveles()[personaje.getNivel() + 1]) {
drawBarra = ANCHOBARRA;
} else {
drawBarra = (personaje.getExperiencia() * ANCHOBARRA)
/ Personaje.getTablaDeNiveles()[personaje.getNivel() + 1];
}
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_8));
g.drawImage(Recursos.getBarraExperiencia(), x + OFFSET_X_BARRA_EXP,
y + OFFSET_Y_BARRA_EXP, drawBarra, ALTOEXPERIENCIA, null);
g.drawString(String.valueOf(personaje.getExperiencia()) + " / "
+ String.valueOf(Personaje.getTablaDeNiveles()[personaje.getNivel() + 1]),
x + OFFSET_X_TABLA_NIVELES, y + OFFSET_Y_NIVELES);
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_10));
g.setColor(Color.GREEN);
g.drawString(String.valueOf(personaje.getNivel()), x + OFFSET_X_NIVELES,
y + OFFSET_Y_NIVELES);
}
/**
* @param g graficador
* @param x posicion x del personaje
* @param y posicion y del personaje
* @param personaje la informacion del personaje
* @param miniaturaPersonaje imagen del personaje
*/
public static void dibujarEstadoDePersonaje(final Graphics g, final int x, final int y,
final PaquetePersonaje personaje, final BufferedImage miniaturaPersonaje) {
int drawBarra = 0;
g.drawImage(Recursos.getEstadoPersonaje(), x, y, null);
g.drawImage(miniaturaPersonaje, x + OFFSET_X_MINIATURA_PERSONAJE,
y + OFFSET_Y_MINIATURA_PERSONAJE, ANCHOMINIATURA, ALTOMINIATURA, null);
g.setColor(Color.WHITE);
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_10));
g.drawImage(Recursos.getBarraSalud(), x + OFFSET_X_BARRA_SALUD_ENERGIA,
y + OFFSET_Y_BARRA_SALUD, ANCHOBARRA, ALTOSALUD, null);
g.drawString(String.valueOf(personaje.getSaludTope()) + " / "
+ String.valueOf(personaje.getSaludTope()), x + OFFSET_X_BARRA_SALUD_ENERGIA_TOPE,
y + OFFSET_Y_BARRA_SALUD_TOPE);
g.drawImage(Recursos.getBarraEnergia(), x + OFFSET_X_BARRA_SALUD_ENERGIA,
y + OFFSET_Y_BARRA_ENERGIA, ANCHOBARRA, ALTOENERGIA, null);
g.drawString(String.valueOf(personaje.getEnergiaTope()) + " / "
+ String.valueOf(personaje.getEnergiaTope()), x + OFFSET_X_BARRA_SALUD_ENERGIA_TOPE,
y + OFFSET_Y_BARRA_ENERGIA_TOPE);
if (personaje.getExperiencia() == Personaje.getTablaDeNiveles()[personaje.getNivel() + 1]) {
drawBarra = ANCHOBARRA;
} else {
drawBarra = (personaje.getExperiencia() * ANCHOBARRA)
/ Personaje.getTablaDeNiveles()[personaje.getNivel() + 1];
}
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_8));
g.drawImage(Recursos.getBarraExperiencia(), x + OFFSET_X_BARRA_EXP,
y + OFFSET_Y_BARRA_EXP, drawBarra, ALTOEXPERIENCIA, null);
g.drawString(String.valueOf(personaje.getExperiencia()) + " / "
+ String.valueOf(Personaje.getTablaDeNiveles()[personaje.getNivel() + 1]),
x + OFFSET_X_TABLA_NIVELES, y + OFFSET_Y_NIVELES);
g.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE_10));
g.setColor(Color.GREEN);
g.drawString(String.valueOf(personaje.getNivel()), x + OFFSET_X_NIVELES, y + OFFSET_Y_NIVELES);
}
}
|
package landmaster.plustic;
import java.util.*;
import landmaster.plustic.api.*;
import landmaster.plustic.block.*;
import landmaster.plustic.proxy.*;
import landmaster.plustic.config.*;
import landmaster.plustic.fluids.*;
import landmaster.plustic.net.*;
import landmaster.plustic.util.*;
import landmaster.plustic.traits.*;
import net.minecraft.block.*;
import net.minecraft.init.*;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.util.text.*;
import net.minecraftforge.common.*;
import net.minecraftforge.fluids.*;
import net.minecraftforge.fml.common.*;
import net.minecraftforge.fml.common.event.*;
import net.minecraftforge.fml.common.registry.*;
import net.minecraftforge.oredict.*;
import net.minecraftforge.fml.common.Mod.*;
import slimeknights.tconstruct.*;
import slimeknights.tconstruct.library.*;
import slimeknights.tconstruct.library.materials.*;
import slimeknights.tconstruct.shared.*;
import static slimeknights.tconstruct.library.materials.MaterialTypes.*;
import static slimeknights.tconstruct.library.utils.HarvestLevels.*;
import static slimeknights.tconstruct.tools.TinkerTraits.*;
@Mod(modid = PlusTiC.MODID, name = PlusTiC.NAME, version = PlusTiC.VERSION, dependencies = PlusTiC.DEPENDS)
public class PlusTiC {
public static final String MODID = "plustic";
public static final String NAME = "PlusTiC";
public static final String VERSION = "3.1";
public static final String DEPENDS = "required-after:mantle;required-after:tconstruct;after:Mekanism;after:BiomesOPlenty;after:Botania;after:advancedRocketry;after:armorplus;after:EnderIO;after:projectred-exploration;after:thermalfoundation";
public static Config config;
@Mod.Instance(PlusTiC.MODID)
public static PlusTiC INSTANCE;
@SidedProxy(serverSide = "landmaster.plustic.proxy.CommonProxy", clientSide = "landmaster.plustic.proxy.ClientProxy")
public static CommonProxy proxy;
public static Map<String,Material> materials = new HashMap<>();
public static Map<String,MaterialIntegration> materialIntegrations = new HashMap<>();
public static final BowMaterialStats justWhy = new BowMaterialStats(0.2f, 0.4f, -1f);
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
Config config = new Config(event);
config.sync();
initBase();
initBoP();
initMekanism();
initBotania();
initAdvRocketry();
initArmorPlus();
initEnderIO();
initTF();
Utils.integrate(materials,materialIntegrations);
Utils.registerModifiers();
}
private void initBase() {
if (Config.base) {
Material tnt = new Material("tnt", TextFormatting.RED);
tnt.addTrait(Explosive.explosive);
tnt.addItem(Blocks.TNT, Material.VALUE_Ingot);
tnt.setRepresentativeItem(Blocks.TNT);
tnt.setCraftable(true);
proxy.setRenderInfo(tnt, 0xFF4F4F);
TinkerRegistry.addMaterialStats(tnt, new ArrowShaftMaterialStats(0.95f, 0));
materials.put("tnt", tnt);
if (TinkerIntegration.isIntegrated(TinkerFluids.aluminum)) {
// alumite is back! (with some changes)
Item alumiteIngot = new Item().setUnlocalizedName("alumiteingot")
.setRegistryName("alumiteingot");
alumiteIngot.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(alumiteIngot);
OreDictionary.registerOre("ingotAlumite", alumiteIngot);
proxy.registerItemRenderer(alumiteIngot, 0, "alumiteingot");
Item alumiteNugget = new Item().setUnlocalizedName("alumitenugget")
.setRegistryName("alumitenugget");
alumiteNugget.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(alumiteNugget);
OreDictionary.registerOre("nuggetAlumite", alumiteNugget);
proxy.registerItemRenderer(alumiteNugget, 0, "alumitenugget");
Block alumiteBlock = new MetalBlock("alumiteblock");
alumiteBlock.setCreativeTab(TinkerRegistry.tabGeneral);
ItemBlock alumiteBlock_item = new ItemBlock(alumiteBlock);
GameRegistry.register(alumiteBlock);
GameRegistry.register(alumiteBlock_item, alumiteBlock.getRegistryName());
OreDictionary.registerOre("blockAlumite", alumiteBlock);
proxy.registerItemRenderer(alumiteBlock_item, 0, "alumiteblock");
Material alumite = new Material("alumite", TextFormatting.RED);
alumite.addTrait(Global.global);
alumite.addItem("ingotAlumite", 1, Material.VALUE_Ingot);
alumite.setCraftable(false).setCastable(true);
alumite.setRepresentativeItem(alumiteIngot);
proxy.setRenderInfo(alumite, 0xFFE0F1);
FluidMolten alumiteFluid = Utils.fluidMetal("alumite", 0xFFE0F1);
alumiteFluid.setTemperature(890);
Utils.initFluidMetal(alumiteFluid);
alumite.setFluid(alumiteFluid);
TinkerRegistry.registerAlloy(new FluidStack(alumiteFluid, 3),
new FluidStack(TinkerFluids.aluminum, 5),
new FluidStack(TinkerFluids.iron, 2),
new FluidStack(TinkerFluids.obsidian, 2));
TinkerRegistry.addMaterialStats(alumite,
new HeadMaterialStats(700, 6.8f, 5.5f, COBALT),
new HandleMaterialStats(1.10f, 70),
new ExtraMaterialStats(80),
new BowMaterialStats(0.65f, 1.6f, 7f));
materials.put("alumite", alumite);
}
}
}
private void initBoP() {
if ((Config.bop && Loader.isModLoaded("BiomesOPlenty"))
|| (Config.projectRed && Loader.isModLoaded("projectred-exploration"))) {
Material sapphire = new Material("sapphire",TextFormatting.BLUE);
sapphire.addTrait(aquadynamic);
sapphire.addItem("gemSapphire", 1, Material.VALUE_Ingot);
sapphire.setCraftable(true);
//sapphire.setRepresentativeItem(OreDictionary.getOres("gemSapphire").get(0));
proxy.setRenderInfo(sapphire,0x0000FF);
TinkerRegistry.addMaterialStats(sapphire, new HeadMaterialStats(700, 5, 6.4f, COBALT));
TinkerRegistry.addMaterialStats(sapphire, new HandleMaterialStats(1, 100));
TinkerRegistry.addMaterialStats(sapphire, new ExtraMaterialStats(120));
TinkerRegistry.addMaterialStats(sapphire, new BowMaterialStats(1,1.5f,4));
materials.put("sapphire", sapphire);
Material ruby = new Material("ruby",TextFormatting.RED);
ruby.addTrait(BloodyMary.bloodymary);
ruby.addTrait(sharp,HEAD);
ruby.addItem("gemRuby", 1, Material.VALUE_Ingot);
ruby.setCraftable(true);
//ruby.setRepresentativeItem(OreDictionary.getOres("gemRuby").get(0));
proxy.setRenderInfo(ruby,0xFF0000);
TinkerRegistry.addMaterialStats(ruby, new HeadMaterialStats(660, 4.6f, 6.4f, COBALT));
TinkerRegistry.addMaterialStats(ruby, new HandleMaterialStats(1.2f, 0));
TinkerRegistry.addMaterialStats(ruby, new ExtraMaterialStats(20));
TinkerRegistry.addMaterialStats(ruby, new BowMaterialStats(1.5f,1.4f,4));
materials.put("ruby", ruby);
Material peridot = new Material("peridot",TextFormatting.GREEN);
peridot.addTrait(NaturesBlessing.naturesblessing);
peridot.addItem("gemPeridot", 1, Material.VALUE_Ingot);
peridot.setCraftable(true);
//peridot.setRepresentativeItem(OreDictionary.getOres("gemPeridot").get(0));
proxy.setRenderInfo(peridot,0xBEFA5C);
TinkerRegistry.addMaterialStats(peridot, new HeadMaterialStats(640, 4.0f, 6.1f, COBALT));
TinkerRegistry.addMaterialStats(peridot, new HandleMaterialStats(1.3f, -30));
TinkerRegistry.addMaterialStats(peridot, new ExtraMaterialStats(20));
TinkerRegistry.addMaterialStats(peridot, new BowMaterialStats(1.4f,1.4f,4));
materials.put("peridot", peridot);
}
if (Config.bop && Loader.isModLoaded("BiomesOPlenty")) {
Material malachite = new Material("malachite_gem",TextFormatting.DARK_GREEN);
malachite.addTrait(NaturesWrath.natureswrath);
malachite.addItem("gemMalachite", 1, Material.VALUE_Ingot);
malachite.setCraftable(true);
Utils.setDispItem(malachite, "biomesoplenty", "gem", 5);
proxy.setRenderInfo(malachite,0x007523);
TinkerRegistry.addMaterialStats(malachite, new HeadMaterialStats(640, 3.0f, 6.1f, COBALT));
TinkerRegistry.addMaterialStats(malachite, new HandleMaterialStats(1.3f, -30));
TinkerRegistry.addMaterialStats(malachite, new ExtraMaterialStats(20));
TinkerRegistry.addMaterialStats(malachite, new BowMaterialStats(1.4f,1.4f,4));
materials.put("malachite", malachite);
Material amber = new Material("amber",TextFormatting.GOLD);
amber.addTrait(shocking);
amber.addTrait(Thundering.thundering, PROJECTILE);
amber.addTrait(Thundering.thundering, SHAFT);
amber.addItem("gemAmber", 1, Material.VALUE_Ingot);
amber.setCraftable(true);
Utils.setDispItem(amber, "biomesoplenty", "gem", 7);
proxy.setRenderInfo(amber,0xFFD000);
TinkerRegistry.addMaterialStats(amber, new HeadMaterialStats(730, 4.6f, 5.7f, COBALT));
TinkerRegistry.addMaterialStats(amber, new HandleMaterialStats(1, 30));
TinkerRegistry.addMaterialStats(amber, new ExtraMaterialStats(100));
TinkerRegistry.addMaterialStats(amber, justWhy);
TinkerRegistry.addMaterialStats(amber, new ArrowShaftMaterialStats(1, 5));
materials.put("amber", amber);
Material topaz = new Material("topaz",TextFormatting.GOLD);
topaz.addTrait(NaturesPower.naturespower);
topaz.addItem("gemTopaz", 1, Material.VALUE_Ingot);
topaz.setCraftable(true);
Utils.setDispItem(topaz, "biomesoplenty", "gem", 3);
proxy.setRenderInfo(topaz,0xFFFF00);
TinkerRegistry.addMaterialStats(topaz, new HeadMaterialStats(690, 6, 6, COBALT));
TinkerRegistry.addMaterialStats(topaz, new HandleMaterialStats(0.8f, 70));
TinkerRegistry.addMaterialStats(topaz, new ExtraMaterialStats(65));
TinkerRegistry.addMaterialStats(topaz, new BowMaterialStats(0.4f,1.4f,7));
materials.put("topaz", topaz);
Material tanzanite = new Material("tanzanite",TextFormatting.LIGHT_PURPLE);
tanzanite.addTrait(freezing);
tanzanite.addItem("gemTanzanite", 1, Material.VALUE_Ingot);
tanzanite.setCraftable(true);
Utils.setDispItem(tanzanite, "biomesoplenty", "gem", 4);
proxy.setRenderInfo(tanzanite,0x6200FF);
TinkerRegistry.addMaterialStats(tanzanite, new HeadMaterialStats(650, 3, 7, COBALT));
TinkerRegistry.addMaterialStats(tanzanite, new HandleMaterialStats(0.7f, 0));
TinkerRegistry.addMaterialStats(tanzanite, new ExtraMaterialStats(25));
TinkerRegistry.addMaterialStats(tanzanite, justWhy);
materials.put("tanzanite", tanzanite);
Material amethyst = new Material("amethyst",TextFormatting.LIGHT_PURPLE);
amethyst.addTrait(Apocalypse.apocalypse);
amethyst.addItem(
Item.REGISTRY.getObject(new ResourceLocation("biomesoplenty", "gem")),
1, Material.VALUE_Ingot);
amethyst.setCraftable(true);
Utils.setDispItem(amethyst, "biomesoplenty", "gem");
proxy.setRenderInfo(amethyst,0xFF00FF);
TinkerRegistry.addMaterialStats(amethyst, new HeadMaterialStats(1200, 6, 10, COBALT));
TinkerRegistry.addMaterialStats(amethyst, new HandleMaterialStats(1.6f, 100));
TinkerRegistry.addMaterialStats(amethyst, new ExtraMaterialStats(100));
TinkerRegistry.addMaterialStats(amethyst, new BowMaterialStats(0.65f, 1.7f, 6.5f));
materials.put("amethyst", amethyst);
}
}
private void initMekanism() {
if (Config.mekanism && Loader.isModLoaded("Mekanism")) {
// ugly workaround for dusts not melting
Item tinDust = new Item().setUnlocalizedName("tindust").setRegistryName("tindust");
tinDust.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(tinDust);
OreDictionary.registerOre("dustTin", tinDust);
proxy.registerItemRenderer(tinDust, 0, "tindust");
Item osmiumDust = new Item().setUnlocalizedName("osmiumdust").setRegistryName("osmiumdust");
osmiumDust.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(osmiumDust);
OreDictionary.registerOre("dustOsmium", osmiumDust);
proxy.registerItemRenderer(osmiumDust, 0, "osmiumdust");
Item steelDust = new Item().setUnlocalizedName("steeldust").setRegistryName("steeldust");
steelDust.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(steelDust);
OreDictionary.registerOre("dustSteel", steelDust);
proxy.registerItemRenderer(steelDust, 0, "steeldust");
Item bronzeNugget = new Item().setUnlocalizedName("bronzenugget").setRegistryName("bronzenugget");
bronzeNugget.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(bronzeNugget);
OreDictionary.registerOre("nuggetBronze", bronzeNugget);
proxy.registerItemRenderer(bronzeNugget, 0, "bronzenugget");
Item bronzeIngot = new Item().setUnlocalizedName("bronzeingot").setRegistryName("bronzeingot");
bronzeIngot.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(bronzeIngot);
OreDictionary.registerOre("ingotBronze", bronzeIngot);
proxy.registerItemRenderer(bronzeIngot, 0, "bronzeingot");
// ugly workaround for molten tin not registering
if (OreDictionary.getOres("ingotTin").size() == 0 || TinkerRegistry.getMelting(OreDictionary.getOres("ingotTin").get(0)) == null) {
MaterialIntegration tinI = new MaterialIntegration(null, TinkerFluids.tin, "Tin");
tinI.integrate();
tinI.integrateRecipes();
materialIntegrations.put("tin", tinI);
}
Material osmium = new Material("osmium",TextFormatting.BLUE);
osmium.addTrait(dense);
osmium.addTrait(established);
osmium.addItem("ingotOsmium", 1, Material.VALUE_Ingot);
osmium.setCraftable(false).setCastable(true);
proxy.setRenderInfo(osmium,0xBFD0FF);
FluidMolten osmiumFluid = Utils.fluidMetal("osmium",0xBFD0FF);
osmiumFluid.setTemperature(820);
Utils.initFluidMetal(osmiumFluid);
osmium.setFluid(osmiumFluid);
TinkerRegistry.addMaterialStats(osmium, new HeadMaterialStats(500, 6, 5.8f, DIAMOND));
TinkerRegistry.addMaterialStats(osmium, new HandleMaterialStats(1.2f, 45));
TinkerRegistry.addMaterialStats(osmium, new ExtraMaterialStats(40));
TinkerRegistry.addMaterialStats(osmium, new BowMaterialStats(0.65f, 1.3f, 5.7f));
materials.put("osmium", osmium);
Material refinedObsidian = new Material("refinedObsidian",TextFormatting.LIGHT_PURPLE);
refinedObsidian.addTrait(dense);
refinedObsidian.addTrait(duritos);
refinedObsidian.addItem("ingotRefinedObsidian", 1, Material.VALUE_Ingot);
refinedObsidian.setCraftable(false).setCastable(true);
proxy.setRenderInfo(refinedObsidian, 0x5D00FF);
FluidMolten refinedObsidianFluid = Utils.fluidMetal("refinedObsidian", 0x5D00FF);
refinedObsidianFluid.setTemperature(860);
Utils.initFluidMetal(refinedObsidianFluid);
refinedObsidian.setFluid(refinedObsidianFluid);
TinkerRegistry.addMaterialStats(refinedObsidian, new HeadMaterialStats(2500, 7, 11, COBALT));
TinkerRegistry.addMaterialStats(refinedObsidian, new HandleMaterialStats(1.5f, -100));
TinkerRegistry.addMaterialStats(refinedObsidian, new ExtraMaterialStats(160));
TinkerRegistry.addMaterialStats(refinedObsidian, justWhy);
materials.put("refinedObsidian", refinedObsidian);
}
}
private void initBotania() {
if (Config.botania && Loader.isModLoaded("Botania")) {
Material terrasteel = new Material("terrasteel",TextFormatting.GREEN);
terrasteel.addTrait(Mana.mana);
terrasteel.addTrait(Terrafirma.terrafirma[0]);
terrasteel.addTrait(Terrafirma.terrafirma[1],HEAD);
terrasteel.addItem("ingotTerrasteel", 1, Material.VALUE_Ingot);
terrasteel.setCraftable(false).setCastable(true);
Utils.setDispItem(terrasteel, "botania", "manaResource", 4);
proxy.setRenderInfo(terrasteel, 0x00FF00);
FluidMolten terrasteelFluid = Utils.fluidMetal("terrasteel", 0x00FF00);
terrasteelFluid.setTemperature(760);
Utils.initFluidMetal(terrasteelFluid);
terrasteel.setFluid(terrasteelFluid);
TinkerRegistry.addMaterialStats(terrasteel, new HeadMaterialStats(1562, 9, 5, OBSIDIAN));
TinkerRegistry.addMaterialStats(terrasteel, new HandleMaterialStats(1f, 10));
TinkerRegistry.addMaterialStats(terrasteel, new ExtraMaterialStats(10));
TinkerRegistry.addMaterialStats(terrasteel, new BowMaterialStats(0.4f, 2f, 9f));
materials.put("terrasteel", terrasteel);
Material elementium = new Material("elementium",TextFormatting.LIGHT_PURPLE);
elementium.addTrait(Mana.mana);
elementium.addTrait(Elemental.elemental,HEAD);
elementium.addItem("ingotElvenElementium", 1, Material.VALUE_Ingot);
elementium.setCraftable(false).setCastable(true);
Utils.setDispItem(elementium, "botania", "manaResource", 7);
proxy.setRenderInfo(elementium, 0xF66AFD);
FluidMolten elementiumFluid = Utils.fluidMetal("elementium", 0xF66AFD);
elementiumFluid.setTemperature(800);
Utils.initFluidMetal(elementiumFluid);
elementium.setFluid(elementiumFluid);
TinkerRegistry.addMaterialStats(elementium,
new HeadMaterialStats(204, 6.00f, 4.00f, DIAMOND),
new HandleMaterialStats(0.85f, 60),
new ExtraMaterialStats(50));
TinkerRegistry.addMaterialStats(elementium, new BowMaterialStats(0.5f, 1.5f, 7f));
materials.put("elvenElementium", elementium);
Material manasteel = new Material("manasteel",TextFormatting.BLUE);
manasteel.addTrait(Mana.mana);
manasteel.addItem("ingotManasteel", 1, Material.VALUE_Ingot);
manasteel.setCraftable(false).setCastable(true);
Utils.setDispItem(manasteel, "botania", "manaResource");
proxy.setRenderInfo(manasteel, 0x54E5FF);
FluidMolten manasteelFluid = Utils.fluidMetal("manasteel", 0x54E5FF);
manasteelFluid.setTemperature(681);
Utils.initFluidMetal(manasteelFluid);
manasteel.setFluid(manasteelFluid);
TinkerRegistry.addMaterialStats(manasteel,
new HeadMaterialStats(540, 7.00f, 6.00f, OBSIDIAN),
new HandleMaterialStats(1.25f, 150),
new ExtraMaterialStats(60));
TinkerRegistry.addMaterialStats(manasteel, new BowMaterialStats(1, 1.1f, 1));
materials.put("manasteel", manasteel);
}
}
private void initAdvRocketry() {
if (Config.advancedRocketry && Loader.isModLoaded("libVulpes")) {
Material iridium = new Material("iridium", TextFormatting.GRAY);
iridium.addTrait(dense);
iridium.addTrait(alien, HEAD);
iridium.addItem("ingotIridium", 1, Material.VALUE_Ingot);
iridium.setCraftable(false).setCastable(true);
Utils.setDispItem(iridium, "libvulpes", "productingot", 10);
proxy.setRenderInfo(iridium, 0xE5E5E5);
FluidMolten iridiumFluid = Utils.fluidMetal("iridium", 0xE5E5E5);
iridiumFluid.setTemperature(810);
Utils.initFluidMetal(iridiumFluid);
iridium.setFluid(iridiumFluid);
TinkerRegistry.addMaterialStats(iridium, new HeadMaterialStats(520, 6, 5.8f, DIAMOND));
TinkerRegistry.addMaterialStats(iridium, new HandleMaterialStats(1.15f, -20));
TinkerRegistry.addMaterialStats(iridium, new ExtraMaterialStats(60));
TinkerRegistry.addMaterialStats(iridium, justWhy);
materials.put("iridium", iridium);
Material titanium = new Material("titanium", TextFormatting.WHITE);
titanium.addTrait(Light.light);
titanium.addTrait(Anticorrosion.anticorrosion, HEAD);
titanium.addItem("ingotTitanium", 1, Material.VALUE_Ingot);
titanium.setCraftable(false).setCastable(true);
Utils.setDispItem(titanium, "libvulpes", "productingot", 7);
proxy.setRenderInfo(titanium, 0xDCE1EA);
FluidMolten titaniumFluid = Utils.fluidMetal("titanium", 0xDCE1EA);
titaniumFluid.setTemperature(790);
Utils.initFluidMetal(titaniumFluid);
titanium.setFluid(titaniumFluid);
TinkerRegistry.addMaterialStats(titanium, new HeadMaterialStats(560, 6, 6, OBSIDIAN));
TinkerRegistry.addMaterialStats(titanium, new HandleMaterialStats(1.4f, 0));
TinkerRegistry.addMaterialStats(titanium, new ExtraMaterialStats(40));
TinkerRegistry.addMaterialStats(titanium, new BowMaterialStats(1.15f, 1.3f, 6.6f));
TinkerRegistry.addMaterialStats(titanium, new FletchingMaterialStats(1.0f, 1.3f));
materials.put("titanium", titanium);
if (Config.mekanism && Loader.isModLoaded("Mekanism")) {
// osmiridium
Item osmiridiumIngot = new Item().setUnlocalizedName("osmiridiumingot")
.setRegistryName("osmiridiumingot");
osmiridiumIngot.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(osmiridiumIngot);
OreDictionary.registerOre("ingotOsmiridium", osmiridiumIngot);
proxy.registerItemRenderer(osmiridiumIngot, 0, "osmiridiumingot");
Item osmiridiumNugget = new Item().setUnlocalizedName("osmiridiumnugget")
.setRegistryName("osmiridiumnugget");
osmiridiumNugget.setCreativeTab(TinkerRegistry.tabGeneral);
GameRegistry.register(osmiridiumNugget);
OreDictionary.registerOre("nuggetOsmiridium", osmiridiumNugget);
proxy.registerItemRenderer(osmiridiumNugget, 0, "osmiridiumnugget");
MetalBlock osmiridiumBlock = new MetalBlock("osmiridiumblock");
osmiridiumBlock.setCreativeTab(TinkerRegistry.tabGeneral);
ItemBlock osmiridiumBlock_item = new ItemBlock(osmiridiumBlock);
GameRegistry.register(osmiridiumBlock);
GameRegistry.register(osmiridiumBlock_item, osmiridiumBlock.getRegistryName());
OreDictionary.registerOre("blockOsmiridium", osmiridiumBlock);
proxy.registerItemRenderer(osmiridiumBlock_item, 0, "osmiridiumblock");
Material osmiridium = new Material("osmiridium", TextFormatting.LIGHT_PURPLE);
osmiridium.addTrait(DevilsStrength.devilsstrength);
osmiridium.addTrait(Anticorrosion.anticorrosion, HEAD);
osmiridium.addItem("ingotOsmiridium", 1, Material.VALUE_Ingot);
osmiridium.setCraftable(false).setCastable(true);
osmiridium.setRepresentativeItem(osmiridiumIngot);
proxy.setRenderInfo(osmiridium, 0x666DFF);
FluidMolten osmiridiumFluid = Utils.fluidMetal("osmiridium", 0x666DFF);
osmiridiumFluid.setTemperature(840);
Utils.initFluidMetal(osmiridiumFluid);
osmiridium.setFluid(osmiridiumFluid);
TinkerRegistry.registerAlloy(new FluidStack(osmiridiumFluid, 2),
new FluidStack(materials.get("osmium").getFluid(), 1),
new FluidStack(iridiumFluid, 1));
TinkerRegistry.addMaterialStats(osmiridium, new HeadMaterialStats(1300, 6.8f, 8, COBALT));
TinkerRegistry.addMaterialStats(osmiridium, new HandleMaterialStats(1.5f, 30));
TinkerRegistry.addMaterialStats(osmiridium, new ExtraMaterialStats(80));
TinkerRegistry.addMaterialStats(osmiridium, new BowMaterialStats(0.38f, 2.05f, 10));
materials.put("osmiridium", osmiridium);
}
}
}
private void initArmorPlus() {
if (Config.armorPlus && Loader.isModLoaded("armorplus")) {
Material witherBone = new Material("witherbone", TextFormatting.BLACK);
witherBone.addTrait(Apocalypse.apocalypse);
witherBone.addItem("witherBone", 1, Material.VALUE_Ingot);
witherBone.setCraftable(true);
proxy.setRenderInfo(witherBone, 0x000000);
TinkerRegistry.addMaterialStats(witherBone, new ArrowShaftMaterialStats(1.0f, 20));
materials.put("witherbone", witherBone);
Material guardianScale = new Material("guardianscale", TextFormatting.AQUA);
guardianScale.addTrait(DivineShield.divineShield, HEAD);
guardianScale.addTrait(aquadynamic);
guardianScale.addItem("scaleGuardian", 1, Material.VALUE_Ingot);
guardianScale.setCraftable(true);
proxy.setRenderInfo(guardianScale, 0x00FFFF);
TinkerRegistry.addMaterialStats(guardianScale, new HeadMaterialStats(600, 6.2f, 7, COBALT));
TinkerRegistry.addMaterialStats(guardianScale, new HandleMaterialStats(0.9f, 40));
TinkerRegistry.addMaterialStats(guardianScale, new ExtraMaterialStats(80));
TinkerRegistry.addMaterialStats(guardianScale, new BowMaterialStats(0.85f, 1.2f, 5.5f));
materials.put("guardianscale", guardianScale);
}
}
private void initEnderIO() {
if (Config.enderIO && Loader.isModLoaded("EnderIO")) {
Fluid coalFluid = Utils.fluidMetal("coal", 0x111111);
coalFluid.setTemperature(500);
Utils.initFluidMetal(coalFluid);
TinkerRegistry.registerMelting("coal", coalFluid, 100);
TinkerRegistry.registerBasinCasting(new ItemStack(Blocks.COAL_BLOCK),
null, coalFluid, 900);
TinkerRegistry.registerTableCasting(new ItemStack(Items.COAL),
null, coalFluid, 100);
Material darkSteel = new Material("darksteel_plustic_enderio", TextFormatting.DARK_GRAY);
darkSteel.addTrait(Portly.portly, HEAD);
darkSteel.addTrait(coldblooded);
darkSteel.addItem("ingotDarkSteel", 1, Material.VALUE_Ingot);
darkSteel.setCraftable(false).setCastable(true);
Utils.setDispItem(darkSteel, "enderio", "itemAlloy", 6);
proxy.setRenderInfo(darkSteel, 0x333333);
Fluid darkSteelFluid = FluidRegistry.getFluid("darksteel");
darkSteel.setFluid(darkSteelFluid);
TinkerRegistry.registerAlloy(new FluidStack(darkSteelFluid, 36),
new FluidStack(TinkerFluids.obsidian, 72),
new FluidStack(TinkerFluids.iron, 36),
new FluidStack(coalFluid, 25));
TinkerRegistry.addMaterialStats(darkSteel,
new HeadMaterialStats(666, 7, 4, OBSIDIAN),
new HandleMaterialStats(1.05f, 40),
new ExtraMaterialStats(40),
new BowMaterialStats(0.38f, 2.05f, 10));
materials.put("darkSteel", darkSteel);
}
}
private void initTF() {
if (Config.thermalFoundation && Loader.isModLoaded("thermalfoundation")) {
Material signalum = new Material("signalum_plustic", TextFormatting.RED);
signalum.addTrait(BloodyMary.bloodymary);
signalum.addItem("ingotSignalum", 1, Material.VALUE_Ingot);
signalum.setCraftable(false).setCastable(true);
Utils.setDispItem(signalum, "ingotSignalum");
proxy.setRenderInfo(signalum, 0xD84100);
FluidMolten signalumFluid = Utils.fluidMetal("signalum", 0xD84100);
signalumFluid.setTemperature(930);
Utils.initFluidMetal(signalumFluid);
signalum.setFluid(signalumFluid);
TinkerRegistry.registerAlloy(new FluidStack(signalumFluid, 72),
new FluidStack(TinkerFluids.copper, 54),
new FluidStack(TinkerFluids.silver, 18),
new FluidStack(FluidRegistry.getFluid("redstone"), 125));
TinkerRegistry.addMaterialStats(signalum,
new HeadMaterialStats(690, 7.5f, 5.2f, OBSIDIAN),
new HandleMaterialStats(1.2f, 0),
new ExtraMaterialStats(55),
new BowMaterialStats(1.2f, 1.6f, 4.4f));
materials.put("signalum", signalum);
Material enderium = new Material("enderium_plustic", TextFormatting.DARK_GREEN);
enderium.addTrait(Portly.portly, HEAD);
enderium.addTrait(Global.global);
enderium.addTrait(enderference);
enderium.addTrait(endspeed, PROJECTILE);
enderium.addTrait(endspeed, SHAFT);
enderium.addItem("ingotEnderium", 1, Material.VALUE_Ingot);
enderium.setCraftable(false).setCastable(true);
Utils.setDispItem(enderium, "ingotEnderium");
proxy.setRenderInfo(enderium, 0x007068);
FluidMolten platinumFluid = Utils.fluidMetal("platinum", 0xB7E7FF);
platinumFluid.setTemperature(680);
Utils.initFluidMetal(platinumFluid);
MaterialIntegration platinumI = new MaterialIntegration(null, platinumFluid, "Platinum");
platinumI.integrate();
platinumI.integrateRecipes();
materialIntegrations.put("platinum", platinumI);
FluidMolten enderiumFluid = Utils.fluidMetal("enderium", 0x007068);
enderiumFluid.setTemperature(970);
Utils.initFluidMetal(enderiumFluid);
enderium.setFluid(enderiumFluid);
TinkerRegistry.registerAlloy(new FluidStack(enderiumFluid, 144),
new FluidStack(TinkerFluids.tin, 72),
new FluidStack(TinkerFluids.silver, 36),
new FluidStack(platinumFluid, 36),
new FluidStack(FluidRegistry.getFluid("ender"), 250));
TinkerRegistry.addMaterialStats(enderium,
new HeadMaterialStats(800, 7.5f, 7, COBALT),
new HandleMaterialStats(1.05f, -5),
new ExtraMaterialStats(65),
new BowMaterialStats(0.9f, 1.9f, 8),
new ArrowShaftMaterialStats(1, 12));
materials.put("enderium", enderium);
Material nickel = new Material("nickel", TextFormatting.YELLOW);
nickel.addTrait(NickOfTime.nickOfTime, HEAD);
nickel.addTrait(magnetic);
nickel.addItem("ingotNickel", 1, Material.VALUE_Ingot);
nickel.setCraftable(false).setCastable(true);
Utils.setDispItem(nickel, "ingotNickel");
proxy.setRenderInfo(nickel, 0xFFF98E);
nickel.setFluid(TinkerFluids.nickel);
TinkerRegistry.addMaterialStats(nickel,
new HeadMaterialStats(460, 6, 4.5f, OBSIDIAN),
new HandleMaterialStats(1, -5),
new ExtraMaterialStats(70),
justWhy,
new FletchingMaterialStats(0.95f, 1.05f));
materials.put("nickel", nickel);
}
}
@EventHandler
public void init(FMLInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(Toggle.class);
proxy.registerKeyBindings();
PacketHandler.init();
// CURSE YOU, MEKANISM AND ARMORPLUS! YOU REGISTERED THE OREDICTS IN INIT INSTEAD OF PREINIT!
Utils.setDispItem(materials.get("refinedObsidian"), "mekanism", "Ingot");
Utils.setDispItem(materials.get("osmium"), "mekanism", "Ingot", 1);
Utils.setDispItem(materials.get("witherbone"), "armorplus", "wither_bone");
Utils.setDispItem(materials.get("guardianscale"), "armorplus", "guardian_scale");
Utils.setDispItem(materials.get("sapphire"), "gemSapphire");
Utils.setDispItem(materials.get("ruby"), "gemRuby");
Utils.setDispItem(materials.get("peridot"), "gemPeridot");
Item bronzeNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzenugget"));
Item bronzeIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzeingot"));
Block osmiridiumBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumblock"));
Item osmiridiumIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumingot"));
Item osmiridiumNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumnugget"));
Block alumiteBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteblock"));
Item alumiteIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteingot"));
Item alumiteNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumitenugget"));
if (bronzeNugget != null) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(bronzeIngot),
"III", "III", "III",
'I', "nuggetBronze"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(bronzeNugget, 9), "ingotBronze"));
}
if (osmiridiumNugget != null) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(osmiridiumBlock),
"III", "III", "III",
'I', "ingotOsmiridium"));
GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumIngot, 9), osmiridiumBlock);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(osmiridiumIngot),
"III", "III", "III",
'I', "nuggetOsmiridium"));
GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumNugget, 9), osmiridiumIngot);
}
if (alumiteNugget != null) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(alumiteBlock),
"III", "III", "III",
'I', "ingotAlumite"));
GameRegistry.addShapelessRecipe(new ItemStack(alumiteIngot, 9), alumiteBlock);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(alumiteIngot),
"III", "III", "III",
'I', "nuggetAlumite"));
GameRegistry.addShapelessRecipe(new ItemStack(alumiteNugget, 9), alumiteIngot);
}
}
}
|
package org.commcare.xml;
import org.commcare.cases.model.Case;
import org.commcare.cases.model.CaseIndex;
import org.commcare.data.xml.TransactionParser;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.xml.util.InvalidStorageStructureException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.ActionableInvalidStructureException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Date;
import java.util.NoSuchElementException;
/**
* The CaseXML Parser is responsible for processing and performing
* case transactions from an incoming XML stream. It will perform
* all of the actions specified by the transaction (Create/modify/close)
* against the application's current storage.
*
* @author ctsims
*/
public class CaseXmlParser extends TransactionParser<Case> {
public static final String ATTACHMENT_FROM_LOCAL = "local";
public static final String ATTACHMENT_FROM_REMOTE = "remote";
public static final String ATTACHMENT_FROM_INLINE = "inline";
public static final String CASE_XML_NAMESPACE = "http://commcarehq.org/case/transaction/v2";
private final IStorageUtilityIndexed storage;
private final boolean acceptCreateOverwrites;
public CaseXmlParser(KXmlParser parser, IStorageUtilityIndexed storage) {
this(parser, true, storage);
}
/**
* Creates a Parser for case blocks in the XML stream provided.
*
* @param parser The parser for incoming XML.
* @param acceptCreateOverwrites Whether an Exception should be thrown if the transaction
* contains create actions for cases which already exist.
*/
public CaseXmlParser(KXmlParser parser, boolean acceptCreateOverwrites,
IStorageUtilityIndexed storage) {
super(parser);
this.acceptCreateOverwrites = acceptCreateOverwrites;
this.storage = storage;
}
public Case parse() throws InvalidStructureException, IOException, XmlPullParserException {
checkNode("case");
String caseId = parser.getAttributeValue(null, "case_id");
if (caseId == null || caseId.equals("")) {
throw InvalidStructureException.readableInvalidStructureException("The case_id attribute of a <case> wasn't set", parser);
}
String dateModified = parser.getAttributeValue(null, "date_modified");
if (dateModified == null) {
throw InvalidStructureException.readableInvalidStructureException("The date_modified attribute of a <case> wasn't set", parser);
}
Date modified = DateUtils.parseDateTime(dateModified);
Case caseForBlock = null;
while (nextTagInBlock("case")) {
String action = parser.getName().toLowerCase();
switch (action) {
case "create":
caseForBlock = createCase(caseId, modified);
break;
case "update":
caseForBlock = updateCase(caseForBlock, caseId);
break;
case "close":
caseForBlock = closeCase(caseForBlock, caseId);
break;
case "index":
caseForBlock = indexCase(caseForBlock, caseId);
break;
case "attachment":
caseForBlock = processCaseAttachment(caseForBlock, caseId);
break;
}
}
if (caseForBlock != null) {
caseForBlock.setLastModified(modified);
commit(caseForBlock);
}
return null;
}
private Case createCase(String caseId, Date modified) throws InvalidStructureException, IOException, XmlPullParserException {
String[] data = new String[3];
Case caseForBlock = null;
while (nextTagInBlock("create")) {
String tag = parser.getName();
switch (tag) {
case "case_type":
data[0] = parser.nextText().trim();
break;
case "owner_id":
data[1] = parser.nextText().trim();
break;
case "case_name":
data[2] = parser.nextText().trim();
break;
default:
throw new InvalidStructureException("Expected one of [case_type, owner_id, case_name], found " + parser.getName(), parser);
}
}
if (data[0] == null || data[2] == null) {
throw new InvalidStructureException("One of [case_type, case_name] is missing for case <create> with ID: " + caseId, parser);
}
if (acceptCreateOverwrites) {
caseForBlock = retrieve(caseId);
if (caseForBlock != null) {
caseForBlock.setName(data[2]);
caseForBlock.setTypeId(data[0]);
}
}
if (caseForBlock == null) {
// The case is either not present on the phone, or we're on strict tolerance
caseForBlock = buildCase(data[2], data[0]);
caseForBlock.setCaseId(caseId);
caseForBlock.setDateOpened(modified);
}
if (data[1] != null) {
caseForBlock.setUserId(data[1]);
}
return caseForBlock;
}
private Case updateCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException {
if (caseForBlock == null) {
caseForBlock = retrieve(caseId);
}
if (caseForBlock == null) {
throw new InvalidStorageStructureException("Unable to update case " + caseId + ", it wasn't found", parser);
}
while (nextTagInBlock("update")) {
String key = parser.getName();
String value = parser.nextText().trim();
switch (key) {
case "case_type":
caseForBlock.setTypeId(value);
break;
case "case_name":
caseForBlock.setName(value);
break;
case "date_opened":
caseForBlock.setDateOpened(DateUtils.parseDate(value));
break;
case "owner_id":
String oldUserId = caseForBlock.getUserId();
if (!oldUserId.equals(value)) {
onIndexDisrupted(caseId);
}
caseForBlock.setUserId(value);
break;
default:
caseForBlock.setProperty(key, value);
break;
}
}
return caseForBlock;
}
private Case closeCase(Case caseForBlock, String caseId) throws IOException {
if (caseForBlock == null) {
caseForBlock = retrieve(caseId);
}
if (caseForBlock == null) {
throw new InvalidStorageStructureException("Unable to update case " + caseId + ", it wasn't found", parser);
}
caseForBlock.setClosed(true);
commit(caseForBlock);
onIndexDisrupted(caseId);
return caseForBlock;
}
private Case indexCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException {
if (caseForBlock == null) {
caseForBlock = retrieve(caseId);
}
while (nextTagInBlock("index")) {
String indexName = parser.getName();
String caseType = parser.getAttributeValue(null, "case_type");
String relationship = parser.getAttributeValue(null, "relationship");
if (relationship == null) {
relationship = CaseIndex.RELATIONSHIP_CHILD;
}
String value = parser.nextText().trim();
if (value.equals(caseId)) {
throw new ActionableInvalidStructureException("case.error.self.index", new String[]{caseId}, "Case " + caseId + " cannot index itself");
}
//Remove any ambiguity associated with empty values
if (value.equals("")) {
value = null;
}
//Process blank inputs in the same manner as data fields (IE: Remove the underlying model)
if (value == null) {
if (caseForBlock.removeIndex(indexName)) {
onIndexDisrupted(caseId);
}
} else {
if (caseForBlock.setIndex(new CaseIndex(indexName, caseType, value,
relationship))) {
onIndexDisrupted(caseId);
}
}
}
return caseForBlock;
}
private Case processCaseAttachment(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException {
if (caseForBlock == null) {
caseForBlock = retrieve(caseId);
}
while (nextTagInBlock("attachment")) {
String attachmentName = parser.getName();
String src = parser.getAttributeValue(null, "src");
String from = parser.getAttributeValue(null, "from");
String fileName = parser.getAttributeValue(null, "name");
if ((src == null || "".equals(src)) && (from == null || "".equals(from))) {
//this is actually an attachment removal
removeAttachment(caseForBlock, attachmentName);
caseForBlock.removeAttachment(attachmentName);
continue;
}
String reference = processAttachment(src, from, fileName, parser);
if (reference != null) {
caseForBlock.updateAttachment(attachmentName, reference);
}
}
return caseForBlock;
}
protected void removeAttachment(Case caseForBlock, String attachmentName) {
}
protected String processAttachment(String src, String from, String name, KXmlParser parser) {
return null;
}
protected Case buildCase(String name, String typeId) {
return new Case(name, typeId);
}
public void commit(Case parsed) throws IOException {
try {
storage().write(parsed);
} catch (StorageFullException e) {
e.printStackTrace();
throw new IOException("Storage full while writing case!");
}
}
public Case retrieve(String entityId) {
try {
return (Case)storage().getRecordForValue(Case.INDEX_CASE_ID, entityId);
} catch (NoSuchElementException nsee) {
return null;
}
}
public IStorageUtilityIndexed storage() {
return storage;
}
/**
* A signal that notes that processing a transaction has resulted in a
* potential change in what cases should be on the phone. This can be
* due to a case's owner changing, a case closing, an index moving, etc.
*
* Does not have to be consumed, but can be used to identify proactively
* when to reconcile what cases should be available.
*
* @param caseId The ID of a case which has changed in a potentially
* disruptive way
*/
public void onIndexDisrupted(String caseId) {
}
}
|
package uk.ac.kent.dover.fastGraph.Gui;
import java.io.File;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import uk.ac.kent.dover.fastGraph.Launcher;
/**
* Dummy class to avoid null checking when methods are run by the command line.<br>
* This implements all public methods of MotifTask, but has no functionality.<br>
* Potentially this could be modified to output to a log file
*
* @author Rob Baker
*
*/
public class MotifTaskDummy extends MotifTask {
int bigP, smallP;
String bigT, smallT;
/**
* Trivial constructor
*/
public MotifTaskDummy() {
this(null,null,null,null,0,0,null,null,null,false);
}
/**
* Trivial constructor. Parameters are not used.
*
* @param launcher Not Used.
* @param bigProgress Not Used.
* @param smallProgress Not Used.
* @param graph Not Used.
* @param minSize Not Used.
* @param maxSize Not Used.
* @param progressBar Not Used.
* @param status Not Used.
* @param saveAll Not Used.
*/
public MotifTaskDummy(Launcher launcher, JProgressBar bigProgress, JProgressBar smallProgress, File graph,
int minSize, int maxSize, JProgressBar progressBar, JLabel status, JPanel panel, boolean saveAll) {
super(launcher, bigProgress, smallProgress, graph, minSize, maxSize, progressBar, status, panel, saveAll, null);
}
/**
* Dummy class to avoid null checking when methods are run by the command line.
*
* @param mainTaskNum Not Used.
* @param mainTaskText Not Used.
* @param childTaskNum Not Used.
* @param childTaskText Not Used.
*/
public void publish(int mainTaskNum, String mainTaskText, int childTaskNum, String childTaskText){
bigP = mainTaskNum;
bigT = mainTaskText;
smallP = childTaskNum;
smallT = childTaskText;
}
/**
* Dummy class to avoid null checking when methods are run by the command line.
*
* @param taskNum Not Used.
* @param taskText Not Used.
* @param main Not Used.
*/
public void publish(int taskNum, String taskText, boolean main){
if(main) {
bigP = taskNum;
bigT = taskText;
} else {
smallP = taskNum;
smallT = taskText;
}
}
/**
* Dummy class to avoid null checking when methods are run by the command line.
* @param Not Used.
*/
public void setSmallIndeterminate(boolean indeterminate) {
}
}
|
package cat.nyaa.nyaacore.utils;
import com.earth2me.essentials.Essentials;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.List;
public class TeleportUtils {
public static boolean Teleport(Player player, Location loc) {
if (!player.isOnline() || loc == null || loc.getWorld() == null) {
return false;
}
Essentials ess = null;
if (Bukkit.getServer().getPluginManager().getPlugin("Essentials") != null) {
ess = (Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials");
}
if (ess != null) {
try {
ess.getUser(player).getTeleport().now(loc, false, PlayerTeleportEvent.TeleportCause.PLUGIN);
return true;
} catch (Exception e) {
return false;
}
} else {
player.setFallDistance(0);
player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);
return true;
}
}
public static void Teleport(List<Player> players, Location loc) {
for (Player p : players) {
Teleport(p, loc);
}
}
}
|
package uk.org.ngo.squeezer.menu;
import uk.org.ngo.squeezer.SqueezerHomeActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class SqueezerMenuFragment extends MenuFragment {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Application icon clicked.
case android.R.id.home:
SqueezerHomeActivity.show(getActivity());
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package cn.heroes.yellow.entity.impl;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import cn.heroes.jkit.utils.ExcelUtils;
import cn.heroes.jkit.utils.exception.EvaluateFormulaException;
import cn.heroes.yellow.entity.TDRow;
import cn.heroes.yellow.exception.CellNotFoundException;
/**
* ExcelTDRow.
* <p>
* Row, Cell are all 1-based.
* </p>
*
* @author Leon Kidd
* @version 1.00, 2014-2-2
*/
public class ExcelRow implements TDRow {
private Row row;
private Workbook book;
/**
* Row and cell are all 1-based.
*
* @param row
* <code>org.apache.poi.ss.usermodel.Row</code>
* @param book
* if book is null, then the FORMULA cell will return FORMULA
* String, else the FORMULA cell will return the value evaluated.
* <code>org.apache.poi.ss.usermodel.Workbook</code>
* @see org.apache.poi.ss.usermodel.Row
*/
public ExcelRow(Row row, Workbook book) {
this.row = row;
this.book = book;
}
/**
* cell
*
* @param i
* 1-based column number
* @throws CellNotFoundException
* cellnull.
* @return
*/
private Cell cell(int i) {
Cell cell = row.getCell(i - 1);
// if (cell == null) {
// throw new CellNotFoundException();
return cell;
}
/**
* @throws EvaluateFormulaException
* When the formula is evaluated error.
*/
@Override
public Object getObject(int i) {
Cell cell = cell(i);
return cell == null ? null : ExcelUtils.getCellValue(cell, book);
}
@Override
public String getString(int i) {
Cell cell = cell(i);
return cell == null ? "" : cell.getStringCellValue();
}
@Override
public double getDouble(int i) {
Cell cell = cell(i);
return cell == null ? 0 : cell.getNumericCellValue();
}
@Override
public float getFloat(int i) {
// TODO ?
Cell cell = cell(i);
return cell == null ? 0 : (float) cell.getNumericCellValue();
}
@Override
public long getLong(int i) {
Cell cell = cell(i);
return cell == null ? 0 : (long) cell.getNumericCellValue();
}
@Override
public int getInt(int i) {
Cell cell = cell(i);
return cell == null ? 0 : (int) cell.getNumericCellValue();
}
@Override
public int length() {
return row.getLastCellNum() + 1;
}
@Override
public int getRowNum() {
return row.getRowNum() + 1;
}
@Override
public Object[] getValues() {
Object[] values = new Object[(int) row.getLastCellNum()];
Iterator<Cell> cells = row.cellIterator();
int i = 0;
while (cells.hasNext()) {
Cell cell = cells.next();
if (book != null) {
values[i++] = ExcelUtils.getCellValue(cell, book);
} else {
values[i++] = ExcelUtils.getCellValue(cell);
}
}
return values;
}
/**
* Get the specified cell's style.
*
* @param i
* 1-based, the first column is 1, the second is 2, ...
* @return
*/
public CellStyle getCellStyle(int i) {
Cell cell = row.getCell(i);
return cell.getCellStyle();
}
}
|
package me.nallar;
import lombok.Data;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.val;
import me.nallar.javatransformer.api.JavaTransformer;
import me.nallar.mixin.internal.MixinApplicator;
import me.nallar.modpatcher.tasks.BinaryProcessor;
import me.nallar.modpatcher.tasks.SourceProcessor;
import net.minecraftforge.gradle.user.UserBaseExtension;
import net.minecraftforge.gradle.user.UserBasePlugin;
import net.minecraftforge.gradle.util.caching.CachedTask;
import org.apache.log4j.Logger;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskInputs;
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class ModPatcherPlugin implements Plugin<Project> {
public static final String DEOBF_BINARY_TASK = "deobfMcMCP";
public static final String REMAP_SOURCE_TASK = "remapMcSources";
public static final String PLUGIN_FORGE_GRADLE_ID = "net.minecraftforge.gradle.forge";
public static final Logger logger = Logger.getLogger("ModPatcher");
public static final String CLASS_GRADLE_TASKACTIONWRAPPER = "org.gradle.api.internal.AbstractTask$TaskActionWrapper";
public static final boolean DISABLE_CACHING = Boolean.parseBoolean(System.getProperty("ModPatcherGradle.disableCaching", "true"));
public ModPatcherGradleExtension extension = new ModPatcherGradleExtension();
private Project project;
@Getter(lazy = true)
private final JavaTransformer mixinTransformer = makeMixinTransformer();
// Add before WriteCacheAction, or cache will be invalidated every time
private static Task doBeforeWriteCacheAction(Task t, Action<Task> action) {
val actions = t.getActions();
int writeCachePosition = actions.size();
for (int i = 0; i < actions.size(); i++) {
if (innerAction(actions.get(i)).getClass().getName().endsWith("WriteCacheAction")) {
writeCachePosition = i;
}
}
if (!disableCaching(t) && writeCachePosition == actions.size()) {
logger.warn("Failed to find WriteCacheAction in " + actions);
actions.forEach(it -> logger.warn(innerAction(it)));
}
actions.add(writeCachePosition, action);
return t;
}
private static boolean disableCaching(Task t) {
if (DISABLE_CACHING && t instanceof CachedTask) {
((CachedTask) t).setDoesCache(false);
return true;
}
return false;
}
@SuppressWarnings("unchecked")
private static Action<? super Task> innerAction(Action<? super Task> action) {
val actionClass = action.getClass();
if (actionClass.getName().equals(CLASS_GRADLE_TASKACTIONWRAPPER)) {
try {
val innerField = actionClass.getDeclaredField("action");
innerField.setAccessible(true);
val inner = (Action<? super Task>) innerField.get(action);
if (inner != null)
return inner;
} catch (Exception e) {
logger.warn("Failed to extract inner action from wrapper", e);
}
}
return action;
}
@SneakyThrows
@Override
public void apply(Project project) {
this.project = project;
project.getPlugins().apply(PLUGIN_FORGE_GRADLE_ID);
// Ensure ForgeGradle useLocalCache -> true
val forgeGradle = ((UserBasePlugin) project.getPlugins().getPlugin(PLUGIN_FORGE_GRADLE_ID));
val blank_at = new File(project.getBuildDir(), "blank_at.cfg");
if (!blank_at.exists() && (blank_at.getParentFile().isDirectory() || blank_at.getParentFile().mkdir()))
Files.write(blank_at.toPath(), new byte[0]);
((UserBaseExtension) forgeGradle.getExtension()).at(blank_at);
project.getExtensions().add("modpatcher", extension);
project.afterEvaluate(this::afterEvaluate);
}
public JavaTransformer makeMixinTransformer() {
val applicator = new MixinApplicator();
applicator.setNoMixinIsError(extension.noMixinIsError);
for (File file : sourceDirsWithMixins(true)) {
applicator.addSource(file.toPath(), extension.getMixinPackageToUse());
}
return applicator.getMixinTransformer();
}
public void mixinTransform(Path toTransform) {
if (extension.shouldMixin()) {
Path old = toTransform.resolveSibling("bak_" + toTransform.getFileName().toString());
try {
Files.deleteIfExists(old);
Files.move(toTransform, old);
try {
getMixinTransformer().transform(old, toTransform);
} finally {
if (!Files.exists(toTransform)) {
Files.move(old, toTransform);
} else {
Files.delete(old);
}
}
} catch (IOException e) {
throw new IOError(e);
}
}
}
@SuppressWarnings("unchecked")
@SneakyThrows
private List<File> sourceDirsWithMixins(boolean root) {
val results = new ArrayList<File>();
val mixinPackage = extension.getMixinPackageToUse().replace('.', '/');
for (SourceSet s : (Iterable<SourceSet>) project.getProperties().get("sourceSets")) {
for (File javaDir : s.getJava().getSrcDirs()) {
File mixinDir = fileWithChild(javaDir, mixinPackage);
if (mixinDir.isDirectory()) {
if (root)
results.add(javaDir);
else
results.add(mixinDir);
}
}
}
if (results.isEmpty())
throw new FileNotFoundException("Couldn't find any mixin packages! Searched for: " + mixinPackage);
return results;
}
private File fileWithChild(File javaDir, String mixinPackageToUse) {
return mixinPackageToUse == null ? javaDir : new File(javaDir, mixinPackageToUse);
}
public void afterEvaluate(Project project) {
val tasks = project.getTasks();
val mixinDirs = sourceDirsWithMixins(true).toArray();
addInputs(tasks.getByName(DEOBF_BINARY_TASK), mixinDirs);
tasks.getByName(REMAP_SOURCE_TASK).getInputs().files(mixinDirs);
doBeforeWriteCacheAction(tasks.getByName(DEOBF_BINARY_TASK), new Action<Task>() {
@SneakyThrows
@Override
public void execute(Task task) {
File f = task.getOutputs().getFiles().iterator().next();
BinaryProcessor.process(ModPatcherPlugin.this, f);
}
});
doBeforeWriteCacheAction(tasks.getByName(REMAP_SOURCE_TASK), new Action<Task>() {
@SneakyThrows
@Override
public void execute(Task task) {
File f = task.getOutputs().getFiles().iterator().next();
SourceProcessor.process(ModPatcherPlugin.this, f);
}
});
}
private void addInputs(Task t, Object[] mixinDirs) {
val inputs = t.getInputs();
inputs.files(mixinDirs);
addVersion(inputs, "ModPatcherGradle", this.getClass());
addVersion(inputs, "Mixin", MixinApplicator.class);
addVersion(inputs, "JavaTransformer", JavaTransformer.class);
}
private void addVersion(TaskInputs inputs, String name, Class c) {
inputs.property(name + "Version", c.getPackage().getImplementationVersion());
}
@Data
public static class ModPatcherGradleExtension {
public String mixinPackage = "";
public boolean noMixinIsError = true;
public boolean extractGeneratedSources = false;
public boolean generateInheritanceHierarchy = false;
public String getMixinPackageToUse() {
return Objects.equals(mixinPackage, "all") ? null : mixinPackage;
}
public boolean shouldMixin() {
return !"".equals(mixinPackage);
}
}
}
|
package co.poynt.postman.model;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import org.springframework.http.HttpHeaders;
public class PostmanRequest {
public String id;
public String headers; // String of \n separated headers with : separate
// name:value.
public String url;
public String method;
public Object data; // Either String of escaped-JSON or [] empty array (for
// GET)
public Object rawModeData;
public String dataMode;
public String name;
public String description;
public String descriptionFormat;
public Long time;
public Integer version;
public Object responses;
public String tests;
public Boolean synced;
public String getData(PostmanVariables var) {
Object dataToUse = dataMode.equals("raw") ? rawModeData : data;
if (dataToUse instanceof String) {
String result = (String) dataToUse;
result = var.replace(result);
return result;
} else if (dataToUse instanceof ArrayList
&& dataMode.equals("urlencoded")) {
ArrayList<Map<String, String>> formData = (ArrayList<Map<String, String>>) dataToUse;
return urlFormEncodeData(var, formData);
} else { // empty array
return "";
}
}
public String urlFormEncodeData(PostmanVariables var,
ArrayList<Map<String, String>> formData) {
String result = "";
int i = 0;
for (Map<String, String> m : formData) {
result += m.get("key") + "="
+ URLEncoder.encode(var.replace(m.get("value")));
if (i < formData.size() - 1) {
result += "&";
}
}
return result;
}
public String getUrl(PostmanVariables var) {
return var.replace(this.url);
}
public HttpHeaders getHeaders(PostmanVariables var) {
HttpHeaders result = new HttpHeaders();
if (this.headers == null || this.headers.isEmpty()) {
return result;
}
String h = var.replace(headers);
String[] splitHeads = h.split("\n");
for (String hp : splitHeads) {
String[] pair = hp.split(":");
String key = pair[0].trim();
String val = pair[1].trim();
result.set(key, val);
}
return result;
}
}
|
package com.akiban.sql.embedded;
import com.akiban.qp.operator.Cursor;
import com.akiban.qp.row.Row;
import com.akiban.server.types.AkType;
import com.akiban.server.types.ToObjectValueTarget;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.extract.Extractors;
import com.akiban.server.types3.Types3Switch;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.util.ByteSource;
import java.sql.*;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Calendar;
import java.util.Map;
public class JDBCResultSet implements ResultSet
{
private Statement statement;
private Cursor cursor;
private Row row;
private boolean wasNull;
public JDBCResultSet(Statement statement, Cursor cursor) {
this.statement = statement;
this.cursor = cursor;
}
protected ValueSource value(int columnIndex) throws SQLException {
if (row == null) {
if (cursor == null)
throw new SQLException("Already closed.");
else
throw new SQLException("Past end.");
}
if ((columnIndex < 1) || (columnIndex > row.rowType().nFields()))
throw new SQLException("Column index out of bounds");
ValueSource value = row.eval(columnIndex - 1);
wasNull = value.isNull();
return value;
}
/* Wrapper */
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface == Cursor.class)
return (T)cursor;
if (iface == Row.class)
return (T)row;
throw new SQLException("Not supported");
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
if (iface == Cursor.class)
return true;
if (iface == Row.class)
return true;
return false;
}
/* ResultSet */
@Override
public boolean next() throws SQLException {
row = cursor.next();
return (row != null);
}
@Override
public void close() {
if (cursor != null) {
cursor.destroy();
cursor = null;
}
}
@Override
public boolean wasNull() throws SQLException {
return wasNull;
}
@Override
public String getString(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return Extractors.getStringExtractor().getObject(value);
}
}
@Override
public boolean getBoolean(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return false;
else
return Extractors.getBooleanExtractor().getBoolean(value, false);
}
}
@Override
public byte getByte(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0;
else
return (byte)Extractors.getLongExtractor(AkType.INT).getLong(value);
}
}
@Override
public short getShort(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0;
else
return (short)Extractors.getLongExtractor(AkType.INT).getLong(value);
}
}
@Override
public int getInt(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0;
else
return (int)Extractors.getLongExtractor(AkType.INT).getLong(value);
}
}
@Override
public long getLong(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0;
else
return Extractors.getLongExtractor(AkType.LONG).getLong(value);
}
}
@Override
public float getFloat(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0.0f;
else
return (float)Extractors.getDoubleExtractor().getDouble(value);
}
}
@Override
public double getDouble(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return 0.0;
else
return Extractors.getDoubleExtractor().getDouble(value);
}
}
@Override
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return Extractors.getDecimalExtractor().getObject(value);
}
}
@Override
public byte[] getBytes(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return Extractors.getByteSourceExtractor().getObject(value).toByteSubarray();
}
}
@Override
public Date getDate(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return new Date(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
}
}
@Override
public Time getTime(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return new Time(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
}
}
@Override
public Timestamp getTimestamp(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else
return new Timestamp(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
}
}
@Override
public InputStream getAsciiStream(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public InputStream getBinaryStream(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public String getString(String columnLabel) throws SQLException {
return getString(findColumn(columnLabel));
}
@Override
public boolean getBoolean(String columnLabel) throws SQLException {
return getBoolean(findColumn(columnLabel));
}
@Override
public byte getByte(String columnLabel) throws SQLException {
return getByte(findColumn(columnLabel));
}
@Override
public short getShort(String columnLabel) throws SQLException {
return getShort(findColumn(columnLabel));
}
@Override
public int getInt(String columnLabel) throws SQLException {
return getInt(findColumn(columnLabel));
}
@Override
public long getLong(String columnLabel) throws SQLException {
return getLong(findColumn(columnLabel));
}
@Override
public float getFloat(String columnLabel) throws SQLException {
return getFloat(findColumn(columnLabel));
}
@Override
public double getDouble(String columnLabel) throws SQLException {
return getDouble(findColumn(columnLabel));
}
@Override
public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException {
return getBigDecimal(findColumn(columnLabel), scale);
}
@Override
public byte[] getBytes(String columnLabel) throws SQLException {
return getBytes(findColumn(columnLabel));
}
@Override
public Date getDate(String columnLabel) throws SQLException {
return getDate(findColumn(columnLabel));
}
@Override
public Time getTime(String columnLabel) throws SQLException {
return getTime(findColumn(columnLabel));
}
@Override
public Timestamp getTimestamp(String columnLabel) throws SQLException {
return getTimestamp(findColumn(columnLabel));
}
@Override
public InputStream getAsciiStream(String columnLabel) throws SQLException {
return getAsciiStream(findColumn(columnLabel));
}
@Override
public InputStream getUnicodeStream(String columnLabel) throws SQLException {
return getUnicodeStream(findColumn(columnLabel));
}
@Override
public InputStream getBinaryStream(String columnLabel) throws SQLException {
return getBinaryStream(findColumn(columnLabel));
}
@Override
public SQLWarning getWarnings() throws SQLException {
throw null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public String getCursorName() throws SQLException {
throw null;
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Object getObject(int columnIndex) throws SQLException {
if (Types3Switch.ON) {
throw new SQLFeatureNotSupportedException();
}
else {
ValueSource value = value(columnIndex);
if (wasNull)
return null;
else {
switch (value.getConversionType()) {
case DATE:
return new Date(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
case TIME:
return new Time(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
case DATETIME:
case TIMESTAMP:
return new Timestamp(Extractors.getLongExtractor(AkType.TIMESTAMP).getLong(value));
case RESULT_SET:
return new JDBCResultSet(statement, value.getResultSet());
default:
return new ToObjectValueTarget().convertFromSource(value);
}
}
}
}
@Override
public Object getObject(String columnLabel) throws SQLException {
return getObject(findColumn(columnLabel));
}
@Override
public int findColumn(String columnLabel) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Reader getCharacterStream(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Reader getCharacterStream(String columnLabel) throws SQLException {
return getCharacterStream(findColumn(columnLabel));
}
@Override
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public BigDecimal getBigDecimal(String columnLabel) throws SQLException {
return getBigDecimal(findColumn(columnLabel));
}
@Override
public boolean isBeforeFirst() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean isAfterLast() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean isFirst() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean isLast() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void beforeFirst() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void afterLast() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean first() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean last() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public int getRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean absolute( int row ) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean relative( int rows ) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean previous() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
if (direction != FETCH_FORWARD)
throw new SQLFeatureNotSupportedException();
}
@Override
public int getFetchDirection() throws SQLException {
return FETCH_FORWARD;
}
@Override
public void setFetchSize(int rows) throws SQLException {
}
@Override
public int getFetchSize() throws SQLException {
return 1;
}
@Override
public int getType() throws SQLException {
return TYPE_FORWARD_ONLY;
}
@Override
public int getConcurrency() throws SQLException {
return CONCUR_READ_ONLY;
}
@Override
public boolean rowUpdated() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean rowInserted() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean rowDeleted() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNull(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateByte(int columnIndex, byte x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateShort(int columnIndex, short x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateInt(int columnIndex, int x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateLong(int columnIndex, long x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateFloat(int columnIndex, float x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateDouble(int columnIndex, double x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateString(int columnIndex, String x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBytes(int columnIndex, byte x[]) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateDate(int columnIndex, Date x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateTime(int columnIndex, Time x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateObject(int columnIndex, Object x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNull(String columnLabel) throws SQLException {
updateNull(findColumn(columnLabel));
}
@Override
public void updateBoolean(String columnLabel, boolean x) throws SQLException {
updateBoolean(findColumn(columnLabel), x);
}
@Override
public void updateByte(String columnLabel, byte x) throws SQLException {
updateByte(findColumn(columnLabel), x);
}
@Override
public void updateShort(String columnLabel, short x) throws SQLException {
updateShort(findColumn(columnLabel), x);
}
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
updateInt(findColumn(columnLabel), x);
}
@Override
public void updateLong(String columnLabel, long x) throws SQLException {
updateLong(findColumn(columnLabel), x);
}
@Override
public void updateFloat(String columnLabel, float x) throws SQLException {
updateFloat(findColumn(columnLabel), x);
}
@Override
public void updateDouble(String columnLabel, double x) throws SQLException {
updateDouble(findColumn(columnLabel), x);
}
@Override
public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException {
updateBigDecimal(findColumn(columnLabel), x);
}
@Override
public void updateString(String columnLabel, String x) throws SQLException {
updateString(findColumn(columnLabel), x);
}
@Override
public void updateBytes(String columnLabel, byte x[]) throws SQLException {
updateBytes(findColumn(columnLabel), x);
}
@Override
public void updateDate(String columnLabel, Date x) throws SQLException {
updateDate(findColumn(columnLabel), x);
}
@Override
public void updateTime(String columnLabel, Time x) throws SQLException {
updateTime(findColumn(columnLabel), x);
}
@Override
public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException {
updateTimestamp(findColumn(columnLabel), x);
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException {
updateAsciiStream(findColumn(columnLabel), x, length);
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException {
updateBinaryStream(findColumn(columnLabel), x, length);
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException {
updateCharacterStream(findColumn(columnLabel), reader, length);
}
@Override
public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException {
updateObject(findColumn(columnLabel), x, scaleOrLength);
}
@Override
public void updateObject(String columnLabel, Object x) throws SQLException {
updateObject(findColumn(columnLabel), x);
}
@Override
public void insertRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void deleteRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void refreshRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void cancelRowUpdates() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void moveToInsertRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void moveToCurrentRow() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Statement getStatement() throws SQLException {
return statement;
}
@Override
public Object getObject(int columnIndex, Map<String,Class<?>> map) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Ref getRef(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Blob getBlob(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Clob getClob(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Array getArray(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Object getObject(String columnLabel, Map<String,Class<?>> map) throws SQLException {
return getObject(findColumn(columnLabel), map);
}
@Override
public Ref getRef(String columnLabel) throws SQLException {
return getRef(findColumn(columnLabel));
}
@Override
public Blob getBlob(String columnLabel) throws SQLException {
return getBlob(findColumn(columnLabel));
}
@Override
public Clob getClob(String columnLabel) throws SQLException {
return getClob(findColumn(columnLabel));
}
@Override
public Array getArray(String columnLabel) throws SQLException {
return getArray(findColumn(columnLabel));
}
@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
return getDate(columnIndex);
}
@Override
public Date getDate(String columnLabel, Calendar cal) throws SQLException {
return getDate(findColumn(columnLabel), cal);
}
@Override
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
return getTime(columnIndex);
}
@Override
public Time getTime(String columnLabel, Calendar cal) throws SQLException {
return getTime(findColumn(columnLabel), cal);
}
@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
return getTimestamp(columnIndex);
}
@Override
public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException {
return getTimestamp(findColumn(columnLabel), cal);
}
@Override
public URL getURL(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public URL getURL(String columnLabel) throws SQLException {
return getURL(findColumn(columnLabel));
}
@Override
public void updateRef(int columnIndex, Ref x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateRef(String columnLabel, Ref x) throws SQLException {
updateRef(findColumn(columnLabel), x);
}
@Override
public void updateBlob(int columnIndex, Blob x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBlob(String columnLabel, Blob x) throws SQLException {
updateBlob(findColumn(columnLabel), x);
}
@Override
public void updateClob(int columnIndex, Clob x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateClob(String columnLabel, Clob x) throws SQLException {
updateClob(findColumn(columnLabel), x);
}
@Override
public void updateArray(int columnIndex, Array x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateArray(String columnLabel, Array x) throws SQLException {
updateArray(findColumn(columnLabel), x);
}
@Override
public RowId getRowId(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public RowId getRowId(String columnLabel) throws SQLException {
return getRowId(findColumn(columnLabel));
}
@Override
public void updateRowId(int columnIndex, RowId x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateRowId(String columnLabel, RowId x) throws SQLException {
updateRowId(findColumn(columnLabel), x);
}
@Override
public int getHoldability() throws SQLException {
return CLOSE_CURSORS_AT_COMMIT;
}
@Override
public boolean isClosed() throws SQLException {
return (cursor == null);
}
@Override
public void updateNString(int columnIndex, String nString) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNString(String columnLabel, String nString) throws SQLException {
updateNString(findColumn(columnLabel), nString);
}
@Override
public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNClob(String columnLabel, NClob nClob) throws SQLException {
updateNClob(findColumn(columnLabel), nClob);
}
@Override
public NClob getNClob(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public NClob getNClob(String columnLabel) throws SQLException {
return getNClob(findColumn(columnLabel));
}
@Override
public SQLXML getSQLXML(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public SQLXML getSQLXML(String columnLabel) throws SQLException {
return getSQLXML(findColumn(columnLabel));
}
@Override
public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException {
updateSQLXML(findColumn(columnLabel), xmlObject);
}
@Override
public String getNString(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public String getNString(String columnLabel) throws SQLException {
return getNString(findColumn(columnLabel));
}
@Override
public Reader getNCharacterStream(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Reader getNCharacterStream(String columnLabel) throws SQLException {
return getNCharacterStream(findColumn(columnLabel));
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
updateNCharacterStream(findColumn(columnLabel), reader, length);
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException {
updateAsciiStream(findColumn(columnLabel), x, length);
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException {
updateBinaryStream(findColumn(columnLabel), x, length);
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
updateCharacterStream(findColumn(columnLabel), reader, length);
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException {
updateBlob(findColumn(columnLabel), inputStream, length);
}
@Override
public void updateClob(int columnIndex, Reader reader, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateClob(String columnLabel, Reader reader, long length) throws SQLException {
updateClob(findColumn(columnLabel), reader, length);
}
@Override
public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException {
updateNClob(findColumn(columnLabel), reader, length);
}
@Override
public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException {
updateNCharacterStream(findColumn(columnLabel), reader);
}
@Override
public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateCharacterStream(int columnIndex, Reader x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException {
updateAsciiStream(findColumn(columnLabel), x);
}
@Override
public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException {
updateBinaryStream(findColumn(columnLabel), x);
}
@Override
public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException {
updateCharacterStream(findColumn(columnLabel), reader);
}
@Override
public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException {
updateBlob(findColumn(columnLabel), inputStream);
}
@Override
public void updateClob(int columnIndex, Reader reader) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateClob(String columnLabel, Reader reader) throws SQLException {
updateClob(findColumn(columnLabel), reader);
}
@Override
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void updateNClob(String columnLabel, Reader reader) throws SQLException {
updateNClob(findColumn(columnLabel), reader);
}
@Override
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public <T> T getObject(String columnLabel, Class<T> type) throws SQLException {
return getObject(findColumn(columnLabel), type);
}
}
|
package com.alorma.github.sdk.security;
import android.net.Uri;
import com.alorma.gitskarios.core.ApiClient;
public class GitHub implements ApiClient {
private String hostname;
public GitHub() {
}
public GitHub(String hostname) {
if (hostname != null) {
Uri parse = Uri.parse(hostname);
if (parse.getScheme() == null) {
parse = parse.buildUpon().scheme("https").build();
}
hostname = parse.toString();
this.hostname = hostname;
}
}
@Override
public String getApiOauthUrlEndpoint() {
return hostname == null ? "https://github.com": hostname;
}
@Override
public String getApiEndpoint() {
String hostname = "https://api.github.com";
if (this.hostname != null) {
hostname = this.hostname;
if (!hostname.endsWith("/")) {
hostname = hostname + "/";
}
hostname = hostname + "api/v3/";
}
return hostname;
}
@Override
public String getType() {
return "github";
}
}
|
/**
* <p>General timezone-API. </p>
*/
/*[deutsch]
* <p>Allgemeines Zeitzonen-API. </p>
*/
package net.time4j.tz;
|
package com.amee.service.unit;
import com.amee.base.utils.UidGen;
import com.amee.domain.AMEEStatus;
import com.amee.domain.unit.AMEEUnit;
import com.amee.domain.unit.AMEEUnitSymbolComparator;
import com.amee.domain.unit.AMEEUnitType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
@Service
public class UnitServiceImpl implements UnitService {
@Autowired
private UnitServiceDAO dao;
// Unit Types.
public List<AMEEUnitType> getUnitTypes() {
return dao.getUnitTypes();
}
@Override
public AMEEUnitType getUnitTypeByIdentifier(String identifier) {
AMEEUnitType unitType = null;
if (UidGen.INSTANCE_12.isValid(identifier)) {
unitType = getUnitTypeByUid(identifier);
}
if (unitType == null) {
unitType = getUnitTypeByName(identifier);
}
return unitType;
}
@Override
public AMEEUnitType getUnitTypeByUid(String uid) {
return dao.getUnitTypeByUid(uid);
}
@Override
public AMEEUnitType getUnitTypeByName(String name) {
return dao.getUnitTypeByName(name);
}
/**
* Returns true if the name of the supplied UnitType is unique.
*
* @param unitType to check for uniqueness
* @return true if the UnitType has a unique name
*/
@Override
public boolean isUnitTypeUniqueByName(AMEEUnitType unitType) {
return dao.isUnitTypeUniqueByName(unitType);
}
@Override
public void persist(AMEEUnitType unitType) {
dao.persist(unitType);
}
@Override
public void remove(AMEEUnitType unitType) {
unitType.setStatus(AMEEStatus.TRASH);
}
// Units.
/**
* Returns all Units. See JavaDoc below for details on sorting.
*
* @return the list of Units
*/
public List<AMEEUnit> getUnits() {
return getUnits(null);
}
/**
* Returns a sorted list of Units for the supplied Unit Type. If the Unit Type is null all Units will be
* returned.
* <p/>
* Units are sorted by external symbols or internal symbol, with external symbol as the preference.
*
* @param unitType to filter Units by, or null if all Units are required
* @return the list of Units
*/
public List<AMEEUnit> getUnits(AMEEUnitType unitType) {
List<AMEEUnit> units = dao.getUnits(unitType);
Collections.sort(units, new AMEEUnitSymbolComparator());
return units;
}
@Override
public AMEEUnit getUnitByIdentifier(String identifier) {
AMEEUnit unit = null;
if (UidGen.INSTANCE_12.isValid(identifier)) {
unit = getUnitByUid(identifier);
}
if (unit == null) {
unit = getUnitBySymbol(identifier);
}
return unit;
}
@Override
public AMEEUnit getUnitByUid(String uid) {
return dao.getUnitByUid(uid);
}
@Override
public AMEEUnit getUnitBySymbol(String symbol) {
return dao.getUnitBySymbol(symbol);
}
/**
* Returns true if the symbol of the supplied Unit is unique.
*
* @param unit to check for uniqueness
* @return true if the Unit has a unique symbol
*/
@Override
public boolean isUnitUniqueBySymbol(AMEEUnit unit) {
return dao.isUnitUniqueBySymbol(unit);
}
@Override
public void persist(AMEEUnit unit) {
dao.persist(unit);
}
@Override
public void remove(AMEEUnit unit) {
unit.setStatus(AMEEStatus.TRASH);
}
// For tests.
public void setUnitServiceDAO(UnitServiceDAO dao) {
this.dao = dao;
}
}
|
package openmods.sync;
import java.io.*;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import openmods.api.IValueProvider;
import openmods.liquids.GenericTank;
import openmods.utils.ByteUtils;
import com.google.common.io.ByteStreams;
public class SyncableTank extends GenericTank implements ISyncableObject, IValueProvider<FluidStack> {
private boolean dirty = false;
public SyncableTank(int capacity, FluidStack... acceptableFluids) {
super(capacity, acceptableFluids);
}
@Override
public boolean isDirty() {
return dirty;
}
@Override
public void markClean() {
dirty = false;
}
@Override
public void markDirty() {
dirty = true;
}
@Override
public void readFromStream(DataInputStream stream) throws IOException {
if (stream.readBoolean()) {
int fluidId = ByteUtils.readVLI(stream);
Fluid fluid = FluidRegistry.getFluid(fluidId);
int fluidAmount = stream.readInt();
this.fluid = new FluidStack(fluid, fluidAmount);
final int tagSize = ByteUtils.readVLI(stream);
if (tagSize > 0) {
this.fluid.tag = CompressedStreamTools.readCompressed(ByteStreams.limit(stream, tagSize));
}
} else {
this.fluid = null;
}
}
@Override
public void writeToStream(DataOutputStream stream) throws IOException {
if (fluid != null) {
stream.writeBoolean(true);
// .fluidID does not compile in Forge >= 1350, but class tranformer fixes it
// NOTE: reloading this class in debugger will bypass transformer and cause crash
ByteUtils.writeVLI(stream, fluid.fluidID);
stream.writeInt(fluid.amount);
if (fluid.tag != null) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
CompressedStreamTools.writeCompressed(fluid.tag, buffer);
byte[] bytes = buffer.toByteArray();
ByteUtils.writeVLI(stream, bytes.length);
stream.write(bytes);
} else {
stream.writeByte(0);
}
} else {
stream.writeBoolean(false);
}
}
@Override
public void writeToNBT(NBTTagCompound tag, String name) {
final NBTTagCompound tankTag = new NBTTagCompound();
this.writeToNBT(tankTag);
tag.setTag(name, tankTag);
}
@Override
public void readFromNBT(NBTTagCompound tag, String name) {
if (tag.hasKey(name, Constants.NBT.TAG_COMPOUND)) {
final NBTTagCompound tankTag = tag.getCompoundTag(name);
this.readFromNBT(tankTag);
} else {
// For legacy worlds - tag was saved in wrong place due to bug
this.readFromNBT(tag);
}
}
@Override
public int fill(FluidStack resource, boolean doFill) {
int filled = super.fill(resource, doFill);
if (doFill && filled > 0) markDirty();
return filled;
}
@Override
public FluidStack drain(FluidStack stack, boolean doDrain) {
FluidStack drained = super.drain(stack, doDrain);
if (doDrain && drained != null) markDirty();
return drained;
}
@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
FluidStack drained = super.drain(maxDrain, doDrain);
if (doDrain && drained != null) markDirty();
return drained;
}
@Override
public FluidStack getValue() {
FluidStack stack = super.getFluid();
return stack != null? stack.copy() : null;
}
}
|
package org.basex.index.ft;
import static org.basex.core.Text.*;
import static org.basex.data.DataText.*;
import static org.basex.util.Token.*;
import static org.basex.util.ft.FTFlag.*;
import java.io.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.index.*;
import org.basex.index.IndexCache.CacheEntry;
import org.basex.io.random.*;
import org.basex.util.*;
import org.basex.util.ft.*;
final class FTFuzzy extends FTIndex {
/** Entry size. */
private static final int ENTRY = 9;
/** Token positions. */
final int[] tp;
/** Levenshtein reference. */
private final Levenshtein ls = new Levenshtein();
/** Index storing each unique token length and pointer
* on the first token with this length. */
private final DataAccess inX;
/** Index storing each token, its data size and pointer on the data. */
final DataAccess inY;
/** Storing pre and pos values for each token. */
final DataAccess inZ;
/**
* Constructor, initializing the index structure.
* @param d data reference
* @throws IOException I/O Exception
*/
FTFuzzy(final Data d) throws IOException {
super(d);
// cache token length index
inY = new DataAccess(d.meta.dbfile(DATAFTX + 'y'));
inZ = new DataAccess(d.meta.dbfile(DATAFTX + 'z'));
inX = new DataAccess(d.meta.dbfile(DATAFTX + 'x'));
tp = new int[d.meta.maxlen + 3];
for(int i = 0; i < tp.length; ++i) tp[i] = -1;
int is = inX.readNum();
while(--is >= 0) {
int p = inX.readNum();
final int r;
if(p < tp.length) {
r = inX.read4();
} else {
// legacy issue (7.0.2 -> 7.1)
r = p << 24 | (inX.read1() & 0xFF) << 16 |
(inX.read1() & 0xFF) << 8 | inX.read1() & 0xFF;
p = p >> 8 | 0x40;
}
tp[p] = r;
}
tp[tp.length - 1] = (int) inY.length();
}
@Override
public synchronized int count(final IndexToken ind) {
if(ind.get().length > data.meta.maxlen) return Integer.MAX_VALUE;
// estimate costs for queries which stretch over multiple index entries
final FTLexer lex = (FTLexer) ind;
if(lex.ftOpt().is(FZ)) return Math.max(1, data.meta.size / 10);
final byte[] tok = lex.get();
final CacheEntry e = cache.get(tok);
if(e != null) return e.size;
int s = 0;
long poi = 0;
final long p = token(tok);
if(p > -1) {
s = size(p, tok.length);
poi = pointer(p, tok.length);
}
cache.add(tok, s, poi);
return s;
}
@Override
public synchronized IndexIterator iter(final IndexToken ind) {
final byte[] tok = ind.get();
// support fuzzy search
if(((FTLexer) ind).ftOpt().is(FZ)) {
int k = data.meta.prop.num(Prop.LSERROR);
if(k == 0) k = tok.length >> 2;
return fuzzy(tok, k, false);
}
// return cached or new result
final CacheEntry e = cache.get(tok);
if(e != null) return iter(e.pointer, e.size, inZ, false);
final int p = token(tok);
return p > -1 ? iter(pointer(p, tok.length),
size(p, tok.length), inZ, false) : FTIndexIterator.FTEMPTY;
}
@Override
public EntryIterator entries(final byte[] prefix) {
return new EntryIterator() {
int ti = prefix.length - 1, i, e, nr;
boolean inner;
@Override
public synchronized byte[] next() {
if(inner) {
// loop through all entries with the same character length
while(i < e) {
final byte[] entry = inY.readBytes(i, ti);
i += ti + ENTRY;
// could be sped up by using binary search for the first entry
if(startsWith(entry, prefix)) {
final long poi = inY.read5();
nr = inY.read4();
if(prefix.length != 0) cache.add(entry, nr, poi);
// mark first hit
return entry;
} else if(nr != 0) {
// stop after last hit
break;
}
}
}
// find next available entry group
while(++ti < tp.length - 1) {
i = tp[ti];
if(i != -1) {
int c = ti + 1;
do e = tp[c++]; while(e == -1);
nr = 0;
inner = true;
// jump to inner loop
final byte[] n = next();
if(n != null) return n;
}
}
// all entries processed: return null
return null;
}
@Override
public int count() {
return nr;
}
};
}
@Override
public synchronized byte[] info() {
final TokenBuilder tb = new TokenBuilder();
tb.add(LI_STRUCTURE + FUZZY + NL);
tb.addExt("- %: %" + NL, STEMMING, Util.flag(data.meta.stemming));
tb.addExt("- %: %" + NL, CASE_SENSITIVITY, Util.flag(data.meta.casesens));
tb.addExt("- %: %" + NL, DIACRITICS, Util.flag(data.meta.diacritics));
if(data.meta.language != null)
tb.addExt("- %: %" + NL, LANGUAGE, data.meta.language);
final long l = inX.length() + inY.length() + inZ.length();
tb.add(LI_SIZE + Performance.format(l, true) + NL);
final IndexStats stats = new IndexStats(data);
addOccs(stats);
stats.print(tb);
return tb.finish();
}
@Override
public synchronized void close() throws IOException {
inX.close();
inY.close();
inZ.close();
}
/**
* Determines the pointer on a token.
* @param tok token looking for
* @return int pointer or {@code -1} if token was not found
*/
private int token(final byte[] tok) {
final int tl = tok.length;
// left limit
int l = tp[tl];
if(l == -1) return -1;
int i = 1;
int r;
// find right limit
do r = tp[tl + i++]; while(r == -1);
final int x = r;
// binary search
final int o = tl + ENTRY;
while(l < r) {
final int m = l + (r - l >> 1) / o * o;
final int c = diff(inY.readBytes(m, tl), tok);
if(c == 0) return m;
if(c < 0) l = m + o;
else r = m - o;
}
// accept entry if pointer is inside relevant tokens
return r != x && l == r && eq(inY.readBytes(l, tl), tok) ? l : -1;
}
/**
* Collects all tokens and their sizes found in the index structure.
* @param stats statistics
*/
private void addOccs(final IndexStats stats) {
int i = 0;
while(i < tp.length && tp[i] == -1) ++i;
int p = tp[i];
int j = i + 1;
while(j < tp.length && tp[j] == -1) ++j;
while(p < tp[tp.length - 1]) {
if(stats.adding(size(p, i))) stats.add(inY.readBytes(p, i));
p += i + ENTRY;
if(p == tp[j]) {
i = j;
while(j + 1 < tp.length && tp[++j] == -1);
}
}
}
/**
* Gets the pointer on ftdata for a token.
* @param pt pointer on token
* @param lt length of the token
* @return int pointer on ftdata
*/
private long pointer(final long pt, final int lt) {
return inY.read5(pt + lt);
}
/**
* Reads the size of ftdata from disk.
* @param pt pointer on token
* @param lt length of the token
* @return size of the ftdata
*/
private int size(final long pt, final int lt) {
return inY.read4(pt + lt + 5);
}
/**
* Performs a fuzzy search for token, with e maximal number
* of errors e.
* @param tok token looking for
* @param k number of errors allowed
* @param f fast evaluation
* @return iterator
*/
private IndexIterator fuzzy(final byte[] tok, final int k, final boolean f) {
FTIndexIterator it = FTIndexIterator.FTEMPTY;
final int tl = tok.length;
final int e = Math.min(tp.length - 1, tl + k);
int s = Math.max(1, tl - k) - 1;
while(++s <= e) {
int p = tp[s];
if(p == -1) continue;
int i = s + 1;
int r = -1;
while(i < tp.length && r == -1) r = tp[i++];
while(p < r) {
if(ls.similar(inY.readBytes(p, s), tok, k)) {
it = FTIndexIterator.union(
iter(pointer(p, s), size(p, s), inZ, f), it);
}
p += s + ENTRY;
}
}
return it;
}
}
|
package org.cojen.tupl.util;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Shared pool of daemon threads. Intended as a faster alternative to launching new threads,
* but not as fast as a work stealing pool.
*
* @author Brian S O'Neill
*/
public final class Runner extends AbstractExecutorService {
private static final ThreadGroup cMainGroup;
private static final Runner cMainRunner;
private static volatile ConcurrentHashMap<ThreadGroup, Runner> cRunners;
static {
cMainGroup = obtainGroup();
cMainRunner = new Runner(cMainGroup);
}
public static void start(Runnable command) {
start(null, command);
}
/**
* @param namePrefix name prefix to assign to the thread
*/
public static void start(final String namePrefix, final Runnable command) {
Objects.requireNonNull(command);
Runnable actual = command;
if (namePrefix != null) {
actual = () -> {
setThreadName(Thread.currentThread(), namePrefix);
command.run();
};
}
current().execute(actual);
}
/**
* Return an executor for the current thread's group or security manager.
*/
public static Runner current() {
ThreadGroup group = obtainGroup();
if (group == cMainGroup) {
return cMainRunner;
}
ConcurrentHashMap<ThreadGroup, Runner> runners = cRunners;
if (runners == null) {
synchronized (Runner.class) {
runners = cRunners;
if (runners == null) {
cRunners = new ConcurrentHashMap<>();
}
}
}
Runner runner = runners.get(group);
if (runner == null) {
synchronized (Runner.class) {
runner = runners.get(group);
if (runner == null) {
runner = new Runner(group);
cRunners.put(group, runner);
}
}
}
return runner;
}
private static ThreadGroup obtainGroup() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ThreadGroup group = sm.getThreadGroup();
if (group != null) {
return group;
}
}
return Thread.currentThread().getThreadGroup();
}
private static void setThreadName(Thread t, String namePrefix) {
t.setName(namePrefix + '-' + Long.toUnsignedString(t.getId()));
}
private final ThreadGroup mGroup;
private Loop mReady;
private Runner(ThreadGroup group) {
mGroup = group;
}
@Override
public void execute(Runnable task) {
Loop ready;
synchronized (this) {
ready = mReady;
if (ready == null) {
new Loop(task).start();
} else {
Loop prev = ready.mPrev;
if (prev != null) {
prev.mNext = null;
ready.mPrev = null;
}
mReady = prev;
ready.mTask = task;
}
}
Parker.unpark(ready);
}
/**
* @throws UnsupportedOperationException
*/
@Override
public void shutdown() {
throw new UnsupportedOperationException();
}
/**
* @throws UnsupportedOperationException
*/
@Override
public List<Runnable> shutdownNow() {
throw new UnsupportedOperationException();
}
/**
* @return false
*/
@Override
public boolean isShutdown() {
return false;
}
/**
* @return false
*/
@Override
public boolean isTerminated() {
return false;
}
/**
* @throws UnsupportedOperationException
*/
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException();
}
private synchronized void enqueue(Loop ready) {
Loop prev = mReady;
if (prev != null) {
prev.mNext = ready;
ready.mPrev = prev;
}
mReady = ready;
}
/**
* @return null if removed, else a task to run
*/
private synchronized Runnable tryRemove(Loop exiting) {
Runnable task = exiting.mTask;
if (task != null) {
return task;
}
Loop prev = exiting.mPrev;
Loop next = exiting.mNext;
if (next != null) {
next.mPrev = prev;
} else {
mReady = prev;
}
if (prev != null) {
prev.mNext = next;
}
return null;
}
private class Loop extends Thread {
private static final long TIMEOUT = 50_000_000_000L;
private static final long JITTER = 10_000_000_000L;
private Loop mPrev, mNext;
private volatile Runnable mTask;
Loop(Runnable task) {
super(mGroup, (Runnable) null);
setDaemon(true);
setThreadName(this, "Runner-" + mGroup.getName());
mTask = task;
}
@Override
public void run() {
final String name = getName();
Runnable task = mTask;
outer: while (true) {
mTask = null;
if (isInterrupted()) {
// Clear interrupt status.
Thread.interrupted();
}
try {
task.run();
} catch (Throwable e) {
try {
getUncaughtExceptionHandler().uncaughtException(this, e);
} catch (Throwable e2) {
// Ignore.
}
}
if (getPriority() != NORM_PRIORITY) {
setPriority(NORM_PRIORITY);
}
if (!name.equals(getName())) {
setName(name);
}
task = null;
enqueue(this);
long timeout = TIMEOUT + ThreadLocalRandom.current().nextLong(JITTER);
long end = System.nanoTime() + timeout;
do {
Parker.parkNanos(this, timeout);
task = mTask;
if (task != null) {
continue outer;
}
timeout = end - System.nanoTime();
} while (timeout > 0);
if ((task = tryRemove(this)) == null) {
return;
}
}
}
}
}
|
package com.conveyal.r5.analyst.broker;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;
import com.conveyal.r5.analyst.cluster.GenericClusterRequest;
import com.conveyal.r5.common.JsonUtilities;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.HttpStatus;
import com.conveyal.r5.analyst.cluster.AnalystWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* This class tracks incoming requests from workers to consume Analyst tasks, and attempts to match those
* requests to enqueued tasks. It aims to draw tasks fairly from all users, and fairly from all jobs within each user,
* while attempting to respect the graph affinity of each worker (give it tasks that require the same graph it has been
* working on recently).
*
* When no work is available or no workers are available, the polling functions return immediately, avoiding spin-wait.
* When they are receiving no work, workers are expected to disconnect and re-poll occasionally, on the order of 30
* seconds. This serves as a signal to the broker that they are still alive and waiting.
*
* TODO if there is a backlog of work (the usual case when jobs are lined up) workers will constantly change graphs.
* Because (at least currently) two users never share the same graph, we can get by with pulling tasks cyclically or
* randomly from all the jobs, and just actively shaping the number of workers with affinity for each graph by forcing
* some of them to accept tasks on graphs other than the one they have declared affinity for.
*
* This could be thought of as "affinity homeostasis". We will constantly keep track of the ideal proportion of workers
* by graph (based on active queues), and the true proportion of consumers by graph (based on incoming requests) then
* we can decide when a worker's graph affinity should be ignored and what it should be forced to.
*
* It may also be helpful to mark jobs every time they are skipped in the LRU queue. Each time a job is serviced,
* it is taken out of the queue and put at its end. Jobs that have not been serviced float to the top.
*
* TODO: occasionally purge closed connections from workersByCategory
* TODO: worker catalog and graph affinity homeostasis
* TODO: catalog of recently seen consumers by affinity with IP: response.getRequest().getRemoteAddr();
*/
public class Broker implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Broker.class);
public final CircularList<Job> jobs = new CircularList<>();
/** The most tasks to deliver to a worker at a time. */
public final int MAX_TASKS_PER_WORKER = 8;
/**
* How long to give workers to start up (in ms) before assuming that they have started (and starting more
* on a given graph if they haven't.
*/
public static final long WORKER_STARTUP_TIME = 60 * 60 * 1000;
private int nUndeliveredTasks = 0; // Including normal priority jobs and high-priority tasks. TODO check that this total is really properly maintained
private int nWaitingConsumers = 0; // including some that might be closed
private int nextTaskId = 0;
/** Maximum number of workers allowed */
private int maxWorkers;
private static final ObjectMapper mapper = JsonUtilities.objectMapper;
private long nextRedeliveryCheckTime = System.currentTimeMillis();
/*static {
mapper.registerModule(AgencyAndIdSerializer.makeModule());
mapper.registerModule(QualifiedModeSetSerializer.makeModule());
mapper.registerModule(JavaLocalDateSerializer.makeModule());
mapper.registerModule(TraverseModeSetSerializer.makeModule());
}*/
/** The configuration for this broker. */
private final Properties brokerConfig;
/** The configuration that will be applied to workers launched by this broker. */
private Properties workerConfig;
/** Keeps track of all the workers that have contacted this broker recently asking for work. */
protected WorkerCatalog workerCatalog = new WorkerCatalog();
/**
* Requests that are not part of a job and can "cut in line" in front of jobs for immediate execution.
* When a high priority task is first received, we attempt to send it to a worker right away via
* the side channels. If that doesn't work, we put them here to be picked up the next time a worker
* is available via normal task distribution channels.
*/
private ArrayListMultimap<WorkerCategory, GenericClusterRequest> stalledHighPriorityTasks = ArrayListMultimap.create();
/**
* High priority requests that have just come and are about to be sent down a single point channel.
* They put here for just 100 ms so that any that arrive together are batched to the same worker.
* If we didn't do this, two requests arriving at basically the same time could get fanned out to
* two different workers because the second came in in between closing the side channel and the worker
* reopening it.
*/
private Multimap<WorkerCategory, GenericClusterRequest> newHighPriorityTasks = ArrayListMultimap.create();
/** Priority requests that have already been farmed out to workers, and are awaiting a response. */
private TIntObjectMap<Response> highPriorityResponses = new TIntObjectHashMap<>();
/** Outstanding requests from workers for tasks, grouped by worker graph affinity. */
Map<WorkerCategory, Deque<Response>> workersByCategory = new HashMap<>();
/**
* Side channels used to send single point requests to workers, cutting in front of any other work on said workers.
* We use a TreeMultimap because it is ordered, and the wrapped response defines an order based on
* machine ID. This way, the same machine will tend to get all single point work for a graph,
* so multiple machines won't stay alive to do single point work.
*/
private Multimap<WorkerCategory, WrappedResponse> singlePointChannels = TreeMultimap.create();
/** should we work offline */
private boolean workOffline;
private AmazonEC2 ec2;
private Timer timer = new Timer();
private String workerName, project;
/**
* keep track of which graphs we have launched workers on and how long ago we launched them,
* so that we don't re-request workers which have been requested.
*/
private TObjectLongMap<WorkerCategory> recentlyRequestedWorkers = new TObjectLongHashMap<>();
// Queue of tasks to complete Delete, Enqueue etc. to avoid synchronizing all the functions ?
public Broker (Properties brokerConfig, String addr, int port) {
// print out date on startup so that CloudWatch logs has a unique fingerprint
LOG.info("Analyst broker starting at {}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
this.brokerConfig = brokerConfig;
Boolean workOffline = Boolean.parseBoolean(brokerConfig.getProperty("work-offline"));
if (workOffline == null) workOffline = true;
this.workOffline = workOffline;
if (!workOffline) {
// create a config for the AWS workers
workerConfig = new Properties();
if (this.brokerConfig.getProperty("worker-config") != null) {
// load the base worker configuration if specified
try {
File f = new File(this.brokerConfig.getProperty("worker-config"));
FileInputStream fis = new FileInputStream(f);
workerConfig.load(fis);
fis.close();
} catch (IOException e) {
LOG.error("Error loading base worker configuration", e);
}
}
workerConfig.setProperty("broker-address", addr);
workerConfig.setProperty("broker-port", "" + port);
if (brokerConfig.getProperty("statistics-queue") != null)
workerConfig.setProperty("statistics-queue", brokerConfig.getProperty("statistics-queue"));
workerConfig.setProperty("graphs-bucket", brokerConfig.getProperty("graphs-bucket"));
workerConfig.setProperty("pointsets-bucket", brokerConfig.getProperty("pointsets-bucket"));
// Tell the workers to shut themselves down automatically
workerConfig.setProperty("auto-shutdown", "true");
}
// TODO what are these for?
workerName = brokerConfig.getProperty("worker-name") != null ? brokerConfig.getProperty("worker-name") : "analyst-worker";
project = brokerConfig.getProperty("project") != null ? brokerConfig.getProperty("project") : "analyst";
this.maxWorkers = brokerConfig.getProperty("max-workers") != null ? Integer.parseInt(brokerConfig.getProperty("max-workers")) : 4;
ec2 = new AmazonEC2Client();
// default to current region when running in EC2
com.amazonaws.regions.Region r = Regions.getCurrentRegion();
if (r != null)
ec2.setRegion(r);
}
/**
* Enqueue a task for execution ASAP, planning to return the response over the same HTTP connection.
* Low-reliability, no re-delivery.
*/
public synchronized void enqueuePriorityTask (GenericClusterRequest task, Response response) {
boolean workersAvailable = workersAvailable(task.getWorkerCategory());
if (!workersAvailable) {
createWorkersInCategory(task.getWorkerCategory());
// chances are it won't be done in 30 seconds, but we want to poll frequently to avoid issues with phasing
try {
response.setHeader("Retry-After", "30");
response.sendError(503,
"No workers available in this category, please retry shortly.");
} catch (IOException e) {
LOG.error("Could not finish high-priority 503 response", e);
}
}
// if we're in offline mode, enqueue anyhow to kick the cluster to build the graph
// note that this will mean that requests get delivered multiple times in offline mode,
// so some unnecessary computation takes place
if (workersAvailable || workOffline) {
task.taskId = nextTaskId++;
newHighPriorityTasks.put(task.getWorkerCategory(), task);
highPriorityResponses.put(task.taskId, response);
// wait 100ms to deliver to workers in case another request comes in almost simultaneously
timer.schedule(new TimerTask() {
@Override
public void run() {
deliverHighPriorityTasks(task.getWorkerCategory());
}
}, 100);
}
// do not notify task delivery thread just yet as we haven't put anything in the task delivery queue yet.
}
/** Attempt to deliver high priority tasks via side channels, or move them into normal channels if need be. */
public synchronized void deliverHighPriorityTasks (WorkerCategory category) {
Collection<GenericClusterRequest> tasks = newHighPriorityTasks.get(category);
if (tasks.isEmpty())
// someone got here first
return;
// try to deliver via side channels
Collection<WrappedResponse> wrs = singlePointChannels.get(category);
if (!wrs.isEmpty()) {
// there is (probably) a single point machine waiting to receive this
WrappedResponse wr = wrs.iterator().next();
try {
wr.response.setContentType("application/json");
OutputStream os = wr.response.getOutputStream();
mapper.writeValue(os, tasks);
os.close();
wr.response.resume();
newHighPriorityTasks.removeAll(category);
return;
} catch (Exception e) {
LOG.info("Failed to deliver single point job via side channel, reverting to normal channel", e);
} finally {
// remove responses whether they are dead or alive
removeSinglePointChannel(category, wr);
}
}
// if we got here we didn't manage to send it via side channel, put it in the rotation for normal channels
// not using putAll as it retains a link to the original collection and then we get a concurrent modification exception later.
tasks.forEach(t -> stalledHighPriorityTasks.put(category, t));
LOG.info("No side channel available for graph {}, delivering {} tasks via normal channel",
category, tasks.size());
nUndeliveredTasks += tasks.size();
newHighPriorityTasks.removeAll(category);
// wake up delivery thread
notify();
}
/** Enqueue some tasks for queued execution possibly much later. Results will be saved to S3. */
public synchronized void enqueueTasks (List<GenericClusterRequest> tasks) {
Job job = findJob(tasks.get(0)); // creates one if it doesn't exist
if (!workersAvailable(job.getWorkerCategory())) {
createWorkersInCategory(job.getWorkerCategory());
}
for (GenericClusterRequest task : tasks) {
task.taskId = nextTaskId++;
job.addTask(task);
nUndeliveredTasks += 1;
LOG.debug("Enqueued task id {} in job {}", task.taskId, job.jobId);
if (!task.graphId.equals(job.workerCategory.graphId)) {
LOG.error("Task graph ID {} does not match job: {}.", task.graphId, job.workerCategory);
}
if (!task.workerVersion.equals(job.workerCategory.workerVersion)) {
LOG.error("Task R5 commit {} does not match job: {}.", task.workerVersion, job.workerCategory);
}
}
// Wake up the delivery thread if it's waiting on input.
// This wakes whatever thread called wait() while holding the monitor for this Broker object.
notify();
}
public boolean workersAvailable (WorkerCategory category) {
// Ensure we don't assign work to dead workers.
workerCatalog.purgeDeadWorkers();
return !workerCatalog.workersByCategory.get(category).isEmpty();
}
/** Create workers for a given job, if need be */
public void createWorkersInCategory (WorkerCategory category) {
String clientToken = UUID.randomUUID().toString().replaceAll("-", "");
if (workOffline) {
LOG.info("Work offline enabled, not creating workers for {}", category);
return;
}
if (workerCatalog.observationsByWorkerId.size() >= maxWorkers) {
LOG.warn("{} workers already started, not starting more; jobs will not complete on {}", maxWorkers, category);
return;
}
// If workers have already been started up, don't repeat the operation.
if (recentlyRequestedWorkers.containsKey(category)
&& recentlyRequestedWorkers.get(category) >= System.currentTimeMillis() - WORKER_STARTUP_TIME){
LOG.info("Workers still starting on {}, not starting more", category);
return;
}
// TODO: compute
int nWorkers = 1;
// There are no workers on this graph with the right worker commit, start some.
LOG.info("Starting {} workers as there are none on {}", nWorkers, category);
RunInstancesRequest req = new RunInstancesRequest();
req.setImageId(brokerConfig.getProperty("ami-id"));
req.setInstanceType(InstanceType.valueOf(brokerConfig.getProperty("worker-type")));
req.setSubnetId(brokerConfig.getProperty("subnet-id"));
// even if we can't get all the workers we want at least get some
req.setMinCount(1);
req.setMaxCount(nWorkers);
// It's fine to just modify the worker config without a protective copy because this method is synchronized.
workerConfig.setProperty("initial-graph-id", category.graphId);
workerConfig.setProperty("worker-version", category.workerVersion);
// Tell the worker where to get its R5 JAR. This is a Conveyal S3 bucket with HTTP access turned on.
String workerDownloadUrl = String.format("http://r5-builds.s3-website-eu-west-1.amazonaws.com/%s.jar",
category.workerVersion);
workerConfig.setProperty("download-url", workerDownloadUrl);
// This is the R5 broker, so always start R5 workers (rather than OTP workers).
workerConfig.setProperty("main-class", AnalystWorker.class.getName());
ByteArrayOutputStream cfg = new ByteArrayOutputStream();
try {
workerConfig.store(cfg, "Worker config");
cfg.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
// Send the config to the new workers as EC2 "user data"
String userData = new String(Base64.getEncoder().encode(cfg.toByteArray()));
req.setUserData(userData);
if (brokerConfig.getProperty("worker-iam-role") != null)
req.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(brokerConfig.getProperty("worker-iam-role")));
// launch into a VPC if desired
if (brokerConfig.getProperty("subnet") != null)
req.setSubnetId(brokerConfig.getProperty("subnet"));
// allow us to retry request at will
req.setClientToken(clientToken);
// allow machine to shut itself completely off
req.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate);
RunInstancesResult res = ec2.runInstances(req);
res.getReservation().getInstances().forEach(i -> {
Collection<Tag> tags = Arrays.asList(
new Tag("name", workerName),
new Tag("project", project)
);
i.setTags(tags);
});
recentlyRequestedWorkers.put(category, System.currentTimeMillis());
LOG.info("Requesting {} workers", nWorkers);
}
/** Consumer long-poll operations are enqueued here. */
public synchronized void registerSuspendedResponse(WorkerCategory category, Response response) {
// Add this worker to our catalog, tracking its graph affinity and the last time it was seen.
String workerId = response.getRequest().getHeader(AnalystWorker.WORKER_ID_HEADER);
if (workerId != null && !workerId.isEmpty()) {
workerCatalog.catalog(workerId, category);
} else {
LOG.error("Worker did not supply a unique ID for itself . Ignoring it.");
return;
}
// Shelf this suspended response in a queue grouped by graph affinity.
Deque<Response> deque = workersByCategory.get(category);
if (deque == null) {
deque = new ArrayDeque<>();
workersByCategory.put(category, deque);
}
deque.addLast(response);
nWaitingConsumers += 1;
// Wake up the delivery thread if it's waiting on consumers.
// This is whatever thread called wait() while holding the monitor for this Broker object.
notify();
}
/** When we notice that a long poll connection has closed, we remove it here. */
public synchronized boolean removeSuspendedResponse(WorkerCategory category, Response response) {
Deque<Response> deque = workersByCategory.get(category);
if (deque == null) {
return false;
}
if (deque.remove(response)) {
nWaitingConsumers -= 1;
LOG.debug("Removed closed connection from queue.");
return true;
}
return false;
}
/**
* Register an HTTP connection that can be used to send single point requests directly to
* workers, bypassing normal task distribution channels.
*/
public synchronized void registerSinglePointChannel (WorkerCategory category, WrappedResponse response) {
singlePointChannels.put(category, response);
// No need to notify as the side channels are not used by the normal task delivery loop.
}
/**
* Remove a single point channel because the connection was closed.
*/
public synchronized boolean removeSinglePointChannel (WorkerCategory category, WrappedResponse response) {
return singlePointChannels.remove(category, response);
}
/**
* This method checks whether there are any high-priority tasks or normal job tasks and attempts to match them with
* waiting workers.
*
* It blocks by calling wait() whenever it has nothing to do (when no tasks or workers available). It is awakened
* whenever new tasks come in or when a worker (re-)connects.
*
* This whole function is synchronized because wait() must be called within a synchronized block. When wait() is
* called, the monitor is released and other threads listening for worker connections or added jobs can act.
*/
public synchronized void deliverTasks() throws InterruptedException {
// Wait until there are some undelivered tasks.
while (nUndeliveredTasks == 0) {
LOG.debug("Task delivery thread is going to sleep, there are no tasks waiting for delivery.");
// Thread will be notified when tasks are added or there are new incoming consumer connections.
wait();
// If a worker connected while there were no tasks queued for delivery,
// we need to check if any should be re-delivered.
for (Job job : jobs) {
nUndeliveredTasks += job.redeliver();
}
}
LOG.debug("Task delivery thread is awake and there are some undelivered tasks.");
while (nWaitingConsumers == 0) {
LOG.debug("Task delivery thread is going to sleep, there are no consumers waiting.");
// Thread will be notified when tasks are added or there are new incoming consumer connections.
wait();
}
LOG.debug("Task delivery thread awake; consumers are waiting and tasks are available");
// Loop over all jobs and send them to consumers
// This makes for an as-fair-as-possible allocation: jobs are fairly allocated between
// workers on their graph.
// start with high-priority tasks
HIGHPRIORITY: for (Map.Entry<WorkerCategory, Collection<GenericClusterRequest>> e : stalledHighPriorityTasks
.asMap().entrySet()) {
// the collection is an arraylist with the most recently added at the end
WorkerCategory workerCategory = e.getKey();
Collection<GenericClusterRequest> tasks = e.getValue();
// See if there are any workers that requested tasks in this category.
// Don't respect graph affinity when working offline; we can't arbitrarily start more workers.
Deque<Response> consumers;
if (!workOffline) {
consumers = workersByCategory.get(workerCategory);
} else {
Optional<Deque<Response>> opt = workersByCategory.values().stream().filter(c -> !c.isEmpty()).findFirst();
if (opt.isPresent()) consumers = opt.get();
else consumers = null;
}
if (consumers == null || consumers.isEmpty()) {
LOG.warn("No worker found for {}, needed for {} high-priority tasks", workerCategory, tasks.size());
continue HIGHPRIORITY;
}
Iterator<GenericClusterRequest> taskIt = tasks.iterator();
while (taskIt.hasNext() && !consumers.isEmpty()) {
Response consumer = consumers.pop();
// package tasks into a job
Job job = new Job("HIGH PRIORITY");
job.workerCategory = workerCategory;
for (int i = 0; i < MAX_TASKS_PER_WORKER && taskIt.hasNext(); i++) {
job.addTask(taskIt.next());
taskIt.remove();
}
// TODO inefficiency here: we should mix single point and multipoint in the same response
deliver(job, consumer);
nWaitingConsumers
}
}
// deliver low priority tasks
while (nWaitingConsumers > 0) {
// ensure we advance at least one; advanceToElement will not advance if the predicate passes
// for the first element.
jobs.advance();
// find a job that both has visible tasks and has available workers
// We don't respect graph affinity when working offline, because we can't start more workers
Job current;
if (!workOffline) {
current = jobs.advanceToElement(job -> !job.tasksAwaitingDelivery.isEmpty() &&
workersByCategory.containsKey(job.workerCategory) &&
!workersByCategory.get(job.workerCategory).isEmpty());
}
else {
current = jobs.advanceToElement(e -> !e.tasksAwaitingDelivery.isEmpty());
}
// nothing to see here
if (current == null) break;
Deque<Response> consumers;
if (!workOffline)
consumers = workersByCategory.get(current.workerCategory);
else {
Optional<Deque<Response>> opt = workersByCategory.values().stream().filter(c -> !c.isEmpty()).findFirst();
if (opt.isPresent()) consumers = opt.get();
else consumers = null;
}
// deliver this job to only one consumer
// This way if there are multiple workers and multiple jobs the jobs will be fairly distributed, more or less
deliver(current, consumers.pop());
nWaitingConsumers
}
// TODO: graph switching
// we've delivered everything we can, prevent anything else from happening until something changes
wait();
}
/**
* This uses a linear search through jobs, which should not be problematic unless there are thousands of
* simultaneous jobs. TODO task IDs should really not be sequential integers should they?
* @return a Job object that contains the given task ID.
*/
public Job getJobForTask (int taskId) {
for (Job job : jobs) {
if (job.containsTask(taskId)) {
return job;
}
}
return null;
}
/**
* Attempt to hand some tasks from the given job to a waiting consumer connection.
* The write will fail if the consumer has closed the connection but it hasn't been removed from the connection
* queue yet. This can happen because the Broker methods are synchronized, and the removal action may be waiting
* to get the monitor while we are trying to distribute tasks here.
* @return whether the handoff succeeded.
*/
public synchronized boolean deliver (Job job, Response response) {
// Check up-front whether the connection is still open.
if (!response.getRequest().getRequest().getConnection().isOpen()) {
LOG.debug("Consumer connection was closed. It will be removed.");
return false;
}
// Get up to N tasks from the tasksAwaitingDelivery deque
List<GenericClusterRequest> tasks = new ArrayList<>();
while (tasks.size() < MAX_TASKS_PER_WORKER && !job.tasksAwaitingDelivery.isEmpty()) {
tasks.add(job.tasksAwaitingDelivery.poll());
}
// Attempt to deliver the tasks to the given consumer.
try {
response.setStatus(HttpStatus.OK_200);
OutputStream out = response.getOutputStream();
mapper.writeValue(out, tasks);
response.resume();
} catch (IOException e) {
// The connection was probably closed by the consumer, but treat it as a server error.
LOG.debug("Consumer connection caused IO error, it will be removed.");
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
response.resume();
// Delivery failed, put tasks back on (the end of) the queue.
job.tasksAwaitingDelivery.addAll(tasks);
return false;
}
LOG.debug("Delivery of {} tasks succeeded.", tasks.size());
nUndeliveredTasks -= tasks.size(); // FIXME keeping a separate counter for this seems redundant, why not compute it?
job.lastDeliveryTime = System.currentTimeMillis();
return true;
}
/**
* Take a normal (non-priority) task out of a job queue, marking it as completed so it will not be re-delivered.
* TODO maybe use unique delivery receipts instead of task IDs to handle redelivered tasks independently
* @return whether the task was found and removed.
*/
public synchronized boolean markTaskCompleted (int taskId) {
Job job = getJobForTask(taskId);
if (job == null) {
LOG.error("Could not find a job containing task {}, and therefore could not mark the task as completed.", taskId);
return false;
}
job.completedTasks.add(taskId);
return true;
}
/**
* Marks the specified priority request as completed, and returns the suspended Response object for the connection
* that submitted the priority request (the UI), which probably still waiting to receive a result back over the
* same connection. A HttpHandler thread can then pump data from the DELETE body back to the origin of the request,
* without blocking the broker thread.
* TODO rename to "deregisterSuspendedProducer" and "deregisterSuspendedConsumer" ?
*/
public synchronized Response deletePriorityTask (int taskId) {
return highPriorityResponses.remove(taskId);
}
/** This is the broker's main event loop. */
@Override
public void run() {
while (true) {
try {
deliverTasks();
} catch (InterruptedException e) {
LOG.info("Task pump thread was interrupted.");
return;
}
}
}
/** Find the job that should contain a given task, creating that job if it does not exist. */
public Job findJob (GenericClusterRequest task) {
Job job = findJob(task.jobId);
if (job != null) {
return job;
}
job = new Job(task.jobId);
job.workerCategory = new WorkerCategory(task.graphId, task.workerVersion);
jobs.insertAtTail(job);
return job;
}
/** Find the job for the given jobId, returning null if that job does not exist. */
public Job findJob (String jobId) {
for (Job job : jobs) {
if (job.jobId.equals(jobId)) {
return job;
}
}
return null;
}
/** Delete the job with the given ID. */
public synchronized boolean deleteJob (String jobId) {
Job job = findJob(jobId);
if (job == null) return false;
nUndeliveredTasks -= job.tasksAwaitingDelivery.size();
return jobs.remove(job);
}
/** Returns whether this broker is tracking and jobs that have unfinished tasks. */
public synchronized boolean anyJobsActive() {
for (Job job : jobs) {
if (!job.isComplete()) return true;
}
return false;
}
/**
* We wrap responses in a class that has a machine ID, and then put them in a TreeSet so that
* the machine with the lowest ID on a given graph always gets single-point work. The reason
* for this is so that a single machine will tend to get single-point work and thus we don't
* unnecessarily keep multiple multipoint machines alive.
*/
public static class WrappedResponse implements Comparable<WrappedResponse> {
public final Response response;
public final String machineId;
public WrappedResponse(Request request, Response response) {
this.response = response;
this.machineId = request.getHeader(AnalystWorker.WORKER_ID_HEADER);
}
@Override public int compareTo(WrappedResponse wrappedResponse) {
return this.machineId.compareTo(wrappedResponse.machineId);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.